@sourcegraph/amp 0.0.1780464815-g688406 → 0.0.1780478921-g021c3e
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.
- package/dist/main.js +10 -10
- package/package.json +2 -2
package/dist/main.js
CHANGED
|
@@ -4177,13 +4177,13 @@ ${K}`))}},error:(V)=>{if(!G)G=!0,Z(Error(`Failed to spawn brew: ${V.message}`))}
|
|
|
4177
4177
|
${K}`;if(J==="pnpm"&&K.includes("Unable to find the global bin directory"))z+=`
|
|
4178
4178
|
|
|
4179
4179
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
4180
|
-
npm install -g ${D}`;Z(Error(z))}},error:(V)=>{if(!I)I=!0,Z(Error(`Failed to spawn ${J}: ${V.message}`))},complete:()=>{if(!I)I=!0,Y()}})})}a0();a0();Kg();var FeQ="@ampcode/cli";async function G50(A,Q,$=FeQ){let E=`${Q||"https://registry.npmjs.org"}/${$}/latest`,D=new AbortController,J=setTimeout(()=>D.abort(),5000);try{let U=await fetch(E,{signal:D.signal});if(!U.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let Y=await U.json(),Z=Y.version??Y["dist-tags"]?.latest;if(!Z)return{hasUpdate:!1,currentVersion:A,source:"npm"};let F=Yp(A,Z),X=F<0,I,G;if(Y.time){let V=Y.time[A],K=Y.time[Z],z=Date.now();if(V)I=Math.floor((z-new Date(V).getTime())/3600000);if(K)G=Math.floor((z-new Date(K).getTime())/3600000)}return S.info("NPM version comparison",{currentVersion:A,latestVersion:Z,compareResult:F,hasUpdate:X,currentVersionAge:I,latestVersionAge:G}),{hasUpdate:X,latestVersion:Z,currentVersion:A,currentVersionAge:I,latestVersionAge:G,source:"npm"}}catch(U){return S.debug("Error checking npm version",{error:U}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(J)}}var XeQ="https://static.ampcode.com/cli/cli-version.txt";async function V50(A){let Q=new AbortController,$=setTimeout(()=>Q.abort(),5000);try{let B=await fetch(`${XeQ}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!B.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let E=(await B.text()).trim();if(!E||!/^\d+\.\d+\.\d+/.test(E))return{hasUpdate:!1,currentVersion:A,source:"bin"};let D=Yp(A,E),J=D<0;return S.info("Bin version comparison",{currentVersion:A,latestVersion:E,compareResult:D,hasUpdate:J}),{hasUpdate:J,latestVersion:E,currentVersion:A,source:"bin"}}catch(B){return S.debug("Error checking bin version",{error:B}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout($)}}function Yp(A,Q){let $=(J)=>{let[U,Y]=J.split("-");return{parts:U?.split(".").map(Number)||[],label:Y}},B=$(A),E=$(Q),D=Math.max(B.parts.length,E.parts.length);for(let J=0;J<D;J++){let U=B.parts[J]||0,Y=E.parts[J]||0;if(U<Y)return-1;if(U>Y)return 1}if(B.label===E.label)return 0;if(!B.label&&E.label)return 1;if(B.label&&!E.label)return-1;if(B.label&&E.label)return B.label<E.label?-1:1;return 0}function Zp(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-(.+))?/);if(!Q)return null;let $=parseInt(Q[1],10),B=$!==0?$*1000:void 0,D=Q[2]?.match(/^g?([a-f0-9]+)$/)?.[1],J=B!==void 0?TV(B):void 0;return{sha:D,timestamp:B,age:J}}catch{return null}}xA();a0();import{readFile as IeQ,realpath as GeQ}from"node:fs/promises";import{dirname as TV4,join as VeQ}from"node:path";async function _V4(A){switch(A){case"binary":case"brew":return KeQ(Jp());case"npm":case"pnpm":case"yarn":case"bun":return zeQ()}}async function KeQ(A){let Q=await _K(A,["--version"],5000);if(Q.reason!=="success")return S.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function zeQ(){try{let A=process.argv[1];if(!A)return null;let Q=await GeQ(A),$=TV4(TV4(Q));return await WeQ(VeQ($,"package.json"))}catch(A){return S.debug("failed to read installed version from package.json",{error:A}),null}}async function WeQ(A){let Q=await IeQ(A,"utf8"),$=JSON.parse(Q);if(!$.name||!Ky0($.name))return S.debug("package.json name mismatch",{pkgJsonPath:A,name:$.name}),null;return $.version||null}a0();import{spawn as CeQ}from"node:child_process";function uy0(A){if(A=A.replace(/\/$/,""),!A.startsWith("http://")&&!A.startsWith("https://"))A=`https://${A}`;try{return new URL(A),A}catch{return S.warn(`Invalid registry URL: ${A}, falling back to npmjs.org`),"https://registry.npmjs.org"}}var K50=null,Fp=null;function SV4(A){return new Promise((Q)=>{let $=CeQ("npm",["config","get",A],{stdio:["ignore","pipe","ignore"],timeout:5000,shell:process.platform==="win32"}),B="";$.stdout.on("data",(E)=>{B+=E.toString()}),$.on("close",(E,D)=>{if(E!==0||D==="SIGTERM"){Q(null);return}let J=B.trim();Q(J&&J!=="undefined"?J:null)}),$.on("error",()=>{Q(null)})})}async function z50(){if(K50)return K50;if(Fp)return Fp;Fp=(async()=>{let A=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(A)return uy0(A);let Q=await SV4("@sourcegraph:registry");if(Q)return uy0(Q);let $=await SV4("registry");if($)return uy0($);return"https://registry.npmjs.org"})();try{return K50=await Fp,K50}finally{Fp=null}}var HeQ=3600000,NeQ=5000;function wy0(A,Q,$={}){let B=new w4,E=B.pipe(C$({shouldCountRefs:!1})),D=$.startDelayMs??0,J=$.checkIntervalMs??HeQ,U=!1,Y=()=>{U=!0};return setImmediate(async()=>{let Z=S.getChild("update");if(D>0){if(await SV(D),U)return}let F=E.subscribe({next:(I)=>{Z.debug("emit new state",I)}}),X=A;try{while(!U){let I=await qeQ(X,Q,Z,B);if(I.stop)return;if(I.updatedTo)X=I.updatedTo;if(I.emittedVisibleState){if(await SV(NeQ),U)return;B.next("hidden")}if(J<=0)return;let G=1000,V=J;while(V>0&&!U){let K=Math.min(G,V);await SV(K),V-=K}}}finally{F.unsubscribe(),B.complete()}}),{state:E,dispose:Y}}async function qeQ(A,Q,$,B){let E={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return $.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),E.stop=!0,E;let D=await Q.get("updates.mode");if(D==="disabled")return $.debug("checking disabled"),E.stop=!0,E;let J=await EZ(),U=J==="binary"||J==="brew",Y=U?void 0:await SK();$.debug("checking",{currentVersion:A,mode:D,packageManager:J,isBinaryDistribution:U,npmPackageName:Y});let Z;if(U)Z=await V50(A);else{let I=await z50();Z=await G50(A,I,Y)}if(!(Z.latestVersion&&Z.hasUpdate))return $.debug("no update available"),E;let F=(I)=>{B.next(I),E.emittedVisibleState=!0};if(J){let I=await _V4(J);if(I&&Yp(I,Z.latestVersion)>=0){if($.debug("on-disk version already up to date",{currentVersion:A,installedVersion:I,latestVersion:Z.latestVersion}),E.updatedTo=I,Yp(A,I)<0){let G=await SX(I),V={from:A,to:I,externallyUpdated:!0,...G};if(G.status==="same")$.info("on-disk already updated by another instance",V),F("updated");else $.warn("on-disk already updated by another instance, with PATH warning",V),F("updated-with-warning")}return E}}let X=()=>{if(Z.currentVersionAge!==void 0&&Z.latestVersionAge!==void 0){let I=Z.currentVersionAge-Z.latestVersionAge,G=0.5;if(Math.abs(I)<0.5)return $.debug("versions too close together, suppressing update warning",{currentVersionAge:Z.currentVersionAge,latestVersionAge:Z.latestVersionAge,ageDifferenceHours:I}),!0}return!1};if(!D)D=J==="pnpm"?"warn":"auto",$.debug("no configured update mode; selected default based on package manager",{packageManager:J,mode:D});if(J==="brew"){if(!X())F("update-available-brew");return E}if(J==="binary"&&process.execPath!==Jp()){if($.debug("non-standard binary path, showing warning"),!X())F("update-available-unrecognized-path");return E}if(D==="warn"){if(!X())F("update-available");return E}if(!J){if($.debug("auto-update not supported, falling back to warn mode"),!X())F("update-available");return E}try{await Up(Z.latestVersion,J),E.updatedTo=Z.latestVersion;let I=await SX(Z.latestVersion),G={from:Z.currentVersion,to:Z.latestVersion,...I};if(I.status==="same")$.info("success",G),F("updated");else $.warn("success with warning",G),F("updated-with-warning")}catch(I){F("update-error")}return E}catch(D){return $.debug("check failed",{error:D}),E}}Kg();import{stderr as EJ}from"node:process";function kV4(A){let Q=new PX().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(B)=>{await Gy0(B.force||!1,B.verbose||!1,"0.0.
|
|
4180
|
+
npm install -g ${D}`;Z(Error(z))}},error:(V)=>{if(!I)I=!0,Z(Error(`Failed to spawn ${J}: ${V.message}`))},complete:()=>{if(!I)I=!0,Y()}})})}a0();a0();Kg();var FeQ="@ampcode/cli";async function G50(A,Q,$=FeQ){let E=`${Q||"https://registry.npmjs.org"}/${$}/latest`,D=new AbortController,J=setTimeout(()=>D.abort(),5000);try{let U=await fetch(E,{signal:D.signal});if(!U.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let Y=await U.json(),Z=Y.version??Y["dist-tags"]?.latest;if(!Z)return{hasUpdate:!1,currentVersion:A,source:"npm"};let F=Yp(A,Z),X=F<0,I,G;if(Y.time){let V=Y.time[A],K=Y.time[Z],z=Date.now();if(V)I=Math.floor((z-new Date(V).getTime())/3600000);if(K)G=Math.floor((z-new Date(K).getTime())/3600000)}return S.info("NPM version comparison",{currentVersion:A,latestVersion:Z,compareResult:F,hasUpdate:X,currentVersionAge:I,latestVersionAge:G}),{hasUpdate:X,latestVersion:Z,currentVersion:A,currentVersionAge:I,latestVersionAge:G,source:"npm"}}catch(U){return S.debug("Error checking npm version",{error:U}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(J)}}var XeQ="https://static.ampcode.com/cli/cli-version.txt";async function V50(A){let Q=new AbortController,$=setTimeout(()=>Q.abort(),5000);try{let B=await fetch(`${XeQ}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!B.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let E=(await B.text()).trim();if(!E||!/^\d+\.\d+\.\d+/.test(E))return{hasUpdate:!1,currentVersion:A,source:"bin"};let D=Yp(A,E),J=D<0;return S.info("Bin version comparison",{currentVersion:A,latestVersion:E,compareResult:D,hasUpdate:J}),{hasUpdate:J,latestVersion:E,currentVersion:A,source:"bin"}}catch(B){return S.debug("Error checking bin version",{error:B}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout($)}}function Yp(A,Q){let $=(J)=>{let[U,Y]=J.split("-");return{parts:U?.split(".").map(Number)||[],label:Y}},B=$(A),E=$(Q),D=Math.max(B.parts.length,E.parts.length);for(let J=0;J<D;J++){let U=B.parts[J]||0,Y=E.parts[J]||0;if(U<Y)return-1;if(U>Y)return 1}if(B.label===E.label)return 0;if(!B.label&&E.label)return 1;if(B.label&&!E.label)return-1;if(B.label&&E.label)return B.label<E.label?-1:1;return 0}function Zp(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-(.+))?/);if(!Q)return null;let $=parseInt(Q[1],10),B=$!==0?$*1000:void 0,D=Q[2]?.match(/^g?([a-f0-9]+)$/)?.[1],J=B!==void 0?TV(B):void 0;return{sha:D,timestamp:B,age:J}}catch{return null}}xA();a0();import{readFile as IeQ,realpath as GeQ}from"node:fs/promises";import{dirname as TV4,join as VeQ}from"node:path";async function _V4(A){switch(A){case"binary":case"brew":return KeQ(Jp());case"npm":case"pnpm":case"yarn":case"bun":return zeQ()}}async function KeQ(A){let Q=await _K(A,["--version"],5000);if(Q.reason!=="success")return S.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function zeQ(){try{let A=process.argv[1];if(!A)return null;let Q=await GeQ(A),$=TV4(TV4(Q));return await WeQ(VeQ($,"package.json"))}catch(A){return S.debug("failed to read installed version from package.json",{error:A}),null}}async function WeQ(A){let Q=await IeQ(A,"utf8"),$=JSON.parse(Q);if(!$.name||!Ky0($.name))return S.debug("package.json name mismatch",{pkgJsonPath:A,name:$.name}),null;return $.version||null}a0();import{spawn as CeQ}from"node:child_process";function uy0(A){if(A=A.replace(/\/$/,""),!A.startsWith("http://")&&!A.startsWith("https://"))A=`https://${A}`;try{return new URL(A),A}catch{return S.warn(`Invalid registry URL: ${A}, falling back to npmjs.org`),"https://registry.npmjs.org"}}var K50=null,Fp=null;function SV4(A){return new Promise((Q)=>{let $=CeQ("npm",["config","get",A],{stdio:["ignore","pipe","ignore"],timeout:5000,shell:process.platform==="win32"}),B="";$.stdout.on("data",(E)=>{B+=E.toString()}),$.on("close",(E,D)=>{if(E!==0||D==="SIGTERM"){Q(null);return}let J=B.trim();Q(J&&J!=="undefined"?J:null)}),$.on("error",()=>{Q(null)})})}async function z50(){if(K50)return K50;if(Fp)return Fp;Fp=(async()=>{let A=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(A)return uy0(A);let Q=await SV4("@sourcegraph:registry");if(Q)return uy0(Q);let $=await SV4("registry");if($)return uy0($);return"https://registry.npmjs.org"})();try{return K50=await Fp,K50}finally{Fp=null}}var HeQ=3600000,NeQ=5000;function wy0(A,Q,$={}){let B=new w4,E=B.pipe(C$({shouldCountRefs:!1})),D=$.startDelayMs??0,J=$.checkIntervalMs??HeQ,U=!1,Y=()=>{U=!0};return setImmediate(async()=>{let Z=S.getChild("update");if(D>0){if(await SV(D),U)return}let F=E.subscribe({next:(I)=>{Z.debug("emit new state",I)}}),X=A;try{while(!U){let I=await qeQ(X,Q,Z,B);if(I.stop)return;if(I.updatedTo)X=I.updatedTo;if(I.emittedVisibleState){if(await SV(NeQ),U)return;B.next("hidden")}if(J<=0)return;let G=1000,V=J;while(V>0&&!U){let K=Math.min(G,V);await SV(K),V-=K}}}finally{F.unsubscribe(),B.complete()}}),{state:E,dispose:Y}}async function qeQ(A,Q,$,B){let E={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return $.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),E.stop=!0,E;let D=await Q.get("updates.mode");if(D==="disabled")return $.debug("checking disabled"),E.stop=!0,E;let J=await EZ(),U=J==="binary"||J==="brew",Y=U?void 0:await SK();$.debug("checking",{currentVersion:A,mode:D,packageManager:J,isBinaryDistribution:U,npmPackageName:Y});let Z;if(U)Z=await V50(A);else{let I=await z50();Z=await G50(A,I,Y)}if(!(Z.latestVersion&&Z.hasUpdate))return $.debug("no update available"),E;let F=(I)=>{B.next(I),E.emittedVisibleState=!0};if(J){let I=await _V4(J);if(I&&Yp(I,Z.latestVersion)>=0){if($.debug("on-disk version already up to date",{currentVersion:A,installedVersion:I,latestVersion:Z.latestVersion}),E.updatedTo=I,Yp(A,I)<0){let G=await SX(I),V={from:A,to:I,externallyUpdated:!0,...G};if(G.status==="same")$.info("on-disk already updated by another instance",V),F("updated");else $.warn("on-disk already updated by another instance, with PATH warning",V),F("updated-with-warning")}return E}}let X=()=>{if(Z.currentVersionAge!==void 0&&Z.latestVersionAge!==void 0){let I=Z.currentVersionAge-Z.latestVersionAge,G=0.5;if(Math.abs(I)<0.5)return $.debug("versions too close together, suppressing update warning",{currentVersionAge:Z.currentVersionAge,latestVersionAge:Z.latestVersionAge,ageDifferenceHours:I}),!0}return!1};if(!D)D=J==="pnpm"?"warn":"auto",$.debug("no configured update mode; selected default based on package manager",{packageManager:J,mode:D});if(J==="brew"){if(!X())F("update-available-brew");return E}if(J==="binary"&&process.execPath!==Jp()){if($.debug("non-standard binary path, showing warning"),!X())F("update-available-unrecognized-path");return E}if(D==="warn"){if(!X())F("update-available");return E}if(!J){if($.debug("auto-update not supported, falling back to warn mode"),!X())F("update-available");return E}try{await Up(Z.latestVersion,J),E.updatedTo=Z.latestVersion;let I=await SX(Z.latestVersion),G={from:Z.currentVersion,to:Z.latestVersion,...I};if(I.status==="same")$.info("success",G),F("updated");else $.warn("success with warning",G),F("updated-with-warning")}catch(I){F("update-error")}return E}catch(D){return $.debug("check failed",{error:D}),E}}Kg();import{stderr as EJ}from"node:process";function kV4(A){let Q=new PX().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(B)=>{await Gy0(B.force||!1,B.verbose||!1,"0.0.1780478921-g021c3e"),process.exit()});A.addCommand(Q,{hidden:!0});let $=new PX("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(B)=>{await MeQ(B.targetVersion)});A.addCommand($)}function ueQ(A){let Q=Boolean(A.isTTY),$=0,B=!1;function E(){if(!Q||!B)return;A.write(`
|
|
4181
4181
|
`),B=!1,$=0}function D(J){if(!Q)return;let U=J.padEnd($," ");A.write(`\r${U}`),B=!0,$=U.length}return{flushProgressLine:E,renderProgress:D}}function weQ(A){if(A.source==="npm"&&A.latestVersionAge!==void 0&&A.latestVersionAge>36)EJ.write(f0.yellow(`The latest Amp CLI version reported by npm is older than expected. Be aware that you may be using an npm proxy with a corporate policy to delay package updates.
|
|
4182
4182
|
`))}async function MeQ(A){let $=process.platform==="win32"&&Uq()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:B,renderProgress:E}=ueQ(EJ);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")EJ.write(f0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
4183
4183
|
|
|
4184
4184
|
`));try{if(!A){EJ.write(f0.blue(`Checking for updates...
|
|
4185
|
-
`));let U=!1,Y;if(Uq()){let Z=await V50("0.0.
|
|
4186
|
-
`));let X=await SX("0.0.
|
|
4185
|
+
`));let U=!1,Y;if(Uq()){let Z=await V50("0.0.1780478921-g021c3e");U=Z.hasUpdate,Y=Z.latestVersion}else{let Z=await z50(),F=await SK(),X=await G50("0.0.1780478921-g021c3e",Z,F);weQ(X),U=X.hasUpdate,Y=X.latestVersion}if(!U){let Z=Zp("0.0.1780478921-g021c3e"),F=Z?.age?`released ${Z.age} ago`:`built ${TV(new Date("2026-06-03T09:34:18.051Z"))} ago`;EJ.write(f0.green(`✓ Amp is already up to date on version ${"0.0.1780478921-g021c3e"} (${F})
|
|
4186
|
+
`));let X=await SX("0.0.1780478921-g021c3e",$);if(X.warning)EJ.write(`
|
|
4187
4187
|
`+f0.yellow(X.warning)+`
|
|
4188
4188
|
`);process.exit(0)}if(!Y)EJ.write(f0.yellow("[WARN] could not find latest version")),process.exit(0);A=Y}EJ.write(f0.blue(`Updating to version ${A}...
|
|
4189
4189
|
`)),await Up(A,void 0,(U)=>{B(),EJ.write(f0.dim(`Running: ${U}
|
|
@@ -4335,7 +4335,7 @@ ${B}`}async function g$6(A,Q){if(!Q?.forceExternal&&Q?.onShowImagePreview&&pH4(A
|
|
|
4335
4335
|
`).length,E=new D0({text:new h(A,new $0({color:$}))});if(B<=T80)return E;return new y0({width:1/0,height:T80,child:new PB({autofocus:!1,controller:Q,child:E})})}function e86(){return new Map([[HA.key("PageUp"),new _80],[HA.key("PageDown"),new $m0],[HA.ctrl("u"),new _80],[HA.shift("Home"),new Bm0],[HA.shift("End"),new Em0]])}function A96(A,Q,$){return Math.max(Q,Math.min(A,$))}var Dm0=8,Kw4=1,zw4=Dm0-1;class Jm0 extends G4{}class Um0 extends G4{}class S80 extends G4{}class k80 extends G4{}class Ym0 extends G4{}class Zm0 extends G4{}class Fm0 extends p0{props;constructor(A){super(A.key===void 0?{}:{key:A.key});this.props=A}createState(){return new Ww4}}class Ww4 extends c0{messageScroll=new G$;initState(){super.initState(),this.messageScroll.followMode=!1,this.messageScroll.jumpTo(0)}dispose(){this.messageScroll.dispose(),super.dispose()}build(A){let Q=this.widget.props,$=Q96(Q,this.messageScroll),B=$96(Q.options.message),E=B?new N4({actions:this.buildScrollActions(),child:new pQ({debugLabel:"SelectDialogScrollShortcuts",shortcuts:E96(),child:$})}):$,D=[{keys:["↑/↓","j/k"],label:"move"},{keys:["Enter"],label:"select"}];if(B)D.push({keys:["Ctrl+E","Ctrl+Y"],label:"scroll"});return D.push({keys:["Esc"],label:"cancel"}),new B1({header:Q.options.title,minWidth:64,maxWidth:80,footer:D,autofocus:!1,onDismiss:Q.onCancel,child:E})}buildScrollActions(){let A=(Q)=>{let $=D96(this.messageScroll.offset+Q,0,this.messageScroll.maxScrollExtent);this.messageScroll.jumpTo($)};return new Map([[Jm0,new pA(()=>A(-Kw4))],[Um0,new pA(()=>A(Kw4))],[S80,new pA(()=>A(-zw4))],[k80,new pA(()=>A(zw4))],[Ym0,new pA(()=>this.messageScroll.jumpTo(0))],[Zm0,new pA(()=>this.messageScroll.jumpTo(this.messageScroll.maxScrollExtent))]])}}function Q96(A,Q){let $=A.options.options.map((E)=>({value:E,label:E})),B=Math.max(0,$.findIndex((E)=>E.value===A.options.initialValue));return new gX({options:$,selectedIndex:B,body:B96(A.options.message,Q),onSelect:(E)=>{if(E===null){A.onCancel();return}A.onSelect(E)},padding:n0.all(0),showBorder:!1,showDismissalMessage:!1,enableMouseInteraction:!0,wrapOptions:!0})}function $96(A){if(A===void 0)return!1;return A.split(`
|
|
4336
4336
|
`).length>Dm0}function B96(A,Q){if(A===void 0)return;let $=A.split(`
|
|
4337
4337
|
`).length,B=Math.min($,Dm0);return new y0({width:1/0,height:B,child:new PB({autofocus:!1,controller:Q,child:new D0({text:new h(A)})})})}function E96(){return new Map([[HA.key("PageUp"),new S80],[HA.key("PageDown"),new k80],[HA.ctrl("u"),new S80],[HA.ctrl("d"),new k80],[HA.ctrl("y"),new Jm0],[HA.ctrl("e"),new Um0],[HA.shift("Home"),new Ym0],[HA.shift("End"),new Zm0]])}function D96(A,Q,$){return Math.max(Q,Math.min(A,$))}var J96=3,U96=2097152,Y96=new UB("PluginDialogOverlay");function f80(A,Q,$){if($!==void 0)return{type:"response",id:A,error:$};if(Q===void 0)return{type:"response",id:A};return{type:"response",id:A,result:Q}}function Z96(A){let Q=new TextEncoder().encode(JSON.stringify(A)).byteLength;if(Q<=U96)return;throw Error(`thread.messages response is too large (${Q} bytes). Request fewer messages.`)}class Xm0{options;unregisterPluginCommands=null;pluginCommandSubscriptions=[];pluginErrorToastKeys=new Set;activeDialog=null;queuedDialogs=[];resolvingDialog=null;pendingOwnerUIRequests=new Map;pendingActorUIRequests=new Map;stateBackedRequestIDs=new Set;pluginUIRespondRequestCounter=0;statusItems=new Map;blockingConfirmDialog=!1;disposed=!1;constructor(A){this.options=A}init(){this.disposed=!1,this.configurePluginPlatform(),this.subscribePluginCommands()}dispose(){this.disposed=!0,this.unregisterPluginCommands?.(),this.unregisterPluginCommands=null;for(let A of this.pluginCommandSubscriptions)A.unsubscribe();this.pluginCommandSubscriptions=[],this.cancelOwnerUIRequests(),this.cancelPendingDialogs(),this.statusItems.clear(),this.clearPluginPlatformStatusHandlers()}handlePluginMessage(A,Q){let $=A.message;if($.type==="response"){this.cancelOwnerUIRequest($.id),this.cancelActorUIRequest($.id);return}if($.type==="event"){if(this.handlePluginUIStateEvent($,Q))return;this.handlePluginEvent($);return}if(this.stateBackedRequestIDs.has($.id))return;if(!F30($.method)){if($.method==="thread.messages")this.handleThreadMessagesRequest($,Q);return}this.handleOwnerUIRequest($,Q)}cancelOwnerUIRequests(){let A=[...this.pendingOwnerUIRequests.values(),...this.pendingActorUIRequests.values()];this.pendingOwnerUIRequests.clear(),this.pendingActorUIRequests.clear(),this.stateBackedRequestIDs.clear();for(let Q of A)Q.abort()}hasBlockingDialog(){return this.activeDialog!==null}hasBlockingConfirmDialog(){return this.activeDialog?.kind==="confirm"}buildDialogLayers(){let A=this.activeDialog;if(!A)return[];return[new c6({key:Y96,debugLabel:"PluginDialogOverlay",autofocus:!1,canRequestFocus:!0,child:this.buildActiveDialog(A)})]}buildActiveDialog(A){switch(A.kind){case"input":return new ml({key:new kK(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 Qm0({key:new kK(A),options:A.options,onConfirm:()=>this.resolveConfirmDialog(A,!0),onCancel:()=>this.resolveConfirmDialog(A,!1)});case"select":return new Fm0({key:new kK(A),options:A.options,onSelect:(Q)=>this.resolveSelectDialog(A,Q),onCancel:()=>this.resolveSelectDialog(A,void 0)})}}getStatusItems(){return[...this.statusItems.values()].flatMap((A)=>A.value===void 0?[]:[{pluginURI:A.pluginURI,id:A.id,value:A.value}])}configurePluginPlatform(){let A=this.options.context.pluginPlatform;if(!A)return;if(A.showToast=(Q)=>this.options.toastController.show(Q,"success"),A.showOpenedURLToast=(Q)=>{this.options.toastController.show(`Opened URL: ${Q}`,"success",8000)},A.appendToThreadHandler=this.options.context.observerOnly?async()=>{throw Error("thread.append is only available from an executor-owned plugin runtime")}:this.options.appendToThread,this.options.readThreadMessages)A.readThreadMessagesHandler=this.readThreadMessages;A.runAgentHandler=this.options.context.observerOnly?async()=>{throw Error("agent.run is only available from an executor-owned plugin runtime")}:this.options.runAgent??(async()=>{throw Error("agent.run is not available in this context")}),A.showInputDialog=this.showInputDialog,A.showConfirmDialog=this.showConfirmDialog,A.showSelectDialog=this.showSelectDialog,A.createStatusItemHandler=this.createStatusItem,A.updateStatusItemHandler=this.updateStatusItem,A.removeStatusItemHandler=this.removeStatusItem}handlePluginEvent(A){if(A.event!=="ui.notify")return;let Q=A.data;if(typeof Q.message==="string")this.options.toastController.show(Q.message,"success")}async handleThreadMessagesRequest(A,Q){try{let{options:$,threadID:B}=this.parseThreadMessagesRequestParams(A.params),E=await this.readThreadMessages($,B);Z96(E),Q(f80(A.id,E))}catch($){Q(f80(A.id,void 0,$ instanceof Error?$.message:String($)))}}parseThreadMessagesRequestParams(A){if(!A||typeof A!=="object")return{options:void 0,threadID:void 0};let Q=A;return{options:Q.options,threadID:typeof Q.threadID==="string"?Q.threadID:void 0}}async handleOwnerUIRequest(A,Q){let $=new AbortController;this.pendingOwnerUIRequests.set(A.id,$);try{let B=await this.dispatchOwnerUIRequest(A,$.signal);if(this.pendingOwnerUIRequests.get(A.id)!==$)return;this.pendingOwnerUIRequests.delete(A.id),Q(f80(A.id,B))}catch(B){if(this.pendingOwnerUIRequests.get(A.id)!==$)return;this.pendingOwnerUIRequests.delete(A.id),Q(f80(A.id,void 0,B instanceof Error?B.message:String(B)))}}dispatchOwnerUIRequest(A,Q){switch(A.method){case"ui.input":return this.showInputDialog(A.params.options,Q);case"ui.confirm":return this.showConfirmDialog(A.params.options,Q);case"ui.select":return this.showSelectDialog(A.params.options,Q);default:throw Error(`Unknown owner UI request method: ${A.method}`)}}cancelOwnerUIRequest(A){let Q=this.pendingOwnerUIRequests.get(A);if(!Q)return;this.pendingOwnerUIRequests.delete(A),Q.abort()}cancelActorUIRequest(A){let Q=this.pendingActorUIRequests.get(A);if(!Q)return;this.pendingActorUIRequests.delete(A),Q.abort()}buildPluginUIRespondRequest(A,Q,$){this.pluginUIRespondRequestCounter+=1;let B={requestId:A};if($!==void 0)B.error=$;else if(Q!==void 0)B.result=Q;return{type:"request",id:`plugin-ui-respond-${A}-${this.pluginUIRespondRequestCounter}`,method:"plugin.ui.respond",params:B}}async handleActorUIRequest(A,Q){let $=new AbortController;this.pendingActorUIRequests.set(A.requestId,$);let B={type:"request",id:A.requestId,method:A.method,params:A.params};try{let E=await this.dispatchOwnerUIRequest(B,$.signal);if(this.pendingActorUIRequests.get(A.requestId)!==$)return;this.pendingActorUIRequests.delete(A.requestId),Q(this.buildPluginUIRespondRequest(A.requestId,E))}catch(E){if(this.pendingActorUIRequests.get(A.requestId)!==$)return;this.pendingActorUIRequests.delete(A.requestId),Q(this.buildPluginUIRespondRequest(A.requestId,void 0,E instanceof Error?E.message:String(E)))}}upsertActorUIState(A,Q){if(this.stateBackedRequestIDs.add(A.requestId),A.status!=="pending"){this.cancelActorUIRequest(A.requestId);return}if(this.pendingActorUIRequests.has(A.requestId))return;this.handleActorUIRequest(A,Q)}handlePluginUISnapshot(A,Q){let $=new Set(A.requests.map((B)=>B.requestId));for(let B of this.pendingActorUIRequests.keys())if(!$.has(B))this.cancelActorUIRequest(B);for(let B of this.stateBackedRequestIDs)if(!$.has(B))this.stateBackedRequestIDs.delete(B);for(let B of A.requests)this.upsertActorUIState(B,Q)}handlePluginUIRequestAdded(A,Q){this.upsertActorUIState(A.request,Q)}handlePluginUIRequestSettled(A,Q){this.upsertActorUIState(A.request,Q)}handlePluginUIRequestRemoved(A){this.cancelActorUIRequest(A.requestId),this.stateBackedRequestIDs.delete(A.requestId)}handlePluginUIStateEvent(A,Q){if(A.event==="plugin.ui.snapshot"){let $=bZ4.safeParse(A.data);if($.success)this.handlePluginUISnapshot($.data,Q);return!0}if(A.event==="plugin.ui.request_added"){let $=hZ4.safeParse(A.data);if($.success)this.handlePluginUIRequestAdded($.data,Q);return!0}if(A.event==="plugin.ui.request_settled"){let $=gZ4.safeParse(A.data);if($.success)this.handlePluginUIRequestSettled($.data,Q);return!0}if(A.event==="plugin.ui.request_removed"){let $=mZ4.safeParse(A.data);if($.success)this.handlePluginUIRequestRemoved($.data);return!0}return!1}clearPluginPlatformStatusHandlers(){let A=this.options.context.pluginPlatform;if(!A)return;if(A.readThreadMessagesHandler===this.readThreadMessages)A.readThreadMessagesHandler=null;if(A.createStatusItemHandler===this.createStatusItem)A.createStatusItemHandler=null;if(A.updateStatusItemHandler===this.updateStatusItem)A.updateStatusItemHandler=null;if(A.removeStatusItemHandler===this.removeStatusItem)A.removeStatusItemHandler=null;if(A.runAgentHandler===this.options.runAgent)A.runAgentHandler=null}subscribePluginCommands(){let A=this.options.context.pluginService;if(!A)return;this.refreshPluginCommands(A.commands.list()),this.pluginCommandSubscriptions=[A.plugins.subscribe((Q)=>{this.removeInactivePluginStatusItems(Q),this.showNewPluginErrorToasts(Q),this.refreshPluginCommands(A.commands.list())}),A.commands.changed.subscribe(()=>{this.refreshPluginCommands(A.commands.list())})]}refreshPluginCommands(A){this.unregisterPluginCommands?.();let $=A.map((B)=>this.createPluginCommand(B)).map((B)=>this.options.commandRegistry.register(B));this.unregisterPluginCommands=()=>{for(let B of $)B()}}showNewPluginErrorToasts(A){let Q=new Set;for(let $ of A){if($.status!=="error")continue;if(Lh($.errorMessage))continue;let B=`${$.uri.toString()}
|
|
4338
|
-
${$.errorMessage??""}`;if(Q.add(B),this.pluginErrorToastKeys.has(B))continue;this.options.toastController.show(this.formatPluginErrorToast($),"error",8000)}this.pluginErrorToastKeys=Q}removeInactivePluginStatusItems(A){let Q=new Set(A.filter((B)=>B.status==="active").map((B)=>B.uri.toString())),$=[];for(let[B,E]of this.statusItems){if(Q.has(E.pluginURI))continue;$.push(B)}if($.length===0)return;this.updateStatusItemState(()=>{for(let B of $)this.statusItems.delete(B)})}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.context.logFilePath}`}createPluginCommand(A){return{id:A.id,noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,status:A.availability,run:async(Q,$,B)=>{B();try{await this.options.context.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(E){S.error("Neo plugin command failed",{error:E,command:A}),this.options.toastController.show(E instanceof Error?E.message:String(E),"error",5000)}}}}showInputDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"input",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=tG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showConfirmDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(!1);return}let B={kind:"confirm",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=tG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showSelectDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"select",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=tG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};createStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let B=this.statusItemKey(A,Q),E={pluginURI:A,id:Q};if($!==void 0)E.value=$;this.statusItems.set(B,E)})};updateStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.set(this.statusItemKey(A,Q),{pluginURI:A,id:Q,value:$})})};removeStatusItem=(A,Q)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.delete(this.statusItemKey(A,Q))})};readThreadMessages=(A,Q)=>{let $=this.options.readThreadMessages;if(!$)return Promise.reject(Error("thread.messages is not available - no active thread"));return $(A,Q)};updateStatusItemState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}statusItemKey(A,Q){return`${A}\x00${Q}`}cancelPendingDialogs(){let A=[];if(this.activeDialog)A.push(this.activeDialog);A.push(...this.queuedDialogs),this.activeDialog=null,this.queuedDialogs=[],this.resolvingDialog=null,this.emitBlockingConfirmDialogChange();for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.abortUnsubscribe(),A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}abortDialog(A){if(this.activeDialog===A){this.advanceDialog(),this.cancelDialog(A);return}let Q=this.queuedDialogs.indexOf(A);if(Q===-1)return;this.updateDialogState(()=>{this.queuedDialogs.splice(Q,1)}),this.cancelDialog(A)}enqueueDialog(A){if(this.activeDialog){if(this.queuedDialogs.push(A),this.resolvingDialog===this.activeDialog)this.advanceResolvingDialog(this.activeDialog);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A}),this.emitBlockingConfirmDialogChange()}resolveInputDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveConfirmDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveSelectDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveDialog(A,Q){if(this.activeDialog!==A||this.resolvingDialog===A)return;this.resolvingDialog=A,A.abortUnsubscribe(),Q(),this.scheduleResolvingDialogAdvance(A,J96)}scheduleResolvingDialogAdvance(A,Q){z6.instance.addPostFrameCallback(()=>{if(this.activeDialog!==A)return;if(this.queuedDialogs.length>0||Q<=1){this.advanceResolvingDialog(A);return}this.scheduleResolvingDialogAdvance(A,Q-1)},"PluginIntegration.advanceDialog")}advanceResolvingDialog(A){if(this.resolvingDialog===A)this.resolvingDialog=null;if(this.activeDialog!==A)return;this.advanceDialog()}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A();this.emitBlockingConfirmDialogChange()}emitBlockingConfirmDialogChange(){let A=this.hasBlockingConfirmDialog();if(A===this.blockingConfirmDialog)return;this.blockingConfirmDialog=A,this.options.onBlockingConfirmDialogChange?.(A)}}a0();import{spawnSync as F96}from"node:child_process";import N9 from"node:process";var Cw4={options:new Set(["settings-file","log-level","log-file","mcp-config"]),booleans:new Set(["color","dangerously-allow-all","ide","jetbrains","neo-orb","notifications"])};function dl(A){let Q=A.getRelaunchThreadIDs();if(A.onRelaunchRequested?.(Q),A.stop)A.stop();else X1.instance.stop()}function Hw4(A){return{noun:"amp",verb:"Relaunch (Quit & Reopen)",description:"Quit, reopen Amp, and resume active threads",keywords:["restart","update"],shortcut:N9.env.NODE_ENV==="development"&&N9.platform==="darwin"?HA.meta("r"):void 0,status:{type:"enabled"},sortBoost:90,run:(Q,$,B)=>{B(),dl(A)}}}function X96(A,Q){let{command:$,args:B}=I96(A),E=N9.execve,D=N9.platform==="win32"||!E,J=D?"spawnSync":"execve";if(S.info("Relaunching Amp; threads will be resumed",{threadIDs:A,relaunchMethod:J}),D){let U=F96($,B,{cwd:Q,env:N9.env,stdio:"inherit"});if(U.error)return S.error("Failed to relaunch Amp",{error:U.error}),1;return U.status??1}try{if(N9.chdir(Q),$.includes("/"))return E($,[$,...B],N9.env);return E("/usr/bin/env",["env",$,...B],N9.env)}catch(U){return S.error("Failed to relaunch Amp",{error:U}),1}}class Im0{relaunchRequested=!1;requestedThreadIDs=[];request=(A)=>{S.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 X96(this.requestedThreadIDs,A)}}function I96(A){let Q=A.length>0?["threads","continue",...A]:[],$=G96(N9.argv),B=K96();if(B)return{command:B.command,args:[...B.args,...$,...Q]};let E=N9.argv[1],D=E&&V96(E)?[E]:[];return{command:N9.execPath,args:[...D,...$,...Q]}}function G96(A){let Q=[],$=A.slice(2);for(let B=0;B<$.length;B+=1){let E=$[B];if(!E?.startsWith("--"))continue;let[D,J]=E.split("=",2);if(!D)continue;let U=D.slice(2),Y=U.startsWith("no-")?U.slice(3):U;if(Cw4.booleans.has(Y)){Q.push(E);continue}if(!Cw4.options.has(U))continue;if(J!==void 0){Q.push(E);continue}let Z=$[B+1];if(Z===void 0||Z.startsWith("--"))continue;Q.push(E,Z),B+=1}return Q}function V96(A){return A!==N9.execPath&&!A.startsWith("/$bunfs/")}function K96(){if(N9.env.NODE_ENV!=="development")return null;let A=N9.env.AMP_DEV_RELAUNCH_COMMAND?.trim();if(!A)return null;let Q=z96(A),$=Q[0];if(!$)return null;return{command:$,args:Q.slice(1)}}function z96(A){if(A.startsWith("["))try{let Q=JSON.parse(A);if(Array.isArray(Q)&&Q.every(($)=>typeof $==="string"))return Q}catch{return[]}return A.split(/\s+/).filter(Boolean)}var W96=48;class Gm0{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 bl({width:W96,title:"Relaunch to Update Amp",message:"Your threads will resume.",variant:"success",mouseBehavior:"click-anywhere",action:{keyboardShortcut:"Ctrl+O",command:"amp: relaunch",confirmShortcut:"Enter",label:"relaunch",onAction:()=>this.activate()}})}notifyListeners(){for(let A of this.listeners)A()}}import{readFile as C96}from"node:fs/promises";import Vm0 from"node:os";H$();function H96(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function Nw4(A,Q){try{return{path:Q,contents:Yf0(await C96(A,"utf8"))}}catch{return null}}async function x80(A,Q){let $=[],B=H96(),E=await j4.getThread({thread:Q},{config:A.configService}),D=E.ok?E.result.thread.data:null;$.push({path:`${B}/thread.json`,contents:JSON.stringify(eD(D),null,2)});let J=await Nw4(SP(Q),`${B}/logs/${Q}.log`);if(J)$.push(J);let U=await Nw4(A.settingsFilePath,`${B}/settings/global.json`);if(U)$.push(U);let Y=await EZ()??"unknown",Z=await j4.sendReport({threadID:Q,files:$,metadata:{clientVersion:"0.0.1780464815-g688406",clientOS:`${Vm0.platform()} ${Vm0.release()} ${Vm0.arch()}`,installMethod:Y}},{config:A.configService});if(!Z.ok)throw Error(`Failed to submit report: ${Z.error.message}`);return Z.result.reportID}class Km0{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.backStack.pop();this.forwardStack.push(Q)}}}}var N96=86400000;class zm0{options;subscription=null;relaunchNotificationShown=!1;relaunchNotificationPending=!1;relaunchNotificationTimer=null;openedAt=Date.now();constructor(A){this.options=A}init(){if(this.subscription=this.options.updateService?.state.subscribe((A)=>{this.handleUpdateState(A)})??null,process.env.DEV_SHOW_RELAUNCH_NOTIF_ON_STARTUP==="1")this.showUpdateRelaunchNotification(!0)}dispose(){if(this.subscription?.unsubscribe(),this.subscription=null,this.relaunchNotificationTimer)clearTimeout(this.relaunchNotificationTimer),this.relaunchNotificationTimer=null}handleUpdateState(A){if(A!=="updated")return;this.showUpdateRelaunchNotification()}showUpdateRelaunchNotification(A=!1){if(this.relaunchNotificationShown)return;let $=(this.options.minimumOpenDurationMs??N96)-(Date.now()-this.openedAt);if($>0&&!A){if(this.relaunchNotificationPending=!0,!this.relaunchNotificationTimer)this.relaunchNotificationTimer=setTimeout(()=>{if(this.relaunchNotificationTimer=null,!this.relaunchNotificationPending)return;this.relaunchNotificationPending=!1,this.showUpdateRelaunchNotification()},$),this.relaunchNotificationTimer.unref();return}this.relaunchNotificationPending=!1,this.relaunchNotificationShown=!0,this.options.relaunchNotificationController.show(()=>dl(this.options))}}class y80 extends R6{offstage;constructor({key:A,offstage:Q=!0,child:$}){super({key:A,child:$});this.offstage=Q}createRenderObject(){return new Wm0(this.offstage)}updateRenderObject(A){if(A instanceof Wm0)A.offstage=this.offstage}}class Wm0 extends bA{_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;rA(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let $=A.constrain(Q.size.width,Q.size.height);this.setSize($.width,$.height),Q.setOffset(0,0)}else{let $=A.smallest;this.setSize($.width,$.height)}super.performLayout()}paint(A,Q,$){if(this._offstage)return;super.paint(A,Q,$)}hitTest(A,Q,$,B){if(this._offstage)return!1;return super.hitTest(A,Q,$,B)}}class cl{_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 Cm0 extends p0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new qw4}}class qw4 extends c0{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 aP,$=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:$})})}pushWithDismiss(A){let Q=new aP,$=this.makeScopedDismiss(Q),B=A($);this.setState(()=>{this.entries.push({key:Q,widget:B,dismiss:$})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new y80({offstage:this.entries.length>0,child:this.widget.root}));for(let $=0;$<this.entries.length;$++){let B=this.entries[$],E=$===this.entries.length-1,D=E?new c6({autofocus:!0,debugLabel:`ModalStackEntry[${$}]`,onKey:(J)=>{if(J.key!=="Escape")return"ignored";return B.dismiss(),"handled"},child:B.widget}):B.widget;Q.push(new y80({key:B.key,offstage:!E,child:D}))}return new QQ({fit:"expand",children:Q})}}class Nm0 extends F4{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter((E)=>E.status.type!=="hidden"),$=u96(Q),B="";return new B1({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:n0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new R5({items:Q,showBorder:!1,getLabel:(E)=>{let D=Hm0(E);return E.keywords&&E.keywords.length>0?`${D} ${E.keywords.join(" ").toLowerCase()}`:D},onQueryChange:(E)=>{B=E},sortItems:(E,D,J)=>{B=J;let U=J.trim().toLowerCase();if(U===""){let V=E.item.status.type==="disabled"?1:0,K=D.item.status.type==="disabled"?1:0;if(V!==K)return V-K;let z=E.item.sortBoost??0,W=D.item.sortBoost??0;if(z!==W)return W-z;let C=E.item.noun?.toLowerCase()??"",H=D.item.noun?.toLowerCase()??"";if(C!==H)return C<H?-1:1;return 0}let Y=uw4(E.item,U),Z=uw4(D.item,U);if(Y!==Z)return Y?-1:1;let F=vq(E.item.verb.toLowerCase(),J),X=vq(D.item.verb.toLowerCase(),J);if(F!==X)return X-F;let I=vq(Hm0(E.item),J),G=vq(Hm0(D.item),J);if(I!==G)return G-I;return D.score-E.score},isItemDisabled:(E)=>E.status.type==="disabled",buildDisabledReasonWidget:(E,D)=>{if(E.status.type!=="disabled")return;let{colors:J}=EA.of(D);return new D0({text:new h(E.status.reason,new $0({color:J.mutedForeground,dim:!0})),textAlign:"center",maxLines:1,overflow:"ellipsis"})},renderItem:(E,D,J,U)=>new ww4({command:E,isSelected:D,isDisabled:J,categoryWidth:$,query:B,buildContext:U}),onAccept:(E)=>{this.props.onAccept(E)},onDismiss:this.props.onDismiss})})}}class ww4 extends F4{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:$,isDisabled:B,categoryWidth:E,query:D,buildContext:J}=this.props,U=EA.of(J),{colors:Y,app:Z}=U,F=$?Z.selectionBackground:void 0,X=$?Z.selectionForeground:Y.foreground,I=$?X:Y.mutedForeground,G=new D0({text:new h(Q.noun?.toLowerCase()??"",new $0({color:I,dim:B||!$})),textAlign:"right",maxLines:1,overflow:"ellipsis"}),V=Q.verb.toLowerCase();if(B)V+=" (unavailable)";let K=q96(Q,D);if(K)V+=` (alias: ${K})`;let z=new D0({text:new h(V,new $0({color:X,bold:!0,dim:B})),maxLines:1,overflow:"ellipsis"}),W=[{child:G,fixedWidth:E},{child:z,expanded:!0}];if(Q.shortcut)W.push({child:w96(Q.shortcut,U,B)});return new Mw4({columns:W,padding:n0.horizontal(1),backgroundColor:F})}}function Hm0(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function uw4(A,Q){return A.keywords?.some(($)=>$.trim().toLowerCase()===Q)??!1}function q96(A,Q){let $=Q.trim().toLowerCase();if($==="")return;return A.keywords?.find((B)=>B.trim().toLowerCase()===$)}function u96(A){return A.reduce((Q,$)=>{return $.noun?Math.max(Q,cA($.noun)):Q},0)}function w96(A,Q,$){let{app:B}=Q,E=new $0({color:B.keybind,bold:!0,dim:$}),D=[],J=fX(A.toString()).split("+");for(let U=0;U<J.length;U++){if(U>0)D.push(new h("+",E));D.push(new h(J[U],E))}return D0.spans(D)}class Mw4 extends F4{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:$=2,padding:B,backgroundColor:E}=this.props,D=[];for(let U=0;U<Q.length;U++){let Y=Q[U];if(U>0&&$>0)D.push(new y0({width:$}));if(Y.fixedWidth!==void 0)D.push(new y0({width:Y.fixedWidth,child:Y.child}));else if(Y.expanded)D.push(new L4({child:Y.child}));else D.push(Y.child)}let J=new LA({crossAxisAlignment:"start",children:D});if(!B&&!E)return J;return new WA({decoration:E?{color:E}:void 0,padding:B,child:J})}}class qm0{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#$(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#$()}}findByID(A){return this.#A.find((Q)=>Q.id===A)}runByID(A,Q){let $=this.findByID(A);if(!$||$.status.type!=="enabled")return!1;return $.run(new cl,Q,()=>{}),!0}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#$(){for(let A of this.#Q)A()}}class eB extends lQ{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=eB.maybeOf(A);if(!Q)throw Error("No CommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(eB)?.commandRegistry??null}}class um0 extends p0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new Ow4}}class Ow4 extends c0{modalStack=new cl;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=eB.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=eB.of(A).commands,$=new Nm0({commands:Q,onAccept:(B)=>{B.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new Cm0({root:$,controller:this.modalStack})}}var Lw4=[{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"]}]}],jw4=[{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 b80 extends F4{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let $=W4.of(A).size.width<50,B=[];for(let E of this.items){let[D,J]=this.renderRow(E),U;if($)U=new IA({crossAxisAlignment:"start",mainAxisSize:"min",children:[D,new hA({padding:n0.only({left:4}),child:J})]});else U=new LA({crossAxisAlignment:"start",children:[new L4({flex:1,child:D}),new y0({width:1}),new L4({flex:1,child:J})]});B.push(new hA({padding:n0.horizontal(6),child:U}))}return new IA({crossAxisAlignment:"start",mainAxisSize:"min",children:B})}}function M96(A){let Q=[...A.keys];if(A.input)Q.push(A.input);return fX(Q.join("+"))}class wm0 extends F4{commands;onDismiss;constructor(A){super();this.commands=A.commands,this.onDismiss=A.onDismiss}build(A){let Q=EA.of(A),{colors:$,app:B}=Q,E=W4.of(A),D=new $0({color:$.secondary,bold:!0}),J=new $0({color:B.keybind}),U=new $0({color:B.command}),Y=new $0({color:$.foreground}),Z=Math.max(40,Math.min(80,E.size.width-4)),X=[...this.commands.filter((V)=>{let K=V.noun?.toLowerCase();return K!=="dev"&&K!=="debug"&&V.status.type!=="hidden"})].sort((V,K)=>{let z=(V.noun??"").toLowerCase(),W=(K.noun??"").toLowerCase(),C=z.localeCompare(W);if(C!==0)return C;return V.verb.toLowerCase().localeCompare(K.verb.toLowerCase())}),I=(V)=>{let K=V.methods.map((z)=>M96(z)).join(", ");return[new D0({text:new h(K,J)}),new D0({text:new h(V.description,Y)})]},G=new PB({autofocus:!0,child:new WA({constraints:new Y4(Z,Z,0,Number.POSITIVE_INFINITY),child:new IA({crossAxisAlignment:"start",mainAxisSize:"min",children:[new hA({padding:n0.horizontal(2),child:new D0({text:new h(`Editor Shortcuts
|
|
4338
|
+
${$.errorMessage??""}`;if(Q.add(B),this.pluginErrorToastKeys.has(B))continue;this.options.toastController.show(this.formatPluginErrorToast($),"error",8000)}this.pluginErrorToastKeys=Q}removeInactivePluginStatusItems(A){let Q=new Set(A.filter((B)=>B.status==="active").map((B)=>B.uri.toString())),$=[];for(let[B,E]of this.statusItems){if(Q.has(E.pluginURI))continue;$.push(B)}if($.length===0)return;this.updateStatusItemState(()=>{for(let B of $)this.statusItems.delete(B)})}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.context.logFilePath}`}createPluginCommand(A){return{id:A.id,noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,status:A.availability,run:async(Q,$,B)=>{B();try{await this.options.context.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(E){S.error("Neo plugin command failed",{error:E,command:A}),this.options.toastController.show(E instanceof Error?E.message:String(E),"error",5000)}}}}showInputDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"input",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=tG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showConfirmDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(!1);return}let B={kind:"confirm",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=tG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showSelectDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"select",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=tG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};createStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let B=this.statusItemKey(A,Q),E={pluginURI:A,id:Q};if($!==void 0)E.value=$;this.statusItems.set(B,E)})};updateStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.set(this.statusItemKey(A,Q),{pluginURI:A,id:Q,value:$})})};removeStatusItem=(A,Q)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.delete(this.statusItemKey(A,Q))})};readThreadMessages=(A,Q)=>{let $=this.options.readThreadMessages;if(!$)return Promise.reject(Error("thread.messages is not available - no active thread"));return $(A,Q)};updateStatusItemState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}statusItemKey(A,Q){return`${A}\x00${Q}`}cancelPendingDialogs(){let A=[];if(this.activeDialog)A.push(this.activeDialog);A.push(...this.queuedDialogs),this.activeDialog=null,this.queuedDialogs=[],this.resolvingDialog=null,this.emitBlockingConfirmDialogChange();for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.abortUnsubscribe(),A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}abortDialog(A){if(this.activeDialog===A){this.advanceDialog(),this.cancelDialog(A);return}let Q=this.queuedDialogs.indexOf(A);if(Q===-1)return;this.updateDialogState(()=>{this.queuedDialogs.splice(Q,1)}),this.cancelDialog(A)}enqueueDialog(A){if(this.activeDialog){if(this.queuedDialogs.push(A),this.resolvingDialog===this.activeDialog)this.advanceResolvingDialog(this.activeDialog);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A}),this.emitBlockingConfirmDialogChange()}resolveInputDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveConfirmDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveSelectDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveDialog(A,Q){if(this.activeDialog!==A||this.resolvingDialog===A)return;this.resolvingDialog=A,A.abortUnsubscribe(),Q(),this.scheduleResolvingDialogAdvance(A,J96)}scheduleResolvingDialogAdvance(A,Q){z6.instance.addPostFrameCallback(()=>{if(this.activeDialog!==A)return;if(this.queuedDialogs.length>0||Q<=1){this.advanceResolvingDialog(A);return}this.scheduleResolvingDialogAdvance(A,Q-1)},"PluginIntegration.advanceDialog")}advanceResolvingDialog(A){if(this.resolvingDialog===A)this.resolvingDialog=null;if(this.activeDialog!==A)return;this.advanceDialog()}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A();this.emitBlockingConfirmDialogChange()}emitBlockingConfirmDialogChange(){let A=this.hasBlockingConfirmDialog();if(A===this.blockingConfirmDialog)return;this.blockingConfirmDialog=A,this.options.onBlockingConfirmDialogChange?.(A)}}a0();import{spawnSync as F96}from"node:child_process";import N9 from"node:process";var Cw4={options:new Set(["settings-file","log-level","log-file","mcp-config"]),booleans:new Set(["color","dangerously-allow-all","ide","jetbrains","neo-orb","notifications"])};function dl(A){let Q=A.getRelaunchThreadIDs();if(A.onRelaunchRequested?.(Q),A.stop)A.stop();else X1.instance.stop()}function Hw4(A){return{noun:"amp",verb:"Relaunch (Quit & Reopen)",description:"Quit, reopen Amp, and resume active threads",keywords:["restart","update"],shortcut:N9.env.NODE_ENV==="development"&&N9.platform==="darwin"?HA.meta("r"):void 0,status:{type:"enabled"},sortBoost:90,run:(Q,$,B)=>{B(),dl(A)}}}function X96(A,Q){let{command:$,args:B}=I96(A),E=N9.execve,D=N9.platform==="win32"||!E,J=D?"spawnSync":"execve";if(S.info("Relaunching Amp; threads will be resumed",{threadIDs:A,relaunchMethod:J}),D){let U=F96($,B,{cwd:Q,env:N9.env,stdio:"inherit"});if(U.error)return S.error("Failed to relaunch Amp",{error:U.error}),1;return U.status??1}try{if(N9.chdir(Q),$.includes("/"))return E($,[$,...B],N9.env);return E("/usr/bin/env",["env",$,...B],N9.env)}catch(U){return S.error("Failed to relaunch Amp",{error:U}),1}}class Im0{relaunchRequested=!1;requestedThreadIDs=[];request=(A)=>{S.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 X96(this.requestedThreadIDs,A)}}function I96(A){let Q=A.length>0?["threads","continue",...A]:[],$=G96(N9.argv),B=K96();if(B)return{command:B.command,args:[...B.args,...$,...Q]};let E=N9.argv[1],D=E&&V96(E)?[E]:[];return{command:N9.execPath,args:[...D,...$,...Q]}}function G96(A){let Q=[],$=A.slice(2);for(let B=0;B<$.length;B+=1){let E=$[B];if(!E?.startsWith("--"))continue;let[D,J]=E.split("=",2);if(!D)continue;let U=D.slice(2),Y=U.startsWith("no-")?U.slice(3):U;if(Cw4.booleans.has(Y)){Q.push(E);continue}if(!Cw4.options.has(U))continue;if(J!==void 0){Q.push(E);continue}let Z=$[B+1];if(Z===void 0||Z.startsWith("--"))continue;Q.push(E,Z),B+=1}return Q}function V96(A){return A!==N9.execPath&&!A.startsWith("/$bunfs/")}function K96(){if(N9.env.NODE_ENV!=="development")return null;let A=N9.env.AMP_DEV_RELAUNCH_COMMAND?.trim();if(!A)return null;let Q=z96(A),$=Q[0];if(!$)return null;return{command:$,args:Q.slice(1)}}function z96(A){if(A.startsWith("["))try{let Q=JSON.parse(A);if(Array.isArray(Q)&&Q.every(($)=>typeof $==="string"))return Q}catch{return[]}return A.split(/\s+/).filter(Boolean)}var W96=48;class Gm0{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 bl({width:W96,title:"Relaunch to Update Amp",message:"Your threads will resume.",variant:"success",mouseBehavior:"click-anywhere",action:{keyboardShortcut:"Ctrl+O",command:"amp: relaunch",confirmShortcut:"Enter",label:"relaunch",onAction:()=>this.activate()}})}notifyListeners(){for(let A of this.listeners)A()}}import{readFile as C96}from"node:fs/promises";import Vm0 from"node:os";H$();function H96(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function Nw4(A,Q){try{return{path:Q,contents:Yf0(await C96(A,"utf8"))}}catch{return null}}async function x80(A,Q){let $=[],B=H96(),E=await j4.getThread({thread:Q},{config:A.configService}),D=E.ok?E.result.thread.data:null;$.push({path:`${B}/thread.json`,contents:JSON.stringify(eD(D),null,2)});let J=await Nw4(SP(Q),`${B}/logs/${Q}.log`);if(J)$.push(J);let U=await Nw4(A.settingsFilePath,`${B}/settings/global.json`);if(U)$.push(U);let Y=await EZ()??"unknown",Z=await j4.sendReport({threadID:Q,files:$,metadata:{clientVersion:"0.0.1780478921-g021c3e",clientOS:`${Vm0.platform()} ${Vm0.release()} ${Vm0.arch()}`,installMethod:Y}},{config:A.configService});if(!Z.ok)throw Error(`Failed to submit report: ${Z.error.message}`);return Z.result.reportID}class Km0{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.backStack.pop();this.forwardStack.push(Q)}}}}var N96=86400000;class zm0{options;subscription=null;relaunchNotificationShown=!1;relaunchNotificationPending=!1;relaunchNotificationTimer=null;openedAt=Date.now();constructor(A){this.options=A}init(){if(this.subscription=this.options.updateService?.state.subscribe((A)=>{this.handleUpdateState(A)})??null,process.env.DEV_SHOW_RELAUNCH_NOTIF_ON_STARTUP==="1")this.showUpdateRelaunchNotification(!0)}dispose(){if(this.subscription?.unsubscribe(),this.subscription=null,this.relaunchNotificationTimer)clearTimeout(this.relaunchNotificationTimer),this.relaunchNotificationTimer=null}handleUpdateState(A){if(A!=="updated")return;this.showUpdateRelaunchNotification()}showUpdateRelaunchNotification(A=!1){if(this.relaunchNotificationShown)return;let $=(this.options.minimumOpenDurationMs??N96)-(Date.now()-this.openedAt);if($>0&&!A){if(this.relaunchNotificationPending=!0,!this.relaunchNotificationTimer)this.relaunchNotificationTimer=setTimeout(()=>{if(this.relaunchNotificationTimer=null,!this.relaunchNotificationPending)return;this.relaunchNotificationPending=!1,this.showUpdateRelaunchNotification()},$),this.relaunchNotificationTimer.unref();return}this.relaunchNotificationPending=!1,this.relaunchNotificationShown=!0,this.options.relaunchNotificationController.show(()=>dl(this.options))}}class y80 extends R6{offstage;constructor({key:A,offstage:Q=!0,child:$}){super({key:A,child:$});this.offstage=Q}createRenderObject(){return new Wm0(this.offstage)}updateRenderObject(A){if(A instanceof Wm0)A.offstage=this.offstage}}class Wm0 extends bA{_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;rA(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let $=A.constrain(Q.size.width,Q.size.height);this.setSize($.width,$.height),Q.setOffset(0,0)}else{let $=A.smallest;this.setSize($.width,$.height)}super.performLayout()}paint(A,Q,$){if(this._offstage)return;super.paint(A,Q,$)}hitTest(A,Q,$,B){if(this._offstage)return!1;return super.hitTest(A,Q,$,B)}}class cl{_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 Cm0 extends p0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new qw4}}class qw4 extends c0{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 aP,$=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:$})})}pushWithDismiss(A){let Q=new aP,$=this.makeScopedDismiss(Q),B=A($);this.setState(()=>{this.entries.push({key:Q,widget:B,dismiss:$})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new y80({offstage:this.entries.length>0,child:this.widget.root}));for(let $=0;$<this.entries.length;$++){let B=this.entries[$],E=$===this.entries.length-1,D=E?new c6({autofocus:!0,debugLabel:`ModalStackEntry[${$}]`,onKey:(J)=>{if(J.key!=="Escape")return"ignored";return B.dismiss(),"handled"},child:B.widget}):B.widget;Q.push(new y80({key:B.key,offstage:!E,child:D}))}return new QQ({fit:"expand",children:Q})}}class Nm0 extends F4{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter((E)=>E.status.type!=="hidden"),$=u96(Q),B="";return new B1({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:n0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new R5({items:Q,showBorder:!1,getLabel:(E)=>{let D=Hm0(E);return E.keywords&&E.keywords.length>0?`${D} ${E.keywords.join(" ").toLowerCase()}`:D},onQueryChange:(E)=>{B=E},sortItems:(E,D,J)=>{B=J;let U=J.trim().toLowerCase();if(U===""){let V=E.item.status.type==="disabled"?1:0,K=D.item.status.type==="disabled"?1:0;if(V!==K)return V-K;let z=E.item.sortBoost??0,W=D.item.sortBoost??0;if(z!==W)return W-z;let C=E.item.noun?.toLowerCase()??"",H=D.item.noun?.toLowerCase()??"";if(C!==H)return C<H?-1:1;return 0}let Y=uw4(E.item,U),Z=uw4(D.item,U);if(Y!==Z)return Y?-1:1;let F=vq(E.item.verb.toLowerCase(),J),X=vq(D.item.verb.toLowerCase(),J);if(F!==X)return X-F;let I=vq(Hm0(E.item),J),G=vq(Hm0(D.item),J);if(I!==G)return G-I;return D.score-E.score},isItemDisabled:(E)=>E.status.type==="disabled",buildDisabledReasonWidget:(E,D)=>{if(E.status.type!=="disabled")return;let{colors:J}=EA.of(D);return new D0({text:new h(E.status.reason,new $0({color:J.mutedForeground,dim:!0})),textAlign:"center",maxLines:1,overflow:"ellipsis"})},renderItem:(E,D,J,U)=>new ww4({command:E,isSelected:D,isDisabled:J,categoryWidth:$,query:B,buildContext:U}),onAccept:(E)=>{this.props.onAccept(E)},onDismiss:this.props.onDismiss})})}}class ww4 extends F4{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:$,isDisabled:B,categoryWidth:E,query:D,buildContext:J}=this.props,U=EA.of(J),{colors:Y,app:Z}=U,F=$?Z.selectionBackground:void 0,X=$?Z.selectionForeground:Y.foreground,I=$?X:Y.mutedForeground,G=new D0({text:new h(Q.noun?.toLowerCase()??"",new $0({color:I,dim:B||!$})),textAlign:"right",maxLines:1,overflow:"ellipsis"}),V=Q.verb.toLowerCase();if(B)V+=" (unavailable)";let K=q96(Q,D);if(K)V+=` (alias: ${K})`;let z=new D0({text:new h(V,new $0({color:X,bold:!0,dim:B})),maxLines:1,overflow:"ellipsis"}),W=[{child:G,fixedWidth:E},{child:z,expanded:!0}];if(Q.shortcut)W.push({child:w96(Q.shortcut,U,B)});return new Mw4({columns:W,padding:n0.horizontal(1),backgroundColor:F})}}function Hm0(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function uw4(A,Q){return A.keywords?.some(($)=>$.trim().toLowerCase()===Q)??!1}function q96(A,Q){let $=Q.trim().toLowerCase();if($==="")return;return A.keywords?.find((B)=>B.trim().toLowerCase()===$)}function u96(A){return A.reduce((Q,$)=>{return $.noun?Math.max(Q,cA($.noun)):Q},0)}function w96(A,Q,$){let{app:B}=Q,E=new $0({color:B.keybind,bold:!0,dim:$}),D=[],J=fX(A.toString()).split("+");for(let U=0;U<J.length;U++){if(U>0)D.push(new h("+",E));D.push(new h(J[U],E))}return D0.spans(D)}class Mw4 extends F4{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:$=2,padding:B,backgroundColor:E}=this.props,D=[];for(let U=0;U<Q.length;U++){let Y=Q[U];if(U>0&&$>0)D.push(new y0({width:$}));if(Y.fixedWidth!==void 0)D.push(new y0({width:Y.fixedWidth,child:Y.child}));else if(Y.expanded)D.push(new L4({child:Y.child}));else D.push(Y.child)}let J=new LA({crossAxisAlignment:"start",children:D});if(!B&&!E)return J;return new WA({decoration:E?{color:E}:void 0,padding:B,child:J})}}class qm0{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#$(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#$()}}findByID(A){return this.#A.find((Q)=>Q.id===A)}runByID(A,Q){let $=this.findByID(A);if(!$||$.status.type!=="enabled")return!1;return $.run(new cl,Q,()=>{}),!0}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#$(){for(let A of this.#Q)A()}}class eB extends lQ{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=eB.maybeOf(A);if(!Q)throw Error("No CommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(eB)?.commandRegistry??null}}class um0 extends p0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new Ow4}}class Ow4 extends c0{modalStack=new cl;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=eB.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=eB.of(A).commands,$=new Nm0({commands:Q,onAccept:(B)=>{B.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new Cm0({root:$,controller:this.modalStack})}}var Lw4=[{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"]}]}],jw4=[{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 b80 extends F4{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let $=W4.of(A).size.width<50,B=[];for(let E of this.items){let[D,J]=this.renderRow(E),U;if($)U=new IA({crossAxisAlignment:"start",mainAxisSize:"min",children:[D,new hA({padding:n0.only({left:4}),child:J})]});else U=new LA({crossAxisAlignment:"start",children:[new L4({flex:1,child:D}),new y0({width:1}),new L4({flex:1,child:J})]});B.push(new hA({padding:n0.horizontal(6),child:U}))}return new IA({crossAxisAlignment:"start",mainAxisSize:"min",children:B})}}function M96(A){let Q=[...A.keys];if(A.input)Q.push(A.input);return fX(Q.join("+"))}class wm0 extends F4{commands;onDismiss;constructor(A){super();this.commands=A.commands,this.onDismiss=A.onDismiss}build(A){let Q=EA.of(A),{colors:$,app:B}=Q,E=W4.of(A),D=new $0({color:$.secondary,bold:!0}),J=new $0({color:B.keybind}),U=new $0({color:B.command}),Y=new $0({color:$.foreground}),Z=Math.max(40,Math.min(80,E.size.width-4)),X=[...this.commands.filter((V)=>{let K=V.noun?.toLowerCase();return K!=="dev"&&K!=="debug"&&V.status.type!=="hidden"})].sort((V,K)=>{let z=(V.noun??"").toLowerCase(),W=(K.noun??"").toLowerCase(),C=z.localeCompare(W);if(C!==0)return C;return V.verb.toLowerCase().localeCompare(K.verb.toLowerCase())}),I=(V)=>{let K=V.methods.map((z)=>M96(z)).join(", ");return[new D0({text:new h(K,J)}),new D0({text:new h(V.description,Y)})]},G=new PB({autofocus:!0,child:new WA({constraints:new Y4(Z,Z,0,Number.POSITIVE_INFINITY),child:new IA({crossAxisAlignment:"start",mainAxisSize:"min",children:[new hA({padding:n0.horizontal(2),child:new D0({text:new h(`Editor Shortcuts
|
|
4339
4339
|
`,D)})}),new b80({items:Lw4.filter((V)=>V.submitOnEnterOnly===void 0||V.submitOnEnterOnly===!0),renderRow:I}),new y0({height:1}),new hA({padding:n0.horizontal(2),child:new D0({text:new h(`Scrolling & Navigation
|
|
4340
4340
|
`,D)})}),new b80({items:jw4,renderRow:I}),new y0({height:1}),new hA({padding:n0.horizontal(2),child:new D0({text:new h(`Command Palette Commands
|
|
4341
4341
|
`,D)})}),new b80({items:X,renderRow:(V)=>{let K=V.noun?`${V.noun}: ${V.verb}`:V.verb;return[new D0({text:new h(K,U)}),new D0({text:new h(V.description,Y)})]}}),new y0({height:1})]})})});return new B1({header:"Amp CLI — Help & Keyboard Shortcuts",minWidth:Z,maxWidth:Z,maxHeight:E.size.height,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["↑↓","j/k"],label:"scroll"}],onDismiss:this.onDismiss,child:G})}}class wv extends lQ{completionBuilder;constructor({completionBuilder:A,child:Q}){super({child:Q});this.completionBuilder=A}updateShouldNotify(A){return!1}static of(A){let Q=A.dependOnInheritedWidgetOfExactType(wv);if(!Q)throw Error("No CompletionBuilderProvider found in widget tree");return Q.completionBuilder}}var O96=250,L96=2000;class Mm0 extends p0{configReloadEvents;toastController;child;constructor(A){super();this.configReloadEvents=A.configReloadEvents,this.toastController=A.toastController,this.child=A.child}createState(){return new Rw4}}class Rw4 extends c0{subscription=null;toastTimer=null;pendingToastType=null;lastToast=null;initState(){this.subscribeToConfigReloadEvents()}didUpdateWidget(A){if(A.configReloadEvents===this.widget.configReloadEvents)return;this.clearPendingToast(),this.subscribeToConfigReloadEvents()}dispose(){this.subscription?.unsubscribe(),this.subscription=null,this.clearPendingToast(),super.dispose()}build(A){return this.widget.child}subscribeToConfigReloadEvents(){this.subscription?.unsubscribe(),this.subscription=this.widget.configReloadEvents.subscribe((A)=>{this.scheduleToast(A)})}scheduleToast(A){if(this.pendingToastType=j96(this.pendingToastType,A),this.toastTimer)clearTimeout(this.toastTimer);this.toastTimer=setTimeout(()=>{if(!this.mounted)return;this.flushToast()},O96),this.toastTimer.unref()}flushToast(){let A=this.pendingToastType;if(this.clearPendingToast(),!A)return;let Q=Date.now();if(R96(this.lastToast,A,Q))return;this.lastToast={type:A,shownAt:Q},P96(this.widget.toastController,A)}clearPendingToast(){if(this.toastTimer)clearTimeout(this.toastTimer),this.toastTimer=null;this.pendingToastType=null}}function j96(A,Q){return A==="failed"||Q.type==="failed"?"failed":"succeeded"}function R96(A,Q,$){return A?.type===Q&&$-A.shownAt<L96}function P96(A,Q){switch(Q){case"succeeded":A.show("Config reloaded","success",1500);break;case"failed":A.show("Config reload failed","error",5000);break}}class HQ extends lQ{context;constructor({context:A,child:Q}){super({child:Q});this.context=A}updateShouldNotify(A){return!1}static of(A){let Q=A.dependOnInheritedWidgetOfExactType(HQ);if(!Q)throw Error("No ContextProvider found in widget tree");return Q.context}}a0();d8();var g80=80,v96=13,T96=1,Pw4=-g80,_96=16,S96=_b0(g80,g80);function vw4({ampURL:A,threadID:Q,logPath:$}){return[`Debug thread ${dG(new URL(A),Q).toString()} (cli log: ${$}). Start with the CLI log, actor logs, and Rivet DB/inspector as sources of truth. Read thread-actors/docs/debugging-actors.md and thread-actors/scripts/README.md. For dev, actor logs are in .amp/in/thread-actors.json.log; for staging/prod, logs are in gcloud.`,"","Problem: "].join(`
|
|
@@ -4422,13 +4422,13 @@ Ctrl-X, Y, Z to unlock`;if(this.widget.centerContent)R=this.widget.centerContent
|
|
|
4422
4422
|
- Real life (in person)
|
|
4423
4423
|
|
|
4424
4424
|
`,new $0({color:Q.foreground})),textAlign:"left"}),new D0({text:new h("All diagnostics data is deleted after 7 days. Amp team members can only access the diagnostics data if you provide the report ID.",new $0({color:Q.foreground,dim:!0})),textAlign:"left"})]})}}var IR4={kind:"fill",modalRows:19};function cZ6(A){return new B1({header:"Sending Report",tone:"default",minWidth:80,maxWidth:80,bodyFit:IR4,onDismiss:A,child:new GR4})}class GR4 extends F4{build(A){let{colors:Q}=EA.of(A);return new LA({mainAxisSize:"min",children:[new rX({color:Q.primary}),new y0({width:1}),new D0({text:new h("Gathering and sending diagnostics data...",new $0({color:Q.foreground,dim:!0}))})]})}}function XR4(A){return new B1({header:A.title,tone:A.tone,barrierOpaque:!0,minWidth:80,maxWidth:80,bodyFit:IR4,onDismiss:A.onDismiss,child:A.child})}function VR4(A,Q){return{noun:"feedback",verb:"send report with diagnostics",description:"Send a report with diagnostics to Amp support",keywords:["bug","support"],get status(){return Q()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:($,B,E)=>{let D=Q()?.client.getThreadId();if(!D)return;$.push(cZ6(E)),A.sendFeedbackReport(D).then(async(J)=>{try{await X1.instance.tuiInstance.clipboard.writeText(J),EQ.maybeOf(B)?.show("Copied report ID to clipboard","success",3000)}catch(U){S.warn("Failed to copy report ID to clipboard",{error:U,reportID:J})}$.push(XR4({title:"Report Sent",tone:"success",onDismiss:E,child:new dc0(J)}))}).catch((J)=>{S.error("Failed to share thread with support",{error:J,threadID:D}),$.push(XR4({title:"Report failed",tone:"error",onDismiss:E,child:new D0({text:new h(`Failed to send report: ${J instanceof Error?J.message:String(J)}`)})}))})}}}bB();import{homedir as pZ6}from"node:os";import{relative as lZ6,sep as iZ6}from"node:path";import{fileURLToPath as nZ6}from"node:url";var aZ6="https://ampcode.com/manual#agent-skills",oZ6="You need to start a new thread to see skills. You can mention skills in your first message.";class cc0 extends G4{}class pc0 extends p0{listSkills;onDismiss;cwd;constructor(A){super();this.listSkills=A.listSkills,this.onDismiss=A.onDismiss,this.cwd=A.cwd}createState(){return new KR4}}class KR4 extends c0{status={kind:"loading"};abortController=null;initState(){this.abortController=new AbortController,this.loadSkills()}dispose(){this.abortController?.abort()}async loadSkills(){try{let A=await this.widget.listSkills(this.abortController?.signal);if(!this.mounted)return;this.setState(()=>{this.status={kind:"ready",skills:A.skills,errors:A.errors}})}catch(A){if(!this.mounted)return;this.setState(()=>{this.status={kind:"error",message:A instanceof Error?A.message:"Unknown error"}})}}build(A){return new m90({status:this.status,cwd:this.widget.cwd,onDismiss:this.widget.onDismiss})}}class m90 extends F4{status;cwd;onDismiss;constructor(A){super();this.status=A.status,this.cwd=A.cwd,this.onDismiss=A.onDismiss}build(A){return new B1({header:rZ6(this.status),onDismiss:this.onDismiss,minWidth:80,maxWidth:120,maxHeight:40,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["↑↓","j/k"],label:"scroll"},{keys:["o"],label:"open manual"}],child:new N4({actions:new Map([[cc0,new pA(()=>{t6(A,aZ6)})]]),child:new pQ({debugLabel:"SkillListShortcuts",shortcuts:new Map([[HA.key("o"),new cc0]]),child:sZ6(A,this.status,this.cwd)})})})}}function rZ6(A){if(A.kind!=="ready")return"Skills";let{skills:Q,errors:$}=A;if(Q.length===0&&$.length===0)return"Skills";if($.length===0)return`Skills (${Q.length})`;let B=`${$.length} ${J1($.length,"error")}`;if(Q.length===0)return`Skills (0, ${B})`;return`Skills (${Q.length}, ${B})`}function sZ6(A,Q,$){let{colors:B}=EA.of(A);switch(Q.kind){case"loading":return new LA({mainAxisSize:"min",children:[new rX({color:B.primary}),new y0({width:1}),new D0({text:new h("Loading skills...",new $0({color:B.foreground,dim:!0}))})]});case"no-thread":return new D0({text:new h(oZ6,new $0({color:B.foreground}))});case"error":return new D0({text:new h(Q.message,new $0({color:B.destructive}))});case"ready":return eZ6(A,Q.skills,Q.errors,$)}}var tZ6=90;function eZ6(A,Q,$,B){let{colors:E,app:D}=EA.of(A),J=new $0({color:E.foreground,dim:!0});if(Q.length===0&&$.length===0)return new D0({text:new h("No skills reported by the executor yet.",J)});let U=W4.sizeOf(A).width>=tZ6;return new PB({child:new IA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:EF6(Q,$,U,{section:new $0({color:E.foreground,bold:!0}),name:new $0({color:D.command}),description:new $0({color:E.foreground}),location:J,errorTitle:new $0({color:E.destructive,bold:!0}),errorName:new $0({color:E.warning,bold:!0}),errorMessage:new $0({color:E.destructive}),cwd:B})})})}var AF6={local:"Local",global:"Global",builtin:"Built-in"},QF6=["local","global","builtin"],$F6={"workspace-agents":"local","workspace-claude":"local","user-agents":"global","user-amp":"global","user-claude":"global",plugin:"global",toolbox:"global","custom-path":"global",builtin:"builtin"};function BF6(A){let Q={local:[],global:[],builtin:[]};for(let $ of A){let B=$.source??"workspace-agents";Q[$F6[B]].push($)}return QF6.filter(($)=>Q[$].length>0).map(($)=>({label:AF6[$],skills:Q[$]}))}function EF6(A,Q,$,B){let E=[];if(BF6(A).forEach((D,J)=>{if(J>0)E.push(new y0({height:1}));E.push(new D0({text:new h(D.label,B.section)}));for(let U of D.skills)E.push(new hA({padding:n0.only({left:2}),child:YF6(U,$,B)}))}),Q.length>0){if(A.length>0)E.push(new y0({height:1}));E.push(new D0({text:new h(`Skipped skills with errors (${Q.length}):`,B.errorTitle)}));for(let D of Q)E.push(new y0({height:1})),E.push(...JF6(D,B))}E.push(new y0({height:1})),E.push(new D0({text:new h("Create your own:",B.section)}));for(let D of DF6)E.push(new hA({padding:n0.only({left:2}),child:new D0({text:new h(`"${D}"`,B.description),maxLines:1,overflow:"ellipsis"})}));return E}var DF6=["Create a skill for searching our production logs","Create a user skill for my preferred commit message style"];function JF6(A,Q){let $=[new hA({padding:n0.only({left:2}),child:new D0({text:new h(`⚠ ${UF6(A.path)}`,Q.errorName)})}),new hA({padding:n0.only({left:4}),child:new D0({text:new h(A.error,Q.errorMessage)})})];if(A.hint)$.push(new hA({padding:n0.only({left:4}),child:new D0({text:new h(A.hint.split(`
|
|
4425
|
-
`)[0]??"",Q.description)})}));return $.push(new hA({padding:n0.only({left:4}),child:new D0({text:new h(zR4(A.path,Q.cwd),Q.location),maxLines:1,overflow:"ellipsis"})})),$}function UF6(A){try{return new URL(A).pathname.split("/").filter(Boolean).at(-2)??"unknown"}catch{return"unknown"}}function YF6(A,Q,$){if(Q)return new LA({crossAxisAlignment:"start",children:[new L4({flex:1,child:new D0({text:new h(A.name,$.name),maxLines:1,overflow:"ellipsis"})}),new y0({width:2}),new L4({flex:2,child:new hA({padding:n0.only({right:1}),child:new D0({text:new h(A.description,$.description),maxLines:1,overflow:"ellipsis"})})})]});return new IA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new LA({crossAxisAlignment:"start",children:[new D0({text:new h(A.name,$.name),maxLines:1,overflow:"ellipsis"}),new L4({child:new D0({text:new h(` ${zR4(A.baseDir,$.cwd)}`,$.location),maxLines:1,overflow:"ellipsis"})})]}),new hA({padding:n0.only({left:2,right:1}),child:new D0({text:new h(A.description,$.description),maxLines:1,overflow:"ellipsis"})})]})}function zR4(A,Q){if(A.startsWith("builtin://"))return"(builtin)";if(!A.startsWith("file://"))return A;let $=nZ6(A),B=lZ6(Q,$);if(B&&!B.startsWith(".."))return`./${B}`;let E=pZ6();if($===E||$.startsWith(E+iZ6))return`~${$.slice(E.length)}`;return $}var XF6=5000,IF6={attach:()=>{},detach:()=>{},unsubscribe:()=>{}};function GF6(A){let Q=WR4(A);return Q?{type:"rgb",value:Q}:void 0}function WR4(A){let Q=A?.match(/^#([0-9a-f]{6})$/i);if(!Q?.[1])return;return{r:Number.parseInt(Q[1].slice(0,2),16),g:Number.parseInt(Q[1].slice(2,4),16),b:Number.parseInt(Q[1].slice(4,6),16)}}function VF6(A){return{r:Math.round(A.r*0.55),g:Math.round(A.g*0.55),b:Math.round(A.b*0.55)}}async function KF6(A){return new Promise((Q)=>{ZF6("git",["branch","--show-current"],{cwd:A},($,B)=>{if($){Q(null);return}let E=B.trim();Q(E||null)})})}function zF6(A,Q){let $=$4(m0.file(A)),B={workspaceRoot:$,workingDirectory:$};if(Q)B.git={branch:Q};return B}class lc0 extends p0{initialAgentMode;initialPluginAgentModeKey;analyzeContextForThread;listSkillsForThread;threadContext;draftThreadSettings;editorController;editorFocusNode;history;updateDraftThreadSettings;onNewThread;sendFeedbackReport;archiveThread;addThreadLabel;removeThreadLabel;configService;hints;ideStatus;statusItems;pluginConfirmationBlocked;notificationService;notice;onDismissNotice;constructor(A){super();this.initialAgentMode=A.initialAgentMode,this.initialPluginAgentModeKey=A.initialPluginAgentModeKey,this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.threadContext=A.threadContext,this.draftThreadSettings=A.draftThreadSettings,this.editorController=A.editorController,this.editorFocusNode=A.editorFocusNode,this.history=A.history,this.updateDraftThreadSettings=A.updateDraftThreadSettings,this.onNewThread=A.onNewThread,this.sendFeedbackReport=A.sendFeedbackReport,this.archiveThread=A.archiveThread,this.addThreadLabel=A.addThreadLabel,this.removeThreadLabel=A.removeThreadLabel,this.configService=A.configService,this.hints=A.hints,this.ideStatus=A.ideStatus,this.statusItems=A.statusItems??[],this.pluginConfirmationBlocked=A.pluginConfirmationBlocked,this.notificationService=A.notificationService,this.notice=A.notice,this.onDismissNotice=A.onDismissNotice}createState(){return new CR4}}class CR4 extends c0{agentMode;pluginAgentModes=[];selectedPluginAgentMode=null;pluginAgentModesSubscription=null;copyOnSelectEnabled=!0;copyOnSelectSubscription=null;expansion=new Xd0;previousThreadIDForReference=null;unregisterCommands=null;configSettingsForReasoning={};currentGitBranch=null;useLocalEnvironmentFallbackForActiveThread=!1;fastModeToastID=null;statusMessage=null;statusMessageTimer=null;isEditorUploadLocked=!1;initState(){this.agentMode=this.widget.initialAgentMode,this.subscribeToPluginAgentModes(),this.applyInitialPluginAgentMode(),this.subscribeToCopyOnSelectEnabled(),this.updateGitBranch()}applyInitialPluginAgentMode(){if(!this.widget.initialPluginAgentModeKey||this.widget.threadContext)return;this.selectedPluginAgentMode=this.pluginAgentModes.find((A)=>A.key===this.widget.initialPluginAgentModeKey)??null}didUpdateWidget(A){if(A.configService!==this.widget.configService)this.subscribeToCopyOnSelectEnabled();if(HQ.of(this.context).pluginService!==HQ.of(this.context).pluginService)this.subscribeToPluginAgentModes();if(A.threadContext?.client!==this.widget.threadContext?.client)if(this.isEditorUploadLocked=!1,!this.widget.threadContext)this.previousThreadIDForReference=A.threadContext?.client.getThreadId()??null,this.useLocalEnvironmentFallbackForActiveThread=!0;else this.previousThreadIDForReference=null,this.useLocalEnvironmentFallbackForActiveThread=A.threadContext===null}dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.copyOnSelectSubscription?.unsubscribe(),this.copyOnSelectSubscription=null,this.pluginAgentModesSubscription?.unsubscribe(),this.pluginAgentModesSubscription=null,this.statusMessageTimer)clearTimeout(this.statusMessageTimer),this.statusMessageTimer=null}updateGitBranch=async()=>{let A=HQ.of(this.context).workspaceRoot,Q=await KF6(A);if(!this.mounted)return;this.setState(()=>{this.currentGitBranch=Q})};subscribeToPluginAgentModes(){this.pluginAgentModesSubscription?.unsubscribe(),this.pluginAgentModesSubscription=null;let A=HQ.of(this.context).pluginService?.agentModes;if(!A){this.syncPluginAgentModes([]);return}this.syncPluginAgentModes(A.list()),this.pluginAgentModesSubscription=A.changed.subscribe({next:()=>this.syncPluginAgentModes(A.list())})}syncPluginAgentModes(A){this.setState(()=>{if(this.pluginAgentModes=A,this.selectedPluginAgentMode&&!A.some((Q)=>Q.key===this.selectedPluginAgentMode?.key))this.selectedPluginAgentMode=null}),this.refreshCommands()}refreshCommands(){this.unregisterCommands?.(),this.unregisterCommands=this.registerCommands()}registerCommands(){let A=eB.of(this.context),Q=HQ.of(this.context),$=this,B=()=>{return $.widget.threadContext??null},E=()=>{let Z=$.widget.threadContext?.client.getThreadId();if(!Z)return null;return dG(new URL(Q.ampURL),Z).toString()},D=lG(void 0,{isInternalUser:Q.isInternalUser}).map(({mode:Z})=>({noun:"mode",verb:`use ${Z}`,description:`Enable ${Z} mode`,get status(){if($.widget.threadContext)return{type:"hidden"};if(Z===$.agentMode)return{type:"disabled",reason:`Already using ${Z} mode`};return{type:"enabled"}},run:(F,X,I)=>{$.setAgentMode(Z),I()}})),J=this.pluginAgentModes.map((Z)=>({noun:"mode",verb:`use ${Z.label}`,description:Z.description??`Enable ${Z.label} mode`,get status(){if($.widget.threadContext)return{type:"hidden"};if(Z.key===$.selectedPluginAgentMode?.key)return{type:"disabled",reason:`Already using ${Z.label} mode`};return{type:"enabled"}},run:(F,X,I)=>{$.setPluginAgentMode(Z),I()}})),Y=[...D,...J,{noun:"speed",get verb(){if($.isFastSpeedEnabled())return"disable fast";let Z=$.speedCostMultiplierLabel();return Z?`use fast (${Z} cost)`:"use fast"},description:"Toggle fast speed for this thread",get status(){return $.speedToggleCommandStatus()},run:(Z,F,X)=>{$.toggleSpeed(),X()}},{noun:"thread",verb:"toggle details",description:"Expand or collapse tool and activity details",keywords:["expand","thinking"],shortcut:HA.alt("t"),status:{type:"enabled"},run:(Z,F,X)=>{$.toggleWorkDetails(),X()}},{noun:"mode",verb:"toggle reasoning effort",description:"Cycle reasoning effort for the active model",shortcut:HA.alt("d"),get status(){if($.widget.threadContext)return{type:"hidden"};return nC($.currentCommandAgentMode())?{type:"enabled"}:{type:"hidden"}},run:(Z,F,X)=>{$.toggleReasoningEffort(),X()}},{noun:"thread",verb:"copy ID",description:"Copy thread ID to clipboard",get status(){return $.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(Z,F,X)=>{let I=B()?.client.getThreadId();if(!I)return;N4.maybeInvoke(F,new ZB(I,"Thread ID copied to clipboard","Failed to copy thread ID")),X()}},{noun:"thread",verb:"copy URL",description:"Copy thread URL to clipboard",keywords:["share"],get status(){return $.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(Z,F,X)=>{let I=E();if(!I)return;N4.maybeInvoke(F,new ZB(I,"Thread URL copied to clipboard","Failed to copy thread URL")),X()}},{noun:"thread",verb:"copy markdown",description:"Copy thread as Markdown",get status(){return $.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(Z,F,X)=>{let I=B()?.client.getThreadId();if(!I)return;(async()=>{try{let G=await Q.getThreadMarkdown(I);if(!G){EQ.error(F,"Failed to copy thread markdown");return}N4.maybeInvoke(F,new ZB(G,"Thread markdown copied to clipboard","Failed to copy thread markdown"))}catch(G){S.error("Failed to render thread markdown from Neo command palette",{error:G,threadID:I}),EQ.error(F,"Failed to copy thread markdown")}finally{X()}})()}},{noun:"thread",verb:"analyze context",description:"Show token usage by prompt section for this thread",keywords:["tokens"],get status(){return $.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(Z,F,X)=>{let I=B()?.client.getThreadId();if(!I)return;Z.push(new Mc0({threadID:I,analyzeContext:$.widget.analyzeContextForThread,onDismiss:X}))}},{noun:"skills",verb:"list",description:"List available skills for this thread",get status(){return{type:"enabled"}},run:(Z,F,X)=>{let I=B()?.client.getThreadId();if(!I){Z.push(new m90({status:{kind:"no-thread"},onDismiss:X,cwd:Q.workspaceRoot}));return}Z.push(new pc0({listSkills:(G)=>$.widget.listSkillsForThread(I,G),onDismiss:X,cwd:Q.workspaceRoot}))}},{noun:"thread",verb:"new",description:"Start new thread",keywords:["create","start"],sortBoost:101,get status(){if($.isEditorUploadLocked)return{type:"disabled",reason:"Prompt editor is not available"};return $.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"Already on a new thread"}},run:(Z,F)=>{if($.isEditorUploadLocked)return;N4.maybeInvoke(F,new Xl)}},{noun:"thread",verb:"open in browser",description:"Open thread in browser",keywords:["web"],get status(){return $.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(Z,F,X)=>{let I=E();if(!I)return;try{await t6(F,I)}finally{X()}}},VR4({sendFeedbackReport:(Z)=>{return this.widget.sendFeedbackReport(Z)}},B),_j4({archiveThread:(Z)=>this.widget.archiveThread(Z)},B),FR4(B),BR4({configService:this.widget.configService,addLabel:(Z,F)=>this.widget.addThreadLabel(Z,F)},B),JR4({configService:this.widget.configService,removeLabel:(Z,F)=>this.widget.removeThreadLabel(Z,F)},B)].map((Z)=>A.register(Z));return()=>{for(let Z of Y)Z()}}currentCommandAgentMode(){if(this.selectedPluginAgentMode&&!this.widget.threadContext)return this.agentMode;return this.widget.threadContext?.observer.agentMode??this.agentMode}currentThreadSettings(){return this.widget.threadContext?.observer.threadSettings().getValue()??this.widget.draftThreadSettings}currentCommandSpeedModel(){if(this.selectedPluginAgentMode&&!this.widget.threadContext)return this.selectedPluginAgentMode.agent.model;return _$(this.currentCommandAgentMode())?.primaryModel}currentCommandModeLabel(){if(this.selectedPluginAgentMode&&!this.widget.threadContext)return this.selectedPluginAgentMode.label;return this.currentCommandAgentMode()}currentSpeedSettingKey(){let A=this.currentCommandSpeedModel();return A?C50(A):void 0}speedCostMultiplierLabel(){let A=this.currentCommandSpeedModel();return A?Py0(A):void 0}isFastSpeedEnabled(){let A=this.currentSpeedSettingKey();return A!==void 0&&this.currentThreadSettings()[A]==="fast"}speedToggleCommandStatus(){if(this.currentSpeedSettingKey()===void 0)return{type:"hidden"};return{type:"enabled"}}updateThreadSettings(A){let Q=this.widget.threadContext;if(Q){let $=Q.observer.threadSettings().getValue()??{},B=A($);return Q.client.sendClientUpdateThreadSettings(B),this.widget.updateDraftThreadSettings(()=>B),"handled"}return this.widget.updateDraftThreadSettings(A),"handled"}toggleSpeed(){return this.setSpeed(this.isFastSpeedEnabled()?"normal":"fast")}setSpeed(A){let Q=this.currentSpeedSettingKey();if(Q===void 0)return"ignored";let $=A==="normal"?"standard":"fast",B=this.updateThreadSettings((E)=>{return{...E,[Q]:$}});if(!(this.selectedPluginAgentMode&&!this.widget.threadContext))this.rememberSpeedForMode(this.currentCommandAgentMode(),$);if(A==="fast")this.showFastModeToast();return B}showFastModeToast(){let A=EQ.maybeOf(this.context);if(!A)return;if(this.fastModeToastID!==null)A.dismiss(this.fastModeToastID);let Q=this.currentCommandModeLabel(),$=this.speedCostMultiplierLabel()??"2.5x";this.fastModeToastID=A.show(`↯${Q} costs ${$} the standard rate for this mode`,"warning",XF6)}dismissFastModeToast(){if(this.fastModeToastID===null)return;EQ.maybeOf(this.context)?.dismiss(this.fastModeToastID),this.fastModeToastID=null}toggleWorkDetails(){return this.expansion.toggle(!1),"handled"}rememberReasoningEffortForMode(A,Q){let $=HQ.of(this.context);$.lastReasoningEffortByMode={...$.lastReasoningEffortByMode??{},[A]:Q}}rememberSpeedForMode(A,Q){let $=HQ.of(this.context);$.lastSpeedByMode={...$.lastSpeedByMode??{},[A]:Q}}applyStickySpeedForMode(A,Q){let $=Yq(Q),B=H50(HQ.of(this.context),Q);if($===void 0||B===void 0)return A;return{...A,[$]:B}}toggleReasoningEffort(){if(this.selectedPluginAgentMode&&!this.widget.threadContext)return"ignored";let A=this.currentCommandAgentMode(),Q=nC(A);if(!Q)return"ignored";return this.updateThreadSettings(($)=>{let B=vy0(A,$,this.configSettingsForReasoning),E=gbA(Q,B);return this.rememberReasoningEffortForMode(A,E),{...$,"reasoning.effort":E}})}onPromptSubmitted=(A)=>{this.widget.history.add(A,FF6.cwd()),this.resetHistory()};handleEditorUploadLockChange=(A)=>{if(this.isEditorUploadLocked===A)return;this.setState(()=>{this.isEditorUploadLocked=A})};resetHistory(){this.widget.history.reset()}setAgentMode=(A)=>{if(this.widget.threadContext)return;if(A!==this.agentMode)this.dismissFastModeToast();this.setState(()=>{this.agentMode=A,this.selectedPluginAgentMode=null}),this.widget.updateDraftThreadSettings((Q)=>{let $=jy0(HQ.of(this.context),A),B={...Q};delete B["reasoning.effort"];let E=$??vy0(A,B,this.configSettingsForReasoning);if(E===void 0){let D={...Q};return delete D["reasoning.effort"],this.applyStickySpeedForMode(D,A)}return this.applyStickySpeedForMode({...Q,"reasoning.effort":E},A)})};setPluginAgentMode=(A)=>{if(this.widget.threadContext)return;this.dismissFastModeToast(),this.setState(()=>{this.selectedPluginAgentMode=A})};buildActions(){let A=new pA((B)=>{return this.setAgentMode(B.mode),"handled"}),Q=new pA(()=>{return this.toggleReasoningEffort()}),$=new pA(()=>{return this.toggleWorkDetails()});return new Map([[lh0,A],[_q,Q],[g70,$]])}build(A){let Q=this.widget.threadContext,$=HQ.of(A),B=WR4(this.selectedPluginAgentMode?.color),E=zF6($.workspaceRoot,this.currentGitBranch),J=[Q?new wc0({editorController:this.widget.editorController,editorFocusNode:this.widget.editorFocusNode,copyOnSelectEnabled:this.copyOnSelectEnabled,observingClient:{client:Q.client,observer:Q.observer,agentModeDisplay:Q.agentModeDisplay},hints:this.widget.hints,ideStatus:this.widget.ideStatus,statusItems:this.widget.statusItems,pluginConfirmationBlocked:this.widget.pluginConfirmationBlocked,onPromptSubmitted:this.onPromptSubmitted,onEditorUploadLockChange:this.handleEditorUploadLockChange,editorUploadLocked:this.isEditorUploadLocked,notificationService:this.widget.notificationService??IF6,environmentFallback:this.useLocalEnvironmentFallbackForActiveThread?E:null}):new mc0({agentMode:this.agentMode,pluginAgentModes:this.pluginAgentModes,selectedPluginAgentMode:this.selectedPluginAgentMode,agentModeLabel:this.selectedPluginAgentMode?.label,pluginAgentModeURI:this.selectedPluginAgentMode?.sourceURI,agentModeColor:GF6(this.selectedPluginAgentMode?.color),splashPrimaryColor:B?VF6(B):void 0,splashSecondaryColor:B,threadSettings:this.widget.draftThreadSettings,configSettings:this.configSettingsForReasoning,editorController:this.widget.editorController,editorFocusNode:this.widget.editorFocusNode,visibility:null,onNewThread:this.widget.onNewThread,onAgentModeChange:this.setAgentMode,onPluginAgentModeChange:this.setPluginAgentMode,onEditorUploadLockChange:this.handleEditorUploadLockChange,editorUploadLocked:this.isEditorUploadLocked,previousThreadIDForReference:this.previousThreadIDForReference,hints:this.widget.hints,ideStatus:this.widget.ideStatus,statusItems:this.widget.statusItems,configService:this.widget.configService,environment:E,notice:this.widget.notice??null,onDismissNotice:this.widget.onDismissNotice??(()=>{}),statusMessage:this.statusMessage})],U=new Map([[HA.alt("t"),new g70]]);return new N4({actions:this.buildActions(),child:new pQ({debugLabel:"ThreadShortcuts",shortcuts:U,child:new xv({history:this.isEditorUploadLocked?void 0:this.widget.history,child:new zJ({controller:this.expansion,child:new QQ({children:J})})})})})}subscribeToCopyOnSelectEnabled(){this.copyOnSelectSubscription?.unsubscribe(),this.copyOnSelectSubscription=this.widget.configService.config.subscribe((A)=>{let Q=A.settings["terminal.copyOnSelect"]??!0,$=A.settings["internal.model"],B=this.configSettingsForReasoning["internal.model"]!==$;if($===void 0)this.configSettingsForReasoning={};else this.configSettingsForReasoning={"internal.model":$};if(this.copyOnSelectEnabled===Q&&!B)return;if(this.copyOnSelectEnabled=Q,this.mounted)this.setState()})}}a0();d8();J4();class QI extends G4{direction;constructor(A){super();this.direction=A}}class d90 extends G4{}class zi extends G4{}class c90 extends G4{index;constructor(A){super();this.index=A}}function ic0(A){return A.length+2}class nc0 extends p0{props;constructor(A){super();this.props=A}createState(){return new HR4}}class HR4 extends c0{selectedIndex=0;initState(){super.initState(),this.selectedIndex=this.findSelectableIndex(this.widget.props.initialSelectedIndex??0)}didUpdateWidget(A){this.selectedIndex=this.findSelectableIndex(this.selectedIndex)}isSelectable(A){let Q=this.widget.props.entries[A];return Q?.type==="item"&&(Q.enabled??!0)}findSelectableIndex(A){let{entries:Q}=this.widget.props;if(Q.length===0)return 0;let $=Math.max(0,Math.min(A,Q.length-1));if(this.isSelectable($))return $;for(let B=1;B<Q.length;B++){let E=$+B;if(E<Q.length&&this.isSelectable(E))return E;let D=$-B;if(D>=0&&this.isSelectable(D))return D}return 0}moveSelection(A){let Q=this.findNextSelectableIndex(A);if(Q===this.selectedIndex)return;this.setState(()=>{this.selectedIndex=Q})}findNextSelectableIndex(A){let{entries:Q}=this.widget.props;for(let $=this.selectedIndex+A;$>=0&&$<Q.length;$+=A)if(this.isSelectable($))return $;return this.selectedIndex}acceptIndex(A){let Q=this.widget.props.entries[A];if(Q?.type!=="item"||!(Q.enabled??!0))return;this.setState(()=>{this.selectedIndex=A}),this.widget.props.onAccept(Q.value)}invoke=(A)=>{if(A instanceof QI)return this.moveSelection(A.direction),"handled";if(A instanceof d90)return this.acceptIndex(this.selectedIndex),"handled";if(A instanceof zi)return this.widget.props.onDismiss(),"handled";if(A instanceof c90)return this.acceptIndex(A.index),"handled";return"ignored"};buildShortcuts(){let A=new Map([[HA.key("ArrowDown"),new QI(1)],[HA.key("j"),new QI(1)],[HA.ctrl("n"),new QI(1)],[HA.key("ArrowUp"),new QI(-1)],[HA.key("k"),new QI(-1)],[HA.ctrl("p"),new QI(-1)],[HA.key("Enter"),new d90],[HA.key("Escape"),new zi],[HA.ctrl("."),new zi]]);return this.widget.props.entries.forEach((Q,$)=>{if(Q.type==="item"&&Q.shortcut)A.set(Q.shortcut,new c90($))}),A}buildActions(){return new Map([[QI,new pA(this.invoke)],[d90,new pA(this.invoke)],[zi,new pA(this.invoke)],[c90,new pA(this.invoke)]])}build(A){let Q=EA.of(A),$=WF6(this.widget.props.entries,W4.of(A).supportsEmojiWidth);return new WA({width:this.widget.props.width,height:ic0(this.widget.props.entries),decoration:new c1(Q.colors.background,W1.all(new C1(Q.colors.border,1,"solid"))),child:new N4({actions:this.buildActions(),child:new pQ({debugLabel:"ContextPickerShortcuts",shortcuts:this.buildShortcuts(),child:new cQ({autofocus:!0,debugLabel:"ContextPicker",child:new IA({mainAxisSize:"min",crossAxisAlignment:"stretch",children:this.widget.props.entries.map((B,E)=>this.buildEntry(B,E,$,Q))})})})})})}buildEntry(A,Q,$,B){if(A.type==="separator")return new WA({height:1,decoration:{border:new W1(new C1(B.colors.border,1,"solid"))}});let E=Q===this.selectedIndex,D=A.enabled??!0,J=new $0({color:E?B.app.selectionForeground:B.colors.foreground,dim:!D}),U=new $0({color:E?B.app.selectionForeground:B.app.keybind,bold:!0,dim:!D});return new iA({onClick:()=>this.acceptIndex(Q),child:new WA({padding:n0.symmetric(1,0),decoration:E?new c1(B.app.selectionBackground):void 0,child:new LA({crossAxisAlignment:"start",children:[new L4({child:new D0({text:new h(A.label,J),maxLines:1,overflow:"ellipsis"})}),new y0({width:1}),new y0({width:$,child:new D0({text:new h(NR4(A),U),textAlign:"right",maxLines:1,overflow:"ellipsis"})})]})})})}}function WF6(A,Q){return A.reduce(($,B)=>{return B.type==="item"?Math.max($,cA(NR4(B),Q)):$},0)}function NR4(A){return A.shortcutLabel??A.shortcut?.toString().toLowerCase()??""}var CF6=36,HF6=24,NF6=72;class qR4 extends p0{child;onContext;constructor(A,Q){super();this.child=A;this.onContext=Q}createState(){return new uR4}}class uR4 extends c0{build(A){return this.widget.onContext(A),this.widget.child}}function wR4(A){if(A==="Just now")return"1m";return A.replace(/ ago$/,"")}function qF6(A){return A.reduce((Q,$)=>Math.max(Q,cA(wR4($.description.timeAgo))),0)}function MR4(A){return Math.max(HF6,Math.min(A,NF6))}class ac0 extends G4{}class oc0 extends G4{}class rc0 extends G4{}class sc0{options;focusScopeNode=new B8({debugLabel:"ThreadListSidebar"});initialized=!1;visible=!1;hasRenderedSidebar=!1;width=CF6;pickerController=new tp;constructor(A){this.options=A}isVisible(){return this.ensureInitialized(),this.visible}visibleWidth(){return this.isVisible()?this.width:0}buildBody(A){return new LA({crossAxisAlignment:"stretch",children:[this.buildSlot(),new L4({child:A})]})}buildSlot(){let A=this.isVisible();if(!this.hasRenderedSidebar)return new y0({width:0});let Q={activeThreadID:this.options.getActiveThreadID(),currentWorkspaceURI:$4(m0.file(this.options.getWorkspaceRoot())),width:this.width,loadThreads:this.options.loadThreads,pickerController:this.pickerController,onSelectThread:this.options.onSelectThread,onDismiss:this.close,onResizeWidth:this.resize};if(this.options.observeThreadSummaries)Q.observeThreadSummaries=this.options.observeThreadSummaries;return new y0({width:A?this.width:0,child:new c6({focusScopeNode:this.focusScopeNode,debugLabel:"ThreadListSidebar",onFocusChange:this.handleFocusChange,child:new OR4(Q)})})}commands(){return[{noun:"thread",verb:"toggle sidebar",description:"Show or hide the thread sidebar",shortcut:HA.alt("s"),status:{type:"enabled"},run:(A,Q,$)=>{$(),this.toggleFromShortcut()}}]}shortcutEntries(){return[[HA.alt("s"),new d70]]}actionEntries(){return[[d70,new pA(()=>this.toggleFromShortcut())]]}toggleFromShortcut=()=>{if(this.isVisible()){if(this.focusScopeNode.hasFocus)return this.close(),"handled";if(this.options.isBlocked())return"ignored";return this.pickerController.requestFocus(),"handled"}if(this.options.isBlocked())return"ignored";return this.pickerController.requestFocus(),this.setVisible(!0),"handled"};close=()=>{this.options.focusMainContent(),this.setVisible(!1)};setVisible(A){if(this.ensureInitialized(),this.visible===A)return;if(A)this.hasRenderedSidebar=!0;this.options.state.setState(()=>{this.visible=A}),JJ((Q)=>({...Q,threadListSidebarVisible:A})).catch((Q)=>{S.warn("Failed to save thread sidebar visibility state",{error:Q instanceof Error?Q.message:String(Q)})})}ensureInitialized(){if(this.initialized)return;this.initialized=!0,this.visible=this.options.getInitialVisible(),this.hasRenderedSidebar=this.visible}handleFocusChange=(A)=>{this.options.state.setState()};dispose(){this.focusScopeNode.dispose()}resize=(A)=>{let Q=MR4(A);if(Q===this.width)return;this.options.state.setState(()=>{this.width=Q})}}class OR4 extends p0{props;constructor(A){super();this.props=A}createState(){return new LR4}}class LR4 extends c0{threads=[];isLoading=!0;isSwitchingThread=!1;hasError=!1;filterByWorkspace=!0;contextMenu=null;pendingThreadMutations=new Map;canonicalThreadSummariesByID=new Map;archivedCanonicalThreadIDs=new Set;liveThreadSummaries=null;resizeSession=null;isResizeHandleHovered=!1;threadItemContexts=new Map;threadSummarySubscription=null;observedThreadSummaries;shortcuts=new Map([[HA.alt("w"),new ac0],[HA.ctrl("."),new oc0],[HA.key("e"),new rc0]]);actions=new Map([[ac0,new pA(()=>{return this.setState(()=>{this.filterByWorkspace=!this.filterByWorkspace,this.contextMenu=null}),"handled"})],[oc0,new pA(()=>this.openContextMenu())],[rc0,new pA(()=>this.archiveSelectedThread())]]);get isBusy(){return this.isLoading}get isResizeActive(){return this.resizeSession!==null||this.isResizeHandleHovered}didUpdateWidget(A){if(super.didUpdateWidget(A),this.contextMenu&&(A.props.width!==this.widget.props.width||A.props.currentWorkspaceURI!==this.widget.props.currentWorkspaceURI))this.contextMenu=null;if(A.props.observeThreadSummaries!==this.widget.props.observeThreadSummaries)this.startThreadSummaryUpdates()}initState(){super.initState(),this.startThreadSummaryUpdates()}dispose(){this.threadSummarySubscription?.unsubscribe(),this.threadSummarySubscription=null,super.dispose()}startThreadSummaryUpdates(){this.threadSummarySubscription?.unsubscribe(),this.threadSummarySubscription=null,this.liveThreadSummaries=null,this.observedThreadSummaries=this.widget.props.observeThreadSummaries;let A=this.widget.props.observeThreadSummaries;if(!A){this.loadThreadSummaries();return}let Q=A();if(!Q){this.loadThreadSummaries();return}this.loadThreadSummaries(),this.threadSummarySubscription=Q.subscribe({next:($)=>this.applyLiveThreadSummaries($),error:($)=>{if(S.error("Failed to observe threads for Neo sidebar",{error:$}),!this.mounted)return;this.setState(()=>{this.isLoading=!1,this.hasError=!0})}})}async loadThreadSummaries(){let A=this.observedThreadSummaries;try{let Q=await this.widget.props.loadThreads(),$=nd0(Q);if(!this.mounted||A!==this.observedThreadSummaries)return;this.archivedCanonicalThreadIDs.clear();for(let B of Q)if(B.archived)this.archivedCanonicalThreadIDs.add(B.id);this.applyCanonicalThreadSummaries($)}catch(Q){if(S.error("Failed to load threads for Neo sidebar",{error:Q}),!this.mounted)return;this.setState(()=>{this.isLoading=!1,this.hasError=!0})}}applyCanonicalThreadSummaries(A){this.canonicalThreadSummariesByID.clear();for(let Q of A)this.canonicalThreadSummariesByID.set(Q.id,Q);this.applyThreadSummaries(this.liveThreadSummaries?this.mergeLiveMetadata():A)}applyLiveThreadSummaries(A){this.liveThreadSummaries=A;let Q=this.mergeLiveMetadata();if(Q.length===0&&this.canonicalThreadSummariesByID.size===0&&this.isLoading)return;this.applyThreadSummaries(Q)}mergeLiveMetadata(){let A=new Map((this.liveThreadSummaries??[]).map((B)=>[B.id,B])),Q=(this.liveThreadSummaries??[]).flatMap((B)=>{if(this.archivedCanonicalThreadIDs.has(B.id))return[];let E=this.canonicalThreadSummariesByID.get(B.id);if(!E){if(!B.updatedAt)return[];return[B]}return[this.mergeLiveThreadSummary(E,B)]}),$=Array.from(this.canonicalThreadSummariesByID.values()).filter((B)=>!A.has(B.id));return[...Q,...$]}mergeLiveThreadSummary(A,Q){return{...A,...Q,updatedAt:Q.updatedAt??A.updatedAt,description:Q.updatedAt?Q.description:A.description,workspaceURI:A.workspaceURI,relationships:A.relationships,diffStats:A.diffStats,agentMode:A.agentMode,details:A.details,archived:A.archived}}applyThreadSummaries(A){if(!this.mounted)return;this.setState(()=>{let Q=this.widget.props.pickerController.selectedItem?.id??this.widget.props.activeThreadID;this.widget.props.pickerController.selectedItem=A.find(($)=>$.id===Q)??A.find(($)=>$.id===this.widget.props.activeThreadID)??null,this.threads=A,this.isLoading=!1,this.hasError=!1})}handleSelectThread=async(A)=>{if(this.isSwitchingThread)return;this.setState(()=>{this.isSwitchingThread=!0});try{await this.widget.props.onSelectThread(A)}catch(Q){S.error("Failed to switch thread from Neo sidebar",{error:Q,threadID:A})}finally{if(this.mounted)this.setState(()=>{this.isSwitchingThread=!1})}};getOptimisticThreads(){return this.threads.flatMap((A)=>{if(this.pendingThreadMutations.get(A.id)?.kind==="archive")return[];return[A]})}getThreadsForDisplay(){let A=this.getOptimisticThreads();return this.filterByWorkspace?A.filter((Q)=>!Q.workspaceURI||Q.workspaceURI===this.widget.props.currentWorkspaceURI):A}buildContextMenuEntries(){return[{type:"item",value:"archive",label:"Archive Thread",shortcut:HA.key("a"),shortcutLabel:"a"},{type:"separator"},{type:"item",value:"copy-id",label:"Copy ID",shortcut:HA.ctrl("c"),shortcutLabel:"ctrl+c"},{type:"item",value:"copy-url",label:"Copy URL",shortcut:new HA("c",{shift:!0,ctrl:!0}),shortcutLabel:"shift+ctrl+c"}]}openContextMenu(){let A=this.widget.props.pickerController.selectedItem;if(!A||this.isBusy||this.isSwitchingThread||this.hasError)return"ignored";let Q=this.buildContextMenuEntries(),$=ic0(Q),B=this.getContextMenuWidth(),E=this.getContextMenuPosition(A.id,$,B);return this.setState(()=>{this.contextMenu={threadID:A.id,left:E.left,top:E.top,width:B,height:$}}),"handled"}archiveSelectedThread(){let A=this.widget.props.pickerController.selectedItem?.id;if(!A||this.contextMenu||this.isBusy||this.isSwitchingThread||this.hasError)return"ignored";return this.archiveThread(A),"handled"}getContextMenuWidth(){let A=Math.max(24,this.widget.props.width-3);return Math.max(1,Math.min(A,this.widget.props.width-2))}getContextMenuPosition(A,Q,$){let B=Math.max(0,Math.min(2,this.widget.props.width-$)),E=1,D=this.threadItemContexts.get(A)?.findRenderObject(),J=this.context.findRenderObject();if(!(D instanceof bA)||!(J instanceof bA))return{left:B,top:1};let U=D.localToGlobal({x:0,y:0}),Y=J.localToGlobal({x:0,y:0}),Z=U.y-Y.y,F=Z+D.size.height,X=W4.sizeOf(this.context).height,I=Math.max(1,Math.min(J.size.height,X-Y.y)),K=I-F>=Q||Z<I/2?F:Z-Q,z=Math.max(0,I-Q);return{left:B,top:Math.max(0,Math.min(K,z))}}closeContextMenu=()=>{if(!this.contextMenu)return;this.setState(()=>{this.contextMenu=null})};handleContextMenuAccept=(A)=>{let Q=this.contextMenu?.threadID;if(!Q)return;if(this.closeContextMenu(),A==="archive"){this.archiveThread(Q);return}if(A==="copy-id"){N4.maybeInvoke(this.context,new ZB(Q,"Thread ID copied to clipboard","Failed to copy thread ID"));return}N4.maybeInvoke(this.context,new ZB(this.getThreadURL(Q),"Thread URL copied to clipboard","Failed to copy thread URL"))};beginOptimisticArchive(A){if(this.pendingThreadMutations.has(A))return!1;if(!this.threads.some(($)=>$.id===A))return!1;let Q={kind:"archive",fallbackSelectedThreadID:null};return this.setState(()=>{this.pendingThreadMutations.set(A,Q)}),z6.instance.addPostFrameCallback(()=>{if(!this.mounted)return;let $=this.pendingThreadMutations.get(A);if($?.kind!=="archive")return;$.fallbackSelectedThreadID=this.widget.props.pickerController.selectedItem?.id??null}),!0}commitOptimisticArchive(A){if(this.pendingThreadMutations.get(A)?.kind!=="archive")return;this.pendingThreadMutations.delete(A),this.canonicalThreadSummariesByID.delete(A),this.threads=this.threads.filter(($)=>$.id!==A)}rollbackOptimisticArchive(A){let Q=this.pendingThreadMutations.get(A);if(Q?.kind!=="archive")return;let $=this.threads.find((B)=>B.id===A);if(!$){this.pendingThreadMutations.delete(A);return}this.setState(()=>{this.pendingThreadMutations.delete(A);let B=this.widget.props.pickerController.selectedItem?.id??null;if(B===null||B===Q.fallbackSelectedThreadID)this.widget.props.pickerController.selectedItem=$})}async archiveThread(A){let Q=EQ.maybeOf(this.context),{configService:$}=HQ.of(this.context);if(!this.beginOptimisticArchive(A))return;try{let B=await H70({configService:$},A);if(!this.mounted)return;if(B){this.rollbackOptimisticArchive(A),Q?.show(B.message,"error");return}this.commitOptimisticArchive(A),Q?.show("Archived thread")}catch(B){if(S.error("Failed to archive thread from Neo sidebar context menu",{error:B,threadID:A}),!this.mounted)return;this.rollbackOptimisticArchive(A),Q?.show("Failed to archive thread","error")}}getThreadURL(A){return dG(new URL(HQ.of(this.context).ampURL),A).toString()}buildContextMenuOverlay(){let A=this.contextMenu;if(!A||!this.getThreadsForDisplay().some((Q)=>Q.id===A.threadID))return null;return new r1({left:A.left,top:A.top,width:A.width,height:A.height,child:new c6({debugLabel:"ThreadListSidebarContextMenu",onFocusChange:(Q)=>{if(!Q)this.closeContextMenu()},child:new nc0({entries:this.buildContextMenuEntries(),width:A.width,onAccept:this.handleContextMenuAccept,onDismiss:this.closeContextMenu})})})}buildContextMenuBackdrop(){return new r1({left:0,top:0,right:0,bottom:0,child:new iA({onClick:()=>this.closeContextMenu(),child:y0.expand()})})}buildThreadItem(A,Q,$,B){let E=EA.of(B),{app:D,colors:J}=E,U=A.id===this.widget.props.activeThreadID,Y=!Q&&!U,Z=Q?D.selectionForeground:J.foreground,F=Q?D.selectionForeground:J.mutedForeground,I=A.agentState!==void 0&&A.agentState!=="idle"?new eX({color:Q?D.selectionForeground:J.primary}):void 0,G=wR4(A.description.timeAgo);return new qR4(new WA({padding:n0.symmetric(1,0),child:new LA({children:[new y0({width:2,child:I}),new L4({child:new D0({text:new h(A.title,new $0({color:Z,dim:Y})),overflow:"ellipsis",maxLines:1})}),new y0({width:2}),new y0({width:$,child:LA.end([new D0({text:new h(G,new $0({color:F,dim:Y}))})])})]})}),(V)=>{this.threadItemContexts.set(A.id,V)})}handleResizeHandlePress=(A)=>{if(A.button!=="left")return;this.setState(()=>{this.resizeSession={baseWidthColumns:this.widget.props.width,startColumn:Math.floor(A.position.x)}})};handleResizeHandleDrag=(A)=>{if(A.button!=="left"||this.resizeSession===null)return;let Q=Math.floor(A.position.x)-this.resizeSession.startColumn,$=MR4(this.resizeSession.baseWidthColumns+Q);if($!==this.widget.props.width)this.widget.props.onResizeWidth($)};handleResizeHandleRelease=(A)=>{if(A.button!=="left"||this.resizeSession===null)return;this.setState(()=>{this.resizeSession=null})};handleResizeHandleEnter=()=>{if(this.isResizeHandleHovered)return;this.setState(()=>{this.isResizeHandleHovered=!0})};handleResizeHandleExit=()=>{if(!this.isResizeHandleHovered)return;this.setState(()=>{this.isResizeHandleHovered=!1})};buildResizeHandle(){return new r1({top:0,right:0,bottom:0,width:1,child:new iA({cursor:d1.EW_RESIZE,onClick:this.handleResizeHandlePress,onDrag:this.handleResizeHandleDrag,onRelease:this.handleResizeHandleRelease,onEnter:this.handleResizeHandleEnter,onExit:this.handleResizeHandleExit,child:new y0({width:1})})})}build(A){let Q=EA.of(A),$=this.getThreadsForDisplay(),B=this.hasError?[]:$,E=qF6(B);this.threadItemContexts.clear();let D=this.isResizeActive?2:1,J=new W1(void 0,new C1(Q.colors.border,D),void 0,void 0),U=this.buildContextMenuOverlay(),Y=[new WA({decoration:new c1(Q.colors.background,J),child:new N4({actions:this.actions,child:new pQ({shortcuts:this.shortcuts,debugLabel:"ThreadListSidebarFilter",child:new R5({items:B,getLabel:(Z)=>`${Z.title} ${Z.id}`,controller:this.widget.props.pickerController,autofocus:!1,onAccept:(Z)=>void this.handleSelectThread(Z.id),onDismiss:this.widget.props.onDismiss,renderItem:(Z,F,X,I)=>this.buildThreadItem(Z,F,E,I),enabled:!this.isBusy,isLoading:this.isBusy,hidePrompt:!0,loadingText:"Loading threads...",emptyStateText:this.hasError?"Failed to load threads":void 0,emptyStateWidget:this.hasError?void 0:(Z)=>ld0(Z,this.filterByWorkspace),maxRenderItems:200,showBorder:!1})})})}),this.buildResizeHandle()];if(U)Y.push(this.buildContextMenuBackdrop()),Y.push(U);return new WA({width:this.widget.props.width,child:new QQ({fit:"expand",children:Y})})}}bB();class tc0 extends p0{toolboxes;onDismiss;constructor(A){super();this.toolboxes=A.toolboxes,this.onDismiss=A.onDismiss}createState(){return new RR4}}class RR4 extends c0{toolboxes=new sB(this,[]);initState(){this.toolboxes.subscribe(this.widget.toolboxes)}didUpdateWidget(A){if(A.toolboxes!==this.widget.toolboxes)this.toolboxes.subscribe(this.widget.toolboxes)}build(A){return new PR4({toolboxes:this.toolboxes.getValue(),onDismiss:this.widget.onDismiss})}}class PR4 extends p0{toolboxes;onDismiss;constructor(A){super();this.toolboxes=A.toolboxes,this.onDismiss=A.onDismiss}createState(){return new vR4}}class vR4 extends c0{scrollController=new G$;canScroll=!1;initState(){this.scrollController.followMode=!1,this.scrollController.jumpTo(0),this.scrollController.addListener(this.updateCanScroll)}dispose(){this.scrollController.removeListener(this.updateCanScroll),this.scrollController.dispose()}updateCanScroll=()=>{let A=this.scrollController.maxScrollExtent>0;if(A===this.canScroll)return;this.setState(()=>{this.canScroll=A})};build(A){return new B1({header:"Toolboxes",onDismiss:this.widget.onDismiss,minWidth:80,maxWidth:120,maxHeight:40,autofocus:!1,footer:uF6(this.canScroll),child:new PB({controller:this.scrollController,child:wF6(A,this.widget.toolboxes)})})}}function uF6(A){let Q=[{keys:["Esc"],label:"close"}];if(A)Q.push({keys:["↑↓","j/k"],label:"scroll"});return Q}function wF6(A,Q){let $=MF6(A,Q);return new IA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new D0({text:new h("",void 0,$),selectable:!0})]})}function MF6(A,Q){let $=EA.of(A),{colors:B}=$,E=new $0({color:B.foreground,dim:!0}),D=new $0({color:B.foreground,bold:!0});if(Q.length===0)return[new h("No toolboxes found.",E)];let J=[];for(let U of Q){let Y=U.tools.length,Z=U.tools.filter((F)=>F.status==="registered").length;if(U.discovering){let F=U.tools.filter((X)=>X.status!=="pending").length;J.push(new h(U.path,D)),J.push(new h(` discovering ${F}/${Y}...
|
|
4425
|
+
`)[0]??"",Q.description)})}));return $.push(new hA({padding:n0.only({left:4}),child:new D0({text:new h(zR4(A.path,Q.cwd),Q.location),maxLines:1,overflow:"ellipsis"})})),$}function UF6(A){try{return new URL(A).pathname.split("/").filter(Boolean).at(-2)??"unknown"}catch{return"unknown"}}function YF6(A,Q,$){if(Q)return new LA({crossAxisAlignment:"start",children:[new L4({flex:1,child:new D0({text:new h(A.name,$.name),maxLines:1,overflow:"ellipsis"})}),new y0({width:2}),new L4({flex:2,child:new hA({padding:n0.only({right:1}),child:new D0({text:new h(A.description,$.description),maxLines:1,overflow:"ellipsis"})})})]});return new IA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new LA({crossAxisAlignment:"start",children:[new D0({text:new h(A.name,$.name),maxLines:1,overflow:"ellipsis"}),new L4({child:new D0({text:new h(` ${zR4(A.baseDir,$.cwd)}`,$.location),maxLines:1,overflow:"ellipsis"})})]}),new hA({padding:n0.only({left:2,right:1}),child:new D0({text:new h(A.description,$.description),maxLines:1,overflow:"ellipsis"})})]})}function zR4(A,Q){if(A.startsWith("builtin://"))return"(builtin)";if(!A.startsWith("file://"))return A;let $=nZ6(A),B=lZ6(Q,$);if(B&&!B.startsWith(".."))return`./${B}`;let E=pZ6();if($===E||$.startsWith(E+iZ6))return`~${$.slice(E.length)}`;return $}var XF6=5000,IF6={attach:()=>{},detach:()=>{},unsubscribe:()=>{}};function GF6(A){let Q=WR4(A);return Q?{type:"rgb",value:Q}:void 0}function WR4(A){let Q=A?.match(/^#([0-9a-f]{6})$/i);if(!Q?.[1])return;return{r:Number.parseInt(Q[1].slice(0,2),16),g:Number.parseInt(Q[1].slice(2,4),16),b:Number.parseInt(Q[1].slice(4,6),16)}}function VF6(A){return{r:Math.round(A.r*0.55),g:Math.round(A.g*0.55),b:Math.round(A.b*0.55)}}async function KF6(A){return new Promise((Q)=>{ZF6("git",["branch","--show-current"],{cwd:A},($,B)=>{if($){Q(null);return}let E=B.trim();Q(E||null)})})}function zF6(A,Q){let $=$4(m0.file(A)),B={workspaceRoot:$,workingDirectory:$};if(Q)B.git={branch:Q};return B}class lc0 extends p0{initialAgentMode;initialPluginAgentModeKey;analyzeContextForThread;listSkillsForThread;threadContext;draftThreadSettings;editorController;editorFocusNode;history;updateDraftThreadSettings;onNewThread;sendFeedbackReport;archiveThread;addThreadLabel;removeThreadLabel;configService;hints;ideStatus;statusItems;pluginConfirmationBlocked;notificationService;notice;onDismissNotice;constructor(A){super();this.initialAgentMode=A.initialAgentMode,this.initialPluginAgentModeKey=A.initialPluginAgentModeKey,this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.threadContext=A.threadContext,this.draftThreadSettings=A.draftThreadSettings,this.editorController=A.editorController,this.editorFocusNode=A.editorFocusNode,this.history=A.history,this.updateDraftThreadSettings=A.updateDraftThreadSettings,this.onNewThread=A.onNewThread,this.sendFeedbackReport=A.sendFeedbackReport,this.archiveThread=A.archiveThread,this.addThreadLabel=A.addThreadLabel,this.removeThreadLabel=A.removeThreadLabel,this.configService=A.configService,this.hints=A.hints,this.ideStatus=A.ideStatus,this.statusItems=A.statusItems??[],this.pluginConfirmationBlocked=A.pluginConfirmationBlocked,this.notificationService=A.notificationService,this.notice=A.notice,this.onDismissNotice=A.onDismissNotice}createState(){return new CR4}}class CR4 extends c0{agentMode;pluginAgentModes=[];selectedPluginAgentMode=null;pluginAgentModesSubscription=null;copyOnSelectEnabled=!0;copyOnSelectSubscription=null;expansion=new Xd0;previousThreadIDForReference=null;unregisterCommands=null;configSettingsForReasoning={};currentGitBranch=null;useLocalEnvironmentFallbackForActiveThread=!1;fastModeToastID=null;statusMessage=null;statusMessageTimer=null;isEditorUploadLocked=!1;initState(){this.agentMode=this.widget.initialAgentMode,this.subscribeToPluginAgentModes(),this.applyInitialPluginAgentMode(),this.subscribeToCopyOnSelectEnabled(),this.updateGitBranch()}applyInitialPluginAgentMode(){if(!this.widget.initialPluginAgentModeKey||this.widget.threadContext)return;this.selectedPluginAgentMode=this.pluginAgentModes.find((A)=>A.key===this.widget.initialPluginAgentModeKey)??null}didUpdateWidget(A){if(A.configService!==this.widget.configService)this.subscribeToCopyOnSelectEnabled();if(HQ.of(this.context).pluginService!==HQ.of(this.context).pluginService)this.subscribeToPluginAgentModes();if(A.threadContext?.client!==this.widget.threadContext?.client)if(this.isEditorUploadLocked=!1,!this.widget.threadContext)this.previousThreadIDForReference=A.threadContext?.client.getThreadId()??null,this.useLocalEnvironmentFallbackForActiveThread=!0;else this.previousThreadIDForReference=null,this.useLocalEnvironmentFallbackForActiveThread=A.threadContext===null}dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.copyOnSelectSubscription?.unsubscribe(),this.copyOnSelectSubscription=null,this.pluginAgentModesSubscription?.unsubscribe(),this.pluginAgentModesSubscription=null,this.statusMessageTimer)clearTimeout(this.statusMessageTimer),this.statusMessageTimer=null}updateGitBranch=async()=>{let A=HQ.of(this.context).workspaceRoot,Q=await KF6(A);if(!this.mounted)return;this.setState(()=>{this.currentGitBranch=Q})};subscribeToPluginAgentModes(){this.pluginAgentModesSubscription?.unsubscribe(),this.pluginAgentModesSubscription=null;let A=HQ.of(this.context).pluginService?.agentModes;if(!A){this.syncPluginAgentModes([]);return}this.syncPluginAgentModes(A.list()),this.pluginAgentModesSubscription=A.changed.subscribe({next:()=>this.syncPluginAgentModes(A.list())})}syncPluginAgentModes(A){this.setState(()=>{if(this.pluginAgentModes=A,this.selectedPluginAgentMode&&!A.some((Q)=>Q.key===this.selectedPluginAgentMode?.key))this.selectedPluginAgentMode=null}),this.refreshCommands()}refreshCommands(){this.unregisterCommands?.(),this.unregisterCommands=this.registerCommands()}registerCommands(){let A=eB.of(this.context),Q=HQ.of(this.context),$=this,B=()=>{return $.widget.threadContext??null},E=()=>{let Z=$.widget.threadContext?.client.getThreadId();if(!Z)return null;return dG(new URL(Q.ampURL),Z).toString()},D=lG(void 0,{isInternalUser:Q.isInternalUser}).map(({mode:Z})=>({noun:"mode",verb:`use ${Z}`,description:`Enable ${Z} mode`,get status(){if($.widget.threadContext)return{type:"hidden"};if(Z===$.agentMode)return{type:"disabled",reason:`Already using ${Z} mode`};return{type:"enabled"}},run:(F,X,I)=>{$.setAgentMode(Z),I()}})),J=this.pluginAgentModes.map((Z)=>({noun:"mode",verb:`use ${Z.label}`,description:Z.description??`Enable ${Z.label} mode`,get status(){if($.widget.threadContext)return{type:"hidden"};if(Z.key===$.selectedPluginAgentMode?.key)return{type:"disabled",reason:`Already using ${Z.label} mode`};return{type:"enabled"}},run:(F,X,I)=>{$.setPluginAgentMode(Z),I()}})),Y=[...D,...J,{noun:"speed",get verb(){if($.isFastSpeedEnabled())return"disable fast";let Z=$.speedCostMultiplierLabel();return Z?`use fast (${Z} cost)`:"use fast"},description:"Toggle fast speed for this thread",get status(){return $.speedToggleCommandStatus()},run:(Z,F,X)=>{$.toggleSpeed(),X()}},{noun:"thread",verb:"toggle details",description:"Expand or collapse tool and activity details",keywords:["expand","thinking"],shortcut:HA.alt("t"),status:{type:"enabled"},run:(Z,F,X)=>{$.toggleWorkDetails(),X()}},{noun:"mode",verb:"toggle reasoning effort",description:"Cycle reasoning effort for the active model",shortcut:HA.alt("d"),get status(){if($.widget.threadContext)return{type:"hidden"};return nC($.currentCommandAgentMode())?{type:"enabled"}:{type:"hidden"}},run:(Z,F,X)=>{$.toggleReasoningEffort(),X()}},{noun:"thread",verb:"copy ID",description:"Copy thread ID to clipboard",get status(){return $.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(Z,F,X)=>{let I=B()?.client.getThreadId();if(!I)return;N4.maybeInvoke(F,new ZB(I,"Thread ID copied to clipboard","Failed to copy thread ID")),X()}},{noun:"thread",verb:"copy URL",description:"Copy thread URL to clipboard",keywords:["share"],get status(){return $.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(Z,F,X)=>{let I=E();if(!I)return;N4.maybeInvoke(F,new ZB(I,"Thread URL copied to clipboard","Failed to copy thread URL")),X()}},{noun:"thread",verb:"copy markdown",description:"Copy thread as Markdown",get status(){return $.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(Z,F,X)=>{let I=B()?.client.getThreadId();if(!I)return;(async()=>{try{let G=await Q.getThreadMarkdown(I);if(!G){EQ.error(F,"Failed to copy thread markdown");return}N4.maybeInvoke(F,new ZB(G,"Thread markdown copied to clipboard","Failed to copy thread markdown"))}catch(G){S.error("Failed to render thread markdown from Neo command palette",{error:G,threadID:I}),EQ.error(F,"Failed to copy thread markdown")}finally{X()}})()}},{noun:"thread",verb:"analyze context",description:"Show token usage by prompt section for this thread",keywords:["tokens"],get status(){return $.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(Z,F,X)=>{let I=B()?.client.getThreadId();if(!I)return;Z.push(new Mc0({threadID:I,analyzeContext:$.widget.analyzeContextForThread,onDismiss:X}))}},{noun:"skills",verb:"list",description:"List available skills for this thread",get status(){return{type:"enabled"}},run:(Z,F,X)=>{let I=B()?.client.getThreadId();if(!I){Z.push(new m90({status:{kind:"no-thread"},onDismiss:X,cwd:Q.workspaceRoot}));return}Z.push(new pc0({listSkills:(G)=>$.widget.listSkillsForThread(I,G),onDismiss:X,cwd:Q.workspaceRoot}))}},{noun:"thread",verb:"new",description:"Start new thread",keywords:["create","start"],sortBoost:101,get status(){if($.isEditorUploadLocked)return{type:"disabled",reason:"Prompt editor is not available"};return $.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"Already on a new thread"}},run:(Z,F)=>{if($.isEditorUploadLocked)return;N4.maybeInvoke(F,new Xl)}},{noun:"thread",verb:"open in browser",description:"Open thread in browser",keywords:["web"],get status(){return $.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(Z,F,X)=>{let I=E();if(!I)return;try{await t6(F,I)}finally{X()}}},VR4({sendFeedbackReport:(Z)=>{return this.widget.sendFeedbackReport(Z)}},B),_j4({archiveThread:(Z)=>this.widget.archiveThread(Z)},B),FR4(B),BR4({configService:this.widget.configService,addLabel:(Z,F)=>this.widget.addThreadLabel(Z,F)},B),JR4({configService:this.widget.configService,removeLabel:(Z,F)=>this.widget.removeThreadLabel(Z,F)},B)].map((Z)=>A.register(Z));return()=>{for(let Z of Y)Z()}}currentCommandAgentMode(){if(this.selectedPluginAgentMode&&!this.widget.threadContext)return this.agentMode;return this.widget.threadContext?.observer.agentMode??this.agentMode}currentThreadSettings(){return this.widget.threadContext?.observer.threadSettings().getValue()??this.widget.draftThreadSettings}currentCommandSpeedModel(){if(this.selectedPluginAgentMode&&!this.widget.threadContext)return this.selectedPluginAgentMode.agent.model;return _$(this.currentCommandAgentMode())?.primaryModel}currentCommandModeLabel(){if(this.selectedPluginAgentMode&&!this.widget.threadContext)return this.selectedPluginAgentMode.label;return this.currentCommandAgentMode()}currentSpeedSettingKey(){let A=this.currentCommandSpeedModel();return A?C50(A):void 0}speedCostMultiplierLabel(){let A=this.currentCommandSpeedModel();return A?Py0(A):void 0}isFastSpeedEnabled(){let A=this.currentSpeedSettingKey();return A!==void 0&&this.currentThreadSettings()[A]==="fast"}speedToggleCommandStatus(){if(this.currentSpeedSettingKey()===void 0)return{type:"hidden"};return{type:"enabled"}}updateThreadSettings(A){let Q=this.widget.threadContext;if(Q){let $=Q.observer.threadSettings().getValue()??{},B=A($);return Q.client.sendClientUpdateThreadSettings(B),this.widget.updateDraftThreadSettings(()=>B),"handled"}return this.widget.updateDraftThreadSettings(A),"handled"}toggleSpeed(){return this.setSpeed(this.isFastSpeedEnabled()?"normal":"fast")}setSpeed(A){let Q=this.currentSpeedSettingKey();if(Q===void 0)return"ignored";let $=A==="normal"?"standard":"fast",B=this.updateThreadSettings((E)=>{return{...E,[Q]:$}});if(!(this.selectedPluginAgentMode&&!this.widget.threadContext))this.rememberSpeedForMode(this.currentCommandAgentMode(),$);if(A==="fast")this.showFastModeToast();return B}showFastModeToast(){let A=EQ.maybeOf(this.context);if(!A)return;if(this.fastModeToastID!==null)A.dismiss(this.fastModeToastID);let Q=this.currentCommandModeLabel(),$=this.speedCostMultiplierLabel()??"2.5x";this.fastModeToastID=A.show(`↯${Q} costs ${$} the standard rate for this mode`,"warning",XF6)}dismissFastModeToast(){if(this.fastModeToastID===null)return;EQ.maybeOf(this.context)?.dismiss(this.fastModeToastID),this.fastModeToastID=null}toggleWorkDetails(){return this.expansion.toggle(!1),"handled"}rememberReasoningEffortForMode(A,Q){let $=HQ.of(this.context);$.lastReasoningEffortByMode={...$.lastReasoningEffortByMode??{},[A]:Q}}rememberSpeedForMode(A,Q){let $=HQ.of(this.context);$.lastSpeedByMode={...$.lastSpeedByMode??{},[A]:Q}}applyStickySpeedForMode(A,Q){let $=Yq(Q),B=H50(HQ.of(this.context),Q);if($===void 0||B===void 0)return A;return{...A,[$]:B}}toggleReasoningEffort(){if(this.selectedPluginAgentMode&&!this.widget.threadContext)return"ignored";let A=this.currentCommandAgentMode(),Q=nC(A);if(!Q)return"ignored";return this.updateThreadSettings(($)=>{let B=vy0(A,$,this.configSettingsForReasoning),E=gbA(Q,B);return this.rememberReasoningEffortForMode(A,E),{...$,"reasoning.effort":E}})}onPromptSubmitted=(A)=>{this.widget.history.add(A,FF6.cwd()),this.resetHistory()};handleEditorUploadLockChange=(A)=>{if(this.isEditorUploadLocked===A)return;this.setState(()=>{this.isEditorUploadLocked=A})};resetHistory(){this.widget.history.reset()}setAgentMode=(A)=>{if(this.widget.threadContext)return;if(A!==this.agentMode)this.dismissFastModeToast();this.setState(()=>{this.agentMode=A,this.selectedPluginAgentMode=null}),this.widget.updateDraftThreadSettings((Q)=>{let $=jy0(HQ.of(this.context),A),B={...Q};delete B["reasoning.effort"];let E=$??vy0(A,B,this.configSettingsForReasoning);if(E===void 0){let D={...Q};return delete D["reasoning.effort"],this.applyStickySpeedForMode(D,A)}return this.applyStickySpeedForMode({...Q,"reasoning.effort":E},A)})};setPluginAgentMode=(A)=>{if(this.widget.threadContext)return;this.dismissFastModeToast(),this.setState(()=>{this.selectedPluginAgentMode=A})};buildActions(){let A=new pA((B)=>{return this.setAgentMode(B.mode),"handled"}),Q=new pA(()=>{return this.toggleReasoningEffort()}),$=new pA(()=>{return this.toggleWorkDetails()});return new Map([[lh0,A],[_q,Q],[g70,$]])}build(A){let Q=this.widget.threadContext,$=HQ.of(A),B=WR4(this.selectedPluginAgentMode?.color),E=zF6($.workspaceRoot,this.currentGitBranch),J=[Q?new wc0({editorController:this.widget.editorController,editorFocusNode:this.widget.editorFocusNode,copyOnSelectEnabled:this.copyOnSelectEnabled,observingClient:{client:Q.client,observer:Q.observer,agentModeDisplay:Q.agentModeDisplay},hints:this.widget.hints,ideStatus:this.widget.ideStatus,statusItems:this.widget.statusItems,pluginConfirmationBlocked:this.widget.pluginConfirmationBlocked,onPromptSubmitted:this.onPromptSubmitted,onEditorUploadLockChange:this.handleEditorUploadLockChange,editorUploadLocked:this.isEditorUploadLocked,notificationService:this.widget.notificationService??IF6,environmentFallback:this.useLocalEnvironmentFallbackForActiveThread?E:null}):new mc0({agentMode:this.agentMode,pluginAgentModes:this.pluginAgentModes,selectedPluginAgentMode:this.selectedPluginAgentMode,agentModeLabel:this.selectedPluginAgentMode?.label,pluginAgentModeURI:this.selectedPluginAgentMode?.sourceURI,agentModeColor:GF6(this.selectedPluginAgentMode?.color),splashPrimaryColor:B?VF6(B):void 0,splashSecondaryColor:B,threadSettings:this.widget.draftThreadSettings,configSettings:this.configSettingsForReasoning,editorController:this.widget.editorController,editorFocusNode:this.widget.editorFocusNode,visibility:null,onNewThread:this.widget.onNewThread,onAgentModeChange:this.setAgentMode,onPluginAgentModeChange:this.setPluginAgentMode,onEditorUploadLockChange:this.handleEditorUploadLockChange,editorUploadLocked:this.isEditorUploadLocked,previousThreadIDForReference:this.previousThreadIDForReference,hints:this.widget.hints,ideStatus:this.widget.ideStatus,statusItems:this.widget.statusItems,configService:this.widget.configService,environment:E,notice:this.widget.notice??null,onDismissNotice:this.widget.onDismissNotice??(()=>{}),statusMessage:this.statusMessage})],U=new Map([[HA.alt("t"),new g70]]);return new N4({actions:this.buildActions(),child:new pQ({debugLabel:"ThreadShortcuts",shortcuts:U,child:new xv({history:this.isEditorUploadLocked?void 0:this.widget.history,child:new zJ({controller:this.expansion,child:new QQ({children:J})})})})})}subscribeToCopyOnSelectEnabled(){this.copyOnSelectSubscription?.unsubscribe(),this.copyOnSelectSubscription=this.widget.configService.config.subscribe((A)=>{let Q=A.settings["terminal.copyOnSelect"]??!0,$=A.settings["internal.model"],B=this.configSettingsForReasoning["internal.model"]!==$;if($===void 0)this.configSettingsForReasoning={};else this.configSettingsForReasoning={"internal.model":$};if(this.copyOnSelectEnabled===Q&&!B)return;if(this.copyOnSelectEnabled=Q,this.mounted)this.setState()})}}a0();d8();J4();class QI extends G4{direction;constructor(A){super();this.direction=A}}class d90 extends G4{}class zi extends G4{}class c90 extends G4{index;constructor(A){super();this.index=A}}function ic0(A){return A.length+2}class nc0 extends p0{props;constructor(A){super();this.props=A}createState(){return new HR4}}class HR4 extends c0{selectedIndex=0;initState(){super.initState(),this.selectedIndex=this.findSelectableIndex(this.widget.props.initialSelectedIndex??0)}didUpdateWidget(A){this.selectedIndex=this.findSelectableIndex(this.selectedIndex)}isSelectable(A){let Q=this.widget.props.entries[A];return Q?.type==="item"&&(Q.enabled??!0)}findSelectableIndex(A){let{entries:Q}=this.widget.props;if(Q.length===0)return 0;let $=Math.max(0,Math.min(A,Q.length-1));if(this.isSelectable($))return $;for(let B=1;B<Q.length;B++){let E=$+B;if(E<Q.length&&this.isSelectable(E))return E;let D=$-B;if(D>=0&&this.isSelectable(D))return D}return 0}moveSelection(A){let Q=this.findNextSelectableIndex(A);if(Q===this.selectedIndex)return;this.setState(()=>{this.selectedIndex=Q})}findNextSelectableIndex(A){let{entries:Q}=this.widget.props;for(let $=this.selectedIndex+A;$>=0&&$<Q.length;$+=A)if(this.isSelectable($))return $;return this.selectedIndex}acceptIndex(A){let Q=this.widget.props.entries[A];if(Q?.type!=="item"||!(Q.enabled??!0))return;this.setState(()=>{this.selectedIndex=A}),this.widget.props.onAccept(Q.value)}invoke=(A)=>{if(A instanceof QI)return this.moveSelection(A.direction),"handled";if(A instanceof d90)return this.acceptIndex(this.selectedIndex),"handled";if(A instanceof zi)return this.widget.props.onDismiss(),"handled";if(A instanceof c90)return this.acceptIndex(A.index),"handled";return"ignored"};buildShortcuts(){let A=new Map([[HA.key("ArrowDown"),new QI(1)],[HA.key("j"),new QI(1)],[HA.ctrl("n"),new QI(1)],[HA.key("ArrowUp"),new QI(-1)],[HA.key("k"),new QI(-1)],[HA.ctrl("p"),new QI(-1)],[HA.key("Enter"),new d90],[HA.key("Escape"),new zi],[HA.ctrl("."),new zi]]);return this.widget.props.entries.forEach((Q,$)=>{if(Q.type==="item"&&Q.shortcut)A.set(Q.shortcut,new c90($))}),A}buildActions(){return new Map([[QI,new pA(this.invoke)],[d90,new pA(this.invoke)],[zi,new pA(this.invoke)],[c90,new pA(this.invoke)]])}build(A){let Q=EA.of(A),$=WF6(this.widget.props.entries,W4.of(A).supportsEmojiWidth);return new WA({width:this.widget.props.width,height:ic0(this.widget.props.entries),decoration:new c1(Q.colors.background,W1.all(new C1(Q.colors.border,1,"solid"))),child:new N4({actions:this.buildActions(),child:new pQ({debugLabel:"ContextPickerShortcuts",shortcuts:this.buildShortcuts(),child:new cQ({autofocus:!0,debugLabel:"ContextPicker",child:new IA({mainAxisSize:"min",crossAxisAlignment:"stretch",children:this.widget.props.entries.map((B,E)=>this.buildEntry(B,E,$,Q))})})})})})}buildEntry(A,Q,$,B){if(A.type==="separator")return new WA({height:1,decoration:{border:new W1(new C1(B.colors.border,1,"solid"))}});let E=Q===this.selectedIndex,D=A.enabled??!0,J=new $0({color:E?B.app.selectionForeground:B.colors.foreground,dim:!D}),U=new $0({color:E?B.app.selectionForeground:B.app.keybind,bold:!0,dim:!D});return new iA({onClick:()=>this.acceptIndex(Q),child:new WA({padding:n0.symmetric(1,0),decoration:E?new c1(B.app.selectionBackground):void 0,child:new LA({crossAxisAlignment:"start",children:[new L4({child:new D0({text:new h(A.label,J),maxLines:1,overflow:"ellipsis"})}),new y0({width:1}),new y0({width:$,child:new D0({text:new h(NR4(A),U),textAlign:"right",maxLines:1,overflow:"ellipsis"})})]})})})}}function WF6(A,Q){return A.reduce(($,B)=>{return B.type==="item"?Math.max($,cA(NR4(B),Q)):$},0)}function NR4(A){return A.shortcutLabel??A.shortcut?.toString().toLowerCase()??""}var CF6=36,HF6=24,NF6=72;class qR4 extends p0{child;onContext;constructor(A,Q){super();this.child=A;this.onContext=Q}createState(){return new uR4}}class uR4 extends c0{build(A){return this.widget.onContext(A),this.widget.child}}function wR4(A){if(A==="Just now")return"1m";return A.replace(/ ago$/,"")}function qF6(A){return A.reduce((Q,$)=>Math.max(Q,cA(wR4($.description.timeAgo))),0)}function MR4(A){return Math.max(HF6,Math.min(A,NF6))}class ac0 extends G4{}class oc0 extends G4{}class rc0 extends G4{}class sc0{options;focusScopeNode=new B8({debugLabel:"ThreadListSidebar"});initialized=!1;visible=!1;hasRenderedSidebar=!1;width=CF6;pickerController=new tp;constructor(A){this.options=A}isVisible(){return this.ensureInitialized(),this.visible}visibleWidth(){return this.isVisible()?this.width:0}buildBody(A){return new LA({crossAxisAlignment:"stretch",children:[this.buildSlot(),new L4({child:A})]})}buildSlot(){let A=this.isVisible();if(!this.hasRenderedSidebar)return new y0({width:0});let Q={activeThreadID:this.options.getActiveThreadID(),currentWorkspaceURI:$4(m0.file(this.options.getWorkspaceRoot())),width:this.width,loadThreads:this.options.loadThreads,pickerController:this.pickerController,onSelectThread:this.options.onSelectThread,onDismiss:this.close,onResizeWidth:this.resize};if(this.options.observeThreadSummaries)Q.observeThreadSummaries=this.options.observeThreadSummaries;return new y0({width:A?this.width:0,child:new c6({focusScopeNode:this.focusScopeNode,debugLabel:"ThreadListSidebar",onFocusChange:this.handleFocusChange,child:new OR4(Q)})})}commands(){return[{noun:"thread",verb:"toggle sidebar",description:"Show or hide the thread sidebar",shortcut:HA.alt("s"),status:{type:"enabled"},run:(A,Q,$)=>{$(),this.toggleVisibility()}}]}shortcutEntries(){return[[HA.alt("s"),new d70]]}actionEntries(){return[[d70,new pA(()=>this.toggleFromShortcut())]]}toggleFromShortcut=()=>{if(this.isVisible()){if(this.focusScopeNode.hasFocus)return this.close(),"handled";if(this.options.isBlocked())return"ignored";return this.pickerController.requestFocus(),"handled"}if(this.options.isBlocked())return"ignored";return this.pickerController.requestFocus(),this.setVisible(!0),"handled"};toggleVisibility=()=>{if(this.isVisible()){this.close();return}if(this.options.isBlocked())return;this.pickerController.requestFocus(),this.setVisible(!0)};close=()=>{this.options.focusMainContent(),this.setVisible(!1)};setVisible(A){if(this.ensureInitialized(),this.visible===A)return;if(A)this.hasRenderedSidebar=!0;this.options.state.setState(()=>{this.visible=A}),JJ((Q)=>({...Q,threadListSidebarVisible:A})).catch((Q)=>{S.warn("Failed to save thread sidebar visibility state",{error:Q instanceof Error?Q.message:String(Q)})})}ensureInitialized(){if(this.initialized)return;this.initialized=!0,this.visible=this.options.getInitialVisible(),this.hasRenderedSidebar=this.visible}handleFocusChange=(A)=>{this.options.state.setState()};dispose(){this.focusScopeNode.dispose()}resize=(A)=>{let Q=MR4(A);if(Q===this.width)return;this.options.state.setState(()=>{this.width=Q})}}class OR4 extends p0{props;constructor(A){super();this.props=A}createState(){return new LR4}}class LR4 extends c0{threads=[];isLoading=!0;isSwitchingThread=!1;hasError=!1;filterByWorkspace=!0;contextMenu=null;pendingThreadMutations=new Map;canonicalThreadSummariesByID=new Map;archivedCanonicalThreadIDs=new Set;liveThreadSummaries=null;resizeSession=null;isResizeHandleHovered=!1;threadItemContexts=new Map;threadSummarySubscription=null;observedThreadSummaries;shortcuts=new Map([[HA.alt("w"),new ac0],[HA.ctrl("."),new oc0],[HA.key("e"),new rc0]]);actions=new Map([[ac0,new pA(()=>{return this.setState(()=>{this.filterByWorkspace=!this.filterByWorkspace,this.contextMenu=null}),"handled"})],[oc0,new pA(()=>this.openContextMenu())],[rc0,new pA(()=>this.archiveSelectedThread())]]);get isBusy(){return this.isLoading}get isResizeActive(){return this.resizeSession!==null||this.isResizeHandleHovered}didUpdateWidget(A){if(super.didUpdateWidget(A),this.contextMenu&&(A.props.width!==this.widget.props.width||A.props.currentWorkspaceURI!==this.widget.props.currentWorkspaceURI))this.contextMenu=null;if(A.props.observeThreadSummaries!==this.widget.props.observeThreadSummaries)this.startThreadSummaryUpdates()}initState(){super.initState(),this.startThreadSummaryUpdates()}dispose(){this.threadSummarySubscription?.unsubscribe(),this.threadSummarySubscription=null,super.dispose()}startThreadSummaryUpdates(){this.threadSummarySubscription?.unsubscribe(),this.threadSummarySubscription=null,this.liveThreadSummaries=null,this.observedThreadSummaries=this.widget.props.observeThreadSummaries;let A=this.widget.props.observeThreadSummaries;if(!A){this.loadThreadSummaries();return}let Q=A();if(!Q){this.loadThreadSummaries();return}this.loadThreadSummaries(),this.threadSummarySubscription=Q.subscribe({next:($)=>this.applyLiveThreadSummaries($),error:($)=>{if(S.error("Failed to observe threads for Neo sidebar",{error:$}),!this.mounted)return;this.setState(()=>{this.isLoading=!1,this.hasError=!0})}})}async loadThreadSummaries(){let A=this.observedThreadSummaries;try{let Q=await this.widget.props.loadThreads(),$=nd0(Q);if(!this.mounted||A!==this.observedThreadSummaries)return;this.archivedCanonicalThreadIDs.clear();for(let B of Q)if(B.archived)this.archivedCanonicalThreadIDs.add(B.id);this.applyCanonicalThreadSummaries($)}catch(Q){if(S.error("Failed to load threads for Neo sidebar",{error:Q}),!this.mounted)return;this.setState(()=>{this.isLoading=!1,this.hasError=!0})}}applyCanonicalThreadSummaries(A){this.canonicalThreadSummariesByID.clear();for(let Q of A)this.canonicalThreadSummariesByID.set(Q.id,Q);this.applyThreadSummaries(this.liveThreadSummaries?this.mergeLiveMetadata():A)}applyLiveThreadSummaries(A){this.liveThreadSummaries=A;let Q=this.mergeLiveMetadata();if(Q.length===0&&this.canonicalThreadSummariesByID.size===0&&this.isLoading)return;this.applyThreadSummaries(Q)}mergeLiveMetadata(){let A=new Map((this.liveThreadSummaries??[]).map((B)=>[B.id,B])),Q=(this.liveThreadSummaries??[]).flatMap((B)=>{if(this.archivedCanonicalThreadIDs.has(B.id))return[];let E=this.canonicalThreadSummariesByID.get(B.id);if(!E){if(!B.updatedAt)return[];return[B]}return[this.mergeLiveThreadSummary(E,B)]}),$=Array.from(this.canonicalThreadSummariesByID.values()).filter((B)=>!A.has(B.id));return[...Q,...$]}mergeLiveThreadSummary(A,Q){return{...A,...Q,updatedAt:Q.updatedAt??A.updatedAt,description:Q.updatedAt?Q.description:A.description,workspaceURI:A.workspaceURI,relationships:A.relationships,diffStats:A.diffStats,agentMode:A.agentMode,details:A.details,archived:A.archived}}applyThreadSummaries(A){if(!this.mounted)return;this.setState(()=>{let Q=this.widget.props.pickerController.selectedItem?.id??this.widget.props.activeThreadID;this.widget.props.pickerController.selectedItem=A.find(($)=>$.id===Q)??A.find(($)=>$.id===this.widget.props.activeThreadID)??null,this.threads=A,this.isLoading=!1,this.hasError=!1})}handleSelectThread=async(A)=>{if(this.isSwitchingThread)return;this.setState(()=>{this.isSwitchingThread=!0});try{await this.widget.props.onSelectThread(A)}catch(Q){S.error("Failed to switch thread from Neo sidebar",{error:Q,threadID:A})}finally{if(this.mounted)this.setState(()=>{this.isSwitchingThread=!1})}};getOptimisticThreads(){return this.threads.flatMap((A)=>{if(this.pendingThreadMutations.get(A.id)?.kind==="archive")return[];return[A]})}getThreadsForDisplay(){let A=this.getOptimisticThreads();return this.filterByWorkspace?A.filter((Q)=>!Q.workspaceURI||Q.workspaceURI===this.widget.props.currentWorkspaceURI):A}buildContextMenuEntries(){return[{type:"item",value:"archive",label:"Archive Thread",shortcut:HA.key("a"),shortcutLabel:"a"},{type:"separator"},{type:"item",value:"copy-id",label:"Copy ID",shortcut:HA.ctrl("c"),shortcutLabel:"ctrl+c"},{type:"item",value:"copy-url",label:"Copy URL",shortcut:new HA("c",{shift:!0,ctrl:!0}),shortcutLabel:"shift+ctrl+c"}]}openContextMenu(){let A=this.widget.props.pickerController.selectedItem;if(!A||this.isBusy||this.isSwitchingThread||this.hasError)return"ignored";let Q=this.buildContextMenuEntries(),$=ic0(Q),B=this.getContextMenuWidth(),E=this.getContextMenuPosition(A.id,$,B);return this.setState(()=>{this.contextMenu={threadID:A.id,left:E.left,top:E.top,width:B,height:$}}),"handled"}archiveSelectedThread(){let A=this.widget.props.pickerController.selectedItem?.id;if(!A||this.contextMenu||this.isBusy||this.isSwitchingThread||this.hasError)return"ignored";return this.archiveThread(A),"handled"}getContextMenuWidth(){let A=Math.max(24,this.widget.props.width-3);return Math.max(1,Math.min(A,this.widget.props.width-2))}getContextMenuPosition(A,Q,$){let B=Math.max(0,Math.min(2,this.widget.props.width-$)),E=1,D=this.threadItemContexts.get(A)?.findRenderObject(),J=this.context.findRenderObject();if(!(D instanceof bA)||!(J instanceof bA))return{left:B,top:1};let U=D.localToGlobal({x:0,y:0}),Y=J.localToGlobal({x:0,y:0}),Z=U.y-Y.y,F=Z+D.size.height,X=W4.sizeOf(this.context).height,I=Math.max(1,Math.min(J.size.height,X-Y.y)),K=I-F>=Q||Z<I/2?F:Z-Q,z=Math.max(0,I-Q);return{left:B,top:Math.max(0,Math.min(K,z))}}closeContextMenu=()=>{if(!this.contextMenu)return;this.setState(()=>{this.contextMenu=null})};handleContextMenuAccept=(A)=>{let Q=this.contextMenu?.threadID;if(!Q)return;if(this.closeContextMenu(),A==="archive"){this.archiveThread(Q);return}if(A==="copy-id"){N4.maybeInvoke(this.context,new ZB(Q,"Thread ID copied to clipboard","Failed to copy thread ID"));return}N4.maybeInvoke(this.context,new ZB(this.getThreadURL(Q),"Thread URL copied to clipboard","Failed to copy thread URL"))};beginOptimisticArchive(A){if(this.pendingThreadMutations.has(A))return!1;if(!this.threads.some(($)=>$.id===A))return!1;let Q={kind:"archive",fallbackSelectedThreadID:null};return this.setState(()=>{this.pendingThreadMutations.set(A,Q)}),z6.instance.addPostFrameCallback(()=>{if(!this.mounted)return;let $=this.pendingThreadMutations.get(A);if($?.kind!=="archive")return;$.fallbackSelectedThreadID=this.widget.props.pickerController.selectedItem?.id??null}),!0}commitOptimisticArchive(A){if(this.pendingThreadMutations.get(A)?.kind!=="archive")return;this.pendingThreadMutations.delete(A),this.canonicalThreadSummariesByID.delete(A),this.threads=this.threads.filter(($)=>$.id!==A)}rollbackOptimisticArchive(A){let Q=this.pendingThreadMutations.get(A);if(Q?.kind!=="archive")return;let $=this.threads.find((B)=>B.id===A);if(!$){this.pendingThreadMutations.delete(A);return}this.setState(()=>{this.pendingThreadMutations.delete(A);let B=this.widget.props.pickerController.selectedItem?.id??null;if(B===null||B===Q.fallbackSelectedThreadID)this.widget.props.pickerController.selectedItem=$})}async archiveThread(A){let Q=EQ.maybeOf(this.context),{configService:$}=HQ.of(this.context);if(!this.beginOptimisticArchive(A))return;try{let B=await H70({configService:$},A);if(!this.mounted)return;if(B){this.rollbackOptimisticArchive(A),Q?.show(B.message,"error");return}this.commitOptimisticArchive(A),Q?.show("Archived thread")}catch(B){if(S.error("Failed to archive thread from Neo sidebar context menu",{error:B,threadID:A}),!this.mounted)return;this.rollbackOptimisticArchive(A),Q?.show("Failed to archive thread","error")}}getThreadURL(A){return dG(new URL(HQ.of(this.context).ampURL),A).toString()}buildContextMenuOverlay(){let A=this.contextMenu;if(!A||!this.getThreadsForDisplay().some((Q)=>Q.id===A.threadID))return null;return new r1({left:A.left,top:A.top,width:A.width,height:A.height,child:new c6({debugLabel:"ThreadListSidebarContextMenu",onFocusChange:(Q)=>{if(!Q)this.closeContextMenu()},child:new nc0({entries:this.buildContextMenuEntries(),width:A.width,onAccept:this.handleContextMenuAccept,onDismiss:this.closeContextMenu})})})}buildContextMenuBackdrop(){return new r1({left:0,top:0,right:0,bottom:0,child:new iA({onClick:()=>this.closeContextMenu(),child:y0.expand()})})}buildThreadItem(A,Q,$,B){let E=EA.of(B),{app:D,colors:J}=E,U=A.id===this.widget.props.activeThreadID,Y=!Q&&!U,Z=Q?D.selectionForeground:J.foreground,F=Q?D.selectionForeground:J.mutedForeground,I=A.agentState!==void 0&&A.agentState!=="idle"?new eX({color:Q?D.selectionForeground:J.primary}):void 0,G=wR4(A.description.timeAgo);return new qR4(new WA({padding:n0.symmetric(1,0),child:new LA({children:[new y0({width:2,child:I}),new L4({child:new D0({text:new h(A.title,new $0({color:Z,dim:Y})),overflow:"ellipsis",maxLines:1})}),new y0({width:2}),new y0({width:$,child:LA.end([new D0({text:new h(G,new $0({color:F,dim:Y}))})])})]})}),(V)=>{this.threadItemContexts.set(A.id,V)})}handleResizeHandlePress=(A)=>{if(A.button!=="left")return;this.setState(()=>{this.resizeSession={baseWidthColumns:this.widget.props.width,startColumn:Math.floor(A.position.x)}})};handleResizeHandleDrag=(A)=>{if(A.button!=="left"||this.resizeSession===null)return;let Q=Math.floor(A.position.x)-this.resizeSession.startColumn,$=MR4(this.resizeSession.baseWidthColumns+Q);if($!==this.widget.props.width)this.widget.props.onResizeWidth($)};handleResizeHandleRelease=(A)=>{if(A.button!=="left"||this.resizeSession===null)return;this.setState(()=>{this.resizeSession=null})};handleResizeHandleEnter=()=>{if(this.isResizeHandleHovered)return;this.setState(()=>{this.isResizeHandleHovered=!0})};handleResizeHandleExit=()=>{if(!this.isResizeHandleHovered)return;this.setState(()=>{this.isResizeHandleHovered=!1})};buildResizeHandle(){return new r1({top:0,right:0,bottom:0,width:1,child:new iA({cursor:d1.EW_RESIZE,onClick:this.handleResizeHandlePress,onDrag:this.handleResizeHandleDrag,onRelease:this.handleResizeHandleRelease,onEnter:this.handleResizeHandleEnter,onExit:this.handleResizeHandleExit,child:new y0({width:1})})})}build(A){let Q=EA.of(A),$=this.getThreadsForDisplay(),B=this.hasError?[]:$,E=qF6(B);this.threadItemContexts.clear();let D=this.isResizeActive?2:1,J=new W1(void 0,new C1(Q.colors.border,D),void 0,void 0),U=this.buildContextMenuOverlay(),Y=[new WA({decoration:new c1(Q.colors.background,J),child:new N4({actions:this.actions,child:new pQ({shortcuts:this.shortcuts,debugLabel:"ThreadListSidebarFilter",child:new R5({items:B,getLabel:(Z)=>`${Z.title} ${Z.id}`,controller:this.widget.props.pickerController,autofocus:!1,onAccept:(Z)=>void this.handleSelectThread(Z.id),onDismiss:this.widget.props.onDismiss,renderItem:(Z,F,X,I)=>this.buildThreadItem(Z,F,E,I),enabled:!this.isBusy,isLoading:this.isBusy,hidePrompt:!0,loadingText:"Loading threads...",emptyStateText:this.hasError?"Failed to load threads":void 0,emptyStateWidget:this.hasError?void 0:(Z)=>ld0(Z,this.filterByWorkspace),maxRenderItems:200,showBorder:!1})})})}),this.buildResizeHandle()];if(U)Y.push(this.buildContextMenuBackdrop()),Y.push(U);return new WA({width:this.widget.props.width,child:new QQ({fit:"expand",children:Y})})}}bB();class tc0 extends p0{toolboxes;onDismiss;constructor(A){super();this.toolboxes=A.toolboxes,this.onDismiss=A.onDismiss}createState(){return new RR4}}class RR4 extends c0{toolboxes=new sB(this,[]);initState(){this.toolboxes.subscribe(this.widget.toolboxes)}didUpdateWidget(A){if(A.toolboxes!==this.widget.toolboxes)this.toolboxes.subscribe(this.widget.toolboxes)}build(A){return new PR4({toolboxes:this.toolboxes.getValue(),onDismiss:this.widget.onDismiss})}}class PR4 extends p0{toolboxes;onDismiss;constructor(A){super();this.toolboxes=A.toolboxes,this.onDismiss=A.onDismiss}createState(){return new vR4}}class vR4 extends c0{scrollController=new G$;canScroll=!1;initState(){this.scrollController.followMode=!1,this.scrollController.jumpTo(0),this.scrollController.addListener(this.updateCanScroll)}dispose(){this.scrollController.removeListener(this.updateCanScroll),this.scrollController.dispose()}updateCanScroll=()=>{let A=this.scrollController.maxScrollExtent>0;if(A===this.canScroll)return;this.setState(()=>{this.canScroll=A})};build(A){return new B1({header:"Toolboxes",onDismiss:this.widget.onDismiss,minWidth:80,maxWidth:120,maxHeight:40,autofocus:!1,footer:uF6(this.canScroll),child:new PB({controller:this.scrollController,child:wF6(A,this.widget.toolboxes)})})}}function uF6(A){let Q=[{keys:["Esc"],label:"close"}];if(A)Q.push({keys:["↑↓","j/k"],label:"scroll"});return Q}function wF6(A,Q){let $=MF6(A,Q);return new IA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new D0({text:new h("",void 0,$),selectable:!0})]})}function MF6(A,Q){let $=EA.of(A),{colors:B}=$,E=new $0({color:B.foreground,dim:!0}),D=new $0({color:B.foreground,bold:!0});if(Q.length===0)return[new h("No toolboxes found.",E)];let J=[];for(let U of Q){let Y=U.tools.length,Z=U.tools.filter((F)=>F.status==="registered").length;if(U.discovering){let F=U.tools.filter((X)=>X.status!=="pending").length;J.push(new h(U.path,D)),J.push(new h(` discovering ${F}/${Y}...
|
|
4426
4426
|
`,E))}else if(J.push(new h(U.path,D)),Y>0)J.push(new h(` ${Z}/${Y} ${J1(Y,"tool")}
|
|
4427
4427
|
`,E));else J.push(new h(`
|
|
4428
4428
|
`));if(U.tools.length===0)J.push(new h(` └─ No tools available
|
|
4429
4429
|
`,E));else for(let F of U.tools)OF6(J,F,$);J.push(new h(`
|
|
4430
4430
|
`))}return J}function OF6(A,Q,$){let{colors:B,app:E}=$,D=LF6(Q.status,$);if(A.push(new h(` ${D.icon} `,new $0({color:D.color}))),A.push(new h(Q.name,new $0({color:Q.status==="pending"?B.warning:E.command}))),Q.status==="pending")A.push(new h(" discovering...",new $0({color:B.foreground,dim:!0})));else if(Q.description)A.push(new h(` ${jR4(Q.description,50)}`,new $0({color:B.foreground,dim:!0})));if(Q.error)A.push(new h(` ${jR4(Q.error,40)}`,new $0({color:E.toolError})));A.push(new h(`
|
|
4431
|
-
`))}function LF6(A,Q){let{colors:$,app:B}=Q;switch(A){case"pending":return{icon:"◌",color:$.warning};case"registered":return{icon:"•",color:$.mutedForeground};case"failed":return{icon:"✗",color:B.toolError};case"duplicate":return{icon:"◇",color:$.warning};default:return{icon:"?",color:$.foreground}}}function jR4(A,Q){let $=A.replace(/\s+/g," ").trim();if(cA($)<=Q)return $;let B="...",E=cA(B);if(Q<=E)return Q8(B,Q);return`${Q8($,Q-E,!0,"")}${B}`}var Qp0="https://ampcode.com/news/neo",$p0=[{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:Qp0,href:Qp0}]}];function jF6(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:Qp0,textAfter:" you'll need to switch to the binary install:",linkWidget:!0},"",{codeBlock:["npm uninstall -g @sourcegraph/amp",A]}]}]}function RF6(){if(process.platform==="win32")return'powershell -c "irm https://ampcode.com/install.ps1 | iex"';return"curl -fsSL https://ampcode.com/install.sh | bash"}var hv=50,tq=40,ec0=1000,PF6=420,vF6=760,TF6=-250,_F6=1100,p90=33,TR4=0.999,SF6=2.1,kF6=720,fF6=420,hR4="Meet the new",gR4="Amp",mR4="CLI",Bp0=B4(hR4).length,xF6=B4(gR4).length,yF6=B4(mR4).length,l90={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}},_R4={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},SR4={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}},kR4=[l90,_R4,SR4,l90,_R4,SR4,l90],bF6=l90;class Ep0 extends p0{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??RF6(),this.introStages=this.variant==="npm-migration"?jF6(this.binaryInstallCommand):$p0,this.dismissible=this.variant!=="npm-migration"}createState(){return new dR4}}class dR4 extends c0{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=ec0;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 v5(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=SE(this.widget.animationProgress),this.firstStageTitleVisible=this.animationProgress>=TR4,this.firstStageHintVisible=this.animationProgress>=TR4,this.firstStageTitleRevealProgress=this.firstStageTitleVisible?1:0,this.firstStageHintRevealProgress=this.firstStageHintVisible?1:0;return}if(!this.widget.animationsEnabled){this.stopStageTransitionTimer(),this.stopDismissAnimation(),this.animationProgress=1,this.isDismissing=!1,this.dismissProgress=0,this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1,this.previousIntroStage=null,this.stageTransitionProgress=1;return}if(this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0,this.startProgressAnimation({from:0,to:1,durationMs:ec0,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=SE(A/vF6);if(this.setState(()=>{this.dismissProgress=Q}),Q>=1)this.stopDismissAnimation(),this.widget.onDismiss()},p90)}canNavigateIntroStage(){if(this.isDismissing)return!1;if(!this.firstStageHintVisible)return!1;if(this.introStage===0&&this.firstStageHintRevealProgress<1)return!1;return!0}advanceIntroStage(){if(!this.canNavigateIntroStage())return;if(this.isFinalIntroStage()){if(this.widget.dismissible)this.startDismissAnimation();return}this.moveIntroStage(1)}dismissFromFinalIntroStage(){if(!this.widget.dismissible||!this.canNavigateIntroStage()||!this.isFinalIntroStage())return!1;return this.startDismissAnimation(),!0}nextIntroStage(){if(!this.canNavigateIntroStage()||this.isFinalIntroStage())return;this.moveIntroStage(1)}goToPreviousIntroStage(){if(!this.canNavigateIntroStage()||this.introStage<=0)return;this.moveIntroStage(-1)}isFinalIntroStage(){return this.introStage>=this.widget.introStages.length-1}moveIntroStage(A){let Q=this.introStage+A;if(this.stopStageTransitionTimer(),this.stageTransitionStartedAt=performance.now(),this.setState(()=>{this.previousIntroStage=this.introStage,this.introStage=Q,this.stageTransitionDirection=A}),this.widget.animationProgress!==void 0||!this.widget.animationsEnabled){this.setState(()=>{this.previousIntroStage=null,this.stageTransitionProgress=1});return}this.setState(()=>{this.stageTransitionProgress=0}),this.stageTransitionTimer=setInterval(()=>{let $=performance.now()-this.stageTransitionStartedAt,B=SE($/PF6);if(this.setState(()=>{if(this.stageTransitionProgress=B,B>=1)this.previousIntroStage=null}),B>=1)this.stopStageTransitionTimer()},p90)}startProgressAnimation({from:A,to:Q,durationMs:$,onComplete:B}){this.stopAnimation(),this.startedAt=performance.now(),this.animationStartProgress=A,this.animationTargetProgress=Q,this.animationDurationMs=$,this.onAnimationComplete=B,this.animationProgress=A,this.animationTimer=setInterval(()=>{let E=performance.now()-this.startedAt,D=SE(E/this.animationDurationMs),J=this.animationStartProgress+(this.animationTargetProgress-this.animationStartProgress)*gv(D);if(this.setState(()=>{this.animationProgress=J}),D>=1)this.stopAnimation(),this.onAnimationComplete?.(),this.onAnimationComplete=null},p90)}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,ec0+TF6),Q=A+_F6;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?SE((A-this.firstStageTitleRevealStartedAt)/kF6):this.firstStageTitleRevealProgress,$=this.firstStageHintRevealStartedAt?SE((A-this.firstStageHintRevealStartedAt)/fF6):this.firstStageHintRevealProgress;if(this.setState(()=>{this.firstStageTitleRevealProgress=Q,this.firstStageHintRevealProgress=$}),Q>=1&&$>=1)this.stopFirstStageRevealTimer()},p90)}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=fR4(this.introStage),Q=this.previousIntroStage===null||this.stageTransitionProgress>=1?A:xR4(fR4(this.previousIntroStage),A,gv(this.stageTransitionProgress));return this.dismissProgress>0?xR4(Q,bF6,gv(this.dismissProgress)):Q}build(A){let Q=c4.of(A).colorScheme,$=EA.of(A),B=this.currentOrbPalette(),E=I7(1,"deep",B),D=W4.of(A).size,U=this.widget.animationProgress??this.animationProgress,Y=Math.max(D.width/hv,D.height/tq)*SF6,Z=Y+(1-Y)*U,F=gv(this.dismissProgress),X=Math.max(hv,Math.round(hv*Z)),I=Math.max(tq,Math.round(tq*Z)),G=Math.round((D.width-X)/2),V=Math.round((D.height-I)/2),K=Math.max(0,Math.floor((D.width-hv)/2)),z=-Math.floor(tq/2),W=Math.round(G+(K-G)*U),C=Math.round(V+(z-V)*U),H=W+X/2,N=C+I/2,q=hF6({dismissProgress:this.dismissProgress,easedDismissProgress:F,introOrbScale:Z,normalOrbCenterX:H,normalOrbCenterY:N,size:D}),w=Math.max(hv,Math.round(hv*q.orbScale)),O=Math.max(tq,Math.round(tq*q.orbScale)),R=q.orbCenterX,_=q.orbCenterY,v=Math.round(R-w/2),k=Math.round(_-O/2),m=Math.max(3,Math.min(D.height-5,Math.floor(tq/2)+2)),x=Math.max(m+3,D.height-3),T=q.textDissolveProgress,f=this.isFinalIntroStage()?q.backdropDissolveProgress:0,c=this.firstStageTitleVisible&&T<1,d=c&&this.firstStageHintVisible,b=d&&this.widget.dismissible&&this.introStage>0&&!this.isFinalIntroStage(),p=this.introStage===0?this.firstStageTitleRevealProgress:1,n=this.introStage===0?this.firstStageHintRevealProgress:1,o=Math.max(24,Math.min(74,D.width-4)),I0=Math.min(12,Math.max(8,D.height-m-6)),E0=Math.max(0,Math.floor((D.width-o)/2)),G0=Math.max(0,Math.min(D.height-I0,Math.floor(D.height*0.55-I0/2))),q0=this.widget.animationProgress!==void 0||!this.widget.animationsEnabled?new tK({width:w,height:O,agentMode:"deep",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,seed:42,fps:0,onClick:()=>{}}):new tK({width:w,height:O,agentMode:"deep",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,onClick:()=>{}});return new c6({autofocus:!0,canRequestFocus:!0,debugLabel:"WelcomeTakeover",onKey:(t)=>{if(t.key==="Enter")return this.advanceIntroStage(),"handled";if(!this.widget.dismissible&&t.key==="c"&&t.ctrlKey)return this.widget.onQuit?.(),"handled";if(!this.widget.dismissible&&t.key==="q")return this.widget.onQuit?.(),"handled";if((t.key===" "||t.key==="Space")&&!this.isFinalIntroStage())return this.advanceIntroStage(),"handled";if(t.key==="Escape"||t.key==="Esc"){if(!this.widget.dismissible)return this.widget.onQuit?.(),"handled";return this.dismissFromFinalIntroStage()?"handled":"ignored"}if(t.key==="ArrowRight")return this.nextIntroStage(),"handled";if(t.key==="ArrowLeft")return this.goToPreviousIntroStage(),"handled";return"ignored"},child:new QQ({fit:"expand",children:[new cR4({color:Q.background,dissolveProgress:f}),new QQ({fit:"expand",children:[new iA({onClick:()=>{},child:y0.expand()}),new r1({left:v,top:k,width:w,height:O,child:q0}),...c?[new r1({left:E0,top:G0,width:o,height:I0,child:mF6({introStages:this.widget.introStages,stage:this.introStage,previousStage:this.previousIntroStage,progress:this.stageTransitionProgress,direction:this.stageTransitionDirection,width:o,height:I0,foreground:Q.foreground,mutedForeground:Q.mutedForeground,accent:E,link:$.app.link,keybind:$.app.keybind,titleRevealProgress:p,dissolveProgress:T,context:A})})]:[],...d?[...b?[new r1({left:E0,top:Math.max(0,x-1),width:o,height:1,child:new D0({text:nF6({stage:this.introStage,featureStageCount:Math.max(0,this.widget.introStages.length-2),foreground:Q.mutedForeground,dissolveProgress:T}),textAlign:"center"})})]:[],new r1({left:E0,top:x,width:o,height:1,child:oF6({finalStage:this.isFinalIntroStage(),dismissible:this.widget.dismissible,foreground:Q.mutedForeground,keybind:$.app.keybind,revealProgress:n,dissolveProgress:T,context:A})})]:[]]})]})})}}class cR4 extends YB{color;dissolveProgress;constructor({color:A,dissolveProgress:Q}){super();this.color=A,this.dissolveProgress=Q}createRenderObject(){return new pR4(this.color,this.dissolveProgress)}updateRenderObject(A){A.update(this.color,this.dissolveProgress)}}class pR4 extends bA{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;rA(!!A,"performLayout called without constraints");let Q=A.constrain(A.biggest.width,A.biggest.height);this.setSize(Q.width,Q.height),super.performLayout()}paint(A,Q=0,$=0){let B=Math.floor(Q+this.offset.x),E=Math.floor($+this.offset.y),D=Math.floor(this.size.width),J=Math.floor(this.size.height),U={bg:this.color},Y=SE(this.dissolveProgress);if(Y<=0){A.fill(B,E,D,J," ",U);return}if(Y>=1)return;for(let Z=0;Z<J;Z++)for(let F=0;F<D;F++)if(!gF6(F,Z,D,J,Y))A.fill(B+F,E+Z,1,1," ",U)}}function SE(A){return Math.min(1,Math.max(0,A))}function gv(A){return 1-(1-A)**3}function fR4(A){return kR4[A]??kR4[0]}function xR4(A,Q,$){return{primary:Tq(A.primary,Q.primary,$),secondary:Tq(A.secondary,Q.secondary,$)}}function hF6({dismissProgress:A,easedDismissProgress:Q,introOrbScale:$,normalOrbCenterX:B,normalOrbCenterY:E,size:D}){return{orbScale:$+($*0.86-$)*Q,orbCenterX:B+(D.width*0.54-B)*Q,orbCenterY:E-D.height*0.44*Q,textDissolveProgress:SE(A/0.52),backdropDissolveProgress:gv(SE((A-0.12)/0.88))}}function gF6(A,Q,$,B,E){let D=B<=1?0:Q/(B-1),J=lR4(A+Q*Math.max(1,$));return(1-D)*0.72+J*0.28<E}function mF6({introStages:A,stage:Q,previousStage:$,progress:B,direction:E,width:D,height:J,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V}){if($===null||B>=1)return Ap0({introStages:A,stage:Q,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V});let K=gv(B),z=E*Math.round((1-K)*D),W=-E*Math.round(K*D);return new zq(new QQ({fit:"expand",children:[new r1({left:W,top:0,width:D,height:J,child:Ap0({introStages:A,stage:$,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:$===0?1:I,dissolveProgress:G,context:V})}),new r1({left:z,top:0,width:D,height:J,child:Ap0({introStages:A,stage:Q,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V})})]}))}function Ap0({introStages:A,stage:Q,foreground:$,mutedForeground:B,accent:E,link:D,keybind:J,titleRevealProgress:U,dissolveProgress:Y,context:Z}){let F=A[Q]??A[0]??$p0[0],X=new $0({color:E,bold:!0}),I=new $0({color:$}),G=A===$p0&&Q===0,V=[...F.title===null?[]:[new D0({text:G?i90(pF6({progress:U,foreground:E,pulseColor:E}),Y):new h(Z8(F.title,Y),X),textAlign:"center"})],...F.body.length>0?[dF6()]:[],...F.body.map((K)=>cF6(K,I,B,D,J,Y,Z))];return new $6({child:new hA({padding:n0.horizontal(1),child:new IA({crossAxisAlignment:"stretch",mainAxisAlignment:"center",mainAxisSize:"min",children:V})})})}function dF6(){return y0.height(1)}function cF6(A,Q,$,B,E,D,J){if(typeof A==="string")return new D0({text:new h(Z8(A,D),Q),textAlign:"center"});if("codeBlock"in A)return new L5({onCopy:(U,Y)=>{if(Y)EQ.success(J,"Copied to clipboard",2000)},child:new IA({mainAxisSize:"min",children:A.codeBlock.map((U)=>new D0({text:new h(Z8(U,D),new $0({color:E})),textAlign:"center",selectable:!0}))})});if("keybind"in A){let U=new D0({text:new h("",void 0,[new h(Z8(A.text,D),new $0({color:$,dim:!0})),new h(Z8(A.keybind,D,B4(A.text).length),new $0({color:E}))]),textAlign:"center",selectable:"selectable"in A?A.selectable:!1});if("selectable"in A)return new $6({child:new L5({child:U})});return U}if("highlightText"in A){let U=L$.createSpan(A.href,A.linkText,new $0({color:B,underline:!0})),Y=oX.of(J),Z=new h("",void 0,[new h(A.text,Q),new h(A.highlightText,new $0({color:E})),new h(A.textAfterHighlight,Q),new h(U.text,U.style,U.children,U.hyperlink,()=>{t6(J,A.href,{forceExternal:!1,onShowImagePreview:Y})}),new h(A.textAfter,Q)]);return new D0({text:i90(Z,D),textAlign:"center"})}if("linkText"in A){if(A.linkWidget)return new IA({mainAxisSize:"min",children:[new D0({text:new h(Z8(A.text,D),Q),textAlign:"center"}),new $6({child:new LA({mainAxisSize:"min",children:[L$.createWidget(J,A.href,Z8(A.linkText,D),new $0({color:B,underline:!0})),new D0({text:new h(Z8(A.textAfter,D),Q)})]})})]});let U=L$.createSpan(A.href,A.linkText,new $0({color:B,underline:!0})),Y=oX.of(J),Z=new h("",void 0,[new h(A.text,Q),new h(U.text,U.style,U.children,U.hyperlink,()=>{t6(J,A.href,{forceExternal:!1,onShowImagePreview:Y})}),new h(A.textAfter,Q)]);return new D0({text:i90(Z,D),textAlign:"center"})}if(D>0)return new D0({text:new h(Z8(A.text,D),new $0({color:B,underline:!0})),textAlign:"center"});return new $6({child:L$.createWidget(J,A.href,A.text,new $0({color:B,underline:!0}))})}function pF6({progress:A,foreground:Q,pulseColor:$}){let B=new $0({color:Q,bold:!0}),E=new $0({color:iF6({progress:A,foreground:Q,pulseColor:$}),bold:!0});return new h("",void 0,[new h(lF6(A).padEnd(Bp0," "),B),new h(" ",B),new h(yR4(gR4,xF6,A,0.72),B),new h(" ",B),new h(yR4(mR4,yF6,A,0.88),E)])}function lF6(A){let Q=B4(hR4),$=Math.min(Bp0,Math.ceil(SE(A/0.62)*Bp0));return Q.slice(0,$).join("")}function yR4(A,Q,$,B){return $>=B?A:"".padEnd(Q," ")}function iF6({progress:A,foreground:Q,pulseColor:$}){if(A<0.88||A>=1)return Q;let B=SE((A-0.88)/0.12);return Math.cos(B*Math.PI*4)*(1-B)>0.12?$:Q}function nF6({stage:A,featureStageCount:Q,foreground:$,dissolveProgress:B}){return new h(Z8(`${A}/${Q}`,B),new $0({color:$,dim:!0}))}function aF6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D}){let J=new $0({color:B}),U=new $0({color:$,dim:!0}),Y=Q?A?"Enter":"Space":"Esc",Z=Q?A?" to get started":" to continue":" to quit",F="",X="",I=`${Z}`;if(!Q)return new h("",void 0,[new h(Y,J),new h(Z,U),new h("",J),new h("",U)]);let G=bR4(Y,E),V=bR4(I,SE((E*(B4(Y).length+B4(I).length)-B4(Y).length)/B4(I).length));return new h("",void 0,[new h(Z8(G,D),J),new h(Z8(V.slice(0,Z.length),D),U),new h(Z8(V.slice(Z.length,Z.length+0),D),J),new h(Z8(V.slice(Z.length+0),D),U)])}function oF6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D,context:J}){if(Q)return new D0({text:aF6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D}),textAlign:"center"});let U=new $0({color:B}),Y=new $0({color:$,dim:!0});return new L5({onCopy:(Z,F)=>{if(F)EQ.success(J,"Copied to clipboard",2000)},child:new D0({text:new h("",void 0,[new h("q",U),new h(" to quit",Y)]),textAlign:"center",selectable:!0})})}function bR4(A,Q){let $=B4(A),B=Math.min($.length,Math.ceil(SE(Q)*$.length));return $.slice(0,B).join("").padEnd($.length," ")}function i90(A,Q,$=0){if(Q<=0)return A;let B=$+B4(A.text??"").length,E=A.children?.map((D)=>{let J=i90(D,Q,B);return B+=B4(D.toPlainText()).length,J});return new h(A.text?Z8(A.text,Q,$):A.text,A.style,E,A.hyperlink,A.onClick)}function Z8(A,Q,$=0){if(Q<=0)return A;return B4(A).map((E,D)=>{if(E.trim()==="")return E;return lR4($+D)<Q?" ":E}).join("")}function lR4(A){let Q=Math.sin((A+1)*12.9898)*43758.5453;return Q-Math.floor(Q)}function rF6(A){let $=A.observer.protocolMessages().filter((B)=>B.role==="assistant").at(-1);if(!$)return null;return $.content.filter((B)=>B.type==="text").map((B)=>B.text).join("")}function sF6(A,Q={}){return new Promise(($,B)=>{let E=!1,D=setTimeout(()=>{J.unsubscribe(),B(Error("Timed out waiting for agent response"))},Q.timeoutMs??600000),J=A.observer.agentState().subscribe((U)=>{if(c3(U)){E=!0;return}if(!E)return;let Y=rF6(A);if(Y===null)return;clearTimeout(D),J.unsubscribe(),$(Y)})})}class Dp0 extends p0{listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;updateService;initialThreadIDs;showWelcome;welcomeVariant;onWelcomeDismissed;notificationService;mcpTrustHandler;onThreadArchived;onActiveThreadChange;onRelaunchRequested;onFirstFrame;initialUserInput;getDefaultNewThreadVisibility;observeThreadSummaries;openThreadPickerOnStart;workspaceSettingsFilePath;context;constructor(A){super();this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.updateService=A.updateService,this.initialThreadIDs=A.initialThreadIDs??[],this.showWelcome=A.showWelcome??!1,this.welcomeVariant=A.welcomeVariant??"intro",this.onWelcomeDismissed=A.onWelcomeDismissed,this.notificationService=A.notificationService,this.mcpTrustHandler=A.mcpTrustHandler,this.onThreadArchived=A.onThreadArchived,this.onActiveThreadChange=A.onActiveThreadChange,this.onRelaunchRequested=A.onRelaunchRequested,this.onFirstFrame=A.onFirstFrame,this.initialUserInput=A.initialUserInput,this.getDefaultNewThreadVisibility=A.getDefaultNewThreadVisibility,this.observeThreadSummaries=A.observeThreadSummaries,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.workspaceSettingsFilePath=A.workspaceSettingsFilePath,this.context=A.context}createState(){return new nR4}}class nR4 extends c0{editorController=new IZ;commandPalette=new jb0(this);commandRegistry=new qm0;toastController=new vb0;relaunchNotificationController=new Gm0;exitHintTimer=new kp(this,1000);ideStatus=new sB(this,{});threadNavigationHistory=new Km0;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;activeThreadIDSubscription=null;activePluginMessageSubscription=null;activePluginUIRequestsSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;executorAlreadyConnectedDialog=null;switchThreadPickerVisible=!1;welcomeVisible=!1;endCreditsVisible=!1;invadersHighScore=0;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;emptyThreadTerminalTitleController=new tl;pluginIntegration=null;mcpTrustIntegration=null;updateRelaunchIntegration=null;noticesPollingTimeout=null;notices;editorFocusNode=new B8({debugLabel:"EditorPanel"});loadThreads=async()=>{return this.widget.context.listThreads()};focusEditor=()=>{this.editorFocusNode.requestFocus()};focusEditorAfterNextFrame(){z6.instance.addPostFrameCallback(()=>{if(!this.mounted)return;this.focusEditor()},"Neo focus editor")}analyzeContextForThread=async(A,Q)=>{return gz4({ampURL:this.widget.context.ampURL,configService:this.widget.configService,threadID:A,signal:Q})};onSwitchThread=(A)=>{return this.connectToExistingThread(A,{recordNavigation:!0,rethrowError:!0})};onSelectSidebarThread=async(A)=>{this.focusEditor(),await this.onSwitchThread(A)};threadListSidebar=new sc0({state:this,isBlocked:()=>this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal(),getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,getWorkspaceRoot:()=>this.widget.context.workspaceRoot,loadThreads:this.loadThreads,observeThreadSummaries:()=>this.widget.observeThreadSummaries(),onSelectThread:this.onSelectSidebarThread,focusMainContent:this.focusEditor,getInitialVisible:()=>this.widget.context.threadListSidebarVisible});sendFeedbackReport=async(A)=>x80({configService:this.widget.configService,settingsFilePath:this.widget.context.settingsFilePath},A);archiveThread=async(A)=>{let Q=await H70({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let $=await pN4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};removeThreadLabel=async(A,Q)=>{let $=await lN4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};initState(){if(kX.getInstance().interceptConsole(),this.invadersHighScore=this.widget.context.invadersHighScore??0,this.notices=new rg0(this.widget.configService,($)=>this.setState($)),z6.instance.addPostFrameCallback(()=>{setTimeout(()=>this.widget.onFirstFrame?.(),0),this.noticesPollingTimeout=setTimeout(()=>{this.noticesPollingTimeout=null,this.notices.startPolling()},500)},"Neo notices polling"),this.widget.showWelcome)this.welcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:$,error:B})=>{if(S.error("Neo failed to connect to thread",{threadID:$,error:B}),!$)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configSubscription=this.widget.configService.config.subscribe(($)=>{this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(K00($.settings)))}),this.updateRelaunchIntegration=new zm0({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested,relaunchNotificationController:this.relaunchNotificationController,updateService:this.widget.updateService}),this.updateRelaunchIntegration.init(),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput,Q=this.widget.initialThreadIDs[0];if(Q){let $={};if(A)$.initialUserInput=A;this.connectToInitialThreads(Q,$)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.context.sessionAgentMode);this.pluginIntegration=new Xm0({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,context:this.widget.context,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread,readThreadMessages:this.readPluginThreadMessages,runAgent:this.runPluginAgent,onBlockingConfirmDialogChange:this.syncEmptyThreadPluginConfirmationTitle}),this.pluginIntegration.init(),this.mcpTrustIntegration=new nh0({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=X1.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this,Q=this.widget.context.pluginService?Xw4({pluginService:this.widget.context.pluginService,workspaceRoot:this.widget.context.workspaceRoot,logFilePath:this.widget.context.logFilePath,toastController:this.toastController}):[],B=[Hw4({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["resume"],status:{type:"enabled"},sortBoost:100,run:(E,D,J)=>{E.pushWithDismiss((U)=>ad0({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,loadThreadTail:this.widget.context.loadThreadTail,onSelectThread:this.onSwitchThread,onDismiss:U,onThreadSelected:J}))}},...this.threadListSidebar.commands(),{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(E,D,J)=>{A.navigateBack(),J()}},IO4({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:(E,D,J)=>{A.navigateForward(),J()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",status:{type:"enabled"},run:(E,D,J)=>{E.push(new $d0({mcpServers:this.widget.context.mcpServers,onDismiss:J}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",status:{type:"enabled"},run:(E)=>{E.pushWithDismiss((D)=>new tc0({toolboxes:this.widget.context.toolboxes,onDismiss:D}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","blog","announcements"],status:{type:"enabled"},run:async(E,D,J)=>{try{await t6(D,"https://ampcode.com/chronicle")}finally{J()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config"],status:{type:"enabled"},run:()=>{yK(this.widget.context.settingsFilePath).catch((E)=>{S.error("Failed to open settings file in editor",{error:E})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains"],status:{type:"enabled"},run:(E,D,J)=>{E.pushWithDismiss((U)=>new Qd0({onCancel:U,onSelect:(Y)=>{this.handleIdeSelection(Y),J()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["manual","?"],status:{type:"enabled"},run:(E,D,J)=>{E.push(new wm0({commands:eB.of(D).commands,onDismiss:J}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",status:{type:"enabled"},run:(E,D,J)=>{J(),A.showWelcome()}},{noun:"amp",verb:"end credits",description:"Roll the full-screen Amp credits",status:{type:"enabled"},run:(E,D,J)=>{J(),A.showEndCredits()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["v"],status:{type:"enabled"},run:(E,D,J)=>{E.push(new B1({header:"Amp Version",maxWidth:72,onDismiss:J,child:new D0({text:new h(i50({version:"0.0.1780464815-g688406",buildTimestamp:"2026-06-03T05:39:07.888Z",buildType:"release"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","bye"],shortcut:HA.ctrl("c"),status:{type:"enabled"},run:(E,D)=>{N4.maybeInvoke(D,new iK)}},...Q,...cN4(this.widget.context.logFilePath)].map((E)=>this.commandRegistry.register(E));return()=>{for(let E of B)E()}}build(A){let Q=this.buildHints(),$=this.ideStatus.getValue(),B=this.notices.current,E=new lc0({initialAgentMode:this.widget.context.sessionAgentMode,initialPluginAgentModeKey:this.widget.context.initialPluginAgentModeKey,analyzeContextForThread:this.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,editorFocusNode:this.editorFocusNode,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,sendFeedbackReport:this.sendFeedbackReport,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:$,statusItems:this.pluginIntegration?.getStatusItems()??[],pluginConfirmationBlocked:this.pluginIntegration?.hasBlockingConfirmDialog()??!1,notificationService:this.widget.notificationService,notice:this.activeThreadContext||this.welcomeVisible?null:B,onDismissNotice:(I)=>this.notices.dismiss(I)}),D=W4.of(A),J=D.capabilities.animationSupport!=="disabled",U=this.threadListSidebar.visibleWidth(),Y=Math.max(0,D.size.width-U),F=[new WA({constraints:Y4.tight(D.size.width,D.size.height),child:this.threadListSidebar.buildBody(E)})];if(this.commandPalette.isEnabled())F.push(new c6({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new um0({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.welcomeVisible)F.push(ad0({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,loadThreadTail:this.widget.context.loadThreadTail,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.welcomeVisible)F.push(new c6({debugLabel:"WelcomeDialogOverlay",child:new Ep0({onDismiss:this.dismissWelcome,onQuit:()=>X1.instance.stop(),animationsEnabled:J,variant:this.widget.welcomeVariant})}));let X=this.executorAlreadyConnectedDialog;if(X)F.push(new c6({debugLabel:"ExecutorAlreadyConnectedDialogOverlay",child:new em0({existingExecutorPid:X.existingExecutorPid,onChoice:this.handleExecutorAlreadyConnectedChoice})}));if(F.push(...this.mcpTrustIntegration?.buildDialogLayers()??[]),F.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.context.isInternalUser)F.push(new Om0({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:n90.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)F.push(new Ad0);if(this.endCreditsVisible)F.push(new nm0({onComplete:this.completeEndCredits,highScore:this.invadersHighScore,onHighScoreChange:this.updateInvadersHighScore}));return new HQ({context:this.widget.context,child:new eB({commandRegistry:this.commandRegistry,child:new wv({completionBuilder:this.widget.completionBuilder,child:new EQ({controller:this.toastController,child:new N4({actions:this.buildActions(),child:new pQ({debugLabel:"AppShortcuts",shortcuts:this.buildShortcuts(),child:new cQ({debugLabel:"AppShellFocus",canRequestFocus:!1,skipTraversal:!0,child:new Tb0({controller:this.toastController,complexToastControllers:[this.relaunchNotificationController,...B&&this.activeThreadContext&&!this.welcomeVisible?[this.notices]:[]],child:new Mm0({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new Bl({left:U,width:Y,child:new QQ({children:F})})})})})})})})})})})}buildShortcuts(){let A=new Map([[HA.ctrl("c"),new y70],[HA.ctrl("o"),new h70],[HA.alt("i"),new m70],[HA.alt("p"),new Wp],[HA.ctrl("."),new p70],[HA.ctrl("t"),new n70],...this.threadListSidebar.shortcutEntries()]);if(n90.env.NODE_ENV==="development"&&n90.platform==="darwin")A.set(HA.meta("r"),new b70);return A}buildActions(){let A=new pA(()=>{if(c2.hasAnyCopyableSelection())return c2.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new pA(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),$=new pA(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),B=new pA(()=>{return this.startNewDraftThread(),"handled"}),E=new pA(()=>{return X1.instance.stop(),"handled"}),D=new pA(()=>{return dl({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),"handled"}),J=new pA((I)=>{if(!I.text)return"ignored";return X1.instance.tuiInstance.clipboard.writeText(I.text).then((G)=>{if(G.ok)this.toastController.show(I.successMessage,"success",2000);else this.toastController.show(`${I.failureMessage}: ${G.userFacingErrorMessage}`,"error",4000)}).catch((G)=>{S.error("Failed to copy Neo text to clipboard",{error:G}),this.toastController.show(I.failureMessage,"error",2000)}),"handled"}),U=new pA(()=>{return X1.instance.toggleFrameStatsOverlay(),"handled"}),Y=new pA(()=>this.notices.dismissCurrent()?"handled":"ignored"),Z=new pA(()=>{if(!this.widget.context.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),F=Tw4({getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,context:this.widget.context,toastController:this.toastController,startNewDraftThread:this.startNewDraftThread,sendFeedbackReport:this.sendFeedbackReport}),X=new pA(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[y70,A],[Xl,B],[iK,E],[b70,D],[ZB,J],[Kl,$],[h70,Q],[m70,Z],...this.threadListSidebar.actionEntries(),[p70,Y],...F,[Wp,U],[n70,X]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.cancelOwnerUIRequests(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),this.widget.onActiveThreadChange?.(null),this.syncEmptyThreadPluginConfirmationTitle(),A.prompt!==void 0)this.editorController.text=A.prompt;this.focusEditorAfterNextFrame()}syncEmptyThreadPluginConfirmationTitle=()=>{this.emptyThreadTerminalTitleController.setPluginConfirmationBlocked(this.activeThreadContext===null&&(this.pluginIntegration?.hasBlockingConfirmDialog()??!1))};closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=this.applySessionDefaultsToThreadSettings(await pP(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){S.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.context.sessionAgentMode,$=A,B=Yq(Q),E=H50(this.widget.context,Q);if(B!==void 0&&E!==void 0)$={...$,[B]:E};return W50($,{agentMode:Q,explicitEffort:this.widget.context.explicitReasoningEffort,sessionState:this.widget.context})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=iR4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if($Y(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=iR4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(lK);if(this.exitHintTimer.isActive())A.add(Xv);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),X1.instance.stop();else this.exitHintTimer.activate()};dismissWelcome=()=>{if(!this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!1}),this.widget.onWelcomeDismissed?.()};updateInvadersHighScore=(A)=>{if(A<=this.invadersHighScore)return;this.setState(()=>{this.invadersHighScore=A}),JJ((Q)=>({...Q,neoInvadersHighScore:Math.max(Q.neoInvadersHighScore,A)})).catch((Q)=>{S.warn("Failed to save Neo Invaders high score",{error:Q instanceof Error?Q.message:String(Q)})})};showWelcome=()=>{if(this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!0})};showEndCredits=()=>{if(this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!0})};completeEndCredits=()=>{if(!this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!1})};promptExecutorAlreadyConnected(A){return new Promise((Q)=>{this.setState(()=>{this.executorAlreadyConnectedDialog={existingExecutorPid:A.existingExecutorPid,resolve:($)=>{Q($==="watch"?"observe":"disconnect")}}})})}handleExecutorAlreadyConnectedChoice=(A)=>{if(this.resolveExecutorAlreadyConnectedDialog(A),A==="exit")X1.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}),this.focusEditorAfterNextFrame()};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,$=null,B,E,D)=>{await this.ensureDraftThreadSettingsInitialized();let J=this.activeThreadContext?.client.getThreadId(),U=A.find(Z00);if(U)this.widget.history.add(U.text,n90.cwd()),this.widget.history.reset();let Y=$?void 0:await this.widget.getDefaultNewThreadVisibility?.(),Z=$??Y??null,F=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,Z??void 0,E,D);if(this.sendUserMessage(F,A,E?void 0:Q,E?void 0:B),!E)this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings);this.threadNavigationHistory.recordNavigation(J),this.setActiveClient(F)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.context.sessionAgentMode=A;let $=Q["reasoning.effort"];if($!==void 0)this.widget.context.lastReasoningEffortByMode={...this.widget.context.lastReasoningEffortByMode??{},[A]:$};let B=Yq(A),E=B?Q[B]:void 0;if(E!==void 0)this.widget.context.lastSpeedByMode={...this.widget.context.lastSpeedByMode??{},[A]:E};JJ((D)=>{let J={...D,agentMode:A};if($!==void 0)J={...J,lastReasoningEffortByMode:{...J.lastReasoningEffortByMode??{},[A]:$}};if(E!==void 0)J={...J,lastSpeedByMode:{...J.lastSpeedByMode??{},[A]:E}};return J}).catch((D)=>{S.warn("Failed to persist Neo session defaults for new message",{error:D instanceof Error?D.message:String(D)})})}sendUserMessage(A,Q,$,B,E){let D=l50(this.ideStatus.getValue());if(B===void 0){A.client.sendUserMessage(Q,$,{steer:E?.steer,userState:D}).catch((J)=>{S.warn("Failed to send user message",{error:J})});return}A.client.sendUserMessage(Q,$,{reasoningEffort:B,steer:E?.steer,userState:D}).catch((J)=>{S.warn("Failed to send user message",{error:J})})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};getRelaunchThreadIDs=()=>{let A=new Set,Q=this.getActiveThreadID();if(Q)A.add(Q);for(let $ of this.widget.clientPool.activeThreadIDs)A.add($);return[...A]};appendPluginMessagesToThread=async(A,Q,$)=>{let B=this.activeThreadContext;if(!B){if(Q){for(let D of A)await this.widget.clientPool.appendUserMessageToThread(Q,D.content,$);return}throw Error("appendToThread is not available - no active thread")}let E=B.client.getThreadId();if(Q&&E!==Q){for(let D of A)await this.widget.clientPool.appendUserMessageToThread(Q,D.content,$);return}for(let D of A)this.sendUserMessage(B,[{type:"text",text:D.content}],void 0,void 0,$)};readPluginThreadMessages=async(A,Q)=>{let $=this.activeThreadContext;if(!$)throw Error("thread.messages is not available - no active thread");let B=$.client.getThreadId();if(Q&&B!==Q)throw Error("thread.messages is only available for the active thread");return BoA(EoA($.observer.protocolMessages()),A)};runPluginAgent=async(A,Q)=>{await this.ensureDraftThreadSettingsInitialized();let $=this.widget.clientPool.createNewThread(this.widget.context.sessionAgentMode,this.draftThreadSettings,void 0,A,Q.agentModeDisplay,Q.parentThreadID,{trackAsLastActive:!1});this.sendUserMessage($,[{type:"text",text:Q.message}]);try{let B=await sF6($,{timeoutMs:Q.timeoutMs}),E=$.client.getThreadId();return E?{threadID:E,text:B}:{text:B}}finally{this.widget.clientPool.disconnect($)}};async connectToExistingThread(A,Q={}){let $=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let B=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:(E)=>this.promptExecutorAlreadyConnected(E)});if(this.setActiveClient(B),Q.recordNavigation&&$!==A)this.threadNavigationHistory.recordNavigation($);if(Q.initialUserInput)this.sendUserMessage(B,[{type:"text",text:Q.initialUserInput}])}catch(B){if(S.error("Failed to load thread",{error:B,threadID:A}),this.toastController.show(`Failed to load ${A}: ${B instanceof Error?B.message:String(B)}`,"error",4000),Q.rethrowError)throw B}finally{this.setState(()=>{this.connectingToThreadID=null})}}async connectToInitialThreads(A,Q={}){await this.connectToExistingThread(A,Q);let $=this.widget.initialThreadIDs.filter((B)=>B!==A);await Promise.all($.map((B)=>this.resumeBackgroundThread(B)))}async resumeBackgroundThread(A){try{await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:async()=>"observe"})}catch(Q){S.error("Failed to resume background thread",{error:Q,threadID:A}),this.toastController.show(`Failed to resume ${A}: ${Q instanceof Error?Q.message:String(Q)}`,"error",4000)}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}setActiveClient({client:A,observer:Q,agentModeDisplay:$}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q,agentModeDisplay:$}}),this.syncEmptyThreadPluginConfirmationTitle(),this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe((B)=>{this.widget.onActiveThreadChange?.(B)}),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription?.unsubscribe(),this.pluginIntegration?.cancelOwnerUIRequests(),this.activePluginMessageSubscription=Q.pluginMessages().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage(B,(E)=>{A.sendPluginMessage(E)})}),this.activePluginUIRequestsSubscription=Q.pluginUIRequests().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage({type:"plugin_message",message:{type:"event",event:"plugin.ui.snapshot",data:{requests:[...B]}}},(E)=>{A.sendPluginMessage(E)})})}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){S.error("Failed to connect to IDE",{error:Q});let $=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${$}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.threadListSidebar.dispose(),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.emptyThreadTerminalTitleController.dispose(),this.mcpTrustIntegration?.dispose(),this.mcpTrustIntegration=null,this.updateRelaunchIntegration?.dispose(),this.updateRelaunchIntegration=null,this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.noticesPollingTimeout)clearTimeout(this.noticesPollingTimeout),this.noticesPollingTimeout=null;this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.notices.dispose(),this.widget.notificationService.detach(),this.toastController.dispose(),this.editorFocusNode.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.executorAlreadyConnectedDialog!==null||this.welcomeVisible||(this.mcpTrustIntegration?.hasBlockingDialog()??!1)||this.endCreditsVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function iR4(A,Q,$){let B={...A};for(let E of tF6(Q,$)){if(!$Y(A[E],Q[E]))continue;let D=$[E];if(D===void 0)delete B[E];else B[E]=D}return B}function tF6(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}hB();function aR4(A,Q,$,B){let E=ZbA(A),D="\x1B[0m",J="\x1B[34m",U="\x1B[90m",Y="\x1B[2m",Z=[];if(A.archived)Z.push("\x1B[90m\x1B[2mArchived\x1B[0m");Z.push(`${E}`),Z.push(`\x1B[34m${Q}\x1B[0m`),Z.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let F=14,X=7,I=new m2(F,X),G=new v5(42),V=new Ov(F,X,F,X,F,X,0,A.agentMode??"smart","intensity","ascii",void 0,void 0,d0.default(),G);V.layout(Y4.tight(F,X)),V.paint(I,0,0);let K=I.getBuffer().getCells(),z=0;for(let R=0;R<X;R++)if(K[R].some((_)=>_.char!==" ")){z=R;break}let W=X-1;for(let R=X-1;R>=0;R--)if(K[R].some((_)=>_.char!==" ")){W=R;break}function C(R,_){if(!R)return"";if(R.type==="rgb"){let{r:v,g:k,b:m}=R.value;if($.getColorDepth()>=24)return`\x1B[${_?38:48};2;${v};${k};${m}m`;let x=Mp(v,k,m);return`\x1B[${_?38:48};5;${x}m`}return""}let H=[];if(W>=z)for(let R=z;R<=W;R++){let _="";for(let v=0;v<F;v++){let k=K[R][v],m=k.char,x=C(k.style.fg,!0);_+=x+m+"\x1B[0m"}H.push(_)}let N=H.length,q=Math.max(N,Z.length),w=Math.floor((q-N)/2),O=Math.floor((q-Z.length)/2);for(let R=0;R<q;R++){let _=" ".repeat(F);if(R>=w&&R<w+N)_=H[R-w];let v=" ",k="";if(R>=O&&R<O+Z.length)k=Z[R-O];$.write(_+v+k+`
|
|
4431
|
+
`))}function LF6(A,Q){let{colors:$,app:B}=Q;switch(A){case"pending":return{icon:"◌",color:$.warning};case"registered":return{icon:"•",color:$.mutedForeground};case"failed":return{icon:"✗",color:B.toolError};case"duplicate":return{icon:"◇",color:$.warning};default:return{icon:"?",color:$.foreground}}}function jR4(A,Q){let $=A.replace(/\s+/g," ").trim();if(cA($)<=Q)return $;let B="...",E=cA(B);if(Q<=E)return Q8(B,Q);return`${Q8($,Q-E,!0,"")}${B}`}var Qp0="https://ampcode.com/news/neo",$p0=[{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:Qp0,href:Qp0}]}];function jF6(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:Qp0,textAfter:" you'll need to switch to the binary install:",linkWidget:!0},"",{codeBlock:["npm uninstall -g @sourcegraph/amp",A]}]}]}function RF6(){if(process.platform==="win32")return'powershell -c "irm https://ampcode.com/install.ps1 | iex"';return"curl -fsSL https://ampcode.com/install.sh | bash"}var hv=50,tq=40,ec0=1000,PF6=420,vF6=760,TF6=-250,_F6=1100,p90=33,TR4=0.999,SF6=2.1,kF6=720,fF6=420,hR4="Meet the new",gR4="Amp",mR4="CLI",Bp0=B4(hR4).length,xF6=B4(gR4).length,yF6=B4(mR4).length,l90={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}},_R4={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},SR4={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}},kR4=[l90,_R4,SR4,l90,_R4,SR4,l90],bF6=l90;class Ep0 extends p0{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??RF6(),this.introStages=this.variant==="npm-migration"?jF6(this.binaryInstallCommand):$p0,this.dismissible=this.variant!=="npm-migration"}createState(){return new dR4}}class dR4 extends c0{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=ec0;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 v5(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=SE(this.widget.animationProgress),this.firstStageTitleVisible=this.animationProgress>=TR4,this.firstStageHintVisible=this.animationProgress>=TR4,this.firstStageTitleRevealProgress=this.firstStageTitleVisible?1:0,this.firstStageHintRevealProgress=this.firstStageHintVisible?1:0;return}if(!this.widget.animationsEnabled){this.stopStageTransitionTimer(),this.stopDismissAnimation(),this.animationProgress=1,this.isDismissing=!1,this.dismissProgress=0,this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1,this.previousIntroStage=null,this.stageTransitionProgress=1;return}if(this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0,this.startProgressAnimation({from:0,to:1,durationMs:ec0,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=SE(A/vF6);if(this.setState(()=>{this.dismissProgress=Q}),Q>=1)this.stopDismissAnimation(),this.widget.onDismiss()},p90)}canNavigateIntroStage(){if(this.isDismissing)return!1;if(!this.firstStageHintVisible)return!1;if(this.introStage===0&&this.firstStageHintRevealProgress<1)return!1;return!0}advanceIntroStage(){if(!this.canNavigateIntroStage())return;if(this.isFinalIntroStage()){if(this.widget.dismissible)this.startDismissAnimation();return}this.moveIntroStage(1)}dismissFromFinalIntroStage(){if(!this.widget.dismissible||!this.canNavigateIntroStage()||!this.isFinalIntroStage())return!1;return this.startDismissAnimation(),!0}nextIntroStage(){if(!this.canNavigateIntroStage()||this.isFinalIntroStage())return;this.moveIntroStage(1)}goToPreviousIntroStage(){if(!this.canNavigateIntroStage()||this.introStage<=0)return;this.moveIntroStage(-1)}isFinalIntroStage(){return this.introStage>=this.widget.introStages.length-1}moveIntroStage(A){let Q=this.introStage+A;if(this.stopStageTransitionTimer(),this.stageTransitionStartedAt=performance.now(),this.setState(()=>{this.previousIntroStage=this.introStage,this.introStage=Q,this.stageTransitionDirection=A}),this.widget.animationProgress!==void 0||!this.widget.animationsEnabled){this.setState(()=>{this.previousIntroStage=null,this.stageTransitionProgress=1});return}this.setState(()=>{this.stageTransitionProgress=0}),this.stageTransitionTimer=setInterval(()=>{let $=performance.now()-this.stageTransitionStartedAt,B=SE($/PF6);if(this.setState(()=>{if(this.stageTransitionProgress=B,B>=1)this.previousIntroStage=null}),B>=1)this.stopStageTransitionTimer()},p90)}startProgressAnimation({from:A,to:Q,durationMs:$,onComplete:B}){this.stopAnimation(),this.startedAt=performance.now(),this.animationStartProgress=A,this.animationTargetProgress=Q,this.animationDurationMs=$,this.onAnimationComplete=B,this.animationProgress=A,this.animationTimer=setInterval(()=>{let E=performance.now()-this.startedAt,D=SE(E/this.animationDurationMs),J=this.animationStartProgress+(this.animationTargetProgress-this.animationStartProgress)*gv(D);if(this.setState(()=>{this.animationProgress=J}),D>=1)this.stopAnimation(),this.onAnimationComplete?.(),this.onAnimationComplete=null},p90)}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,ec0+TF6),Q=A+_F6;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?SE((A-this.firstStageTitleRevealStartedAt)/kF6):this.firstStageTitleRevealProgress,$=this.firstStageHintRevealStartedAt?SE((A-this.firstStageHintRevealStartedAt)/fF6):this.firstStageHintRevealProgress;if(this.setState(()=>{this.firstStageTitleRevealProgress=Q,this.firstStageHintRevealProgress=$}),Q>=1&&$>=1)this.stopFirstStageRevealTimer()},p90)}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=fR4(this.introStage),Q=this.previousIntroStage===null||this.stageTransitionProgress>=1?A:xR4(fR4(this.previousIntroStage),A,gv(this.stageTransitionProgress));return this.dismissProgress>0?xR4(Q,bF6,gv(this.dismissProgress)):Q}build(A){let Q=c4.of(A).colorScheme,$=EA.of(A),B=this.currentOrbPalette(),E=I7(1,"deep",B),D=W4.of(A).size,U=this.widget.animationProgress??this.animationProgress,Y=Math.max(D.width/hv,D.height/tq)*SF6,Z=Y+(1-Y)*U,F=gv(this.dismissProgress),X=Math.max(hv,Math.round(hv*Z)),I=Math.max(tq,Math.round(tq*Z)),G=Math.round((D.width-X)/2),V=Math.round((D.height-I)/2),K=Math.max(0,Math.floor((D.width-hv)/2)),z=-Math.floor(tq/2),W=Math.round(G+(K-G)*U),C=Math.round(V+(z-V)*U),H=W+X/2,N=C+I/2,q=hF6({dismissProgress:this.dismissProgress,easedDismissProgress:F,introOrbScale:Z,normalOrbCenterX:H,normalOrbCenterY:N,size:D}),w=Math.max(hv,Math.round(hv*q.orbScale)),O=Math.max(tq,Math.round(tq*q.orbScale)),R=q.orbCenterX,_=q.orbCenterY,v=Math.round(R-w/2),k=Math.round(_-O/2),m=Math.max(3,Math.min(D.height-5,Math.floor(tq/2)+2)),x=Math.max(m+3,D.height-3),T=q.textDissolveProgress,f=this.isFinalIntroStage()?q.backdropDissolveProgress:0,c=this.firstStageTitleVisible&&T<1,d=c&&this.firstStageHintVisible,b=d&&this.widget.dismissible&&this.introStage>0&&!this.isFinalIntroStage(),p=this.introStage===0?this.firstStageTitleRevealProgress:1,n=this.introStage===0?this.firstStageHintRevealProgress:1,o=Math.max(24,Math.min(74,D.width-4)),I0=Math.min(12,Math.max(8,D.height-m-6)),E0=Math.max(0,Math.floor((D.width-o)/2)),G0=Math.max(0,Math.min(D.height-I0,Math.floor(D.height*0.55-I0/2))),q0=this.widget.animationProgress!==void 0||!this.widget.animationsEnabled?new tK({width:w,height:O,agentMode:"deep",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,seed:42,fps:0,onClick:()=>{}}):new tK({width:w,height:O,agentMode:"deep",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,onClick:()=>{}});return new c6({autofocus:!0,canRequestFocus:!0,debugLabel:"WelcomeTakeover",onKey:(t)=>{if(t.key==="Enter")return this.advanceIntroStage(),"handled";if(!this.widget.dismissible&&t.key==="c"&&t.ctrlKey)return this.widget.onQuit?.(),"handled";if(!this.widget.dismissible&&t.key==="q")return this.widget.onQuit?.(),"handled";if((t.key===" "||t.key==="Space")&&!this.isFinalIntroStage())return this.advanceIntroStage(),"handled";if(t.key==="Escape"||t.key==="Esc"){if(!this.widget.dismissible)return this.widget.onQuit?.(),"handled";return this.dismissFromFinalIntroStage()?"handled":"ignored"}if(t.key==="ArrowRight")return this.nextIntroStage(),"handled";if(t.key==="ArrowLeft")return this.goToPreviousIntroStage(),"handled";return"ignored"},child:new QQ({fit:"expand",children:[new cR4({color:Q.background,dissolveProgress:f}),new QQ({fit:"expand",children:[new iA({onClick:()=>{},child:y0.expand()}),new r1({left:v,top:k,width:w,height:O,child:q0}),...c?[new r1({left:E0,top:G0,width:o,height:I0,child:mF6({introStages:this.widget.introStages,stage:this.introStage,previousStage:this.previousIntroStage,progress:this.stageTransitionProgress,direction:this.stageTransitionDirection,width:o,height:I0,foreground:Q.foreground,mutedForeground:Q.mutedForeground,accent:E,link:$.app.link,keybind:$.app.keybind,titleRevealProgress:p,dissolveProgress:T,context:A})})]:[],...d?[...b?[new r1({left:E0,top:Math.max(0,x-1),width:o,height:1,child:new D0({text:nF6({stage:this.introStage,featureStageCount:Math.max(0,this.widget.introStages.length-2),foreground:Q.mutedForeground,dissolveProgress:T}),textAlign:"center"})})]:[],new r1({left:E0,top:x,width:o,height:1,child:oF6({finalStage:this.isFinalIntroStage(),dismissible:this.widget.dismissible,foreground:Q.mutedForeground,keybind:$.app.keybind,revealProgress:n,dissolveProgress:T,context:A})})]:[]]})]})})}}class cR4 extends YB{color;dissolveProgress;constructor({color:A,dissolveProgress:Q}){super();this.color=A,this.dissolveProgress=Q}createRenderObject(){return new pR4(this.color,this.dissolveProgress)}updateRenderObject(A){A.update(this.color,this.dissolveProgress)}}class pR4 extends bA{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;rA(!!A,"performLayout called without constraints");let Q=A.constrain(A.biggest.width,A.biggest.height);this.setSize(Q.width,Q.height),super.performLayout()}paint(A,Q=0,$=0){let B=Math.floor(Q+this.offset.x),E=Math.floor($+this.offset.y),D=Math.floor(this.size.width),J=Math.floor(this.size.height),U={bg:this.color},Y=SE(this.dissolveProgress);if(Y<=0){A.fill(B,E,D,J," ",U);return}if(Y>=1)return;for(let Z=0;Z<J;Z++)for(let F=0;F<D;F++)if(!gF6(F,Z,D,J,Y))A.fill(B+F,E+Z,1,1," ",U)}}function SE(A){return Math.min(1,Math.max(0,A))}function gv(A){return 1-(1-A)**3}function fR4(A){return kR4[A]??kR4[0]}function xR4(A,Q,$){return{primary:Tq(A.primary,Q.primary,$),secondary:Tq(A.secondary,Q.secondary,$)}}function hF6({dismissProgress:A,easedDismissProgress:Q,introOrbScale:$,normalOrbCenterX:B,normalOrbCenterY:E,size:D}){return{orbScale:$+($*0.86-$)*Q,orbCenterX:B+(D.width*0.54-B)*Q,orbCenterY:E-D.height*0.44*Q,textDissolveProgress:SE(A/0.52),backdropDissolveProgress:gv(SE((A-0.12)/0.88))}}function gF6(A,Q,$,B,E){let D=B<=1?0:Q/(B-1),J=lR4(A+Q*Math.max(1,$));return(1-D)*0.72+J*0.28<E}function mF6({introStages:A,stage:Q,previousStage:$,progress:B,direction:E,width:D,height:J,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V}){if($===null||B>=1)return Ap0({introStages:A,stage:Q,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V});let K=gv(B),z=E*Math.round((1-K)*D),W=-E*Math.round(K*D);return new zq(new QQ({fit:"expand",children:[new r1({left:W,top:0,width:D,height:J,child:Ap0({introStages:A,stage:$,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:$===0?1:I,dissolveProgress:G,context:V})}),new r1({left:z,top:0,width:D,height:J,child:Ap0({introStages:A,stage:Q,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V})})]}))}function Ap0({introStages:A,stage:Q,foreground:$,mutedForeground:B,accent:E,link:D,keybind:J,titleRevealProgress:U,dissolveProgress:Y,context:Z}){let F=A[Q]??A[0]??$p0[0],X=new $0({color:E,bold:!0}),I=new $0({color:$}),G=A===$p0&&Q===0,V=[...F.title===null?[]:[new D0({text:G?i90(pF6({progress:U,foreground:E,pulseColor:E}),Y):new h(Z8(F.title,Y),X),textAlign:"center"})],...F.body.length>0?[dF6()]:[],...F.body.map((K)=>cF6(K,I,B,D,J,Y,Z))];return new $6({child:new hA({padding:n0.horizontal(1),child:new IA({crossAxisAlignment:"stretch",mainAxisAlignment:"center",mainAxisSize:"min",children:V})})})}function dF6(){return y0.height(1)}function cF6(A,Q,$,B,E,D,J){if(typeof A==="string")return new D0({text:new h(Z8(A,D),Q),textAlign:"center"});if("codeBlock"in A)return new L5({onCopy:(U,Y)=>{if(Y)EQ.success(J,"Copied to clipboard",2000)},child:new IA({mainAxisSize:"min",children:A.codeBlock.map((U)=>new D0({text:new h(Z8(U,D),new $0({color:E})),textAlign:"center",selectable:!0}))})});if("keybind"in A){let U=new D0({text:new h("",void 0,[new h(Z8(A.text,D),new $0({color:$,dim:!0})),new h(Z8(A.keybind,D,B4(A.text).length),new $0({color:E}))]),textAlign:"center",selectable:"selectable"in A?A.selectable:!1});if("selectable"in A)return new $6({child:new L5({child:U})});return U}if("highlightText"in A){let U=L$.createSpan(A.href,A.linkText,new $0({color:B,underline:!0})),Y=oX.of(J),Z=new h("",void 0,[new h(A.text,Q),new h(A.highlightText,new $0({color:E})),new h(A.textAfterHighlight,Q),new h(U.text,U.style,U.children,U.hyperlink,()=>{t6(J,A.href,{forceExternal:!1,onShowImagePreview:Y})}),new h(A.textAfter,Q)]);return new D0({text:i90(Z,D),textAlign:"center"})}if("linkText"in A){if(A.linkWidget)return new IA({mainAxisSize:"min",children:[new D0({text:new h(Z8(A.text,D),Q),textAlign:"center"}),new $6({child:new LA({mainAxisSize:"min",children:[L$.createWidget(J,A.href,Z8(A.linkText,D),new $0({color:B,underline:!0})),new D0({text:new h(Z8(A.textAfter,D),Q)})]})})]});let U=L$.createSpan(A.href,A.linkText,new $0({color:B,underline:!0})),Y=oX.of(J),Z=new h("",void 0,[new h(A.text,Q),new h(U.text,U.style,U.children,U.hyperlink,()=>{t6(J,A.href,{forceExternal:!1,onShowImagePreview:Y})}),new h(A.textAfter,Q)]);return new D0({text:i90(Z,D),textAlign:"center"})}if(D>0)return new D0({text:new h(Z8(A.text,D),new $0({color:B,underline:!0})),textAlign:"center"});return new $6({child:L$.createWidget(J,A.href,A.text,new $0({color:B,underline:!0}))})}function pF6({progress:A,foreground:Q,pulseColor:$}){let B=new $0({color:Q,bold:!0}),E=new $0({color:iF6({progress:A,foreground:Q,pulseColor:$}),bold:!0});return new h("",void 0,[new h(lF6(A).padEnd(Bp0," "),B),new h(" ",B),new h(yR4(gR4,xF6,A,0.72),B),new h(" ",B),new h(yR4(mR4,yF6,A,0.88),E)])}function lF6(A){let Q=B4(hR4),$=Math.min(Bp0,Math.ceil(SE(A/0.62)*Bp0));return Q.slice(0,$).join("")}function yR4(A,Q,$,B){return $>=B?A:"".padEnd(Q," ")}function iF6({progress:A,foreground:Q,pulseColor:$}){if(A<0.88||A>=1)return Q;let B=SE((A-0.88)/0.12);return Math.cos(B*Math.PI*4)*(1-B)>0.12?$:Q}function nF6({stage:A,featureStageCount:Q,foreground:$,dissolveProgress:B}){return new h(Z8(`${A}/${Q}`,B),new $0({color:$,dim:!0}))}function aF6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D}){let J=new $0({color:B}),U=new $0({color:$,dim:!0}),Y=Q?A?"Enter":"Space":"Esc",Z=Q?A?" to get started":" to continue":" to quit",F="",X="",I=`${Z}`;if(!Q)return new h("",void 0,[new h(Y,J),new h(Z,U),new h("",J),new h("",U)]);let G=bR4(Y,E),V=bR4(I,SE((E*(B4(Y).length+B4(I).length)-B4(Y).length)/B4(I).length));return new h("",void 0,[new h(Z8(G,D),J),new h(Z8(V.slice(0,Z.length),D),U),new h(Z8(V.slice(Z.length,Z.length+0),D),J),new h(Z8(V.slice(Z.length+0),D),U)])}function oF6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D,context:J}){if(Q)return new D0({text:aF6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D}),textAlign:"center"});let U=new $0({color:B}),Y=new $0({color:$,dim:!0});return new L5({onCopy:(Z,F)=>{if(F)EQ.success(J,"Copied to clipboard",2000)},child:new D0({text:new h("",void 0,[new h("q",U),new h(" to quit",Y)]),textAlign:"center",selectable:!0})})}function bR4(A,Q){let $=B4(A),B=Math.min($.length,Math.ceil(SE(Q)*$.length));return $.slice(0,B).join("").padEnd($.length," ")}function i90(A,Q,$=0){if(Q<=0)return A;let B=$+B4(A.text??"").length,E=A.children?.map((D)=>{let J=i90(D,Q,B);return B+=B4(D.toPlainText()).length,J});return new h(A.text?Z8(A.text,Q,$):A.text,A.style,E,A.hyperlink,A.onClick)}function Z8(A,Q,$=0){if(Q<=0)return A;return B4(A).map((E,D)=>{if(E.trim()==="")return E;return lR4($+D)<Q?" ":E}).join("")}function lR4(A){let Q=Math.sin((A+1)*12.9898)*43758.5453;return Q-Math.floor(Q)}function rF6(A){let $=A.observer.protocolMessages().filter((B)=>B.role==="assistant").at(-1);if(!$)return null;return $.content.filter((B)=>B.type==="text").map((B)=>B.text).join("")}function sF6(A,Q={}){return new Promise(($,B)=>{let E=!1,D=setTimeout(()=>{J.unsubscribe(),B(Error("Timed out waiting for agent response"))},Q.timeoutMs??600000),J=A.observer.agentState().subscribe((U)=>{if(c3(U)){E=!0;return}if(!E)return;let Y=rF6(A);if(Y===null)return;clearTimeout(D),J.unsubscribe(),$(Y)})})}class Dp0 extends p0{listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;updateService;initialThreadIDs;showWelcome;welcomeVariant;onWelcomeDismissed;notificationService;mcpTrustHandler;onThreadArchived;onActiveThreadChange;onRelaunchRequested;onFirstFrame;initialUserInput;getDefaultNewThreadVisibility;observeThreadSummaries;openThreadPickerOnStart;workspaceSettingsFilePath;context;constructor(A){super();this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.updateService=A.updateService,this.initialThreadIDs=A.initialThreadIDs??[],this.showWelcome=A.showWelcome??!1,this.welcomeVariant=A.welcomeVariant??"intro",this.onWelcomeDismissed=A.onWelcomeDismissed,this.notificationService=A.notificationService,this.mcpTrustHandler=A.mcpTrustHandler,this.onThreadArchived=A.onThreadArchived,this.onActiveThreadChange=A.onActiveThreadChange,this.onRelaunchRequested=A.onRelaunchRequested,this.onFirstFrame=A.onFirstFrame,this.initialUserInput=A.initialUserInput,this.getDefaultNewThreadVisibility=A.getDefaultNewThreadVisibility,this.observeThreadSummaries=A.observeThreadSummaries,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.workspaceSettingsFilePath=A.workspaceSettingsFilePath,this.context=A.context}createState(){return new nR4}}class nR4 extends c0{editorController=new IZ;commandPalette=new jb0(this);commandRegistry=new qm0;toastController=new vb0;relaunchNotificationController=new Gm0;exitHintTimer=new kp(this,1000);ideStatus=new sB(this,{});threadNavigationHistory=new Km0;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;activeThreadIDSubscription=null;activePluginMessageSubscription=null;activePluginUIRequestsSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;executorAlreadyConnectedDialog=null;switchThreadPickerVisible=!1;welcomeVisible=!1;endCreditsVisible=!1;invadersHighScore=0;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;emptyThreadTerminalTitleController=new tl;pluginIntegration=null;mcpTrustIntegration=null;updateRelaunchIntegration=null;noticesPollingTimeout=null;notices;editorFocusNode=new B8({debugLabel:"EditorPanel"});loadThreads=async()=>{return this.widget.context.listThreads()};focusEditor=()=>{this.editorFocusNode.requestFocus()};focusEditorAfterNextFrame(){z6.instance.addPostFrameCallback(()=>{if(!this.mounted)return;this.focusEditor()},"Neo focus editor")}analyzeContextForThread=async(A,Q)=>{return gz4({ampURL:this.widget.context.ampURL,configService:this.widget.configService,threadID:A,signal:Q})};onSwitchThread=(A)=>{return this.connectToExistingThread(A,{recordNavigation:!0,rethrowError:!0})};onSelectSidebarThread=async(A)=>{this.focusEditor(),await this.onSwitchThread(A)};threadListSidebar=new sc0({state:this,isBlocked:()=>this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal(),getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,getWorkspaceRoot:()=>this.widget.context.workspaceRoot,loadThreads:this.loadThreads,observeThreadSummaries:()=>this.widget.observeThreadSummaries(),onSelectThread:this.onSelectSidebarThread,focusMainContent:this.focusEditor,getInitialVisible:()=>this.widget.context.threadListSidebarVisible});sendFeedbackReport=async(A)=>x80({configService:this.widget.configService,settingsFilePath:this.widget.context.settingsFilePath},A);archiveThread=async(A)=>{let Q=await H70({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let $=await pN4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};removeThreadLabel=async(A,Q)=>{let $=await lN4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};initState(){if(kX.getInstance().interceptConsole(),this.invadersHighScore=this.widget.context.invadersHighScore??0,this.notices=new rg0(this.widget.configService,($)=>this.setState($)),z6.instance.addPostFrameCallback(()=>{setTimeout(()=>this.widget.onFirstFrame?.(),0),this.noticesPollingTimeout=setTimeout(()=>{this.noticesPollingTimeout=null,this.notices.startPolling()},500)},"Neo notices polling"),this.widget.showWelcome)this.welcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:$,error:B})=>{if(S.error("Neo failed to connect to thread",{threadID:$,error:B}),!$)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configSubscription=this.widget.configService.config.subscribe(($)=>{this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(K00($.settings)))}),this.updateRelaunchIntegration=new zm0({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested,relaunchNotificationController:this.relaunchNotificationController,updateService:this.widget.updateService}),this.updateRelaunchIntegration.init(),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput,Q=this.widget.initialThreadIDs[0];if(Q){let $={};if(A)$.initialUserInput=A;this.connectToInitialThreads(Q,$)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.context.sessionAgentMode);this.pluginIntegration=new Xm0({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,context:this.widget.context,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread,readThreadMessages:this.readPluginThreadMessages,runAgent:this.runPluginAgent,onBlockingConfirmDialogChange:this.syncEmptyThreadPluginConfirmationTitle}),this.pluginIntegration.init(),this.mcpTrustIntegration=new nh0({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=X1.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this,Q=this.widget.context.pluginService?Xw4({pluginService:this.widget.context.pluginService,workspaceRoot:this.widget.context.workspaceRoot,logFilePath:this.widget.context.logFilePath,toastController:this.toastController}):[],B=[Hw4({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["resume"],status:{type:"enabled"},sortBoost:100,run:(E,D,J)=>{E.pushWithDismiss((U)=>ad0({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,loadThreadTail:this.widget.context.loadThreadTail,onSelectThread:this.onSwitchThread,onDismiss:U,onThreadSelected:J}))}},...this.threadListSidebar.commands(),{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(E,D,J)=>{A.navigateBack(),J()}},IO4({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:(E,D,J)=>{A.navigateForward(),J()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",status:{type:"enabled"},run:(E,D,J)=>{E.push(new $d0({mcpServers:this.widget.context.mcpServers,onDismiss:J}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",status:{type:"enabled"},run:(E)=>{E.pushWithDismiss((D)=>new tc0({toolboxes:this.widget.context.toolboxes,onDismiss:D}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","blog","announcements"],status:{type:"enabled"},run:async(E,D,J)=>{try{await t6(D,"https://ampcode.com/chronicle")}finally{J()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config"],status:{type:"enabled"},run:()=>{yK(this.widget.context.settingsFilePath).catch((E)=>{S.error("Failed to open settings file in editor",{error:E})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains"],status:{type:"enabled"},run:(E,D,J)=>{E.pushWithDismiss((U)=>new Qd0({onCancel:U,onSelect:(Y)=>{this.handleIdeSelection(Y),J()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["manual","?"],status:{type:"enabled"},run:(E,D,J)=>{E.push(new wm0({commands:eB.of(D).commands,onDismiss:J}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",status:{type:"enabled"},run:(E,D,J)=>{J(),A.showWelcome()}},{noun:"amp",verb:"end credits",description:"Roll the full-screen Amp credits",status:{type:"enabled"},run:(E,D,J)=>{J(),A.showEndCredits()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["v"],status:{type:"enabled"},run:(E,D,J)=>{E.push(new B1({header:"Amp Version",maxWidth:72,onDismiss:J,child:new D0({text:new h(i50({version:"0.0.1780478921-g021c3e",buildTimestamp:"2026-06-03T09:34:18.051Z",buildType:"release"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","bye"],shortcut:HA.ctrl("c"),status:{type:"enabled"},run:(E,D)=>{N4.maybeInvoke(D,new iK)}},...Q,...cN4(this.widget.context.logFilePath)].map((E)=>this.commandRegistry.register(E));return()=>{for(let E of B)E()}}build(A){let Q=this.buildHints(),$=this.ideStatus.getValue(),B=this.notices.current,E=new lc0({initialAgentMode:this.widget.context.sessionAgentMode,initialPluginAgentModeKey:this.widget.context.initialPluginAgentModeKey,analyzeContextForThread:this.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,editorFocusNode:this.editorFocusNode,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,sendFeedbackReport:this.sendFeedbackReport,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:$,statusItems:this.pluginIntegration?.getStatusItems()??[],pluginConfirmationBlocked:this.pluginIntegration?.hasBlockingConfirmDialog()??!1,notificationService:this.widget.notificationService,notice:this.activeThreadContext||this.welcomeVisible?null:B,onDismissNotice:(I)=>this.notices.dismiss(I)}),D=W4.of(A),J=D.capabilities.animationSupport!=="disabled",U=this.threadListSidebar.visibleWidth(),Y=Math.max(0,D.size.width-U),F=[new WA({constraints:Y4.tight(D.size.width,D.size.height),child:this.threadListSidebar.buildBody(E)})];if(this.commandPalette.isEnabled())F.push(new c6({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new um0({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.welcomeVisible)F.push(ad0({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,loadThreadTail:this.widget.context.loadThreadTail,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.welcomeVisible)F.push(new c6({debugLabel:"WelcomeDialogOverlay",child:new Ep0({onDismiss:this.dismissWelcome,onQuit:()=>X1.instance.stop(),animationsEnabled:J,variant:this.widget.welcomeVariant})}));let X=this.executorAlreadyConnectedDialog;if(X)F.push(new c6({debugLabel:"ExecutorAlreadyConnectedDialogOverlay",child:new em0({existingExecutorPid:X.existingExecutorPid,onChoice:this.handleExecutorAlreadyConnectedChoice})}));if(F.push(...this.mcpTrustIntegration?.buildDialogLayers()??[]),F.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.context.isInternalUser)F.push(new Om0({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:n90.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)F.push(new Ad0);if(this.endCreditsVisible)F.push(new nm0({onComplete:this.completeEndCredits,highScore:this.invadersHighScore,onHighScoreChange:this.updateInvadersHighScore}));return new HQ({context:this.widget.context,child:new eB({commandRegistry:this.commandRegistry,child:new wv({completionBuilder:this.widget.completionBuilder,child:new EQ({controller:this.toastController,child:new N4({actions:this.buildActions(),child:new pQ({debugLabel:"AppShortcuts",shortcuts:this.buildShortcuts(),child:new cQ({debugLabel:"AppShellFocus",canRequestFocus:!1,skipTraversal:!0,child:new Tb0({controller:this.toastController,complexToastControllers:[this.relaunchNotificationController,...B&&this.activeThreadContext&&!this.welcomeVisible?[this.notices]:[]],child:new Mm0({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new Bl({left:U,width:Y,child:new QQ({children:F})})})})})})})})})})})}buildShortcuts(){let A=new Map([[HA.ctrl("c"),new y70],[HA.ctrl("o"),new h70],[HA.alt("i"),new m70],[HA.alt("p"),new Wp],[HA.ctrl("."),new p70],[HA.ctrl("t"),new n70],...this.threadListSidebar.shortcutEntries()]);if(n90.env.NODE_ENV==="development"&&n90.platform==="darwin")A.set(HA.meta("r"),new b70);return A}buildActions(){let A=new pA(()=>{if(c2.hasAnyCopyableSelection())return c2.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new pA(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),$=new pA(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),B=new pA(()=>{return this.startNewDraftThread(),"handled"}),E=new pA(()=>{return X1.instance.stop(),"handled"}),D=new pA(()=>{return dl({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),"handled"}),J=new pA((I)=>{if(!I.text)return"ignored";return X1.instance.tuiInstance.clipboard.writeText(I.text).then((G)=>{if(G.ok)this.toastController.show(I.successMessage,"success",2000);else this.toastController.show(`${I.failureMessage}: ${G.userFacingErrorMessage}`,"error",4000)}).catch((G)=>{S.error("Failed to copy Neo text to clipboard",{error:G}),this.toastController.show(I.failureMessage,"error",2000)}),"handled"}),U=new pA(()=>{return X1.instance.toggleFrameStatsOverlay(),"handled"}),Y=new pA(()=>this.notices.dismissCurrent()?"handled":"ignored"),Z=new pA(()=>{if(!this.widget.context.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),F=Tw4({getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,context:this.widget.context,toastController:this.toastController,startNewDraftThread:this.startNewDraftThread,sendFeedbackReport:this.sendFeedbackReport}),X=new pA(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[y70,A],[Xl,B],[iK,E],[b70,D],[ZB,J],[Kl,$],[h70,Q],[m70,Z],...this.threadListSidebar.actionEntries(),[p70,Y],...F,[Wp,U],[n70,X]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.cancelOwnerUIRequests(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),this.widget.onActiveThreadChange?.(null),this.syncEmptyThreadPluginConfirmationTitle(),A.prompt!==void 0)this.editorController.text=A.prompt;this.focusEditorAfterNextFrame()}syncEmptyThreadPluginConfirmationTitle=()=>{this.emptyThreadTerminalTitleController.setPluginConfirmationBlocked(this.activeThreadContext===null&&(this.pluginIntegration?.hasBlockingConfirmDialog()??!1))};closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=this.applySessionDefaultsToThreadSettings(await pP(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){S.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.context.sessionAgentMode,$=A,B=Yq(Q),E=H50(this.widget.context,Q);if(B!==void 0&&E!==void 0)$={...$,[B]:E};return W50($,{agentMode:Q,explicitEffort:this.widget.context.explicitReasoningEffort,sessionState:this.widget.context})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=iR4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if($Y(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=iR4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(lK);if(this.exitHintTimer.isActive())A.add(Xv);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),X1.instance.stop();else this.exitHintTimer.activate()};dismissWelcome=()=>{if(!this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!1}),this.widget.onWelcomeDismissed?.()};updateInvadersHighScore=(A)=>{if(A<=this.invadersHighScore)return;this.setState(()=>{this.invadersHighScore=A}),JJ((Q)=>({...Q,neoInvadersHighScore:Math.max(Q.neoInvadersHighScore,A)})).catch((Q)=>{S.warn("Failed to save Neo Invaders high score",{error:Q instanceof Error?Q.message:String(Q)})})};showWelcome=()=>{if(this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!0})};showEndCredits=()=>{if(this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!0})};completeEndCredits=()=>{if(!this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!1})};promptExecutorAlreadyConnected(A){return new Promise((Q)=>{this.setState(()=>{this.executorAlreadyConnectedDialog={existingExecutorPid:A.existingExecutorPid,resolve:($)=>{Q($==="watch"?"observe":"disconnect")}}})})}handleExecutorAlreadyConnectedChoice=(A)=>{if(this.resolveExecutorAlreadyConnectedDialog(A),A==="exit")X1.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}),this.focusEditorAfterNextFrame()};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,$=null,B,E,D)=>{await this.ensureDraftThreadSettingsInitialized();let J=this.activeThreadContext?.client.getThreadId(),U=A.find(Z00);if(U)this.widget.history.add(U.text,n90.cwd()),this.widget.history.reset();let Y=$?void 0:await this.widget.getDefaultNewThreadVisibility?.(),Z=$??Y??null,F=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,Z??void 0,E,D);if(this.sendUserMessage(F,A,E?void 0:Q,E?void 0:B),!E)this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings);this.threadNavigationHistory.recordNavigation(J),this.setActiveClient(F)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.context.sessionAgentMode=A;let $=Q["reasoning.effort"];if($!==void 0)this.widget.context.lastReasoningEffortByMode={...this.widget.context.lastReasoningEffortByMode??{},[A]:$};let B=Yq(A),E=B?Q[B]:void 0;if(E!==void 0)this.widget.context.lastSpeedByMode={...this.widget.context.lastSpeedByMode??{},[A]:E};JJ((D)=>{let J={...D,agentMode:A};if($!==void 0)J={...J,lastReasoningEffortByMode:{...J.lastReasoningEffortByMode??{},[A]:$}};if(E!==void 0)J={...J,lastSpeedByMode:{...J.lastSpeedByMode??{},[A]:E}};return J}).catch((D)=>{S.warn("Failed to persist Neo session defaults for new message",{error:D instanceof Error?D.message:String(D)})})}sendUserMessage(A,Q,$,B,E){let D=l50(this.ideStatus.getValue());if(B===void 0){A.client.sendUserMessage(Q,$,{steer:E?.steer,userState:D}).catch((J)=>{S.warn("Failed to send user message",{error:J})});return}A.client.sendUserMessage(Q,$,{reasoningEffort:B,steer:E?.steer,userState:D}).catch((J)=>{S.warn("Failed to send user message",{error:J})})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};getRelaunchThreadIDs=()=>{let A=new Set,Q=this.getActiveThreadID();if(Q)A.add(Q);for(let $ of this.widget.clientPool.activeThreadIDs)A.add($);return[...A]};appendPluginMessagesToThread=async(A,Q,$)=>{let B=this.activeThreadContext;if(!B){if(Q){for(let D of A)await this.widget.clientPool.appendUserMessageToThread(Q,D.content,$);return}throw Error("appendToThread is not available - no active thread")}let E=B.client.getThreadId();if(Q&&E!==Q){for(let D of A)await this.widget.clientPool.appendUserMessageToThread(Q,D.content,$);return}for(let D of A)this.sendUserMessage(B,[{type:"text",text:D.content}],void 0,void 0,$)};readPluginThreadMessages=async(A,Q)=>{let $=this.activeThreadContext;if(!$)throw Error("thread.messages is not available - no active thread");let B=$.client.getThreadId();if(Q&&B!==Q)throw Error("thread.messages is only available for the active thread");return BoA(EoA($.observer.protocolMessages()),A)};runPluginAgent=async(A,Q)=>{await this.ensureDraftThreadSettingsInitialized();let $=this.widget.clientPool.createNewThread(this.widget.context.sessionAgentMode,this.draftThreadSettings,void 0,A,Q.agentModeDisplay,Q.parentThreadID,{trackAsLastActive:!1});this.sendUserMessage($,[{type:"text",text:Q.message}]);try{let B=await sF6($,{timeoutMs:Q.timeoutMs}),E=$.client.getThreadId();return E?{threadID:E,text:B}:{text:B}}finally{this.widget.clientPool.disconnect($)}};async connectToExistingThread(A,Q={}){let $=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let B=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:(E)=>this.promptExecutorAlreadyConnected(E)});if(this.setActiveClient(B),Q.recordNavigation&&$!==A)this.threadNavigationHistory.recordNavigation($);if(Q.initialUserInput)this.sendUserMessage(B,[{type:"text",text:Q.initialUserInput}])}catch(B){if(S.error("Failed to load thread",{error:B,threadID:A}),this.toastController.show(`Failed to load ${A}: ${B instanceof Error?B.message:String(B)}`,"error",4000),Q.rethrowError)throw B}finally{this.setState(()=>{this.connectingToThreadID=null})}}async connectToInitialThreads(A,Q={}){await this.connectToExistingThread(A,Q);let $=this.widget.initialThreadIDs.filter((B)=>B!==A);await Promise.all($.map((B)=>this.resumeBackgroundThread(B)))}async resumeBackgroundThread(A){try{await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:async()=>"observe"})}catch(Q){S.error("Failed to resume background thread",{error:Q,threadID:A}),this.toastController.show(`Failed to resume ${A}: ${Q instanceof Error?Q.message:String(Q)}`,"error",4000)}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}setActiveClient({client:A,observer:Q,agentModeDisplay:$}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q,agentModeDisplay:$}}),this.syncEmptyThreadPluginConfirmationTitle(),this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe((B)=>{this.widget.onActiveThreadChange?.(B)}),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription?.unsubscribe(),this.pluginIntegration?.cancelOwnerUIRequests(),this.activePluginMessageSubscription=Q.pluginMessages().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage(B,(E)=>{A.sendPluginMessage(E)})}),this.activePluginUIRequestsSubscription=Q.pluginUIRequests().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage({type:"plugin_message",message:{type:"event",event:"plugin.ui.snapshot",data:{requests:[...B]}}},(E)=>{A.sendPluginMessage(E)})})}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){S.error("Failed to connect to IDE",{error:Q});let $=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${$}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.threadListSidebar.dispose(),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.emptyThreadTerminalTitleController.dispose(),this.mcpTrustIntegration?.dispose(),this.mcpTrustIntegration=null,this.updateRelaunchIntegration?.dispose(),this.updateRelaunchIntegration=null,this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.noticesPollingTimeout)clearTimeout(this.noticesPollingTimeout),this.noticesPollingTimeout=null;this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.notices.dispose(),this.widget.notificationService.detach(),this.toastController.dispose(),this.editorFocusNode.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.executorAlreadyConnectedDialog!==null||this.welcomeVisible||(this.mcpTrustIntegration?.hasBlockingDialog()??!1)||this.endCreditsVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function iR4(A,Q,$){let B={...A};for(let E of tF6(Q,$)){if(!$Y(A[E],Q[E]))continue;let D=$[E];if(D===void 0)delete B[E];else B[E]=D}return B}function tF6(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}hB();function aR4(A,Q,$,B){let E=ZbA(A),D="\x1B[0m",J="\x1B[34m",U="\x1B[90m",Y="\x1B[2m",Z=[];if(A.archived)Z.push("\x1B[90m\x1B[2mArchived\x1B[0m");Z.push(`${E}`),Z.push(`\x1B[34m${Q}\x1B[0m`),Z.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let F=14,X=7,I=new m2(F,X),G=new v5(42),V=new Ov(F,X,F,X,F,X,0,A.agentMode??"smart","intensity","ascii",void 0,void 0,d0.default(),G);V.layout(Y4.tight(F,X)),V.paint(I,0,0);let K=I.getBuffer().getCells(),z=0;for(let R=0;R<X;R++)if(K[R].some((_)=>_.char!==" ")){z=R;break}let W=X-1;for(let R=X-1;R>=0;R--)if(K[R].some((_)=>_.char!==" ")){W=R;break}function C(R,_){if(!R)return"";if(R.type==="rgb"){let{r:v,g:k,b:m}=R.value;if($.getColorDepth()>=24)return`\x1B[${_?38:48};2;${v};${k};${m}m`;let x=Mp(v,k,m);return`\x1B[${_?38:48};5;${x}m`}return""}let H=[];if(W>=z)for(let R=z;R<=W;R++){let _="";for(let v=0;v<F;v++){let k=K[R][v],m=k.char,x=C(k.style.fg,!0);_+=x+m+"\x1B[0m"}H.push(_)}let N=H.length,q=Math.max(N,Z.length),w=Math.floor((q-N)/2),O=Math.floor((q-Z.length)/2);for(let R=0;R<q;R++){let _=" ".repeat(F);if(R>=w&&R<w+N)_=H[R-w];let v=" ",k="";if(R>=O&&R<O+Z.length)k=Z[R-O];$.write(_+v+k+`
|
|
4432
4432
|
`)}if(B)$.write(`
|
|
4433
4433
|
\x1B[90m${B}\x1B[0m
|
|
4434
4434
|
`)}a0();class Jp0{status=f3.status;constructor(){this.autoConnect()}async connect(A){await f3.start(A,!0,"user-initiated"),f3.selectConfig(A)}autoConnect(){let A=f3.getSelectedConfig();if(A){f3.start(A,!0,"auto-startup").catch((Q)=>{S.error("Failed to auto-connect to IDE",{error:Q})});return}this.discoverAndConnect()}async discoverAndConnect(){try{await ThA();let A=await sC({});if(A.length===1&&A[0])f3.selectConfig(A[0]),await f3.start(A[0],!0,"auto-startup")}catch(A){S.error("Failed to auto-discover IDE",{error:A})}}}a0();a0();import{exec as eq}from"node:child_process";function oR4(A="idle"){try{if(A==="idle"){if(process.platform==="darwin")eq("afplay /System/Library/Sounds/Submarine.aiff");else if(process.platform==="win32")eq("powershell [console]::beep(800,200)");else if(process.platform==="linux")eq("paplay /usr/share/sounds/freedesktop/stereo/message.oga || beep")}else if(A==="idle-review"){if(process.platform==="darwin")eq("afplay /System/Library/Sounds/Glass.aiff")}else if(A==="requires-user-input"){if(process.platform==="darwin")eq("afplay /System/Library/Sounds/Ping.aiff");else if(process.platform==="win32")eq("powershell [console]::beep(1000,300)");else if(process.platform==="linux")eq("paplay /usr/share/sounds/freedesktop/stereo/dialog-information.oga || beep -f 1000 -l 100")}}catch(Q){S.error(`Failed to play notification sound (${A}):`,Q)}}Pp();Hb0();var eF6=2000,AX6="Agent is ready",QX6="Waiting for approval";function rR4(A){let Q=!0,$=!0,B=A.configService.config.subscribe((W)=>{Q=W.settings["notifications.enabled"]??!0,$=W.settings["notifications.system.enabled"]!==!1}),E=0,D=()=>{let W=G?.prepareTerminalTitleForNotification();if(W!==void 0)process.stdout.write(cK4(W))},J=(W)=>{if(!Q)return;let C=Date.now();if(C-E<eF6)return;if(E=C,xK())return;if(PG4())D(),setTimeout(vG4,Eb0);else oR4(W)},U=()=>{J("idle"),V(AX6)},Y=()=>{J("requires-user-input"),V(QX6)},Z=(W)=>W?.attempt===void 0||W.attempt===0,F=null,X=null,I=null,G,V=(W)=>{if(!Q||!$)return;if(xK()&&!Cb0()&&!T50())return;D(),setTimeout(()=>{process.stdout.write(dK4(W))},Eb0)},K=()=>{F?.unsubscribe(),X?.unsubscribe(),F=null,X=null,I=null,G=void 0};return{attach:(W,C,H)=>{if(K(),G=H,C)X=C.subscribe({next:(N)=>{if(N===null)return;if(!Z(N))return;U()},error:(N)=>{S.debug("Neo notification active error stream errored",{error:N})}});F=W.subscribe({next:(N)=>{try{let q=I!==null&&c3(I),w=I==="awaiting_approval",O=q||w;if(N==="awaiting_approval"&&!w)Y();else if(N==="idle"&&O)U()}catch(q){S.debug("Neo notification handling failed",{error:q})}finally{I=N}},error:(N)=>{S.debug("Neo notification agent state stream errored",{error:N})}})},detach:K,unsubscribe(){K(),B.unsubscribe()}}}function $X6({initialUserInput:A,showWelcome:Q,hideWelcome:$,welcomeVariant:B,welcomeDismissed:E}){if($)return{show:!1,markDismissedOnDismiss:!1};if(B==="npm-migration")return{show:!0,markDismissedOnDismiss:!1};if(Q)return{show:!0,markDismissedOnDismiss:!0};let D=!A&&!E;return{show:D,markDismissedOnDismiss:D}}async function BX6(A){await JJ((Q)=>nP(Q,A,"interactive"))}async function sR4(A,Q={}){let{initialThreadIDs:$=[],initialUserInput:B,getDefaultNewThreadVisibility:E,openThreadPickerOnStart:D=!1,observerOnly:J=!1,initialAgentMode:U,initialPluginAgentModeKey:Y,initialReasoningEffort:Z,onFirstFrame:F,showWelcome:X=!1,hideWelcome:I=!1,welcomeVariant:G="intro"}=Q,V=G==="npm-migration";if($.length>1)S.info("Resuming multiple initial threads",{threadIDs:$});let K=async(m)=>{let x=await A.getThreadFromServer(m);if(!x)return null;return g30(x)},z=async(m)=>{let x=await A.getThreadFromServer(m);if(!x)throw Error(`Thread ${m} not found`);let T=await JB(m,A.configService,A.apiKey,{usesThreadActors:!0}),f=Z7({endpoint:A.rivetEndpoint,poolName:T.poolName}),c={wsToken:T.wsToken,transport:"json-rpc"},b=await f.threadActor.get([T.threadId],{params:c}).fetch("/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({thread:m30(x)}),skipReadyWait:!0});if(!b.ok&&b.status!==409)throw Error(`Thread import failed (${b.status}): ${await b.text()}`);try{await o30(m,A.configService,A.apiKey,{executorType:"local-client"})}catch(p){S.warn("failed to mark thread as imported on server",{threadID:m,error:p instanceof Error?p.message:String(p)})}},W=new ay0(A.rivetEndpoint,A.apiKey,A.configService,{clientID:uK.parse(`neo-${crypto.randomUUID()}`),toolService:A.toolService,skillService:A.skillService,requestPluginToolCall:(m)=>A.pluginService.event.toolCall(m),requestPluginToolResult:(m)=>A.pluginService.event.toolResult(m),pluginService:A.pluginService,pluginPlatform:A.pluginPlatform,canUseV2LocalThreadChanges:A.canUseV2LocalThreadChanges,invokeTool:async(m,x)=>{let T=typeof x.args==="object"&&x.args!==null?x.args:{},f=await vK({toolName:x.toolName,configService:A.configService,toolService:A.toolService,mcpService:A.mcpService,skillService:A.skillService,toolUseID:x.toolCallId,threadId:m});return A.toolService.invokeTool(x.toolName,{args:T},f)},persistLastThreadID:BX6,readFileSystemDirectory:A.readFileSystemDirectory},K,z),C=await Zq(),H=$X6({initialUserInput:B,showWelcome:X,hideWelcome:I,welcomeVariant:G,welcomeDismissed:C.neoWelcomeDismissed}),N={ampURL:A.ampURL,configService:A.configService,getThreadMarkdown:async(m)=>{let x=await A.getThreadFromServer(m);return x?FQ0(x):null},isInternalUser:A.isInternalUser,listThreads:A.listThreads,loadThreadTail:A.getThreadTail,logFilePath:pc,mcpServers:A.mcpService.servers,pluginPlatform:A.pluginPlatform,pluginService:A.pluginService,toolboxes:A.toolboxes,observerOnly:V?!1:J,invadersHighScore:C.neoInvadersHighScore,sessionAgentMode:U??C.agentMode,threadListSidebarVisible:C.threadListSidebarVisible,initialPluginAgentModeKey:Y,explicitReasoningEffort:Z,lastReasoningEffortByMode:C.lastReasoningEffortByMode,lastSpeedByMode:C.lastSpeedByMode,settingsFilePath:A.settingsFilePath,workspaceRoot:A.workspaceRoot},q=(m,x)=>{return OK4({ampURL:A.ampURL,configService:A.configService,threadID:m,signal:x})},w=()=>jK4({apiKey:A.apiKey,configService:A.configService,rivetEndpoint:A.rivetEndpoint}),O=new Jp0,R=rR4({configService:A.configService}),_=await A.configService.getLatest();X1.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:_.settings["terminal.animation"]===!1}});let v=new Set,k=new Im0;try{await Nb0(new Dp0({clientPool:W,listSkillsForThread:q,completionBuilder:A.completionBuilder,history:new Ly0,ideManager:O,configService:A.configService,updateService:A.updateService,initialThreadIDs:V?[]:$,notificationService:R,mcpTrustHandler:A.mcpTrustHandler,initialUserInput:V?void 0:B,getDefaultNewThreadVisibility:E,observeThreadSummaries:w,openThreadPickerOnStart:V?!1:D,workspaceSettingsFilePath:A.workspaceSettingsFilePath,context:N,showWelcome:H.show,welcomeVariant:G,onActiveThreadChange:A.setActiveThreadID,onRelaunchRequested:k.request,onWelcomeDismissed:H.markDismissedOnDismiss?()=>{JJ(TK4).catch((x)=>{S.warn("Failed to mark Neo welcome as dismissed",{error:x})})}:void 0,onThreadArchived:(x)=>{v.add(x)},onFirstFrame:F}));let m=W.lastActiveObservingClient;if(m&&k.shouldShowExitSummary){let{client:x,observer:T}=m,f=x.getThreadId();if(f){let c={id:f,title:T.title().getValue(),agentMode:T.agentMode,archived:v.has(f)},d=`${A.ampURL.replace(/\/$/,"")}/threads/${f}`;aR4(c,d,process.stdout)}}}finally{process.stdout.write(k50("")),R.unsubscribe(),W.dispose(),await A.dispose?.()}process.exit(k.relaunchIfRequested(A.workspaceRoot)??0)}import{execFile as EX6}from"node:child_process";import{closeSync as tR4,openSync as DX6,writeSync as JX6}from"node:fs";import UX6 from"node:tty";var YX6="\x1B[c",ZX6="\x1B[?1004h",FX6="\x1B[?1004l",XX6="\x1B[?u",eR4=200,IX6="\x1B[>4;2m",GX6="\x1B[?9001h",VX6="\x1B[?9001l";function AP4(){let A=null;try{if(process.stdout.isTTY){let Q=process.stdout.getWindowSize();A=[Q[0],Q[1]]}}catch{}return{isTTY:process.stdout.isTTY,columns:process.stdout.columns??null,rows:process.stdout.rows??null,windowSize:A,hasRefreshSize:typeof process.stdout._refreshSize==="function"}}function KX6(){if(process.stdout.isTTY)return{stream:process.stdout,target:"stdout",dispose:()=>{}};if(process.stderr.isTTY)return{stream:process.stderr,target:"stderr",dispose:()=>{}};if(process.platform!=="win32")try{let A=DX6("/dev/tty","w");if(UX6.isatty(A))return{stream:{write(Q){return JX6(A,Q),!0}},target:"dev-tty",dispose:()=>{tR4(A)}};tR4(A)}catch{}return{stream:process.stdout,target:"stdout",dispose:()=>{}}}function j$(A,Q){if(!process.stdout.writable||process.stdout.destroyed){Q?.();return}let $=`${JSON.stringify(A)}
|
|
@@ -6359,7 +6359,7 @@ Start Amp from a smaller directory.`};function $I(A,Q){if(!CG4())return;S.debug(
|
|
|
6359
6359
|
`)}function ev4(A,Q){A.command("usage").description("Show your current Amp usage and credit balance").action(async($,B)=>{let E=B.optsWithGlobals(),D=await Q(E),J=await t30(D),U=await j4.userDisplayBalanceInfo({},{config:J});if(!U.ok){if(U.error.code==="auth-required")process.stderr.write(f0.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(f0.red("Error: ")+U.error.message+`
|
|
6360
6360
|
`),process.exit(1)}process.stdout.write(await yK6(U.result.displayText)+`
|
|
6361
6361
|
`),process.exit(0)})}var JN6=pi.join(AY,"logs","headless.log"),Ji0=pi.join(ty,"device-id.json");MX4();async function UN6(){let A=await Promise.all(rC.map(async(Q)=>{try{return{query:Q,hasConfigs:(await Q.listConfigs()).length>0}}catch($){return S.debug("Failed to detect query-based IDE integration",{ideName:Q.ideName,error:$}),{query:Q,hasConfigs:!1}}}));for(let Q of A)if(Q.hasConfigs)return Q.query;return}function jk4(){UN6().then((A)=>{if(A){let Q=P00(A.ideName);if(Q)pC(Q)}})}try{if(process.platform==="win32")await Promise.resolve().then(() => M4(VT(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){q7.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
|
|
6362
|
-
`)}function YN6(A){process.emitWarning=(Q,$,B,E)=>{let D=typeof Q==="string"?Q:Q.message||String(Q),J=$||"Warning",U=!1;A.warn(D,{name:J,code:B})}}function u3(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")iG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli"&&KT(Q.mode))iG("experimental.agentMode",Q.mode)}function ZN6(A,Q){if(!J$(Q))return;if(!_7(Q.user.email)){if(A.model)throw new GA("The --model flag is only available for Amp employees.",1);iG("internal.model",void 0);return}if(A.model)iG("internal.model",IN6(A.model))}function Nk4(A){let Q=A.indexOf(":");if(Q===-1)throw new GA(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let $=A.slice(0,Q).trim(),B=A.slice(Q+1).trim();if(!$||!B)throw new GA(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function FN6(A){if(A===void 0)return;let Q=A.trim();if(I00(Q))return Q;throw new GA(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function XN6(A,Q){if(nC(A))return;throw new GA(`Reasoning effort "${Q}" is not available for ${A} mode.`,1)}function IN6(A){if(!A.includes("="))return Nk4(A),A;let Q={};for(let $ of A.split(",")){let B=$.trim();if(!B)continue;let E=B.indexOf("=");if(E===-1)throw new GA(`Invalid mode-specific model entry "${B}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let D=B.slice(0,E).trim(),J=B.slice(E+1).trim();if(!D)throw new GA(`Missing mode name in "${B}". Expected "mode=provider:model".`,1);if(!J)throw new GA(`Missing model value for mode "${D}". Expected "${D}=provider:model".`,1);Nk4(J),Q[D]=J}if(Object.keys(Q).length===0)throw new GA("No valid model overrides found in --model flag value.",1);return Q}function sE0(A,Q,$){let B=Number(A);if(!Number.isInteger(B)||B<$.min)throw new L30(`${Q} must be an integer >= ${$.min}`);if($.max!==void 0&&B>$.max)throw new L30(`${Q} must be an integer <= ${$.max}`);return B}function GN6(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 VN6(A){try{return await Lk4(A,"utf-8")}catch{return A}}async function KN6(A,Q,$){let B=GN6(A,Q);if(!B)return;let E=J$($)?$.features:[],D=J$($)?$.user.email:void 0;if(!Zi0(E,WD.HARNESS_SYSTEM_PROMPT)&&!(D&&_7(D)))throw new GA("You are not allowed to do this.",1);iG("systemPrompt",await VN6(B))}function Zi0(A,Q){return A?.some(($)=>$.name===Q&&$.enabled)??!1}async function zN6(A,Q){let $=await j4.getUserInfo({},{config:A});return $.ok?Zi0($.result.features,Q):!1}function WN6(A){return A!=="pending"}function Gu(A){if(!J$(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function CN6(A){let Q=Gu(A);if(Q)return Q.id;if(lC(A))throw Error(A.error.message);throw Error("unreachable")}function HN6(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 NN6(A){let B=HN6(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 GA(`Couldn't connect to the Amp server at ${A}.`,1,B)}function Fi0(A,Q){let $=fx0(Error(A.error.message));if($.message===W3.networkOffline||$.message===W3.networkTimeout)return NN6(Q);if($.message!==W3.internalBug)return new GA($.message,1,$.suggestion);return new GA(A.error.message.replace(/^Error: /,""),1)}async function qN6(){if(process.versions.bun)return!1;try{return await EZ()==="npm"}catch(A){return S.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var qk4=[{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??$2,description:`Custom settings file path (overrides the default location ${$2})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(S).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${pc})`},{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:jE(),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:s9.SMART.key,description:`Set the agent mode (${lG({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Show migration instructions for the removed legacy runtime",hidden:!0},{name:"orb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"hideWelcome",long:"hide-welcome",type:"switch",description:"Skip the welcome experience on startup",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],uk4=(A)=>("deprecated"in A)&&A.deprecated===!0,uN6=(A)=>("hidden"in A)&&A.hidden===!0,wN6=(A)=>("default"in A),MN6=(A)=>("default"in A)?A.default:void 0;function wk4(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let $=FN6(Q.effort);if($!==void 0){if(KT(Q.mode))XN6(Q.mode,$)}return $}var ON6="Amp Neo is now Amp and available to everyone. If you need to finish work in the old Amp, you can use an older version. For instructions on how to do that and more information: https://ampcode.com/news/drop-the-neo";function KT(A){return Object.values(s9).some((Q)=>Q.key===A)}function LN6(A,Q){if(KT(A))return A;throw new GA(`${Q} does not support plugin-defined agent modes`,1)}function Rk4(A,Q){if(KT(Q))return{agentMode:Q};let $=A.agentModes.list().find((E)=>E.key===Q||E.label===Q);if(!$){let E=lG({}).map((U)=>U.mode).join(", "),D=A.agentModes.list().map((U)=>U.label).join(", "),J=D?` Plugin modes: ${D}.`:"";throw new GA(`Unknown agent mode '${Q}'. Built-in modes: ${E}.${J}`,1)}let B={label:$.label};if($.color!==void 0)B.color=$.color;return{agentMode:s9.SMART.key,agent:$.agent,agentModeDisplay:B,pluginAgentModeKey:$.key}}async function jN6(A,Q,$){if(A.getOptionValueSourceWithGlobals("mode")!=="cli")return;return await Q.initialized,Rk4(Q,$)}function RN6(A,Q){let $=Q.args[0],B=Q.commands.map((D)=>D.name());if($&&!$.includes(" ")&&$.length<30&&!/[./\\]/.test($)){let D=B.filter((U)=>$.includes(U)||U.includes($)),J="Run amp --help for a list of available commands.";if(D.length>0)J=`Did you mean: ${D.join(", ")}? Or run amp --help for all commands.`;throw new GA(W3.unknownCommand($),1,J)}}var tE0=m0.file(DN6.homedir()),Ui0=process.env.XDG_CONFIG_HOME?m0.file(process.env.XDG_CONFIG_HOME):BA.joinPath(tE0,".config");async function vB(A,Q,$){let B=$?.deferAuth??!1,E=$?.skipToolProviders??!1;NbA("0.0.1780464815-g688406");let D=u00({storage:A.settings,secretStorage:A.secrets,workspaceRoot:process.cwd(),defaultAmpURL:A.ampURL,homeDir:tE0,userConfigDir:Ui0}),J=A.secrets.get("apiKey",A.ampURL),U=AL(D),Y=null,Z=()=>{return},F=new Promise((t)=>{Z=t}),X=J.then(async(t)=>{if(!t&&!B)await F;return Y??=U.subscribe(()=>{}),T4(U.pipe(U5(WN6)))});X.catch(()=>{return}),kv4(D);let I=await D.getLatest();S.debug("Global configuration initialized",{settingsKeys:Object.keys(I.settings)});let G=!1;{let t=await J;if(G=Boolean(t),S.info("API key lookup before login",{found:Boolean(t),ampURL:A.ampURL,deferAuth:B}),!t)if(B)S.info("No API key found, continuing startup with deferred auth");else{vQ.write(`No API key found. Starting login flow...
|
|
6362
|
+
`)}function YN6(A){process.emitWarning=(Q,$,B,E)=>{let D=typeof Q==="string"?Q:Q.message||String(Q),J=$||"Warning",U=!1;A.warn(D,{name:J,code:B})}}function u3(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")iG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli"&&KT(Q.mode))iG("experimental.agentMode",Q.mode)}function ZN6(A,Q){if(!J$(Q))return;if(!_7(Q.user.email)){if(A.model)throw new GA("The --model flag is only available for Amp employees.",1);iG("internal.model",void 0);return}if(A.model)iG("internal.model",IN6(A.model))}function Nk4(A){let Q=A.indexOf(":");if(Q===-1)throw new GA(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let $=A.slice(0,Q).trim(),B=A.slice(Q+1).trim();if(!$||!B)throw new GA(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function FN6(A){if(A===void 0)return;let Q=A.trim();if(I00(Q))return Q;throw new GA(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function XN6(A,Q){if(nC(A))return;throw new GA(`Reasoning effort "${Q}" is not available for ${A} mode.`,1)}function IN6(A){if(!A.includes("="))return Nk4(A),A;let Q={};for(let $ of A.split(",")){let B=$.trim();if(!B)continue;let E=B.indexOf("=");if(E===-1)throw new GA(`Invalid mode-specific model entry "${B}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let D=B.slice(0,E).trim(),J=B.slice(E+1).trim();if(!D)throw new GA(`Missing mode name in "${B}". Expected "mode=provider:model".`,1);if(!J)throw new GA(`Missing model value for mode "${D}". Expected "${D}=provider:model".`,1);Nk4(J),Q[D]=J}if(Object.keys(Q).length===0)throw new GA("No valid model overrides found in --model flag value.",1);return Q}function sE0(A,Q,$){let B=Number(A);if(!Number.isInteger(B)||B<$.min)throw new L30(`${Q} must be an integer >= ${$.min}`);if($.max!==void 0&&B>$.max)throw new L30(`${Q} must be an integer <= ${$.max}`);return B}function GN6(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 VN6(A){try{return await Lk4(A,"utf-8")}catch{return A}}async function KN6(A,Q,$){let B=GN6(A,Q);if(!B)return;let E=J$($)?$.features:[],D=J$($)?$.user.email:void 0;if(!Zi0(E,WD.HARNESS_SYSTEM_PROMPT)&&!(D&&_7(D)))throw new GA("You are not allowed to do this.",1);iG("systemPrompt",await VN6(B))}function Zi0(A,Q){return A?.some(($)=>$.name===Q&&$.enabled)??!1}async function zN6(A,Q){let $=await j4.getUserInfo({},{config:A});return $.ok?Zi0($.result.features,Q):!1}function WN6(A){return A!=="pending"}function Gu(A){if(!J$(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function CN6(A){let Q=Gu(A);if(Q)return Q.id;if(lC(A))throw Error(A.error.message);throw Error("unreachable")}function HN6(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 NN6(A){let B=HN6(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 GA(`Couldn't connect to the Amp server at ${A}.`,1,B)}function Fi0(A,Q){let $=fx0(Error(A.error.message));if($.message===W3.networkOffline||$.message===W3.networkTimeout)return NN6(Q);if($.message!==W3.internalBug)return new GA($.message,1,$.suggestion);return new GA(A.error.message.replace(/^Error: /,""),1)}async function qN6(){if(process.versions.bun)return!1;try{return await EZ()==="npm"}catch(A){return S.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var qk4=[{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??$2,description:`Custom settings file path (overrides the default location ${$2})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(S).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${pc})`},{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:jE(),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:s9.SMART.key,description:`Set the agent mode (${lG({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Show migration instructions for the removed legacy runtime",hidden:!0},{name:"orb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"hideWelcome",long:"hide-welcome",type:"switch",description:"Skip the welcome experience on startup",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],uk4=(A)=>("deprecated"in A)&&A.deprecated===!0,uN6=(A)=>("hidden"in A)&&A.hidden===!0,wN6=(A)=>("default"in A),MN6=(A)=>("default"in A)?A.default:void 0;function wk4(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let $=FN6(Q.effort);if($!==void 0){if(KT(Q.mode))XN6(Q.mode,$)}return $}var ON6="Amp Neo is now Amp and available to everyone. If you need to finish work in the old Amp, you can use an older version. For instructions on how to do that and more information: https://ampcode.com/news/drop-the-neo";function KT(A){return Object.values(s9).some((Q)=>Q.key===A)}function LN6(A,Q){if(KT(A))return A;throw new GA(`${Q} does not support plugin-defined agent modes`,1)}function Rk4(A,Q){if(KT(Q))return{agentMode:Q};let $=A.agentModes.list().find((E)=>E.key===Q||E.label===Q);if(!$){let E=lG({}).map((U)=>U.mode).join(", "),D=A.agentModes.list().map((U)=>U.label).join(", "),J=D?` Plugin modes: ${D}.`:"";throw new GA(`Unknown agent mode '${Q}'. Built-in modes: ${E}.${J}`,1)}let B={label:$.label};if($.color!==void 0)B.color=$.color;return{agentMode:s9.SMART.key,agent:$.agent,agentModeDisplay:B,pluginAgentModeKey:$.key}}async function jN6(A,Q,$){if(A.getOptionValueSourceWithGlobals("mode")!=="cli")return;return await Q.initialized,Rk4(Q,$)}function RN6(A,Q){let $=Q.args[0],B=Q.commands.map((D)=>D.name());if($&&!$.includes(" ")&&$.length<30&&!/[./\\]/.test($)){let D=B.filter((U)=>$.includes(U)||U.includes($)),J="Run amp --help for a list of available commands.";if(D.length>0)J=`Did you mean: ${D.join(", ")}? Or run amp --help for all commands.`;throw new GA(W3.unknownCommand($),1,J)}}var tE0=m0.file(DN6.homedir()),Ui0=process.env.XDG_CONFIG_HOME?m0.file(process.env.XDG_CONFIG_HOME):BA.joinPath(tE0,".config");async function vB(A,Q,$){let B=$?.deferAuth??!1,E=$?.skipToolProviders??!1;NbA("0.0.1780478921-g021c3e");let D=u00({storage:A.settings,secretStorage:A.secrets,workspaceRoot:process.cwd(),defaultAmpURL:A.ampURL,homeDir:tE0,userConfigDir:Ui0}),J=A.secrets.get("apiKey",A.ampURL),U=AL(D),Y=null,Z=()=>{return},F=new Promise((t)=>{Z=t}),X=J.then(async(t)=>{if(!t&&!B)await F;return Y??=U.subscribe(()=>{}),T4(U.pipe(U5(WN6)))});X.catch(()=>{return}),kv4(D);let I=await D.getLatest();S.debug("Global configuration initialized",{settingsKeys:Object.keys(I.settings)});let G=!1;{let t=await J;if(G=Boolean(t),S.info("API key lookup before login",{found:Boolean(t),ampURL:A.ampURL,deferAuth:B}),!t)if(B)S.info("No API key found, continuing startup with deferred auth");else{vQ.write(`No API key found. Starting login flow...
|
|
6363
6363
|
`);let W0=await PN6(A),l=await A.secrets.get("apiKey",A.ampURL);if(S.info("Login flow completed",{success:W0,storedKeyPresent:Boolean(l),ampURL:A.ampURL}),!W0)await $Z(),process.exit(1);G=!0,Z()}}{let t=await D.getLatest(),W0=t.settings.url,l=t.secrets.isSet?.[W0];S.info("Config secrets state after login",{configURL:W0,apiKeySet:l?.apiKey??!1})}let V=B?"pending":await X;if(!B)S.info("Server status resolved",{status:"ready",isAuthenticated:J$(V),isError:lC(V),errorMessage:lC(V)?V.error.message:void 0});ZN6(Q,V);let K=X.then((t)=>CN6(t));K.catch(()=>{return});let z=J$(V),W=!1;if(process.env.AMP_DISABLE_PLUGINS==="1")S.warn("Ignoring AMP_DISABLE_PLUGINS outside development");let C=W?"off":"all",{toolService:H,dispose:N}=tD4({configService:D}),q=new Map,w=()=>q.clear(),O=new kM0(D,A.settings.getWorkspaceRootPath()),R=ltA({configService:D}),_=LaA({configService:D,trustStore:O,skillMCPServers:R.skillMCPServers,uploadImageAttachments:z,createOAuthProvider:async(t,W0,l)=>{let i=`${t}:${W0}`,A0=q.get(i);if(A0)return S.debug("Reusing existing OAuth provider for server",{serverName:t,serverUrl:W0}),A0;S.debug("Creating OAuth provider for server",{serverName:t,serverUrl:W0});let s=(async()=>{let B0=new BH(A.secrets),Q0=await B0.getClientInfo(t,W0),V0=l?.scopes??Q0?.scopes,K0=fG4();S.info("OAuth headless mode check",{useHeadless:K0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:vQ.isTTY});let w0;if(K0)w0=A.executeMode?kG4():SG4(t);let X0=new Lq0({storage:B0,serverName:t,serverUrl:W0,clientId:l?.clientId??Q0?.clientId,clientSecret:l?.clientSecret??Q0?.clientSecret,authUrl:l?.authUrl??Q0?.authUrl,tokenUrl:l?.tokenUrl??Q0?.tokenUrl,scopes:V0,headlessAuthHandler:w0});return S.debug("OAuth provider created",{serverName:t,serverUrl:W0,hasManualClientId:!!(l?.clientId??Q0?.clientId),willUseDCR:!(l?.clientId??Q0?.clientId),scopes:V0,headlessMode:K0,executeMode:A.executeMode}),X0})();return q.set(i,s),s}}),v=fL0({configService:D,spawn:GQ0}),k=Q.headless?sP4():void 0,m=k??new DE0({configService:D}),x=m instanceof DE0?m:void 0;if(x)x.pluginExecutorKind="local";let T=new K4(null),f=null,c=z&&!W?[...Av4(I.settings)?[{name:"permissions",entryPoint:up0}]:[],{name:"thread-visibility",entryPoint:Bv4(D,()=>X.then(Gu),()=>f,(t)=>{f=t}),alwaysLoad:!0}]:[],d=nM0({configService:D,platform:m,loadGlobalPlugins:sx0(D),pluginFilter:C,activeThread$:T,internalPlugins:c}),b=OoA(d),p=[_,v,b],n;if(E)n=new Map;else if(A.executeMode){let t=await W04({toolService:H,providers:p,initialTimeout:15000});n=t.registrations;for(let[W0,l]of t.initErrors)S.warn(`${W0} provider initialization slow or failed:`,l)}else n=xL0({toolService:H,providers:p});if(Q.jetbrains)pC("JetBrains");else if(Q.ide&&mG4())pC("VS Code");else if(Q.ide&&dG4())pC("Neovim");else if(Q.ide&&A.executeMode)jk4();if(A.executeMode)qbA(!0);let o,I0=f3.status.pipe(aA((t)=>Boolean(t.connected&&t.authenticated&&t.ideName&&MhA(t.ideName))),UQ()).subscribe((t)=>{if(t){if(!o)o=H.registerTool(z04)}else o?.dispose(),o=void 0}),E0;if(!A.executeMode){let t=await A.settings.get("fuzzy.alwaysIncludePaths")??[];E0=new s30(process.cwd(),{alwaysIncludePaths:t},!0)}else E0=new class extends s30{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let G0=Ug(D);S.info("Starting Amp background services");let F0=new Pp0,q0={configService:D,toolService:H,mcpService:_,skillService:R,toolboxService:v,trustStore:O,threadRemote:G0,setThreadMeta:G0.setThreadMeta,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:E0,terminal:F0,pluginService:d,pluginPlatform:x,headlessPluginPlatform:k,activeThread$:T,serverStatus:V,serverStatusPromise:X,viewerUserIDPromise:K,hasAPIKeyAtStartup:G,consumeDraftNewThreadVisibility:()=>{let t=f;return f=null,t}};return{...q0,async asyncDispose(){if(q0.mcpService.hasAuthenticatingClients())S.info("Waiting for OAuth authentication to complete before exit..."),await q0.mcpService.waitForAuthentication();for(let t of n.values())t.dispose();await q0.mcpService.dispose(),w(),q0.configService.unsubscribe(),Y?.unsubscribe(),N(),q0.fuzzyServer.dispose(),q0.settingsStorage[Symbol.dispose](),I0.unsubscribe(),o?.dispose(),await q0.pluginService.dispose()}}}async function PN6(A){if(!A.executeMode){if(!await $E0("Would you like to log in to Amp? [(y)es, (n)o]: "))return vQ.write(`Login cancelled. Run the command again to retry.
|
|
6364
6364
|
`),!1}return await Pk4(A)}async function Pk4(A){let Q=$N6(32).toString("hex"),$=await zp0(A.ampURL,Q),B=new AbortController;try{await eU($,B.signal)}catch(D){S.error("Error opening browser",{error:D})}let E=await zp0(A.ampURL,Q,!1);vQ.write(`If your browser does not open automatically, visit:
|
|
6365
6365
|
|
|
@@ -6367,7 +6367,7 @@ ${f0.blue.bold(E)}
|
|
|
6367
6367
|
|
|
6368
6368
|
`);try{return await SP4(A.ampURL,Q,A.secrets,B),vQ.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(D){return S.error("Login failed",{error:D}),q7.write(`
|
|
6369
6369
|
Login failed: ${D instanceof Error?D.message:String(D)}
|
|
6370
|
-
`),!1}}async function vN6(A,Q,$){let B=await Q.get("apiKey",A);if(!B)throw new GA("No Amp API key found. Run `amp login` first.",1);let E=QN6("curl",["-H",`Authorization: Bearer ${B}`,...$],{stdio:"inherit"});process.exitCode=await new Promise((D,J)=>{E.on("error",J),E.on("close",(U)=>D(U??1))})}function TN6(A){let Q=new PX().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, unlisted, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((C)=>{if(C.code==="commander.help"||C.code==="commander.version"||C.exitCode===0)rN(),process.exit(0);let H=C.originalError??C;pX4(H)}),dz4(Q,{version:"0.0.
|
|
6370
|
+
`),!1}}async function vN6(A,Q,$){let B=await Q.get("apiKey",A);if(!B)throw new GA("No Amp API key found. Run `amp login` first.",1);let E=QN6("curl",["-H",`Authorization: Bearer ${B}`,...$],{stdio:"inherit"});process.exitCode=await new Promise((D,J)=>{E.on("error",J),E.on("close",(U)=>D(U??1))})}function TN6(A){let Q=new PX().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, unlisted, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((C)=>{if(C.code==="commander.help"||C.code==="commander.version"||C.exitCode===0)rN(),process.exit(0);let H=C.originalError??C;pX4(H)}),dz4(Q,{version:"0.0.1780478921-g021c3e",buildTimestamp:"2026-06-03T09:34:18.051Z",buildType:"release"}),Q.addHelpText("after",DV4()),Q.configureHelp({formatHelp:JV4}),Q.command("logout").description("Log out by removing stored API key").action(async(C,H)=>{let N=H.optsWithGlobals(),q=await E6(N);await dN6(q)}),Q.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(C,H)=>{let N=H.optsWithGlobals(),q=await E6(N);await mN6(q,await Mp0(N,q.settings))}),zv4(Q,E6);let B=Q.command("internal",{hidden:!0}).description("Internal commands").command("curl [args...]").description("Internal: run curl with the current Amp API key as a bearer token").allowUnknownOption(!0).allowExcessArguments(!0).action(async(...C)=>{let H=C.find((O)=>typeof O==="object"&&O!==null&&typeof O.optsWithGlobals==="function")??B,N=C.filter((O)=>O!==H).flatMap((O)=>Array.isArray(O)?O:typeof O==="string"?[O]:[]),q=H.optsWithGlobals(),w=await E6(q);await vN6(w.ampURL,w.secrets,N),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(C,H,N)=>{let q=N.optsWithGlobals(),w=await E6(q);await qG4(C??"get",w.ampURL,w.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit [args...]",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements Git signing helper interfaces. Used inside sandboxes for commit signing.").allowUnknownOption(!0).allowExcessArguments(!0).action(async(C,H,N)=>{let q=N.optsWithGlobals(),w=await E6(q);await wG4(w,C),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(C)=>{await BP4({raw:C.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(`
|
|
6371
6371
|
`)).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(C,H,N)=>{if(C&&H.apply)throw new GA("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let q=H.apply??C;if(!q||q.trim().length===0)vQ.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.
|
|
6372
6372
|
|
|
6373
6373
|
`),N.outputHelp(),process.exit(0);let w=J3(q)??A8(q),O=N.optsWithGlobals(),R=await E6(O);u3(N,O);let _=await vB(R,O),v=!1;try{if(H.checkout&&H.skipCheckout)throw new GA("Choose either --checkout or --skip-checkout, not both.",1);if(lC(_.serverStatus))throw Fi0(_.serverStatus,R.ampURL);let k=J$(_.serverStatus)?_.serverStatus.features:void 0;if(!Zi0(k,WD.V2))throw new GA("live-sync is not enabled for your user",1);await qP4({ampURL:R.ampURL,threadId:w,configService:_.configService,threadSnapshotReader:{get:_.threadRemote.getThread},apiKey:process.env.AMP_API_KEY,applyOnce:typeof H.apply==="string",checkoutMode:H.checkout?"always":H.skipCheckout?"never":"prompt",promptForYesNo:$E0}),v=!0}finally{if(await _.asyncDispose(),v)process.exit(0)}});let E=async(C,H,N)=>{u00({storage:H.settings,secretStorage:H.secrets,workspaceRoot:process.cwd(),defaultAmpURL:H.ampURL,homeDir:tE0,userConfigDir:Ui0});let q={...H,executeMode:!1};await Yi0(q,{...C,openThreadSwitcher:!0},N)},D=Q.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").option("--include-archived","Include archived threads in the list").option("--limit <number>","Maximum number of threads to return",(C)=>sE0(C,"--limit",{min:1,max:500})).option("--offset <number>","Number of threads to skip",(C)=>sE0(C,"--offset",{min:0})).action(async(C,H)=>{let N=H.optsWithGlobals(),q=await E6(N);await Ok4(N,q,H)});D.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, unlisted, workspace, group)").action(async(C,H)=>{let N=H.optsWithGlobals(),q=await E6(N);await Qq6(N,q,H)}),D.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(C,H,N)=>{let q=N.optsWithGlobals(),w=await E6(q),O=Array.isArray(C)?C:[];if(H.pick)q7.write(`${f0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
|
|
@@ -6392,8 +6392,8 @@ ${R}
|
|
|
6392
6392
|
|
|
6393
6393
|
`)},async input(){return},async confirm(){return!1},async select(){return},async ask(){return{result:"uncertain",probability:0.5,reason:"AI not available"}}},loadGlobalPlugins:sx0(q),pluginFilter:process.env.PLUGINS??"all"}),asyncDispose:async()=>{}}}),wv4(Q,async(C)=>{let H=C.optsWithGlobals(),N=await E6(H);u3(C,H);let q=await vB(N,H),w=await q.secretStorage.get("apiKey",N.ampURL);if(!w)throw await q.asyncDispose(),new GA("API key required. Please run `amp login` first.",1);return{configService:q.configService,actorOptions:{apiKey:w,ampURL:N.ampURL,workspaceRoot:process.cwd(),dependencies:q},cleanupTerminal:rN,asyncDispose:q.asyncDispose.bind(q)}}),_v4(Q,async(C)=>{let H=C.optsWithGlobals(),N=await E6(H);u3(C,H);let q=await vB(N,H);return{settings:N.settings,configService:q.configService,skillService:q.skillService,asyncDispose:q.asyncDispose.bind(q)}}),nP4(Q,async(C)=>{let H=C.optsWithGlobals();return await E6(H)}),hP4(Q,async(C)=>{let H=await E6(C);return{settings:H.settings,secretStorage:H.secrets,getThreadDeps:async(N)=>{u3(N,C);let q=await vB(H,C);return{mcpService:q.mcpService,settings:H.settings,asyncDispose:q.asyncDispose.bind(q)}}}}),qX4(Q,E6),xX4(Q,E6),ev4(Q,E6);function Z(C,H,N){let w=typeof C.description==="string"?C.description:N===void 0?C.description(!0):C.description(N),O=new h2(H,w),R=MN6(C);if(R)O.default(R);if(O.hidden=uN6(C)||uk4(C),"choices"in C&&Array.isArray(C.choices))if("hiddenChoices"in C){let _=[...C.choices],v=Array.isArray(C.hiddenChoices)?C.hiddenChoices:[],k=new Set([..._,...v]);O.argParser((m)=>{if(!k.has(m))throw new L30(`Allowed choices are ${_.join(", ")}.`);return m})}else O.choices([...C.choices]);return O}for(let C of qk4){switch(C.type){case"flag":{Q.addOption(Z(C,`--${C.long}`)),Q.addOption(Z(C,`--no-${C.long}`,!1));break}case"switch":{Q.addOption(Z(C,`--${C.long}`,!0));break}case"optional-option":{Q.addOption(Z(C,`${"short"in C?`-${C.short}, `:""}--${C.long} [value]`));break}default:{Q.addOption(Z(C,`${"short"in C?`-${C.short}, `:""}--${C.long} <value>`));break}}if("aliases"in C&&Array.isArray(C.aliases))for(let H of C.aliases){let N=new h2(`--${H}`,C.description);N.hidden=!0,N.implies({[C.name]:!0}),Q.addOption(N)}}Q.hook("preAction",(C,H)=>{if(H.optsWithGlobals().takeMeBack)Y6(ON6)});let F=new h2("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);Q.addOption(F);let X=new h2("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp(!0);Q.addOption(X);let I=new h2("--stream-json","When used with --execute, output in Claude Code-compatible stream JSON format instead of plain text.").default(!1);Q.addOption(I);let G=new h2("--stream-json-thinking","Include thinking blocks in stream JSON output (non-Claude Code extension). Implies --stream-json.").default(!1);Q.addOption(G);let V=new h2("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);Q.addOption(V);let K=new h2("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);Q.addOption(K);let z=new h2("--archive","When used with --execute, archive the thread after the command finishes.").default(!1);Q.addOption(z);let W=new h2("-l, --label <label>","When used with --execute, add a label to the thread. Repeat the flag for multiple labels.").argParser((C,H)=>{if(H===void 0)return[C];return[...H,C]});return Q.addOption(W),Q.action(async(C,H)=>{let N=C,q=await E6(N);if(Object.keys(N).forEach((w)=>{let O=qk4.find((R)=>R.name===w);if(O&&uk4(O)&&!wN6(O))q7.write(f0.yellow(`Warning: '--${w}' flag is deprecated
|
|
6394
6394
|
`))}),H.args.length>0)RN6(q,H);await Yi0(q,N,H)}),kV4(Q),Q}async function vk4(A,Q){await JJ(($)=>nP($,A,Q))}async function _N6(A){if(A.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof A.execute==="string"){let Q=(await Op0()).trimEnd();return{userInput:A.execute,stdinInput:Q||null}}return{userInput:(await Op0()).trimEnd(),stdinInput:null}}function SN6(A,Q,$){if(A.remote&&!Q)throw new GA("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(A.streamJson&&!Q)throw new GA("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new GA("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new GA("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new GA("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 GA("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archive&&!Q)throw new GA("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 GA("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Q&&$===""&&!A.streamJsonInput&&!A.headless)throw new GA("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"
|
|
6395
|
-
Or pipe via stdin: echo "your message" | amp --execute`)}function kN6(){rmA([N00.parse({tool:"*",action:"allow"})]),wmA({bypass:!0})}function fN6(A){if(A.threadId&&!h7(A.threadId))delete A.threadId}async function Yi0(A,Q,$){if(Q.headless)return xN6(A,Q,$);let B=await vB(A,Q);if(Q.showWelcome&&Q.hideWelcome)throw await B.asyncDispose(),new GA("Cannot use --show-welcome and --hide-welcome together",1);let E=!A.executeMode&&await qN6();return kN6(),fN6(Q),yN6(A,Q,$,B,{showNpmMigrationWelcome:E})}async function xN6(A,Q,$){let B=(W,C)=>{let H=Number(process.hrtime.bigint()-C)/1e6,N=wX4();S.info("Startup phase",{phase:W,phaseMs:Math.round(H),sinceMainMs:N===null?void 0:Math.round(N)})};u3($,Q);let E=process.hrtime.bigint(),D=await vB(A,Q);B("runMainThread:createThreadDependencies",E);let{serverStatus:J}=D;if(lC(J))throw Fi0(J,A.ampURL);let U=J$(J)?J:null,Y=U?.user.email;await KN6($,Q,J);let Z=Gu(J),F=Ci(Q,Z);if(F instanceof Error)Y6(F.message);if(U&&KT(Q.mode)&&!G00(Q.mode,Y))throw new GA(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!Y||!_7(Y)))throw new GA("Headless executor mode is only available for Amp employees",1);_x0();let I=await D.secretStorage.get("apiKey",A.ampURL);if(!I)throw new GA("API key required for headless mode. Please run `amp login` first.",1);let G=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(G&&!h7(G))throw new GA(`Invalid thread ID: ${G}`,1);let V=G?void 0:await eN6({dependencies:D,apiKey:I,visibility:F??void 0}),K=G??V?.threadId;if(!K)throw new GA("Failed to resolve headless thread ID",1);let z=await hG4(K);if(z.status==="already-running")await D.asyncDispose(),await $Z(),process.exit(0);try{await jG4({ampURL:A.ampURL,apiKey:I,workspaceRoot:process.cwd(),threadId:K,ownerUserId:V?.ownerUserId,threadVersion:V?.threadVersion,agentMode:V?.agentMode,initialToolDiscovery:Promise.all([D.mcpService.initialized,D.toolboxService.initialized,D.pluginService.initialized]).then(()=>{return}),configService:D.configService,mcpService:D.mcpService,toolService:D.toolService,skillService:D.skillService,pluginService:D.pluginService,pluginPlatform:D.headlessPluginPlatform,setActiveThreadID:(W)=>D.activeThread$.next(W)})}finally{await z.release(),await D.asyncDispose()}await $Z(),process.exit(0)}async function yN6(A,Q,$,B,E){let{userInput:D,stdinInput:J}=await _N6(Q),U=!!Q.streamJson||!!Q.streamJsonThinking;SN6({...Q,streamJson:U},A.executeMode,D),u3($,Q),vX4(),_x0();let Y=Q.threadId,Z=Q.resumeThreadIDs??(Y?[Y]:[]),F=Q.observe?J3(Q.observe)??A8(Q.observe):void 0,X=await B.serverStatusPromise;if(lC(X))throw Fi0(X,A.ampURL);let I=Gu(X),G=()=>zN6(B.configService,zkA.V2_LOCAL_THREAD_CHANGES),V=Ci(Q,I);if(V instanceof Error)Y6(V.message);if(A.executeMode&&Q.remote){if(!KT(Q.mode))throw new GA("Remote execute mode does not support plugin-defined agent modes",1);if(!J$(X)||!_7(X.user.email))throw new GA("Remote execute mode is only available for Amp employees",1);await Zv4(D,J,B.configService,Q.mode),await B.asyncDispose(),await $Z(),process.exit(0)}let K=null,z=async()=>{let H=B.consumeDraftNewThreadVisibility();if(H!==null)return H;return K??=(async()=>{let N=await x30(A.settings,process.cwd(),I,V);if(N instanceof Error)Y6(N.message);return N})(),K},W=await B.secretStorage.get("apiKey",A.ampURL);if(!W)throw new GA("API key required. Please run `amp login` first.",1);let C=J$(X)&&_7(X.user.email);if(A.executeMode){if(Z.length>1)throw new GA("Execute mode can only resume one thread.",1);cP4(B.mcpService,A.settings);try{await B.pluginService.initialized;let H=Rk4(B.pluginService,Q.mode),N=wk4($,Q),q=await Zq(),w=Y?N:Ry0({agentMode:H.agentMode,explicitEffort:N,sessionState:q}),O=Y?void 0:W50(await pP(B.configService),{agentMode:H.agentMode,explicitEffort:N,sessionState:q}),R=Y?void 0:await z(),{threadID:_}=await r30({apiKey:W,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:B,userInput:D,stdinInput:J,stats:!!Q.stats,streamJson:U,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:H.agentMode,reasoningEffort:H.agent?void 0:w,agent:H.agent,labels:Q.label,initialThreadID:Y,initialThreadMeta:R,initialSettings:O});if(await vk4(_,"execute"),Q.archive)await B.threadRemote.archiveThread(_,!0)}finally{await B.asyncDispose()}await $Z(),process.exit(0)}else{let H=wk4($,Q),N=await jN6($,B.pluginService,Q.mode),q=E.showNpmMigrationWelcome?"npm-migration":"intro",w=wy0("0.0.
|
|
6396
|
-
`);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,$=process.stdout.isTTY&&process.stderr.isTTY;S.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let B=await TaA({get:async(U)=>{if(U!==Ch)return;try{let Y=await Lk4(Ji0,"utf-8");return JSON.parse(Y).installationID}catch{return}},set:async(U,Y)=>{if(U!==Ch)return;await BN6(pi.dirname(Ji0),{recursive:!0}),await EN6(Ji0,JSON.stringify({installationID:Y},null,2),{mode:384})}},{clientType:"cli",platform:x40()});ubA(B);let E=await vv4({...A,workspaceTrust:{current:!0,changes:Jy},getHook:process.env.AMP_URL?(U,Y)=>{if(U==="url")return Promise.resolve(process.env.AMP_URL);return Y()}:void 0});if(A.mcpConfig){let U=await mP4(A.mcpConfig);E=dP4(E,U)}let D=pi.dirname(E.getSettingsFilePath());$J4(ty,D),E=ZkA(E);let J=await E.get("url","admin")??await E.get("url","global");if(!J)J=g8;if(S.info("Resolved Amp URL",{ampURL:J,settingsFile:E.getSettingsFilePath(),workspaceRoot:E.getWorkspaceRootPath()}),!aO(J))S.info("Targeting custom Amp server",{ampURL:J});return{executeMode:Q,isTTY:$,ampURL:J,settings:E,secrets:Mv4(await Mp0(A,E))}}function bN6(A){let Q={};for(let $=0;$<A.length;$++){let B=A[$];if(B?.startsWith("--")){let D=B.slice(2).replace(/-([a-z])/g,(U,Y)=>Y.toUpperCase()),J=A[$+1];if(J&&!J.startsWith("--"))Q[D]=J,$++}}return Q}function hN6(A,Q){let $=A.includes("--headless")||A.some((E)=>E.startsWith("--headless=")),B=pi.resolve(Q.logFile??process.env.AMP_LOG_FILE??($?JN6:pc));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:B}}async function gN6(){uX4();let A=bN6(process.argv),Q=hN6(process.argv,A),$=TX4(Q);xB0("silent");let B=process.argv.includes("--no-color"),E=process.argv.includes("--color"),D=process.stdout.isTTY&&process.stderr.isTTY;if(B||!E&&!D)f0.level=0;if(YN6(S),S.info("Starting Amp CLI.",{version:"0.0.
|
|
6395
|
+
Or pipe via stdin: echo "your message" | amp --execute`)}function kN6(){rmA([N00.parse({tool:"*",action:"allow"})]),wmA({bypass:!0})}function fN6(A){if(A.threadId&&!h7(A.threadId))delete A.threadId}async function Yi0(A,Q,$){if(Q.headless)return xN6(A,Q,$);let B=await vB(A,Q);if(Q.showWelcome&&Q.hideWelcome)throw await B.asyncDispose(),new GA("Cannot use --show-welcome and --hide-welcome together",1);let E=!A.executeMode&&await qN6();return kN6(),fN6(Q),yN6(A,Q,$,B,{showNpmMigrationWelcome:E})}async function xN6(A,Q,$){let B=(W,C)=>{let H=Number(process.hrtime.bigint()-C)/1e6,N=wX4();S.info("Startup phase",{phase:W,phaseMs:Math.round(H),sinceMainMs:N===null?void 0:Math.round(N)})};u3($,Q);let E=process.hrtime.bigint(),D=await vB(A,Q);B("runMainThread:createThreadDependencies",E);let{serverStatus:J}=D;if(lC(J))throw Fi0(J,A.ampURL);let U=J$(J)?J:null,Y=U?.user.email;await KN6($,Q,J);let Z=Gu(J),F=Ci(Q,Z);if(F instanceof Error)Y6(F.message);if(U&&KT(Q.mode)&&!G00(Q.mode,Y))throw new GA(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!Y||!_7(Y)))throw new GA("Headless executor mode is only available for Amp employees",1);_x0();let I=await D.secretStorage.get("apiKey",A.ampURL);if(!I)throw new GA("API key required for headless mode. Please run `amp login` first.",1);let G=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(G&&!h7(G))throw new GA(`Invalid thread ID: ${G}`,1);let V=G?void 0:await eN6({dependencies:D,apiKey:I,visibility:F??void 0}),K=G??V?.threadId;if(!K)throw new GA("Failed to resolve headless thread ID",1);let z=await hG4(K);if(z.status==="already-running")await D.asyncDispose(),await $Z(),process.exit(0);try{await jG4({ampURL:A.ampURL,apiKey:I,workspaceRoot:process.cwd(),threadId:K,ownerUserId:V?.ownerUserId,threadVersion:V?.threadVersion,agentMode:V?.agentMode,initialToolDiscovery:Promise.all([D.mcpService.initialized,D.toolboxService.initialized,D.pluginService.initialized]).then(()=>{return}),configService:D.configService,mcpService:D.mcpService,toolService:D.toolService,skillService:D.skillService,pluginService:D.pluginService,pluginPlatform:D.headlessPluginPlatform,setActiveThreadID:(W)=>D.activeThread$.next(W)})}finally{await z.release(),await D.asyncDispose()}await $Z(),process.exit(0)}async function yN6(A,Q,$,B,E){let{userInput:D,stdinInput:J}=await _N6(Q),U=!!Q.streamJson||!!Q.streamJsonThinking;SN6({...Q,streamJson:U},A.executeMode,D),u3($,Q),vX4(),_x0();let Y=Q.threadId,Z=Q.resumeThreadIDs??(Y?[Y]:[]),F=Q.observe?J3(Q.observe)??A8(Q.observe):void 0,X=await B.serverStatusPromise;if(lC(X))throw Fi0(X,A.ampURL);let I=Gu(X),G=()=>zN6(B.configService,zkA.V2_LOCAL_THREAD_CHANGES),V=Ci(Q,I);if(V instanceof Error)Y6(V.message);if(A.executeMode&&Q.remote){if(!KT(Q.mode))throw new GA("Remote execute mode does not support plugin-defined agent modes",1);if(!J$(X)||!_7(X.user.email))throw new GA("Remote execute mode is only available for Amp employees",1);await Zv4(D,J,B.configService,Q.mode),await B.asyncDispose(),await $Z(),process.exit(0)}let K=null,z=async()=>{let H=B.consumeDraftNewThreadVisibility();if(H!==null)return H;return K??=(async()=>{let N=await x30(A.settings,process.cwd(),I,V);if(N instanceof Error)Y6(N.message);return N})(),K},W=await B.secretStorage.get("apiKey",A.ampURL);if(!W)throw new GA("API key required. Please run `amp login` first.",1);let C=J$(X)&&_7(X.user.email);if(A.executeMode){if(Z.length>1)throw new GA("Execute mode can only resume one thread.",1);cP4(B.mcpService,A.settings);try{await B.pluginService.initialized;let H=Rk4(B.pluginService,Q.mode),N=wk4($,Q),q=await Zq(),w=Y?N:Ry0({agentMode:H.agentMode,explicitEffort:N,sessionState:q}),O=Y?void 0:W50(await pP(B.configService),{agentMode:H.agentMode,explicitEffort:N,sessionState:q}),R=Y?void 0:await z(),{threadID:_}=await r30({apiKey:W,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:B,userInput:D,stdinInput:J,stats:!!Q.stats,streamJson:U,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:H.agentMode,reasoningEffort:H.agent?void 0:w,agent:H.agent,labels:Q.label,initialThreadID:Y,initialThreadMeta:R,initialSettings:O});if(await vk4(_,"execute"),Q.archive)await B.threadRemote.archiveThread(_,!0)}finally{await B.asyncDispose()}await $Z(),process.exit(0)}else{let H=wk4($,Q),N=await jN6($,B.pluginService,Q.mode),q=E.showNpmMigrationWelcome?"npm-migration":"intro",w=wy0("0.0.1780478921-g021c3e",B.settingsStorage,{startDelayMs:3000}),O=new Wp0(B.mcpService,A.settings.getWorkspaceRootPath()),R=Ug(B.configService),_=new Sp0(B.fuzzyServer),v=process.cwd();await sR4({ampURL:A.ampURL,apiKey:W,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??I9(A.ampURL),configService:B.configService,toolService:B.toolService,pluginPlatform:B.pluginPlatform,pluginService:B.pluginService,skillService:B.skillService,mcpService:B.mcpService,readFileSystemDirectory:({uri:k})=>xP({workspaceRoot:v},k),canUseV2LocalThreadChanges:G,completionBuilder:_,updateService:w,workspaceRoot:v,listThreads:()=>R.listThreads(),getThreadFromServer:(k)=>R.getThread(k),getThreadTail:async(k,m)=>{let x=await j4.getThreadTail({thread:k,limit:m},{config:B.configService});if(!x.ok){if(x.error.code==="thread-not-found")return null;throw Error(x.error.message??x.error.code)}return{...x.result.thread.data,messages:x.result.messages}},toolboxes:B.toolboxService.toolboxes,isInternalUser:C,settingsFilePath:B.settingsStorage.getSettingsFilePath(),workspaceSettingsFilePath:B.settingsStorage.getWorkspaceSettingsPath(),mcpTrustHandler:O,setActiveThreadID:(k)=>B.activeThread$.next(k),dispose:()=>{return O.dispose(),w.dispose(),B.asyncDispose()}},{initialThreadIDs:F?[F]:Z,initialUserInput:D||void 0,getDefaultNewThreadVisibility:z,onFirstFrame:Q.ide?jk4:void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!F,hideWelcome:!!Q.hideWelcome,showWelcome:Q.showWelcome,welcomeVariant:q,initialAgentMode:N?.agentMode,initialPluginAgentModeKey:N?.pluginAgentModeKey,initialReasoningEffort:H}),process.exit(0)}}async function E6(A){if(S.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)q7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
6396
|
+
`);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,$=process.stdout.isTTY&&process.stderr.isTTY;S.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let B=await TaA({get:async(U)=>{if(U!==Ch)return;try{let Y=await Lk4(Ji0,"utf-8");return JSON.parse(Y).installationID}catch{return}},set:async(U,Y)=>{if(U!==Ch)return;await BN6(pi.dirname(Ji0),{recursive:!0}),await EN6(Ji0,JSON.stringify({installationID:Y},null,2),{mode:384})}},{clientType:"cli",platform:x40()});ubA(B);let E=await vv4({...A,workspaceTrust:{current:!0,changes:Jy},getHook:process.env.AMP_URL?(U,Y)=>{if(U==="url")return Promise.resolve(process.env.AMP_URL);return Y()}:void 0});if(A.mcpConfig){let U=await mP4(A.mcpConfig);E=dP4(E,U)}let D=pi.dirname(E.getSettingsFilePath());$J4(ty,D),E=ZkA(E);let J=await E.get("url","admin")??await E.get("url","global");if(!J)J=g8;if(S.info("Resolved Amp URL",{ampURL:J,settingsFile:E.getSettingsFilePath(),workspaceRoot:E.getWorkspaceRootPath()}),!aO(J))S.info("Targeting custom Amp server",{ampURL:J});return{executeMode:Q,isTTY:$,ampURL:J,settings:E,secrets:Mv4(await Mp0(A,E))}}function bN6(A){let Q={};for(let $=0;$<A.length;$++){let B=A[$];if(B?.startsWith("--")){let D=B.slice(2).replace(/-([a-z])/g,(U,Y)=>Y.toUpperCase()),J=A[$+1];if(J&&!J.startsWith("--"))Q[D]=J,$++}}return Q}function hN6(A,Q){let $=A.includes("--headless")||A.some((E)=>E.startsWith("--headless=")),B=pi.resolve(Q.logFile??process.env.AMP_LOG_FILE??($?JN6:pc));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:B}}async function gN6(){uX4();let A=bN6(process.argv),Q=hN6(process.argv,A),$=TX4(Q);xB0("silent");let B=process.argv.includes("--no-color"),E=process.argv.includes("--color"),D=process.stdout.isTTY&&process.stderr.isTTY;if(B||!E&&!D)f0.level=0;if(YN6(S),S.info("Starting Amp CLI.",{version:"0.0.1780478921-g021c3e",buildTimestamp:"2026-06-03T09:34:18.051Z"}),process.platform==="win32"&&Uq())PV4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new GA(W3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await TN6($).parseAsync(process.argv)}AJ4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await gN6().catch(y30)});async function mN6(A,Q){let $=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!$)await A.settings.set("url",process.env.AMP_URL,"global"),vQ.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
6397
6397
|
`);else if(!aO(A.ampURL))vQ.write(`Logging in to ${new URL(A.ampURL).hostname}
|
|
6398
6398
|
`);let B=process.env.AMP_API_KEY;if(B)vQ.write(`API key found in environment variable, storing...
|
|
6399
6399
|
`),await Q.set("apiKey",B,A.ampURL),vQ.write(`API key successfully stored.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sourcegraph/amp",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.1780478921-g021c3e",
|
|
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.
|
|
11
|
+
"@ampcode/cli": "0.0.1780478921-g021c3e"
|
|
12
12
|
},
|
|
13
13
|
"files": [
|
|
14
14
|
"dist/main.js",
|