@sourcegraph/amp 0.0.1777279521-gff806d → 0.0.1777279908-g9ebba6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +9 -9
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -4651,12 +4651,12 @@ ${E}`))}},error:(K)=>{if(!U)U=!0,X(Error(`Failed to spawn brew: ${K.message}`))}
4651
4651
  ${E}`;if(Y==="pnpm"&&E.includes("Unable to find the global bin directory"))W+=`
4652
4652
 
4653
4653
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
4654
- npm install -g @sourcegraph/amp`;X(Error(W))}},error:(K)=>{if(!V)V=!0,X(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,F()}})})}l0();l0();UI();async function rU0(A,Q){let J=`${Q||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,Y=new AbortController,Z=setTimeout(()=>Y.abort(),5000);try{let F=await fetch(J,{signal:Y.signal});if(!F.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let X=await F.json(),D=X.version??X["dist-tags"]?.latest;if(!D)return{hasUpdate:!1,currentVersion:A,source:"npm"};let G=Je(A,D),V=G<0,U,K;if(X.time){let E=X.time[A],W=X.time[D],H=Date.now();if(E)U=Math.floor((H-new Date(E).getTime())/3600000);if(W)K=Math.floor((H-new Date(W).getTime())/3600000)}return T.info("NPM version comparison",{currentVersion:A,latestVersion:D,compareResult:G,hasUpdate:V,currentVersionAge:U,latestVersionAge:K}),{hasUpdate:V,latestVersion:D,currentVersion:A,currentVersionAge:U,latestVersionAge:K,source:"npm"}}catch(F){return T.debug("Error checking npm version",{error:F}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var Li5="https://static.ampcode.com/cli/cli-version.txt";async function sU0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${Li5}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!$.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let J=(await $.text()).trim();if(!J||!/^\d+\.\d+\.\d+/.test(J))return{hasUpdate:!1,currentVersion:A,source:"bin"};let Y=Je(A,J),Z=Y<0;return T.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return T.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var Oi5=604800000;function ms4(A){if(!A)return null;let Q=typeof A==="number"?A:new Date(A).getTime();if(isNaN(Q))return null;let B=Date.now()-Q;if(B>Oi5)return{ageMs:B};return null}function Je(A,Q){let B=(Z)=>{let[F,X]=Z.split("-");return{parts:F?.split(".").map(Number)||[],label:X}},$=B(A),J=B(Q),Y=Math.max($.parts.length,J.parts.length);for(let Z=0;Z<Y;Z++){let F=$.parts[Z]||0,X=J.parts[Z]||0;if(F<X)return-1;if(F>X)return 1}if($.label===J.label)return 0;if(!$.label&&J.label)return 1;if($.label&&!J.label)return-1;if($.label&&J.label)return $.label<J.label?-1:1;return 0}function T81(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Q)return null;let B=parseInt(Q[1],10)*1000,$=Q[2],J=B!==0?vU(B):void 0;return{sha:$,age:J}}catch{return null}}O1();l0();import{readFile as ji5,realpath as Ri5}from"node:fs/promises";import{homedir as Pi5}from"node:os";import{dirname as ps4,join as S81}from"node:path";async function ds4(A){switch(A){case"binary":case"brew":return _i5(Ae());case"npm":case"pnpm":case"yarn":case"bun":return Ti5();case"bootstrap":return Si5()}}async function _i5(A){let Q=await PG(A,["--version"],5000);if(Q.reason!=="success")return T.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function Ti5(){try{let A=process.argv[1];if(!A)return null;let Q=await Ri5(A),B=ps4(ps4(Q));return await cs4(S81(B,"package.json"))}catch(A){return T.debug("failed to read installed version from package.json",{error:A}),null}}async function Si5(){try{let A=process.env.AMP_HOME??S81(Pi5(),".amp");return await cs4(S81(A,"package","package.json"))}catch(A){return T.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function cs4(A){let Q=await ji5(A,"utf8"),B=JSON.parse(Q);if(B.name!=="@sourcegraph/amp")return T.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var ki5=3600000,vi5=5000;function k81(A,Q,B={}){let $=new XA,J=$.pipe(sA({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??ki5,F=!1,X=()=>{F=!0};return setImmediate(async()=>{let D=new VD().scoped("update");if(Y>0){if(await kU(Y),F)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!F){let U=await yi5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await kU(vi5),F)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!F){let W=Math.min(K,E);await kU(W),E-=W}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:X}}async function yi5(A,Q,B,$){let J={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return B.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),J.stop=!0,J;let Y=await Q.get("updates.mode");if(Y==="disabled")return B.debug("checking disabled"),J.stop=!0,J;let Z=await aU0(),F=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:F});let X;if(F)X=await sU0(A);else{let V=await WP();X=await rU0(A,V)}if(!(X.latestVersion&&X.hasUpdate))return B.debug("no update available"),J;let D=(V)=>{$.next(V),J.emittedVisibleState=!0};if(Z){let V=await ds4(Z);if(V&&Je(V,X.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:X.latestVersion}),J.updatedTo=V,Je(A,V)<0){let U=await vH(V),K={from:A,to:V,externallyUpdated:!0,...U};if(U.status==="same")B.info("on-disk already updated by another instance",K),D("updated");else B.warn("on-disk already updated by another instance, with PATH warning",K),D("updated-with-warning")}return J}}let G=()=>{if(X.currentVersionAge!==void 0&&X.latestVersionAge!==void 0){let V=X.currentVersionAge-X.latestVersionAge,U=0.5;if(Math.abs(V)<0.5)return B.debug("versions too close together, suppressing update warning",{currentVersionAge:X.currentVersionAge,latestVersionAge:X.latestVersionAge,ageDifferenceHours:V}),!0}return!1};if(!Y)Y=Z==="pnpm"?"warn":"auto",B.debug("no configured update mode; selected default based on package manager",{packageManager:Z,mode:Y});if(Z==="brew"){if(!G())D("update-available-brew");return J}if(Z==="binary"&&process.execPath!==Ae()){if(B.debug("non-standard binary path, showing warning"),!G())D("update-available-unrecognized-path");return J}if(Y==="warn"){if(!G())D("update-available");return J}if(!Z){if(B.debug("auto-update not supported, falling back to warn mode"),!G())D("update-available");return J}if(Z==="binary"&&process.platform==="win32"){if(B.debug("binary auto-update not supported on Windows, falling back to warn mode"),!G())D("update-available");return J}try{await $e(X.latestVersion,Z),J.updatedTo=X.latestVersion;let V=await vH(X.latestVersion),U={from:X.currentVersion,to:X.latestVersion,...V};if(V.status==="same")B.info("success",U),D("updated");else B.warn("success with warning",U),D("updated-with-warning")}catch(V){D("update-error")}return J}catch(Y){return B.debug("check failed",{error:Y}),J}}UI();import{stderr as _G}from"node:process";function ls4(A){let Q=new fI().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async($)=>{await q81($.force||!1,$.verbose||!1,"0.0.1777279521-gff806d"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new fI("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async($)=>{await fi5($.targetVersion)});A.addCommand(B)}function xi5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
4654
+ npm install -g @sourcegraph/amp`;X(Error(W))}},error:(K)=>{if(!V)V=!0,X(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,F()}})})}l0();l0();UI();async function rU0(A,Q){let J=`${Q||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,Y=new AbortController,Z=setTimeout(()=>Y.abort(),5000);try{let F=await fetch(J,{signal:Y.signal});if(!F.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let X=await F.json(),D=X.version??X["dist-tags"]?.latest;if(!D)return{hasUpdate:!1,currentVersion:A,source:"npm"};let G=Je(A,D),V=G<0,U,K;if(X.time){let E=X.time[A],W=X.time[D],H=Date.now();if(E)U=Math.floor((H-new Date(E).getTime())/3600000);if(W)K=Math.floor((H-new Date(W).getTime())/3600000)}return T.info("NPM version comparison",{currentVersion:A,latestVersion:D,compareResult:G,hasUpdate:V,currentVersionAge:U,latestVersionAge:K}),{hasUpdate:V,latestVersion:D,currentVersion:A,currentVersionAge:U,latestVersionAge:K,source:"npm"}}catch(F){return T.debug("Error checking npm version",{error:F}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var Li5="https://static.ampcode.com/cli/cli-version.txt";async function sU0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${Li5}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!$.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let J=(await $.text()).trim();if(!J||!/^\d+\.\d+\.\d+/.test(J))return{hasUpdate:!1,currentVersion:A,source:"bin"};let Y=Je(A,J),Z=Y<0;return T.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return T.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var Oi5=604800000;function ms4(A){if(!A)return null;let Q=typeof A==="number"?A:new Date(A).getTime();if(isNaN(Q))return null;let B=Date.now()-Q;if(B>Oi5)return{ageMs:B};return null}function Je(A,Q){let B=(Z)=>{let[F,X]=Z.split("-");return{parts:F?.split(".").map(Number)||[],label:X}},$=B(A),J=B(Q),Y=Math.max($.parts.length,J.parts.length);for(let Z=0;Z<Y;Z++){let F=$.parts[Z]||0,X=J.parts[Z]||0;if(F<X)return-1;if(F>X)return 1}if($.label===J.label)return 0;if(!$.label&&J.label)return 1;if($.label&&!J.label)return-1;if($.label&&J.label)return $.label<J.label?-1:1;return 0}function T81(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Q)return null;let B=parseInt(Q[1],10)*1000,$=Q[2],J=B!==0?vU(B):void 0;return{sha:$,age:J}}catch{return null}}O1();l0();import{readFile as ji5,realpath as Ri5}from"node:fs/promises";import{homedir as Pi5}from"node:os";import{dirname as ps4,join as S81}from"node:path";async function ds4(A){switch(A){case"binary":case"brew":return _i5(Ae());case"npm":case"pnpm":case"yarn":case"bun":return Ti5();case"bootstrap":return Si5()}}async function _i5(A){let Q=await PG(A,["--version"],5000);if(Q.reason!=="success")return T.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function Ti5(){try{let A=process.argv[1];if(!A)return null;let Q=await Ri5(A),B=ps4(ps4(Q));return await cs4(S81(B,"package.json"))}catch(A){return T.debug("failed to read installed version from package.json",{error:A}),null}}async function Si5(){try{let A=process.env.AMP_HOME??S81(Pi5(),".amp");return await cs4(S81(A,"package","package.json"))}catch(A){return T.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function cs4(A){let Q=await ji5(A,"utf8"),B=JSON.parse(Q);if(B.name!=="@sourcegraph/amp")return T.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var ki5=3600000,vi5=5000;function k81(A,Q,B={}){let $=new XA,J=$.pipe(sA({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??ki5,F=!1,X=()=>{F=!0};return setImmediate(async()=>{let D=new VD().scoped("update");if(Y>0){if(await kU(Y),F)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!F){let U=await yi5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await kU(vi5),F)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!F){let W=Math.min(K,E);await kU(W),E-=W}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:X}}async function yi5(A,Q,B,$){let J={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return B.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),J.stop=!0,J;let Y=await Q.get("updates.mode");if(Y==="disabled")return B.debug("checking disabled"),J.stop=!0,J;let Z=await aU0(),F=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:F});let X;if(F)X=await sU0(A);else{let V=await WP();X=await rU0(A,V)}if(!(X.latestVersion&&X.hasUpdate))return B.debug("no update available"),J;let D=(V)=>{$.next(V),J.emittedVisibleState=!0};if(Z){let V=await ds4(Z);if(V&&Je(V,X.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:X.latestVersion}),J.updatedTo=V,Je(A,V)<0){let U=await vH(V),K={from:A,to:V,externallyUpdated:!0,...U};if(U.status==="same")B.info("on-disk already updated by another instance",K),D("updated");else B.warn("on-disk already updated by another instance, with PATH warning",K),D("updated-with-warning")}return J}}let G=()=>{if(X.currentVersionAge!==void 0&&X.latestVersionAge!==void 0){let V=X.currentVersionAge-X.latestVersionAge,U=0.5;if(Math.abs(V)<0.5)return B.debug("versions too close together, suppressing update warning",{currentVersionAge:X.currentVersionAge,latestVersionAge:X.latestVersionAge,ageDifferenceHours:V}),!0}return!1};if(!Y)Y=Z==="pnpm"?"warn":"auto",B.debug("no configured update mode; selected default based on package manager",{packageManager:Z,mode:Y});if(Z==="brew"){if(!G())D("update-available-brew");return J}if(Z==="binary"&&process.execPath!==Ae()){if(B.debug("non-standard binary path, showing warning"),!G())D("update-available-unrecognized-path");return J}if(Y==="warn"){if(!G())D("update-available");return J}if(!Z){if(B.debug("auto-update not supported, falling back to warn mode"),!G())D("update-available");return J}if(Z==="binary"&&process.platform==="win32"){if(B.debug("binary auto-update not supported on Windows, falling back to warn mode"),!G())D("update-available");return J}try{await $e(X.latestVersion,Z),J.updatedTo=X.latestVersion;let V=await vH(X.latestVersion),U={from:X.currentVersion,to:X.latestVersion,...V};if(V.status==="same")B.info("success",U),D("updated");else B.warn("success with warning",U),D("updated-with-warning")}catch(V){D("update-error")}return J}catch(Y){return B.debug("check failed",{error:Y}),J}}UI();import{stderr as _G}from"node:process";function ls4(A){let Q=new fI().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async($)=>{await q81($.force||!1,$.verbose||!1,"0.0.1777279908-g9ebba6"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new fI("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async($)=>{await fi5($.targetVersion)});A.addCommand(B)}function xi5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
4655
4655
  `),$=!1,B=0}function Y(Z){if(!Q)return;let F=Z.padEnd(B," ");A.write(`\r${F}`),$=!0,B=F.length}return{flushProgressLine:J,renderProgress:Y}}async function fi5(A){let B=process.platform==="win32"&&EP()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:$,renderProgress:J}=xi5(_G);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")_G.write(n0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4656
4656
 
4657
4657
  `));try{if(!A){_G.write(n0.blue(`Checking for updates...
4658
- `));let F=!1,X;if(EP()){let D=await sU0("0.0.1777279521-gff806d");F=D.hasUpdate,X=D.latestVersion}else{let D=await WP(),G=await rU0("0.0.1777279521-gff806d",D);F=G.hasUpdate,X=G.latestVersion}if(!F){let D=T81("0.0.1777279521-gff806d"),G=D?.age?`released ${D.age} ago`:`built ${vU(new Date("2026-04-27T08:50:02.827Z"))} ago`;_G.write(n0.green(`✓ Amp is already up to date on version ${"0.0.1777279521-gff806d"} (${G})
4659
- `));let V=await vH("0.0.1777279521-gff806d",B);if(V.warning)_G.write(`
4658
+ `));let F=!1,X;if(EP()){let D=await sU0("0.0.1777279908-g9ebba6");F=D.hasUpdate,X=D.latestVersion}else{let D=await WP(),G=await rU0("0.0.1777279908-g9ebba6",D);F=G.hasUpdate,X=G.latestVersion}if(!F){let D=T81("0.0.1777279908-g9ebba6"),G=D?.age?`released ${D.age} ago`:`built ${vU(new Date("2026-04-27T08:55:43.407Z"))} ago`;_G.write(n0.green(`✓ Amp is already up to date on version ${"0.0.1777279908-g9ebba6"} (${G})
4659
+ `));let V=await vH("0.0.1777279908-g9ebba6",B);if(V.warning)_G.write(`
4660
4660
  `+n0.yellow(V.warning)+`
4661
4661
  `);process.exit(0)}if(!X)_G.write(n0.yellow("[WARN] could not find latest version")),process.exit(0);A=X}_G.write(n0.blue(`Updating to version ${A}...
4662
4662
  `)),await $e(A,void 0,(F)=>{$(),_G.write(n0.dim(`Running: ${F}
@@ -5167,7 +5167,7 @@ Ctrl-X, Y, Z to unlock`;if(U){let x=D.text.replace(/`([^`]+)`/g,"$1")+`
5167
5167
 
5168
5168
  `,new h({color:$.toolSuccess,bold:!0})),new O(`This thread has been shared with Amp support for debugging and bug prioritization.
5169
5169
  `,new h({color:B.foreground})),new O(`This is not a support request.
5170
- `,new h({color:B.foreground,dim:!0})),new O("If you need a reply, post on X @AmpCode or email amp-devs@ampcode.com.",new h({color:B.foreground,dim:!0}))]),textAlign:"center"})})}}function R9A(A){return new V3({header:A.title,minWidth:80,maxWidth:80,chromePadding:M0.symmetric(1,0),footer:"none",onDismiss:A.onDismiss,child:A.child})}function i78(A,Q,B){return new p1({child:new u0({constraints:new W1(80,80,0,12),child:new sH({commandName:"Share with Support",title:"Share Thread with Support",placeholder:"What went wrong? (Need a reply? Email amp-devs@ampcode.com.)",isRequiredArg:!1,onSubmit:async($)=>{try{await A.shareThreadWithSupport(Q,$||void 0),B.pushResultPane(R9A({title:"Shared with Support",onDismiss:B.dismissFlow,child:new B10}))}catch(J){T.error("Failed to share thread with support",{error:J,threadID:Q}),B.pushResultPane(R9A({title:"Share with Support failed",onDismiss:B.dismissFlow,child:new t({text:new O(`Failed to share thread with support: ${J instanceof Error?J.message:String(J)}`)})}))}},onDismiss:B.dismissFlow})})})}function P9A(A,Q){return{noun:"thread",verb:"share with support",description:"Share with Amp support for debugging",get status(){return Q()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(B,$,J)=>{let Y=Q()?.client.getThreadId();if(!Y)return;B.push(i78(A,Y,{dismissFlow:J,pushResultPane:(Z)=>B.push(Z)}))}}}class $10 extends y0{props;constructor(A){super();this.props=A}createState(){return new _9A}}class _9A extends v0{result=void 0;isLoading=!1;build(A){let Q=[];if(this.isLoading)Q.push(new fQ({message:"Updating visibility..."}));else if(this.result!==void 0)Q.push(new i7({message:this.result,onDismiss:()=>{this.widget.props.onDismiss()}}));else{let B=["private","workspace","unlisted","public"],$=this.widget.props.workspace?.groups&&this.widget.props.workspace.groups.length>0?["private","workspace","group","unlisted","public"]:B;Q.push(new k5({items:$,getLabel:(J)=>{switch(J){case"private":return"Private - Only you can see this thread";case"workspace":return"Workspace - Visible to workspace members";case"group":return"Group - Visible to group members";case"unlisted":return"Unlisted - Anyone with the link can view";case"public":return"Public - Searchable and on your public profile"}},title:"Select Thread Visibility",onAccept:async(J)=>{this.setState(()=>{this.isLoading=!0});let Y=await this.widget.props.execute(J);this.setState(()=>{this.isLoading=!1,this.result=Y})},onDismiss:this.widget.props.onDismiss}))}return new CA({children:Q,fit:"expand"})}}function n78(A,Q,B){return new p1({child:new u0({constraints:new W1(80,80,0,16),child:new $10({workspace:null,threadID:Q,execute:($)=>A.setVisibility(Q,$),onDismiss:B})})})}function T9A(A,Q){return{noun:"thread",verb:"set visibility",description:"Set thread visibility",keywords:["share","private","workspace","public","unlisted","team","group"],get status(){return Q()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(B,$,J)=>{let Y=Q()?.client?.getThreadId();if(!Y)return;B.push(n78(A,Y,J))}}}class $B1 extends y0{initialAgentMode;analyzeContextForThread;listSkillsForThread;threadContext;draftThreadSettings;editorController;history;updateDraftThreadSettings;onNewThread;shareThreadWithSupport;setThreadVisibility;archiveThread;addThreadLabel;removeThreadLabel;configService;connectionErrorMessage;hints;ideStatus;constructor(A){super();this.initialAgentMode=A.initialAgentMode,this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.threadContext=A.threadContext,this.draftThreadSettings=A.draftThreadSettings,this.editorController=A.editorController,this.history=A.history,this.updateDraftThreadSettings=A.updateDraftThreadSettings,this.onNewThread=A.onNewThread,this.shareThreadWithSupport=A.shareThreadWithSupport,this.setThreadVisibility=A.setThreadVisibility,this.archiveThread=A.archiveThread,this.addThreadLabel=A.addThreadLabel,this.removeThreadLabel=A.removeThreadLabel,this.configService=A.configService,this.connectionErrorMessage=A.connectionErrorMessage,this.hints=A.hints,this.ideStatus=A.ideStatus}createState(){return new S9A}}class S9A extends v0{historyIndex=-1;historyDraft=null;promptHistoryPicker=new me(this);agentMode;copyOnSelectEnabled=!0;expansion=new VQ1;previousThreadIDForReference=null;unregisterCommands=null;initState(){this.agentMode=this.widget.initialAgentMode,this.unregisterCommands=this.registerCommands(),this.loadCopyOnSelectEnabled()}didUpdateWidget(A){if(A.configService!==this.widget.configService)this.loadCopyOnSelectEnabled();if(A.threadContext?.client!==this.widget.threadContext?.client)if(this.historyIndex=-1,this.historyDraft=null,!this.widget.threadContext)this.previousThreadIDForReference=A.threadContext?.client.getThreadId()??null;else this.previousThreadIDForReference=null}dispose(){this.unregisterCommands?.(),this.unregisterCommands=null}registerCommands(){let A=OX.of(this.context),Q=l7.of(this.context),B=this,$=()=>{return B.widget.threadContext??null},J=()=>{let X=B.widget.threadContext?.client.getThreadId();if(!X)return null;return TY(new URL(Q.ampURL),X).toString()},F=[...s$(void 0,{isInternalUser:Q.isInternalUser}).map(({mode:X})=>({noun:"mode",verb:`use ${X}`,description:`Enable ${X} mode`,get status(){if(B.widget.threadContext)return{type:"disabled",reason:"Mode can only be changed on a new thread"};if(X===B.agentMode)return{type:"disabled",reason:`Already using ${X} mode`};return{type:"enabled"}},run:(D,G,V)=>{B.setAgentMode(X),V()}})),{noun:"speed",verb:"toggle speed",description:"Toggle speed (fast/standard) for this thread",keywords:["anthropic","openai","fast","standard","smart","deep"],get status(){let X=B.currentCommandAgentMode();return X==="smart"||y2(X)?{type:"enabled"}:{type:"hidden"}},run:(X,D,G)=>{B.toggleSpeed(),G()}},{noun:"thread",verb:"toggle thinking blocks",description:"Expand or collapse all thinking blocks",keywords:["thinking","expand","collapse","reasoning"],shortcut:a1.alt("t"),status:{type:"enabled"},run:(X,D,G)=>{B.toggleGlobalThinking(),G()}},{noun:"mode",verb:"toggle reasoning effort",description:"Cycle reasoning effort for the active model",keywords:["deep","thinking","reasoning","effort","depth","anthropic","openai","smart","frontier"],shortcut:a1.alt("d"),get status(){return Nc(B.currentCommandAgentMode())?{type:"enabled"}:{type:"hidden"}},run:(X,D,G)=>{B.toggleReasoningEffort(),G()}},{noun:"prompt",verb:"history",description:"Restore a previous prompt",keywords:["recent","reuse","search"],shortcut:a1.ctrl("r"),status:{type:"enabled"},run:(X,D,G)=>{X.pushWithDismiss((V)=>new cW0({entries:this.widget.history.getAll(),currentCwd:BB1.cwd(),onAccept:(U)=>{this.restorePromptHistory(U),G()},onDismiss:V}))}},{noun:"thread",verb:"copy ID",description:"Copy thread ID to clipboard",keywords:["identifier","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=$()?.client.getThreadId();if(!V)return;A6.maybeInvoke(D,new hG(V,"Thread ID copied to clipboard","Failed to copy thread ID")),G()}},{noun:"thread",verb:"copy URL",description:"Copy thread URL to clipboard",keywords:["link","share","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=J();if(!V)return;A6.maybeInvoke(D,new hG(V,"Thread URL copied to clipboard","Failed to copy thread URL")),G()}},{noun:"thread",verb:"copy markdown",description:"Copy thread as Markdown",keywords:["markdown","export","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=$()?.client.getThreadId();if(!V)return;(async()=>{try{let U=await Q.getThreadMarkdown(V);if(!U){xK.error(D,"Failed to copy thread markdown");return}A6.maybeInvoke(D,new hG(U,"Thread markdown copied to clipboard","Failed to copy thread markdown"))}catch(U){T.error("Failed to render thread markdown from Neo command palette",{error:U,threadID:V}),xK.error(D,"Failed to copy thread markdown")}finally{G()}})()}},{noun:"thread",verb:"analyze context",description:"Analyze context token usage",keywords:["tokens","usage","window","size","cost"],get status(){let X=B.widget.threadContext;if(!X)return{type:"disabled",reason:"No active thread"};let D=t$(X.observer.agentMode);if(!v3A.includes(D))return{type:"disabled",reason:"Context analysis requires Claude Opus 4.7 (smart) or GPT-5.4 (deep)"};return{type:"enabled"}},run:(X)=>{let D=$()?.client.getThreadId();if(!D)return;X.pushWithDismiss((G)=>{return new V3({header:"Context Usage Analysis",minWidth:60,maxWidth:60,chromePadding:M0.symmetric(1,0),footer:[{keys:["Esc"],label:"close"}],onDismiss:G,child:new l00({embedded:!0,contentWidth:58,thread:null,dtwAnalyze:(K)=>{return B.widget.analyzeContextForThread(D,K)},onDismiss:G})})})}},{noun:"skills",verb:"list",description:"List available skills for this thread",keywords:["agent","show"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X)=>{let D=$()?.client.getThreadId();if(!D)return;X.pushWithDismiss((G)=>new QB1({listSkills:(V)=>B.widget.listSkillsForThread(D,V),onDismiss:G,cwd:Q.workspaceRoot}))}},{noun:"thread",verb:"new",description:"Start new thread",keywords:["create","start","reset","clear"],sortBoost:101,get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"Already on a new thread"}},run:(X,D)=>{A6.maybeInvoke(D,new u00)}},{noun:"thread",verb:"open in browser",description:"Open thread in browser",keywords:["web","view","launch"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(X,D,G)=>{let V=J();if(!V)return;try{await V5(D,V)}finally{G()}}},P9A({shareThreadWithSupport:(X,D)=>{return this.widget.shareThreadWithSupport(X,D)}},$),T9A({setVisibility:(X,D)=>this.widget.setThreadVisibility(X,D)},$),i2A({archiveThread:(X)=>this.widget.archiveThread(X)},$),j9A($),K9A({configService:this.widget.configService,addLabel:(X,D)=>this.widget.addThreadLabel(X,D)},$),H9A({configService:this.widget.configService,removeLabel:(X,D)=>this.widget.removeThreadLabel(X,D)},$)].map((X)=>A.register(X));return()=>{for(let X of F)X()}}currentCommandAgentMode(){return this.widget.threadContext?.observer.agentMode??this.agentMode}updateThreadSettings(A){let Q=this.widget.threadContext;if(Q){let B=Q.observer.threadSettings().getValue()??{},$=A(B);return Q.client.sendClientUpdateThreadSettings($),this.widget.updateDraftThreadSettings(()=>$),"handled"}return this.widget.updateDraftThreadSettings(A),"handled"}toggleSpeed(){let A=this.currentCommandAgentMode();if(A==="smart")return this.updateThreadSettings((Q)=>{let B={...Q};if(B["anthropic.speed"]==="fast")delete B["anthropic.speed"];else B["anthropic.speed"]="fast";return B});if(y2(A))return this.updateThreadSettings((Q)=>{let B={...Q};if(B["openai.speed"]==="fast")B["openai.speed"]="standard";else B["openai.speed"]="fast";return B});return"ignored"}toggleGlobalThinking(){return this.expansion.toggle(),"handled"}toggleReasoningEffort(){let A=this.currentCommandAgentMode(),Q=Nc(A);if(!Q)return"ignored";return this.updateThreadSettings((B)=>{let $=j90(A,B);if(!$)return B;let J=B[$]??J3(A)?.reasoningEffort,Y=O90(Q,J);return{...B,[$]:Y}})}onPromptSubmitted=(A)=>{this.widget.history.add(A,BB1.cwd()),this.resetHistory()};restorePromptHistory(A){this.resetHistory(),this.widget.editorController.text=A,this.widget.editorController.moveCursorToEnd()}handlePromptHistorySelection=(A)=>{this.promptHistoryPicker.disable(),this.restorePromptHistory(A)};navigateHistoryPrevious=()=>{let A=this.widget.history.previous();if(A!==null){if(this.historyIndex===-1)this.historyDraft=this.widget.editorController.text;this.historyIndex++,this.widget.editorController.text=A,this.widget.editorController.moveCursorToStart()}return"handled"};navigateHistoryNext=()=>{let A=this.widget.history.next();if(A!==null)this.historyIndex--,this.widget.editorController.text=A,this.widget.editorController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.widget.editorController.text=this.historyDraft||"",this.widget.editorController.moveCursorToEnd(),this.historyDraft=null;return"handled"};resetHistory(){this.widget.history.reset(),this.historyIndex=-1,this.historyDraft=null}setAgentMode(A){if(this.widget.threadContext)return;this.setState(()=>{this.agentMode=A}),NZ((Q)=>({...Q,agentMode:A}))}buildActions(){let A=new S4(()=>{return this.promptHistoryPicker.enable(),"handled"}),Q=new S4(()=>{return this.navigateHistoryPrevious()}),B=new S4(()=>{return this.navigateHistoryNext()}),$=new S4((Z)=>{return this.setAgentMode(Z.mode),"handled"}),J=new S4(()=>{return this.toggleReasoningEffort()}),Y=new S4(()=>{return this.toggleGlobalThinking()});return new Map([[uH,A],[OW0,B],[LW0,Q],[p00,$],[jW0,J],[wW0,Y]])}build(A){let Q=this.widget.threadContext,$=[Q?new oQ1({editorController:this.widget.editorController,copyOnSelectEnabled:this.copyOnSelectEnabled,observingClient:{client:Q.client,observer:Q.observer},hints:this.widget.hints,ideStatus:this.widget.ideStatus,onPromptSubmitted:this.onPromptSubmitted}):new eQ1({agentMode:this.agentMode,threadSettings:this.widget.draftThreadSettings,editorController:this.widget.editorController,onNewThread:this.widget.onNewThread,previousThreadIDForReference:this.previousThreadIDForReference,connectionErrorMessage:this.widget.connectionErrorMessage,hints:this.widget.hints,ideStatus:this.widget.ideStatus})];if(this.promptHistoryPicker.isEnabled())$.push(new cW0({entries:this.widget.history.getAll(),currentCwd:BB1.cwd(),onAccept:this.handlePromptHistorySelection,onDismiss:this.promptHistoryPicker.disable}));let J=new Map([[a1.ctrl("r"),new uH],[a1.alt("d"),new jW0],[a1.alt("t"),new wW0]]);if(this.promptHistoryPicker.isEnabled())J.set(a1.ctrl("o"),new uH);else J.set(a1.ctrl("n"),new OW0),J.set(a1.ctrl("p"),new LW0);return new A6({actions:this.buildActions(),child:new G3({debugLabel:"NeoThreadShortcuts",shortcuts:J,child:new jX({controller:this.expansion,child:new CA({children:$})})})})}async loadCopyOnSelectEnabled(){let Q=(await this.widget.configService.getLatest()).settings["terminal.copyOnSelect"]??!0;if(this.copyOnSelectEnabled===Q)return;if(this.copyOnSelectEnabled=Q,this.mounted)this.setState()}}class JB1 extends y0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;isFirstOpen;notificationService;onThreadArchived;initialUserInput;openThreadPickerOnStart;neoContext;constructor(A){super();this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.initialThreadID=A.initialThreadID,this.isFirstOpen=A.isFirstOpen??!1,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.initialUserInput=A.initialUserInput,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new k9A}}class k9A extends v0{editorController=new I2;commandPalette=new me(this);commandRegistry=new AQ1;toastController=new n31;exitHintTimer=new ge(this,1000);connectionErrorMessage=new r3(this,null);ideStatus=new r3(this,{});draftThreadSettings={};draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;ideErrorSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;firstOpenDialogVisible=!1;focusDebugVisible=!1;unregisterCommands=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.clearConnectionError(),this.connectToExistingThread(A)};shareThreadWithSupport=async(A,Q)=>{let B;if(this.activeThreadContext&&this.activeThreadContext.client.getThreadId()===A){let $=this.activeThreadContext.observer.activeError().getValue();if($)B={message:$.message,type:$.code,stack:$.stack,retryAfterSeconds:$.retryAt!==void 0?Math.max(0,Math.ceil(($.retryAt-Date.now())/1000)):void 0}}await t8A({configService:this.widget.configService},A,Q,B)};setThreadVisibility=(A,Q)=>{return e8A({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await E1A({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await W1A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};removeThreadLabel=async(A,Q)=>{let B=await H1A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(W$.getInstance().interceptConsole(),this.widget.isFirstOpen)this.firstOpenDialogVisible=!0;if(this.connectionErrorMessage.subscribe(this.widget.clientPool.connectionErrors$.pipe(nE(({threadID:Q,error:B})=>{T.error("Neo failed to connect to thread",{threadID:Q,error:B})}),N5(({threadID:Q})=>this.isConnectionErrorRelevant(Q)),nE(()=>this.clearActiveClientForConnectionError()),w1(({threadID:Q,error:B})=>{return Q?`Connection failed for ${Q}: ${B.message}`:`Connection failed: ${B.message}`}))),this.ideStatus.subscribe(this.widget.ideManager.status),this.ideErrorSubscription=this.widget.ideManager.errors$.subscribe((Q)=>{if(Q)this.setState(()=>{this.connectionErrorMessage.setValue(Q)})}),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID)this.connectToExistingThread(this.widget.initialThreadID,A);else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=i4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let Q=[{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(B,$,J)=>{B.pushWithDismiss((Y)=>cQ1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:Y,onThreadSelected:J}))}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(B)=>{B.pushWithDismiss(($)=>new GQ1({mcpServers:this.widget.neoContext.mcpServers,onDismiss:$}))}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{pJ(this.widget.neoContext.settingsFilePath).catch((B)=>{T.error("Failed to open settings file in editor",{error:B})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(B,$,J)=>{B.pushWithDismiss((Y)=>new XQ1({onCancel:Y,onSelect:(Z)=>{this.handleIdeSelection(Z),J()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(B,$)=>{B.pushWithDismiss((J)=>new YQ1({commands:OX.of($).commands,onDismiss:J}))}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(B)=>{B.pushWithDismiss(($)=>new V3({header:"Amp Version",maxWidth:72,onDismiss:$,child:new t({text:new O(m31({version:"0.0.1777279521-gff806d",buildTimestamp:"2026-04-27T08:50:02.827Z",buildType:"'release'"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:a1.ctrl("c"),status:{type:"enabled"},run:(B,$)=>{A6.maybeInvoke($,new du)}},...s8A(this.widget.neoContext.logFilePath)].map((B)=>this.commandRegistry.register(B));return()=>{for(let B of Q)B()}}build(A){let Q=this.buildHints(),B=this.connectionErrorMessage.getValue(),$=this.ideStatus.getValue(),J=new $B1({initialAgentMode:this.widget.neoContext.sessionAgentMode,analyzeContextForThread:this.widget.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,shareThreadWithSupport:this.shareThreadWithSupport,setThreadVisibility:this.setThreadVisibility,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,connectionErrorMessage:B,hints:Q,ideStatus:$}),Y=F4.of(A),F=[new u0({constraints:W1.tight(Y.size.width,Y.size.height),child:J})];if(this.commandPalette.isEnabled())F.push(new QQ1({onDismiss:this.commandPalette.disable}));if(this.switchThreadPickerVisible)F.push(cQ1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.firstOpenDialogVisible)F.push(new ZQ1({onDismiss:this.dismissFirstOpenDialog}));if(this.focusDebugVisible)F.push(new FQ1);return new l7({neoContext:this.widget.neoContext,child:new OX({commandRegistry:this.commandRegistry,child:new tC({completionBuilder:this.widget.completionBuilder,child:new xK({controller:this.toastController,child:new A6({actions:this.buildActions(),child:new G3({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[a1.ctrl("c"),new IW0],[a1.ctrl("o"),new CW0],[a1.ctrl("t"),new MW0]]),child:new e4({debugLabel:"AppShellFocus",child:new a31({controller:this.toastController,child:new CA({children:F})})})})})})})})})}buildActions(){let A=new S4(()=>{return this.onExitPressed(),"handled"}),Q=new S4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new S4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new S4(()=>{return this.commandPalette.disable(),this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.writeTerminalTitle(void 0),this.activeThreadContext=null,this.connectingToThreadID=null,this.connectionErrorMessage.setValue(null)}),"handled"}),J=new S4(()=>{return i4.instance.stop(),"handled"}),Y=new S4((F)=>{if(!F.text)return"ignored";return i4.instance.tuiInstance.clipboard.writeText(F.text).then(()=>{this.toastController.show(F.successMessage,"success",2000)}).catch((X)=>{T.error("Failed to copy Neo text to clipboard",{error:X}),this.toastController.show(F.failureMessage,"error",2000)}),"handled"}),Z=new S4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[IW0,A],[u00,$],[du,J],[hG,Y],[m00,B],[CW0,Q],[MW0,Z]])}ensureDraftThreadSettingsInitialized(){if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=await PK0(this.widget.configService);if(!this.mounted)return;this.setState(()=>{this.draftThreadSettings=A})}catch(A){T.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(gu);if(this.exitHintTimer.isActive())A.add(k00);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),i4.instance.stop();else this.exitHintTimer.activate()};dismissFirstOpenDialog=()=>{if(!this.firstOpenDialogVisible)return;this.setState(()=>{this.firstOpenDialogVisible=!1})};closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q)=>{await this.ensureDraftThreadSettingsInitialized();let B=A.find((J)=>J.type==="text");if(B&&B.type==="text")this.widget.history.add(B.text,lW0.cwd()),this.widget.history.reset();let $=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings);this.clearConnectionError(),this.sendUserMessage($,A,Q),this.setActiveClient($)};sendUserMessage(A,Q,B){A.observer.markMessageSent();let $=bX0(this.ideStatus.getValue());A.client.sendUserMessage(Q,B,{userState:$})}async connectToExistingThread(A,Q){this.setState(()=>{this.connectingToThreadID=A});try{let B=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly});if(this.setActiveClient(B),Q)this.sendUserMessage(B,[{type:"text",text:Q}])}catch(B){T.error("Failed to load thread",{error:B,threadID:A}),this.connectionErrorMessage.setValue(`Failed to load ${A}: ${B instanceof Error?B.message:String(B)}`)}finally{this.setState(()=>{this.connectingToThreadID=null})}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q},this.connectionErrorMessage.setValue(null),this.subscribeTitleUpdates(Q),this.subscribeNotifications(Q)})}subscribeTitleUpdates(A){this.titleSubscription?.unsubscribe(),this.titleSubscription=A.title().subscribe({next:(Q)=>{this.writeTerminalTitle(Q)}})}subscribeNotifications(A){this.widget.notificationService.attach(A.agentState())}writeTerminalTitle(A){let Q=lW0.cwd().replace(lW0.env.HOME||"","~"),B=A?`amp - ${A} - ${Q}`:"";lW0.stdout.write(jC(B))}handleIdeSelection=async(A)=>{await this.widget.ideManager.connect(A)};dispose(){this.unregisterCommands?.(),this.unregisterCommands=null,this.titleSubscription?.unsubscribe(),this.ideErrorSubscription?.unsubscribe(),this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}isConnectionErrorRelevant(A){if(!this.activeThreadContext)return!0;if(!A)return!0;return this.activeThreadContext.client.getThreadId()===A}clearConnectionError(){if(!this.connectionErrorMessage.getValue())return;this.setState(()=>{this.connectionErrorMessage.setValue(null)})}clearActiveClientForConnectionError(){if(!this.activeThreadContext)return;this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.widget.notificationService.detach(),this.writeTerminalTitle(void 0),this.activeThreadContext=null})}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.firstOpenDialogVisible}}t4();function v9A(A,Q,B,$){let J=mk(A),Y="\x1B[0m",Z="\x1B[34m",F="\x1B[90m",X="\x1B[2m",D=[];if(A.archived)D.push("\x1B[90m\x1B[2mArchived\x1B[0m");D.push(`${J}`),D.push(`\x1B[34m${Q}\x1B[0m`),D.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let G=14,V=7,U=new HZ(G,V),K=new mJ(42),E=new TC(G,V,G,V,G,V,0,A.agentMode??"smart","intensity",void 0,void 0,C0.default(),K);E.layout(W1.tight(G,V)),E.paint(U,0,0);let W=U.getBuffer().getCells(),H=0;for(let j=0;j<V;j++)if(W[j].some((P)=>P.char!==" ")){H=j;break}let z=V-1;for(let j=V-1;j>=0;j--)if(W[j].some((P)=>P.char!==" ")){z=j;break}function q(j,P){if(!j)return"";if(j.type==="rgb"){let{r:R,g:b,b:g}=j.value;if(B.getColorDepth()>=24)return`\x1B[${P?38:48};2;${R};${b};${g}m`;let f=NP(R,b,g);return`\x1B[${P?38:48};5;${f}m`}return""}let N=[];if(z>=H)for(let j=H;j<=z;j++){let P="";for(let R=0;R<G;R++){let b=W[j][R],g=b.char,f=q(b.style.fg,!0);P+=f+g+"\x1B[0m"}N.push(P)}let I=N.length,C=Math.max(I,D.length),w=Math.floor((C-I)/2),M=Math.floor((C-D.length)/2);for(let j=0;j<C;j++){let P=" ".repeat(G);if(j>=w&&j<w+I)P=N[j-w];let R=" ",b="";if(j>=M&&j<M+D.length)b=D[j-M];B.write(P+R+b+`
5170
+ `,new h({color:B.foreground,dim:!0})),new O("If you need a reply, post on X @AmpCode or email amp-devs@ampcode.com.",new h({color:B.foreground,dim:!0}))]),textAlign:"center"})})}}function R9A(A){return new V3({header:A.title,minWidth:80,maxWidth:80,chromePadding:M0.symmetric(1,0),footer:"none",onDismiss:A.onDismiss,child:A.child})}function i78(A,Q,B){return new p1({child:new u0({constraints:new W1(80,80,0,12),child:new sH({commandName:"Share with Support",title:"Share Thread with Support",placeholder:"What went wrong? (Need a reply? Email amp-devs@ampcode.com.)",isRequiredArg:!1,onSubmit:async($)=>{try{await A.shareThreadWithSupport(Q,$||void 0),B.pushResultPane(R9A({title:"Shared with Support",onDismiss:B.dismissFlow,child:new B10}))}catch(J){T.error("Failed to share thread with support",{error:J,threadID:Q}),B.pushResultPane(R9A({title:"Share with Support failed",onDismiss:B.dismissFlow,child:new t({text:new O(`Failed to share thread with support: ${J instanceof Error?J.message:String(J)}`)})}))}},onDismiss:B.dismissFlow})})})}function P9A(A,Q){return{noun:"thread",verb:"share with support",description:"Share with Amp support for debugging",get status(){return Q()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(B,$,J)=>{let Y=Q()?.client.getThreadId();if(!Y)return;B.push(i78(A,Y,{dismissFlow:J,pushResultPane:(Z)=>B.push(Z)}))}}}class $10 extends y0{props;constructor(A){super();this.props=A}createState(){return new _9A}}class _9A extends v0{result=void 0;isLoading=!1;build(A){let Q=[];if(this.isLoading)Q.push(new fQ({message:"Updating visibility..."}));else if(this.result!==void 0)Q.push(new i7({message:this.result,onDismiss:()=>{this.widget.props.onDismiss()}}));else{let B=["private","workspace","unlisted","public"],$=this.widget.props.workspace?.groups&&this.widget.props.workspace.groups.length>0?["private","workspace","group","unlisted","public"]:B;Q.push(new k5({items:$,getLabel:(J)=>{switch(J){case"private":return"Private - Only you can see this thread";case"workspace":return"Workspace - Visible to workspace members";case"group":return"Group - Visible to group members";case"unlisted":return"Unlisted - Anyone with the link can view";case"public":return"Public - Searchable and on your public profile"}},title:"Select Thread Visibility",onAccept:async(J)=>{this.setState(()=>{this.isLoading=!0});let Y=await this.widget.props.execute(J);this.setState(()=>{this.isLoading=!1,this.result=Y})},onDismiss:this.widget.props.onDismiss}))}return new CA({children:Q,fit:"expand"})}}function n78(A,Q,B){return new p1({child:new u0({constraints:new W1(80,80,0,16),child:new $10({workspace:null,threadID:Q,execute:($)=>A.setVisibility(Q,$),onDismiss:B})})})}function T9A(A,Q){return{noun:"thread",verb:"set visibility",description:"Set thread visibility",keywords:["share","private","workspace","public","unlisted","team","group"],get status(){return Q()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(B,$,J)=>{let Y=Q()?.client?.getThreadId();if(!Y)return;B.push(n78(A,Y,J))}}}class $B1 extends y0{initialAgentMode;analyzeContextForThread;listSkillsForThread;threadContext;draftThreadSettings;editorController;history;updateDraftThreadSettings;onNewThread;shareThreadWithSupport;setThreadVisibility;archiveThread;addThreadLabel;removeThreadLabel;configService;connectionErrorMessage;hints;ideStatus;constructor(A){super();this.initialAgentMode=A.initialAgentMode,this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.threadContext=A.threadContext,this.draftThreadSettings=A.draftThreadSettings,this.editorController=A.editorController,this.history=A.history,this.updateDraftThreadSettings=A.updateDraftThreadSettings,this.onNewThread=A.onNewThread,this.shareThreadWithSupport=A.shareThreadWithSupport,this.setThreadVisibility=A.setThreadVisibility,this.archiveThread=A.archiveThread,this.addThreadLabel=A.addThreadLabel,this.removeThreadLabel=A.removeThreadLabel,this.configService=A.configService,this.connectionErrorMessage=A.connectionErrorMessage,this.hints=A.hints,this.ideStatus=A.ideStatus}createState(){return new S9A}}class S9A extends v0{historyIndex=-1;historyDraft=null;promptHistoryPicker=new me(this);agentMode;copyOnSelectEnabled=!0;expansion=new VQ1;previousThreadIDForReference=null;unregisterCommands=null;initState(){this.agentMode=this.widget.initialAgentMode,this.unregisterCommands=this.registerCommands(),this.loadCopyOnSelectEnabled()}didUpdateWidget(A){if(A.configService!==this.widget.configService)this.loadCopyOnSelectEnabled();if(A.threadContext?.client!==this.widget.threadContext?.client)if(this.historyIndex=-1,this.historyDraft=null,!this.widget.threadContext)this.previousThreadIDForReference=A.threadContext?.client.getThreadId()??null;else this.previousThreadIDForReference=null}dispose(){this.unregisterCommands?.(),this.unregisterCommands=null}registerCommands(){let A=OX.of(this.context),Q=l7.of(this.context),B=this,$=()=>{return B.widget.threadContext??null},J=()=>{let X=B.widget.threadContext?.client.getThreadId();if(!X)return null;return TY(new URL(Q.ampURL),X).toString()},F=[...s$(void 0,{isInternalUser:Q.isInternalUser}).map(({mode:X})=>({noun:"mode",verb:`use ${X}`,description:`Enable ${X} mode`,get status(){if(B.widget.threadContext)return{type:"disabled",reason:"Mode can only be changed on a new thread"};if(X===B.agentMode)return{type:"disabled",reason:`Already using ${X} mode`};return{type:"enabled"}},run:(D,G,V)=>{B.setAgentMode(X),V()}})),{noun:"speed",verb:"toggle speed",description:"Toggle speed (fast/standard) for this thread",keywords:["anthropic","openai","fast","standard","smart","deep"],get status(){let X=B.currentCommandAgentMode();return X==="smart"||y2(X)?{type:"enabled"}:{type:"hidden"}},run:(X,D,G)=>{B.toggleSpeed(),G()}},{noun:"thread",verb:"toggle thinking blocks",description:"Expand or collapse all thinking blocks",keywords:["thinking","expand","collapse","reasoning"],shortcut:a1.alt("t"),status:{type:"enabled"},run:(X,D,G)=>{B.toggleGlobalThinking(),G()}},{noun:"mode",verb:"toggle reasoning effort",description:"Cycle reasoning effort for the active model",keywords:["deep","thinking","reasoning","effort","depth","anthropic","openai","smart","frontier"],shortcut:a1.alt("d"),get status(){return Nc(B.currentCommandAgentMode())?{type:"enabled"}:{type:"hidden"}},run:(X,D,G)=>{B.toggleReasoningEffort(),G()}},{noun:"prompt",verb:"history",description:"Restore a previous prompt",keywords:["recent","reuse","search"],shortcut:a1.ctrl("r"),status:{type:"enabled"},run:(X,D,G)=>{X.pushWithDismiss((V)=>new cW0({entries:this.widget.history.getAll(),currentCwd:BB1.cwd(),onAccept:(U)=>{this.restorePromptHistory(U),G()},onDismiss:V}))}},{noun:"thread",verb:"copy ID",description:"Copy thread ID to clipboard",keywords:["identifier","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=$()?.client.getThreadId();if(!V)return;A6.maybeInvoke(D,new hG(V,"Thread ID copied to clipboard","Failed to copy thread ID")),G()}},{noun:"thread",verb:"copy URL",description:"Copy thread URL to clipboard",keywords:["link","share","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=J();if(!V)return;A6.maybeInvoke(D,new hG(V,"Thread URL copied to clipboard","Failed to copy thread URL")),G()}},{noun:"thread",verb:"copy markdown",description:"Copy thread as Markdown",keywords:["markdown","export","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=$()?.client.getThreadId();if(!V)return;(async()=>{try{let U=await Q.getThreadMarkdown(V);if(!U){xK.error(D,"Failed to copy thread markdown");return}A6.maybeInvoke(D,new hG(U,"Thread markdown copied to clipboard","Failed to copy thread markdown"))}catch(U){T.error("Failed to render thread markdown from Neo command palette",{error:U,threadID:V}),xK.error(D,"Failed to copy thread markdown")}finally{G()}})()}},{noun:"thread",verb:"analyze context",description:"Analyze context token usage",keywords:["tokens","usage","window","size","cost"],get status(){let X=B.widget.threadContext;if(!X)return{type:"disabled",reason:"No active thread"};let D=t$(X.observer.agentMode);if(!v3A.includes(D))return{type:"disabled",reason:"Context analysis requires Claude Opus 4.7 (smart) or GPT-5.4 (deep)"};return{type:"enabled"}},run:(X)=>{let D=$()?.client.getThreadId();if(!D)return;X.pushWithDismiss((G)=>{return new V3({header:"Context Usage Analysis",minWidth:60,maxWidth:60,chromePadding:M0.symmetric(1,0),footer:[{keys:["Esc"],label:"close"}],onDismiss:G,child:new l00({embedded:!0,contentWidth:58,thread:null,dtwAnalyze:(K)=>{return B.widget.analyzeContextForThread(D,K)},onDismiss:G})})})}},{noun:"skills",verb:"list",description:"List available skills for this thread",keywords:["agent","show"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X)=>{let D=$()?.client.getThreadId();if(!D)return;X.pushWithDismiss((G)=>new QB1({listSkills:(V)=>B.widget.listSkillsForThread(D,V),onDismiss:G,cwd:Q.workspaceRoot}))}},{noun:"thread",verb:"new",description:"Start new thread",keywords:["create","start","reset","clear"],sortBoost:101,get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"Already on a new thread"}},run:(X,D)=>{A6.maybeInvoke(D,new u00)}},{noun:"thread",verb:"open in browser",description:"Open thread in browser",keywords:["web","view","launch"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(X,D,G)=>{let V=J();if(!V)return;try{await V5(D,V)}finally{G()}}},P9A({shareThreadWithSupport:(X,D)=>{return this.widget.shareThreadWithSupport(X,D)}},$),T9A({setVisibility:(X,D)=>this.widget.setThreadVisibility(X,D)},$),i2A({archiveThread:(X)=>this.widget.archiveThread(X)},$),j9A($),K9A({configService:this.widget.configService,addLabel:(X,D)=>this.widget.addThreadLabel(X,D)},$),H9A({configService:this.widget.configService,removeLabel:(X,D)=>this.widget.removeThreadLabel(X,D)},$)].map((X)=>A.register(X));return()=>{for(let X of F)X()}}currentCommandAgentMode(){return this.widget.threadContext?.observer.agentMode??this.agentMode}updateThreadSettings(A){let Q=this.widget.threadContext;if(Q){let B=Q.observer.threadSettings().getValue()??{},$=A(B);return Q.client.sendClientUpdateThreadSettings($),this.widget.updateDraftThreadSettings(()=>$),"handled"}return this.widget.updateDraftThreadSettings(A),"handled"}toggleSpeed(){let A=this.currentCommandAgentMode();if(A==="smart")return this.updateThreadSettings((Q)=>{let B={...Q};if(B["anthropic.speed"]==="fast")delete B["anthropic.speed"];else B["anthropic.speed"]="fast";return B});if(y2(A))return this.updateThreadSettings((Q)=>{let B={...Q};if(B["openai.speed"]==="fast")B["openai.speed"]="standard";else B["openai.speed"]="fast";return B});return"ignored"}toggleGlobalThinking(){return this.expansion.toggle(),"handled"}toggleReasoningEffort(){let A=this.currentCommandAgentMode(),Q=Nc(A);if(!Q)return"ignored";return this.updateThreadSettings((B)=>{let $=j90(A,B);if(!$)return B;let J=B[$]??J3(A)?.reasoningEffort,Y=O90(Q,J);return{...B,[$]:Y}})}onPromptSubmitted=(A)=>{this.widget.history.add(A,BB1.cwd()),this.resetHistory()};restorePromptHistory(A){this.resetHistory(),this.widget.editorController.text=A,this.widget.editorController.moveCursorToEnd()}handlePromptHistorySelection=(A)=>{this.promptHistoryPicker.disable(),this.restorePromptHistory(A)};navigateHistoryPrevious=()=>{let A=this.widget.history.previous();if(A!==null){if(this.historyIndex===-1)this.historyDraft=this.widget.editorController.text;this.historyIndex++,this.widget.editorController.text=A,this.widget.editorController.moveCursorToStart()}return"handled"};navigateHistoryNext=()=>{let A=this.widget.history.next();if(A!==null)this.historyIndex--,this.widget.editorController.text=A,this.widget.editorController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.widget.editorController.text=this.historyDraft||"",this.widget.editorController.moveCursorToEnd(),this.historyDraft=null;return"handled"};resetHistory(){this.widget.history.reset(),this.historyIndex=-1,this.historyDraft=null}setAgentMode(A){if(this.widget.threadContext)return;this.setState(()=>{this.agentMode=A}),NZ((Q)=>({...Q,agentMode:A}))}buildActions(){let A=new S4(()=>{return this.promptHistoryPicker.enable(),"handled"}),Q=new S4(()=>{return this.navigateHistoryPrevious()}),B=new S4(()=>{return this.navigateHistoryNext()}),$=new S4((Z)=>{return this.setAgentMode(Z.mode),"handled"}),J=new S4(()=>{return this.toggleReasoningEffort()}),Y=new S4(()=>{return this.toggleGlobalThinking()});return new Map([[uH,A],[OW0,B],[LW0,Q],[p00,$],[jW0,J],[wW0,Y]])}build(A){let Q=this.widget.threadContext,$=[Q?new oQ1({editorController:this.widget.editorController,copyOnSelectEnabled:this.copyOnSelectEnabled,observingClient:{client:Q.client,observer:Q.observer},hints:this.widget.hints,ideStatus:this.widget.ideStatus,onPromptSubmitted:this.onPromptSubmitted}):new eQ1({agentMode:this.agentMode,threadSettings:this.widget.draftThreadSettings,editorController:this.widget.editorController,onNewThread:this.widget.onNewThread,previousThreadIDForReference:this.previousThreadIDForReference,connectionErrorMessage:this.widget.connectionErrorMessage,hints:this.widget.hints,ideStatus:this.widget.ideStatus})];if(this.promptHistoryPicker.isEnabled())$.push(new cW0({entries:this.widget.history.getAll(),currentCwd:BB1.cwd(),onAccept:this.handlePromptHistorySelection,onDismiss:this.promptHistoryPicker.disable}));let J=new Map([[a1.ctrl("r"),new uH],[a1.alt("d"),new jW0],[a1.alt("t"),new wW0]]);if(this.promptHistoryPicker.isEnabled())J.set(a1.ctrl("o"),new uH);else J.set(a1.ctrl("n"),new OW0),J.set(a1.ctrl("p"),new LW0);return new A6({actions:this.buildActions(),child:new G3({debugLabel:"NeoThreadShortcuts",shortcuts:J,child:new jX({controller:this.expansion,child:new CA({children:$})})})})}async loadCopyOnSelectEnabled(){let Q=(await this.widget.configService.getLatest()).settings["terminal.copyOnSelect"]??!0;if(this.copyOnSelectEnabled===Q)return;if(this.copyOnSelectEnabled=Q,this.mounted)this.setState()}}class JB1 extends y0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;isFirstOpen;notificationService;onThreadArchived;initialUserInput;openThreadPickerOnStart;neoContext;constructor(A){super();this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.initialThreadID=A.initialThreadID,this.isFirstOpen=A.isFirstOpen??!1,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.initialUserInput=A.initialUserInput,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new k9A}}class k9A extends v0{editorController=new I2;commandPalette=new me(this);commandRegistry=new AQ1;toastController=new n31;exitHintTimer=new ge(this,1000);connectionErrorMessage=new r3(this,null);ideStatus=new r3(this,{});draftThreadSettings={};draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;ideErrorSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;firstOpenDialogVisible=!1;focusDebugVisible=!1;unregisterCommands=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.clearConnectionError(),this.connectToExistingThread(A)};shareThreadWithSupport=async(A,Q)=>{let B;if(this.activeThreadContext&&this.activeThreadContext.client.getThreadId()===A){let $=this.activeThreadContext.observer.activeError().getValue();if($)B={message:$.message,type:$.code,stack:$.stack,retryAfterSeconds:$.retryAt!==void 0?Math.max(0,Math.ceil(($.retryAt-Date.now())/1000)):void 0}}await t8A({configService:this.widget.configService},A,Q,B)};setThreadVisibility=(A,Q)=>{return e8A({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await E1A({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await W1A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};removeThreadLabel=async(A,Q)=>{let B=await H1A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(W$.getInstance().interceptConsole(),this.widget.isFirstOpen)this.firstOpenDialogVisible=!0;if(this.connectionErrorMessage.subscribe(this.widget.clientPool.connectionErrors$.pipe(nE(({threadID:Q,error:B})=>{T.error("Neo failed to connect to thread",{threadID:Q,error:B})}),N5(({threadID:Q})=>this.isConnectionErrorRelevant(Q)),nE(()=>this.clearActiveClientForConnectionError()),w1(({threadID:Q,error:B})=>{return Q?`Connection failed for ${Q}: ${B.message}`:`Connection failed: ${B.message}`}))),this.ideStatus.subscribe(this.widget.ideManager.status),this.ideErrorSubscription=this.widget.ideManager.errors$.subscribe((Q)=>{if(Q)this.setState(()=>{this.connectionErrorMessage.setValue(Q)})}),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID)this.connectToExistingThread(this.widget.initialThreadID,A);else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=i4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let Q=[{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(B,$,J)=>{B.pushWithDismiss((Y)=>cQ1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:Y,onThreadSelected:J}))}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(B)=>{B.pushWithDismiss(($)=>new GQ1({mcpServers:this.widget.neoContext.mcpServers,onDismiss:$}))}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{pJ(this.widget.neoContext.settingsFilePath).catch((B)=>{T.error("Failed to open settings file in editor",{error:B})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(B,$,J)=>{B.pushWithDismiss((Y)=>new XQ1({onCancel:Y,onSelect:(Z)=>{this.handleIdeSelection(Z),J()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(B,$)=>{B.pushWithDismiss((J)=>new YQ1({commands:OX.of($).commands,onDismiss:J}))}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(B)=>{B.pushWithDismiss(($)=>new V3({header:"Amp Version",maxWidth:72,onDismiss:$,child:new t({text:new O(m31({version:"0.0.1777279908-g9ebba6",buildTimestamp:"2026-04-27T08:55:43.407Z",buildType:"'release'"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:a1.ctrl("c"),status:{type:"enabled"},run:(B,$)=>{A6.maybeInvoke($,new du)}},...s8A(this.widget.neoContext.logFilePath)].map((B)=>this.commandRegistry.register(B));return()=>{for(let B of Q)B()}}build(A){let Q=this.buildHints(),B=this.connectionErrorMessage.getValue(),$=this.ideStatus.getValue(),J=new $B1({initialAgentMode:this.widget.neoContext.sessionAgentMode,analyzeContextForThread:this.widget.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,shareThreadWithSupport:this.shareThreadWithSupport,setThreadVisibility:this.setThreadVisibility,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,connectionErrorMessage:B,hints:Q,ideStatus:$}),Y=F4.of(A),F=[new u0({constraints:W1.tight(Y.size.width,Y.size.height),child:J})];if(this.commandPalette.isEnabled())F.push(new QQ1({onDismiss:this.commandPalette.disable}));if(this.switchThreadPickerVisible)F.push(cQ1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.firstOpenDialogVisible)F.push(new ZQ1({onDismiss:this.dismissFirstOpenDialog}));if(this.focusDebugVisible)F.push(new FQ1);return new l7({neoContext:this.widget.neoContext,child:new OX({commandRegistry:this.commandRegistry,child:new tC({completionBuilder:this.widget.completionBuilder,child:new xK({controller:this.toastController,child:new A6({actions:this.buildActions(),child:new G3({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[a1.ctrl("c"),new IW0],[a1.ctrl("o"),new CW0],[a1.ctrl("t"),new MW0]]),child:new e4({debugLabel:"AppShellFocus",child:new a31({controller:this.toastController,child:new CA({children:F})})})})})})})})})}buildActions(){let A=new S4(()=>{return this.onExitPressed(),"handled"}),Q=new S4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new S4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new S4(()=>{return this.commandPalette.disable(),this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.writeTerminalTitle(void 0),this.activeThreadContext=null,this.connectingToThreadID=null,this.connectionErrorMessage.setValue(null)}),"handled"}),J=new S4(()=>{return i4.instance.stop(),"handled"}),Y=new S4((F)=>{if(!F.text)return"ignored";return i4.instance.tuiInstance.clipboard.writeText(F.text).then(()=>{this.toastController.show(F.successMessage,"success",2000)}).catch((X)=>{T.error("Failed to copy Neo text to clipboard",{error:X}),this.toastController.show(F.failureMessage,"error",2000)}),"handled"}),Z=new S4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[IW0,A],[u00,$],[du,J],[hG,Y],[m00,B],[CW0,Q],[MW0,Z]])}ensureDraftThreadSettingsInitialized(){if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=await PK0(this.widget.configService);if(!this.mounted)return;this.setState(()=>{this.draftThreadSettings=A})}catch(A){T.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(gu);if(this.exitHintTimer.isActive())A.add(k00);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),i4.instance.stop();else this.exitHintTimer.activate()};dismissFirstOpenDialog=()=>{if(!this.firstOpenDialogVisible)return;this.setState(()=>{this.firstOpenDialogVisible=!1})};closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q)=>{await this.ensureDraftThreadSettingsInitialized();let B=A.find((J)=>J.type==="text");if(B&&B.type==="text")this.widget.history.add(B.text,lW0.cwd()),this.widget.history.reset();let $=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings);this.clearConnectionError(),this.sendUserMessage($,A,Q),this.setActiveClient($)};sendUserMessage(A,Q,B){A.observer.markMessageSent();let $=bX0(this.ideStatus.getValue());A.client.sendUserMessage(Q,B,{userState:$})}async connectToExistingThread(A,Q){this.setState(()=>{this.connectingToThreadID=A});try{let B=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly});if(this.setActiveClient(B),Q)this.sendUserMessage(B,[{type:"text",text:Q}])}catch(B){T.error("Failed to load thread",{error:B,threadID:A}),this.connectionErrorMessage.setValue(`Failed to load ${A}: ${B instanceof Error?B.message:String(B)}`)}finally{this.setState(()=>{this.connectingToThreadID=null})}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q},this.connectionErrorMessage.setValue(null),this.subscribeTitleUpdates(Q),this.subscribeNotifications(Q)})}subscribeTitleUpdates(A){this.titleSubscription?.unsubscribe(),this.titleSubscription=A.title().subscribe({next:(Q)=>{this.writeTerminalTitle(Q)}})}subscribeNotifications(A){this.widget.notificationService.attach(A.agentState())}writeTerminalTitle(A){let Q=lW0.cwd().replace(lW0.env.HOME||"","~"),B=A?`amp - ${A} - ${Q}`:"";lW0.stdout.write(jC(B))}handleIdeSelection=async(A)=>{await this.widget.ideManager.connect(A)};dispose(){this.unregisterCommands?.(),this.unregisterCommands=null,this.titleSubscription?.unsubscribe(),this.ideErrorSubscription?.unsubscribe(),this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}isConnectionErrorRelevant(A){if(!this.activeThreadContext)return!0;if(!A)return!0;return this.activeThreadContext.client.getThreadId()===A}clearConnectionError(){if(!this.connectionErrorMessage.getValue())return;this.setState(()=>{this.connectionErrorMessage.setValue(null)})}clearActiveClientForConnectionError(){if(!this.activeThreadContext)return;this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.widget.notificationService.detach(),this.writeTerminalTitle(void 0),this.activeThreadContext=null})}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.firstOpenDialogVisible}}t4();function v9A(A,Q,B,$){let J=mk(A),Y="\x1B[0m",Z="\x1B[34m",F="\x1B[90m",X="\x1B[2m",D=[];if(A.archived)D.push("\x1B[90m\x1B[2mArchived\x1B[0m");D.push(`${J}`),D.push(`\x1B[34m${Q}\x1B[0m`),D.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let G=14,V=7,U=new HZ(G,V),K=new mJ(42),E=new TC(G,V,G,V,G,V,0,A.agentMode??"smart","intensity",void 0,void 0,C0.default(),K);E.layout(W1.tight(G,V)),E.paint(U,0,0);let W=U.getBuffer().getCells(),H=0;for(let j=0;j<V;j++)if(W[j].some((P)=>P.char!==" ")){H=j;break}let z=V-1;for(let j=V-1;j>=0;j--)if(W[j].some((P)=>P.char!==" ")){z=j;break}function q(j,P){if(!j)return"";if(j.type==="rgb"){let{r:R,g:b,b:g}=j.value;if(B.getColorDepth()>=24)return`\x1B[${P?38:48};2;${R};${b};${g}m`;let f=NP(R,b,g);return`\x1B[${P?38:48};5;${f}m`}return""}let N=[];if(z>=H)for(let j=H;j<=z;j++){let P="";for(let R=0;R<G;R++){let b=W[j][R],g=b.char,f=q(b.style.fg,!0);P+=f+g+"\x1B[0m"}N.push(P)}let I=N.length,C=Math.max(I,D.length),w=Math.floor((C-I)/2),M=Math.floor((C-D.length)/2);for(let j=0;j<C;j++){let P=" ".repeat(G);if(j>=w&&j<w+I)P=N[j-w];let R=" ",b="";if(j>=M&&j<M+D.length)b=D[j-M];B.write(P+R+b+`
5171
5171
  `)}if($)B.write(`
5172
5172
  \x1B[90m${$}\x1B[0m
5173
5173
  `)}l0();dK0();var a78=2000;function y9A(A){let Q=!0,B=!0,$=A.configService.config.subscribe((V)=>{Q=V.settings["notifications.enabled"]??!0,B=V.settings["notifications.system.enabled"]!==!1}),J=0,Y=(V)=>{if(!Q)return;let U=Date.now();if(U-J<a78)return;if(J=U,PP())return;if(uU0())hU0();else cr(V)},Z=(V)=>{if(!Q||!B)return;if(PP()&&!ve()&&!FK0())return;process.stdout.write(SG(`\x1B]777;notify;Amp;${V}\x1B\\`))},F=null,X=null,D=()=>{F?.unsubscribe(),F=null,X=null};return{attach:(V)=>{D(),F=V.subscribe({next:(U)=>{try{let K=X!==null&&zC(X),E=X==="awaiting_approval";if(U==="awaiting_approval"&&!E)Y("requires-user-input"),Z("Waiting for approval");else if((U==="idle"||U==="error")&&(K||E))Y("idle"),Z("Agent is ready")}catch(K){T.debug("Neo notification handling failed",{error:K})}finally{X=U}},error:(U)=>{T.debug("Neo notification agent state stream errored",{error:U})}})},detach:D,unsubscribe(){D(),$.unsubscribe()}}}l0();BW();z4();O1();function x9A(A,Q){if(!Q)return A;let B=Q.toLowerCase(),$=[];for(let J of A){let Y=o78(J,B);if(Y>0)$.push({...J,score:Y})}return $.sort((J,Y)=>{let Z=Y.score-J.score;if(Z!==0)return Z;return A.indexOf(J)-A.indexOf(Y)}),$}function o78(A,Q){let B=r78(A,Q),$=s78(A.message.toLowerCase(),Q);return Math.max(B,$)}function r78(A,Q){let B=A.hash.toLowerCase(),$=A.shortHash.toLowerCase();if($===Q)return 1000;if($.startsWith(Q))return 900;if(B.startsWith(Q))return 850;if(B.includes(Q)||$.includes(Q))return 400;return 0}function s78(A,Q){if(A===Q)return 800;if(A.startsWith(Q))return 700;let B=A.indexOf(Q);if(B!==-1)return 600-Math.min(B,500);let $=t78(A,Q);if($>0)return $;return 0}function t78(A,Q){let B=0,$=0,J=-1;while(B<A.length&&$<Q.length){if(A[B]===Q[$]){if(J===-1)J=B;$++}B++}if($===Q.length)return 250-Math.min(J,150);return 0}var f9A=":";function V_(A,Q){if(!VP())return;T.debug("[file mention completions]",{event:A,...Q})}function su(A){return A.length<=80?A:`${A.slice(0,77)}...`}class U_{fuzzyClient;cachedDirtyFiles=[];cachedCommits=[];refreshPromise;refreshCommitsPromise;constructor(A){this.fuzzyClient=A;this.refreshDirtyFilesInBackground(),this.refreshCommitsInBackground()}async buildOptions(A){if(A.trigger==="@"){let Q=A.query;if(Q.toLowerCase().startsWith(f9A)){let Z=Q.slice(f9A.length);return V_("commit_query_detected",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:Z.length,queryPreview:su(Z)}),this.buildCommitOptions(Z)}let $=Q.length===0?18:20,J=await this.buildFileOptions(Q,$),Y=this.appendHintOptions(Q,J);return V_("build_options_completed",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:Q.length,queryPreview:su(Q),maxResults:$,fileOptionCount:J.filter((Z)=>Z.type==="file").length,hintOptionCount:Y.filter((Z)=>Z.type==="hint").length,finalOptionCount:Y.length,firstFilePaths:Y.filter((Z)=>Z.type==="file").slice(0,5).map((Z)=>Z.path)}),Y}return[]}async buildFileOptions(A,Q){try{let B=await this.getOpenFiles(),$=this.cachedDirtyFiles;this.refreshDirtyFilesInBackground();let J=await this.fuzzyClient.queryCompletions(A,Q,B,$),Y=J.map((Z)=>H2A(Z));return V_("file_options_built",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:su(A),maxResults:Q,openFilesCount:B?.length??0,dirtyFilesCount:$.length,completionItemCount:J.length,fileOptionCount:Y.length,firstPaths:Y.slice(0,5).map((Z)=>Z.path)}),Y}catch(B){return V_("file_options_failed",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:su(A),maxResults:Q,error:B instanceof Error?B.message:String(B)}),[]}}async getOpenFiles(){let A=await k1(i8.status);if(!A.connected)return;let Q=[];if(A.openFile)Q.push(Z1.parse(A.openFile).fsPath);if(A.visibleFiles)for(let B of A.visibleFiles){let $=Z1.parse(B).fsPath;if(!Q.includes($))Q.push($)}if(Q.length===0)return;return Q}refreshDirtyFilesInBackground(){if(this.refreshPromise!==void 0)return;this.refreshPromise=Pk4(this.fuzzyClient.workspaceRoot).then((A)=>{this.cachedDirtyFiles=A}).catch(()=>{}).finally(()=>{this.refreshPromise=void 0})}async buildCommitOptions(A){this.refreshCommitsInBackground();let Q=this.cachedCommits;if(!Q.length)return V_("commit_options_empty_cache",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:su(A)}),[];let B=x9A(Q,A).slice(0,20);return V_("commit_options_built",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:su(A),commitCacheCount:Q.length,resultCount:B.length,firstCommitHashes:B.slice(0,5).map(($)=>$.shortHash)}),B.map(($)=>({type:"commit",hash:$.hash,shortHash:$.shortHash,message:$.message,relativeDate:$.relativeDate}))}refreshCommitsInBackground(){if(this.refreshCommitsPromise!==void 0)return;this.refreshCommitsPromise=_k4(this.fuzzyClient.workspaceRoot).then((A)=>{this.cachedCommits=A}).catch(()=>{}).finally(()=>{this.refreshCommitsPromise=void 0})}appendHintOptions(A,Q){if(A.length>0)return Q;let B=[{type:"hint",kind:"commit",message:"mention a commit"},{type:"hint",kind:"thread",message:"mention a thread"}];return V_("hint_options_appended",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,fileOptionCount:Q.filter(($)=>$.type==="file").length,hintOptionCount:B.length,hintOnly:Q.length===0,firstFilePaths:Q.filter(($)=>$.type==="file").slice(0,5).map(($)=>$.path)}),[...Q,...B]}}var AQ8=[{long:"neo",description:"Use the Neo TUI",type:"boolean",default:!1},{long:"url",short:"u",description:"Amp server URL",type:"string",default:""},{long:"dangerously-allow-all",description:"Disable all command confirmation prompts (agent will execute all commands without asking)",type:"boolean",default:!1},{long:"observe",description:"Connect to an existing thread as observer only (no local executor). Accepts a thread ID or thread URL.",type:"string",default:""}],Lh2=d0A({name:"amp neo",description:"Start the Neo TUI",options:AQ8,positionals:[],action:async({options:A})=>{let Q=b9A(A);if(A.observe){let B=C3(A.observe)??EB(A.observe);await iW0(Q,{initialThreadID:B,observerOnly:!0});return}await iW0(Q)},subcommands:[{name:"threads",alias:"t",description:"List and manage threads",options:[],positionals:[],subcommands:[{name:"continue",alias:"c",description:"Continue an existing thread",options:[],positionals:[{name:"thread-id",description:"Thread ID to continue"}],action:async({globalOptions:A,positionals:Q})=>{let $=b9A(A);if(!Q["thread-id"]){await iW0($,{openThreadPickerOnStart:!0});return}let J=C3(Q["thread-id"]);if(!J)throw"invalid thread ID";await iW0($,{initialThreadID:J})}}]}]});function QQ8(A){if(A)return A;if(process.env.AMP_URL)return process.env.AMP_URL;return k9}function BQ8(A){if(process.env.RIVET_PUBLIC_ENDPOINT)return process.env.RIVET_PUBLIC_ENDPOINT;return fJ(A)}var u9A=Z1.file(e78.homedir()),$Q8=process.env.XDG_CONFIG_HOME?Z1.file(process.env.XDG_CONFIG_HOME):G1.joinPath(u9A,".config");async function JQ8(A){await NZ((Q)=>yK0(Q,A,"interactive"))}function b9A(A){return{url:A.url,dangerouslyAllowAll:A["dangerously-allow-all"]}}async function iW0(A,Q={}){let{initialThreadID:B,openThreadPickerOnStart:$=!1,observerOnly:J=!1}=Q,Y=QQ8(A.url),Z={dataDir:void 0,getHook:(I,C)=>{if(I==="url")return Promise.resolve(Y);return C()}},F=await cU0(Z),X=vK0(await nt(Z,F)),D=BQ8(Y);if(A.dangerouslyAllowAll)S9("dangerouslyAllowAll",!0);let G=await X.get("apiKey",Y);if(!G)throw new K4("API key required. Please run `amp login` first.",1);let V=bk({storage:F,secretStorage:X,workspaceRoot:g0.of(Z1.file(process.cwd())),defaultAmpURL:Y,homeDir:u9A,userConfigDir:$Q8}),U=cO(V),K=ND0({configService:V}),E=s$0({configService:V,filesystem:k8}),W={registerToolsWithToolService:()=>({dispose:()=>{}}),getClient:()=>{return},servers:g0.of([]),getPrompt:async()=>null,searchResources:async()=>[],searchPrompts:()=>g0.of([]),getToolsForServer:async()=>{return}},H=process.cwd(),z=async({uri:I})=>{return qC({fileSystem:k8,workspaceRoot:H},I)},q=new ab(H,{},!0),N=new U_(q);await YB1({ampURL:Y,apiKey:G,rivetEndpoint:D,configService:V,toolService:K.toolService,skillService:E,mcpService:W,readFileSystemDirectory:z,completionBuilder:N,workspaceRoot:H,listThreads:()=>U.listThreads(),getThreadFromServer:(I)=>U.getThread(I),isInternalUser:!1,settingsFilePath:F.getSettingsFilePath(),dispose:()=>{q.dispose(),K.dispose()}},{initialThreadID:B,openThreadPickerOnStart:$,observerOnly:J})}async function YB1(A,Q={}){let{initialThreadID:B,initialUserInput:$,openThreadPickerOnStart:J=!1,observerOnly:Y=!1,initialAgentMode:Z}=Q,F=async(z)=>{let q=await A.getThreadFromServer(z);if(!q)return null;return wU0(q)},X=new q31(A.rivetEndpoint,A.apiKey,A.configService,{clientID:EC.parse(`neo-${crypto.randomUUID()}`),toolService:A.toolService,skillService:A.skillService,invokeTool:async(z,q)=>{let N=typeof q.args==="object"&&q.args!==null?q.args:{},I=await RK({toolName:q.toolName,configService:A.configService,toolService:A.toolService,mcpService:A.mcpService,skillService:A.skillService,toolUseID:q.toolCallId,threadID:z});return A.toolService.invokeTool(q.toolName,{args:N},I)},persistLastThreadID:JQ8,readFileSystemDirectory:A.readFileSystemDirectory},F),D=await Yu(),G={ampURL:A.ampURL,configService:A.configService,getThreadMarkdown:async(z)=>{let q=await A.getThreadFromServer(z);return q?VU(q):null},isInternalUser:A.isInternalUser,listThreads:A.listThreads,logFilePath:Pt,mcpServers:A.mcpService.servers,observerOnly:Y,sessionAgentMode:Z??D.agentMode,settingsFilePath:A.settingsFilePath,workspaceRoot:A.workspaceRoot},V=(z,q)=>{return Mb({ampURL:A.ampURL,configService:A.configService,threadID:z,signal:q})},U=(z,q)=>{return oe4({ampURL:A.ampURL,configService:A.configService,threadID:z,signal:q})},K=new g31,E=A0A(D);NZ(Q0A);let W=y9A({configService:A.configService}),H=new Set;try{await ye(new JB1({clientPool:X,analyzeContextForThread:V,listSkillsForThread:U,completionBuilder:A.completionBuilder,history:new ut,ideManager:K,configService:A.configService,initialThreadID:B,notificationService:W,initialUserInput:$,openThreadPickerOnStart:J,neoContext:G,isFirstOpen:E,onThreadArchived:(q)=>{H.add(q)}}));let z=X.lastActiveObservingClient;if(z){let{client:q,observer:N}=z,I=q.getThreadId();if(I){let C={id:I,title:N.title().getValue(),agentMode:N.agentMode,archived:H.has(I)},w=`${A.ampURL.replace(/\/$/,"")}/threads/${I}`;v9A(C,w,process.stdout)}}}finally{process.stdout.write(jC("")),W.unsubscribe(),X.dispose(),await A.dispose?.()}process.exit(0)}Kl();hL();async function YQ8(A,Q,B){let $=y70(A);if(!$.success)throw Error(`Invalid permission format: ${$.error.message}`);if($.data.length===0)throw Error("No permission entry provided");let J=yq($.data);if(!J.success){let X=J.error.issues.map((D)=>D.message).join(", ");throw Error(`Invalid permission entry: ${X}`)}let Y=await Q.get("permissions",B)??[],F=[$.data[0],...Y];await Q.set("permissions",F,B)}async function h9A(A){try{let Q=A.args.map((B)=>{if(/[\s/\\*?[\]{}()"]/.test(B))return`"${B}"`;return B}).join(" ");await YQ8(Q,A.settings,A.scope),A.exit(0)}catch(Q){let B=Q instanceof Error?Q.message:"Unknown error";A.stderr.write(`Error: ${B}
@@ -5952,7 +5952,7 @@ ${J}`,Q);this.line=B,this.column=$,this.codeblock=J}}/*!
5952
5952
  `),Y=[];for(let Z=0;Z<J.length;Z++){let D=J[Z].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let G of D)if(G.startsWith("\x00")&&G.endsWith("\x01"))Y.push(new O(G.slice(1,-1),new h({color:$.app.keybind,bold:!0})));else Y.push(new O(G,new h({color:B.colorScheme.foreground})));if(Z<J.length-1)Y.push(new O(`
5953
5953
  `))}return new u0({decoration:{color:B.colorScheme.background,border:Q4.all(new e1($.app.keybind,1,"rounded"))},child:new x0({padding:M0.symmetric(0,1),child:new t({text:new O(void 0,void 0,Y)})})})}}class I$1 extends a2{chartData;highlightIndex;showAxes;colors;constructor({key:A,chartData:Q,highlightIndex:B=null,showAxes:$=!0,colors:J=Hz0}){super(A?{key:A}:{});this.chartData=Q,this.highlightIndex=B,this.showAxes=$,this.colors=J}createRenderObject(){return new q$1({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(A){let Q=A;Q.chartData=this.chartData,Q.highlightIndex=this.highlightIndex,Q.showAxes=this.showAxes,Q.colors=this.colors,Q.markNeedsLayout()}}function K$A(A,Q,B,$,J,Y,Z){if(Y<=0)return null;switch(A){case"horizontal-bar":{let F=B;return F>=0&&F<Y?F:null}case"bar":case"stacked-bar":{let F=Z?A2:0,X=$-F;if(X<=0)return null;let D=Q-F;if(D<0||D>=X)return null;let G=Math.max(1,Math.floor(X/Y)),V=Math.floor(D/G);return V>=0&&V<Y?V:null}case"line":case"sparkline":case"stacked-area":{let F=Z?A2:0,X=$-F;if(X<=0)return null;let D=Math.max(0,Math.min(X-1,Q-F));if(Y===1)return 0;let G=X/(Y-1),V=Math.round(D/G);return Math.max(0,Math.min(Y-1,V))}default:return null}}function VX8(A,Q,B,$,J,Y,Z,F){if(J<=0||Q<0||Q>=J)return null;let X=2;switch(A){case"horizontal-bar":return{x:Math.floor(B/2),y:Q};case"bar":case"stacked-bar":{let D=Y?A2:0,G=B-D,V=$-(Y?X:0);if(G<=0||V<=0)return null;let U=Math.max(1,Math.floor(G/J)),K=D+Q*U+Math.floor(U/2),E=F>0?Z/F:0,W=Math.round((1-E)*(V-1));return{x:K,y:W}}case"line":case"sparkline":case"stacked-area":{let D=Y?A2:0,G=B-D,V=$-(Y?X:0);if(G<=0||V<=0)return null;let U=J>1?D+Math.round(Q/(J-1)*(G-1)):D+Math.floor(G/2),K=F>0?Z/F:0,E=Math.round((1-K)*(V-1));return{x:U,y:E}}default:return null}}function UX8(A){let Q=0;for(let B of A)for(let $ of B.points)if($.value>Q)Q=$.value;return Q||1}function KX8(A,Q,B,$,J){if(B.length<=1){let F=$(A.value),X=A.meta?` (${A.meta})`:"";return A.label.length+2+F.length+X.length}let Y=A.label.length,Z=0;for(let F of B){let X=F.points[Q];if(!X)continue;Z+=X.value;let D=2+F.name.length+2+$(X.value).length;Y=Math.max(Y,D)}if(J){let F=9+$(Z).length;Y=Math.max(Y,F)}return Y}function EX8(A,Q,B,$,J,Y,Z){let F;try{let E=S1.of(A),W=S0.of(A);F={foreground:E.colorScheme.foreground,background:E.colorScheme.background,border:W.app.keybind}}catch{F={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let X=new h({color:F.foreground,bold:!0}),D=new h({color:F.foreground}),G=new h({color:F.foreground,dim:!0}),V=[],U=new h({color:F.foreground,underline:!0}),K=(E,W)=>new O(W,U,void 0,JK0(E),()=>{V5(A,E)});if($.length<=1){if(V.push(new O(`${Q.label}: `,X)),Q.link)V.push(K(Q.link,Y(Q.value)));else V.push(new O(Y(Q.value),D));if(Q.meta)V.push(new O(` (${Q.meta})`,G))}else{let E=Z==="stacked-bar"||Z==="stacked-area";V.push(new O(`${Q.label}
5954
5954
  `,X));let W=0;for(let H=0;H<$.length;H++){let z=$[H],q=z.points[B];if(!q)continue;W+=q.value;let N=z.color??J[H%J.length]??F.foreground;if(V.push(new O("● ",new h({color:N}))),V.push(new O(`${z.name}: `,G)),q.link)V.push(K(q.link,Y(q.value)));else V.push(new O(Y(q.value),D));if(H<$.length-1||E)V.push(new O(`
5955
- `))}if(E)V.push(new O(" ",G)),V.push(new O("Total: ",G)),V.push(new O(Y(W),D))}return new u0({decoration:{color:F.background,border:Q4.all(new e1(F.border,1,"rounded"))},child:new t({text:new O(void 0,void 0,V)})})}l0();c8();cL();v9();C8();W7();xo();WF();EQ();WQ();aB();DR();t4();Cy();Hk();O1();l0();EQ();class C$1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(A,Q){this.enabled=A;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let A=Array.from(this.commandCounts.entries()).map(([Q,B])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1777279521-gff806d"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await T70(Q,this.configService)}catch(Q){T.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class Iw extends y0{props;constructor(A){super();this.props=A}createState(){return new E$A}}class E$A extends v0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(A){let Q=(B)=>{this.setState(()=>{this._state=B(this._state)})};return this.widget.props.builder(A,Q,this._state)}}aB();class W$A extends v0{controller=new I2;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new E6({debugLabel:"CommandMultilinePrompt",onKey:(A)=>{if(A.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(A)=>{if(this.imageAttachments.length>=SY)return!1;let Q=await RX(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(A){let Q=S0.of(A),{colors:B,app:$}=Q,Y=F4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),F=new mG({controller:this.controller,triggers:[new nJ],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(K)=>{this.widget.props.onSubmit(K.trim(),this.imageAttachments)},theme:B,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:i4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),X=new e4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:F}),D=new u0({constraints:new W1({maxHeight:Z}),padding:M0.symmetric(1,0),child:X}),G=new u0({padding:M0.symmetric(1,0),child:new t({text:new O("",void 0,[new O("Command: ",new h({color:B.foreground})),new O(this.widget.props.commandName,new h({color:$.command,bold:!0}))])})}),V=new u0({padding:M0.symmetric(1,0),child:new t({text:this.isConfirmingClearInput?new O("",void 0,[new O("Esc",new h({color:$.keybind})),new O(" again to clear input",new h({color:B.foreground,dim:!0}))]):new O("",void 0,[new O("Press ",new h({color:B.foreground,dim:!0})),new O("Enter",new h({color:$.keybind})),new O(" to submit, ",new h({color:B.foreground,dim:!0})),new O("Esc",new h({color:$.keybind})),new O(" to clear",new h({color:B.foreground,dim:!0}))])})}),U=[G,new j0({height:1}),new y1({child:D}),new j0({height:1}),V];return new u0({decoration:{border:Q4.all(new e1(B.foreground,1,"solid")),color:B.background},padding:M0.all(1),child:new m0({children:U})})}}class w$1 extends y0{props;constructor(A){super();this.props=A}createState(){return new W$A}}function H$A(A){let B=new Date().getTime()-A.getTime(),$=Math.floor(B/60000),J=Math.floor(B/3600000),Y=Math.floor(B/86400000);if($<1)return"just now";if($<60)return`${$}m ago`;if(J<24)return`${J}h ago`;if(Y<7)return`${Y}d ago`;return A.toLocaleDateString()}class M$1 extends T1{props;debugLabel="NewsFeedPicker";constructor(A){super();this.props=A}build(A){let Q=[...this.props.entries].sort((J,Y)=>Y.pubDate.getTime()-J.pubDate.getTime()),B=Math.max(0,...Q.map((J)=>H$A(J.pubDate).length));return new k5({items:Q,getLabel:(J)=>J.title,onAccept:(J)=>this.props.onSelect?.(J),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(J,Y,Z,F)=>{let X=S0.of(F),{colors:D}=X,G=X.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(W,H)=>new j0({width:H,child:F1.end([new t({text:new O(W,new h({color:K}))})])});return new u0({decoration:V?{color:V}:void 0,padding:M0.symmetric(2,0),child:new F1({children:[new y1({child:new t({text:new O(J.title,new h({color:U})),overflow:"ellipsis",maxLines:1})}),new j0({width:2}),E(H$A(J.pubDate),B)]})})}})}}class SB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!SB._instance)SB._instance=new SB;return SB._instance}get allExpanded(){return this._allExpanded}setAllExpanded(A){if(this._allExpanded===A)return;this._allExpanded=A,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(A){return this._listeners.add(A),()=>this.removeListener(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A()}}c8();class z$A extends y0{props;constructor(A){super();this.props=A}createState(){return new q$A}}class q$A extends v0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=A.startsWith("file://")?A.slice(7):A,B=this.widget.props.cwd;if(Q.startsWith(B))return Q.slice(B.length+1);return Q}statusIcon(A){let Q=s3.default(),{colors:B,app:$}=Q;switch(A){case"loading":return{icon:"◌",color:B.warning};case"active":return{icon:"✓",color:$.toolSuccess};case"error":return{icon:"✗",color:$.toolError}}}build(A){let Q=S0.of(A),{app:B}=Q;if(this.plugins.length===0)return new t({text:new O("No plugins found.",new h({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((X)=>X.status==="active").length,Z=this.plugins.reduce((X,D)=>X+D.registeredCommands.length,0),F=this.plugins.reduce((X,D)=>X+D.registeredTools.length,0);if($.push(new O(`${Y}/${J} ${w4(J,"plugin")} active`,new h({bold:!0}))),Z>0||F>0)$.push(new O(` (${Z} ${w4(Z,"command")}, ${F} ${w4(F,"tool")})`,new h({dim:!0})));$.push(new O(`
5955
+ `))}if(E)V.push(new O(" ",G)),V.push(new O("Total: ",G)),V.push(new O(Y(W),D))}return new u0({decoration:{color:F.background,border:Q4.all(new e1(F.border,1,"rounded"))},child:new t({text:new O(void 0,void 0,V)})})}l0();c8();cL();v9();C8();W7();xo();WF();EQ();WQ();aB();DR();t4();Cy();Hk();O1();l0();EQ();class C$1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(A,Q){this.enabled=A;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let A=Array.from(this.commandCounts.entries()).map(([Q,B])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1777279908-g9ebba6"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await T70(Q,this.configService)}catch(Q){T.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class Iw extends y0{props;constructor(A){super();this.props=A}createState(){return new E$A}}class E$A extends v0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(A){let Q=(B)=>{this.setState(()=>{this._state=B(this._state)})};return this.widget.props.builder(A,Q,this._state)}}aB();class W$A extends v0{controller=new I2;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new E6({debugLabel:"CommandMultilinePrompt",onKey:(A)=>{if(A.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(A)=>{if(this.imageAttachments.length>=SY)return!1;let Q=await RX(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(A){let Q=S0.of(A),{colors:B,app:$}=Q,Y=F4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),F=new mG({controller:this.controller,triggers:[new nJ],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(K)=>{this.widget.props.onSubmit(K.trim(),this.imageAttachments)},theme:B,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:i4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),X=new e4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:F}),D=new u0({constraints:new W1({maxHeight:Z}),padding:M0.symmetric(1,0),child:X}),G=new u0({padding:M0.symmetric(1,0),child:new t({text:new O("",void 0,[new O("Command: ",new h({color:B.foreground})),new O(this.widget.props.commandName,new h({color:$.command,bold:!0}))])})}),V=new u0({padding:M0.symmetric(1,0),child:new t({text:this.isConfirmingClearInput?new O("",void 0,[new O("Esc",new h({color:$.keybind})),new O(" again to clear input",new h({color:B.foreground,dim:!0}))]):new O("",void 0,[new O("Press ",new h({color:B.foreground,dim:!0})),new O("Enter",new h({color:$.keybind})),new O(" to submit, ",new h({color:B.foreground,dim:!0})),new O("Esc",new h({color:$.keybind})),new O(" to clear",new h({color:B.foreground,dim:!0}))])})}),U=[G,new j0({height:1}),new y1({child:D}),new j0({height:1}),V];return new u0({decoration:{border:Q4.all(new e1(B.foreground,1,"solid")),color:B.background},padding:M0.all(1),child:new m0({children:U})})}}class w$1 extends y0{props;constructor(A){super();this.props=A}createState(){return new W$A}}function H$A(A){let B=new Date().getTime()-A.getTime(),$=Math.floor(B/60000),J=Math.floor(B/3600000),Y=Math.floor(B/86400000);if($<1)return"just now";if($<60)return`${$}m ago`;if(J<24)return`${J}h ago`;if(Y<7)return`${Y}d ago`;return A.toLocaleDateString()}class M$1 extends T1{props;debugLabel="NewsFeedPicker";constructor(A){super();this.props=A}build(A){let Q=[...this.props.entries].sort((J,Y)=>Y.pubDate.getTime()-J.pubDate.getTime()),B=Math.max(0,...Q.map((J)=>H$A(J.pubDate).length));return new k5({items:Q,getLabel:(J)=>J.title,onAccept:(J)=>this.props.onSelect?.(J),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(J,Y,Z,F)=>{let X=S0.of(F),{colors:D}=X,G=X.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(W,H)=>new j0({width:H,child:F1.end([new t({text:new O(W,new h({color:K}))})])});return new u0({decoration:V?{color:V}:void 0,padding:M0.symmetric(2,0),child:new F1({children:[new y1({child:new t({text:new O(J.title,new h({color:U})),overflow:"ellipsis",maxLines:1})}),new j0({width:2}),E(H$A(J.pubDate),B)]})})}})}}class SB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!SB._instance)SB._instance=new SB;return SB._instance}get allExpanded(){return this._allExpanded}setAllExpanded(A){if(this._allExpanded===A)return;this._allExpanded=A,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(A){return this._listeners.add(A),()=>this.removeListener(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A()}}c8();class z$A extends y0{props;constructor(A){super();this.props=A}createState(){return new q$A}}class q$A extends v0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=A.startsWith("file://")?A.slice(7):A,B=this.widget.props.cwd;if(Q.startsWith(B))return Q.slice(B.length+1);return Q}statusIcon(A){let Q=s3.default(),{colors:B,app:$}=Q;switch(A){case"loading":return{icon:"◌",color:B.warning};case"active":return{icon:"✓",color:$.toolSuccess};case"error":return{icon:"✗",color:$.toolError}}}build(A){let Q=S0.of(A),{app:B}=Q;if(this.plugins.length===0)return new t({text:new O("No plugins found.",new h({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((X)=>X.status==="active").length,Z=this.plugins.reduce((X,D)=>X+D.registeredCommands.length,0),F=this.plugins.reduce((X,D)=>X+D.registeredTools.length,0);if($.push(new O(`${Y}/${J} ${w4(J,"plugin")} active`,new h({bold:!0}))),Z>0||F>0)$.push(new O(` (${Z} ${w4(Z,"command")}, ${F} ${w4(F,"tool")})`,new h({dim:!0})));$.push(new O(`
5956
5956
 
5957
5957
  `));for(let X of this.plugins){let{icon:D,color:G}=this.statusIcon(X.status),V=this.getRelativePath(X.uri.toString());if($.push(new O(`${D} `,new h({color:G}))),$.push(new O(V,new h({bold:!0}))),$.push(new O(` ${X.status}`,new h({dim:!0}))),$.push(new O(`
5958
5958
  `)),X.status==="active"&&X.registeredEvents.length>0)$.push(new O(" Events: ",new h({dim:!0}))),$.push(new O(X.registeredEvents.join(", "),new h({color:B.link}))),$.push(new O(`
@@ -6134,7 +6134,7 @@ ${o.content||""}`:o.content||"",P0=[],b0=o.baseDir.startsWith("file://")?oz0(o.b
6134
6134
  `)}function HZA(A,Q){A.command("usage").description("Show your current Amp usage and credit balance").action(async(B,$)=>{let J=$.optsWithGlobals(),Y=await Q(J),Z=await Y.settings.get("proxy"),F=U54({settings:{url:Y.ampURL,proxy:Z},secrets:{getToken:(D,G)=>Y.secrets.get(D,G)}}),X=await lA.userDisplayBalanceInfo({},{config:F});if(!X.ok){if(X.error.code==="auth-required")process.stderr.write(n0.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(n0.red("Error: ")+X.error.message+`
6135
6135
  `),process.exit(1)}process.stdout.write(await dU8(X.result.displayText)+`
6136
6136
  `),process.exit(0)})}var Gz8=V40.join(EF,"logs","headless.log"),SZ1=V40.join(rb,"device-id.json"),Vz8=`cli-tui-${cDA(16).toString("hex")}`;async function Uz8(){for(let A of nL)try{if((await A.listConfigs()).length>0)return A}catch(Q){T.debug("Failed to detect query-based IDE integration",{ideName:A.ideName,error:Q})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => H4(ah(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){P$.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
6137
- `)}function Kz8(A){process.emitWarning=(Q,B,$,J)=>{let Y=typeof Q==="string"?Q:Q.message||String(Q),Z=B||"Warning",F=!1;A.warn(Y,{name:Z,code:$})}}function Y7(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")S9("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")S9("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)S9("internal.model",Ez8(Q.model))}function bDA(A){let Q=A.indexOf(":");if(Q===-1)throw new K4(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let B=A.slice(0,Q).trim(),$=A.slice(Q+1).trim();if(!B||!$)throw new K4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function Ez8(A){if(!A.includes("="))return bDA(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new K4(`Invalid mode-specific model entry "${$}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let Y=$.slice(0,J).trim(),Z=$.slice(J+1).trim();if(!Y)throw new K4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new K4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);bDA(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new K4("No valid model overrides found in --model flag value.",1);return Q}function Wz8(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 Hz8(A){try{return await lDA(A,"utf-8")}catch{return A}}async function uDA(A,Q,B){let $=Wz8(A,Q);if(!$)return;let J=gA(B)?B.features:[],Y=gA(B)?B.user.email:void 0;if(!oh(J,Y9.HARNESS_SYSTEM_PROMPT)&&!(Y&&K7(Y)))throw new K4("You are not allowed to do this.",1);S9("systemPrompt",await Hz8($))}function oh(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function zz8(A){return A!=="pending"}function sh(A){if(!gA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function qz8(A){let Q=sh(A);if(Q)return Q.id;if(GW(A))throw Error(A.error.message);throw Error("unreachable")}function Nz8(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 Iz8(A){let $=Nz8(A)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new K4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function vZ1(A,Q){let B=W51(Error(A.error.message));if(B.message===h7.networkOffline||B.message===h7.networkTimeout)return Iz8(Q);if(B.message!==h7.internalBug)return new K4(B.message,1,B.suggestion);return new K4(A.error.message.replace(/^Error: /,""),1)}var hDA=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH; enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??qX,description:`Custom settings file path (overrides the default location ${qX})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(T).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Pt})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:M9(),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:pL.SMART.key,description:`Set the agent mode (${s$({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(s$().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neo",long:"neo",type:"switch",description:"Use the Neo TUI",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],gDA=(A)=>("deprecated"in A)&&A.deprecated===!0,Cz8=(A)=>("hidden"in A)&&A.hidden===!0,wz8=(A)=>("default"in A),Mz8=(A)=>("default"in A)?A.default:void 0,iDA=[{name:"toggle-skills-count",entryPoint:ZB1}];function Lz8(A,Q){let B=Q.args[0],$=Q.commands.map((Y)=>Y.name());if(B&&!B.includes(" ")&&B.length<30&&!/[./\\]/.test(B)){let Y=$.filter((F)=>B.includes(F)||F.includes(B)),Z="Run amp --help for a list of available commands.";if(Y.length>0)Z=`Did you mean: ${Y.join(", ")}? Or run amp --help for all commands.`;throw new K4(h7.unknownCommand(B),1,Z)}}async function gq0(A){return{...A,getThreadEnvironment:EH,osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new gO(A.fileSystem),generateThreadTitle:OK4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>ZJ(A.configService),pluginService:A.pluginService}}function nDA(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:EH,filesystem:A.fileSystem,threadService:A.threadService}}var aDA="code-tour";function kZ1(A){return A.filter((Q)=>Q.name!==aDA)}function Oz8(A){return{...A,skills:A.skills.pipe(w1(kZ1)),getSkills:async()=>kZ1(await A.getSkills()),getSkill:async(Q)=>Q===aDA?void 0:A.getSkill(Q),getSkillsList:async()=>{let Q=kZ1(await A.getSkills());return zy(Q)}}}var uq0=Z1.file(Dz8.homedir()),yZ1=process.env.XDG_CONFIG_HOME?Z1.file(process.env.XDG_CONFIG_HOME):G1.joinPath(uq0,".config");function jz8(A){return iy4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(uU0())hU0();else if(process.platform==="darwin"&&Q==="idle"&&A.isTUIVoiceNotifEnabled())ly4();else cr(Q);let B=PP(),$=ve();if((!B||$||FK0())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(SG("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(SG("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(PP()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function A9(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;o54("0.0.1777279521-gff806d");let Y=bk({storage:A.settings,secretStorage:A.secrets,workspaceRoot:g0.of(Z1.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:uq0,userConfigDir:yZ1});Z7A(Y);let Z=await Y.getLatest();T.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let F=!1;{let m=await A.secrets.get("apiKey",A.ampURL);if(F=Boolean(m),T.info("API key lookup before login",{found:Boolean(m),ampURL:A.ampURL,deferAuth:$}),!m)if($)T.info("No API key found, continuing startup with deferred auth");else{E5.write(`No API key found. Starting login flow...
6137
+ `)}function Kz8(A){process.emitWarning=(Q,B,$,J)=>{let Y=typeof Q==="string"?Q:Q.message||String(Q),Z=B||"Warning",F=!1;A.warn(Y,{name:Z,code:$})}}function Y7(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")S9("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")S9("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)S9("internal.model",Ez8(Q.model))}function bDA(A){let Q=A.indexOf(":");if(Q===-1)throw new K4(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let B=A.slice(0,Q).trim(),$=A.slice(Q+1).trim();if(!B||!$)throw new K4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function Ez8(A){if(!A.includes("="))return bDA(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new K4(`Invalid mode-specific model entry "${$}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let Y=$.slice(0,J).trim(),Z=$.slice(J+1).trim();if(!Y)throw new K4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new K4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);bDA(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new K4("No valid model overrides found in --model flag value.",1);return Q}function Wz8(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 Hz8(A){try{return await lDA(A,"utf-8")}catch{return A}}async function uDA(A,Q,B){let $=Wz8(A,Q);if(!$)return;let J=gA(B)?B.features:[],Y=gA(B)?B.user.email:void 0;if(!oh(J,Y9.HARNESS_SYSTEM_PROMPT)&&!(Y&&K7(Y)))throw new K4("You are not allowed to do this.",1);S9("systemPrompt",await Hz8($))}function oh(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function zz8(A){return A!=="pending"}function sh(A){if(!gA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function qz8(A){let Q=sh(A);if(Q)return Q.id;if(GW(A))throw Error(A.error.message);throw Error("unreachable")}function Nz8(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 Iz8(A){let $=Nz8(A)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new K4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function vZ1(A,Q){let B=W51(Error(A.error.message));if(B.message===h7.networkOffline||B.message===h7.networkTimeout)return Iz8(Q);if(B.message!==h7.internalBug)return new K4(B.message,1,B.suggestion);return new K4(A.error.message.replace(/^Error: /,""),1)}var hDA=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH; enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??qX,description:`Custom settings file path (overrides the default location ${qX})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(T).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Pt})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:M9(),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:pL.SMART.key,description:`Set the agent mode (${s$({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(s$().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neo",long:"neo",type:"switch",description:"Use the Neo TUI",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],gDA=(A)=>("deprecated"in A)&&A.deprecated===!0,Cz8=(A)=>("hidden"in A)&&A.hidden===!0,wz8=(A)=>("default"in A),Mz8=(A)=>("default"in A)?A.default:void 0,iDA=[{name:"toggle-skills-count",entryPoint:ZB1}];function Lz8(A,Q){let B=Q.args[0],$=Q.commands.map((Y)=>Y.name());if(B&&!B.includes(" ")&&B.length<30&&!/[./\\]/.test(B)){let Y=$.filter((F)=>B.includes(F)||F.includes(B)),Z="Run amp --help for a list of available commands.";if(Y.length>0)Z=`Did you mean: ${Y.join(", ")}? Or run amp --help for all commands.`;throw new K4(h7.unknownCommand(B),1,Z)}}async function gq0(A){return{...A,getThreadEnvironment:EH,osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new gO(A.fileSystem),generateThreadTitle:OK4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>ZJ(A.configService),pluginService:A.pluginService}}function nDA(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:EH,filesystem:A.fileSystem,threadService:A.threadService}}var aDA="code-tour";function kZ1(A){return A.filter((Q)=>Q.name!==aDA)}function Oz8(A){return{...A,skills:A.skills.pipe(w1(kZ1)),getSkills:async()=>kZ1(await A.getSkills()),getSkill:async(Q)=>Q===aDA?void 0:A.getSkill(Q),getSkillsList:async()=>{let Q=kZ1(await A.getSkills());return zy(Q)}}}var uq0=Z1.file(Dz8.homedir()),yZ1=process.env.XDG_CONFIG_HOME?Z1.file(process.env.XDG_CONFIG_HOME):G1.joinPath(uq0,".config");function jz8(A){return iy4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(uU0())hU0();else if(process.platform==="darwin"&&Q==="idle"&&A.isTUIVoiceNotifEnabled())ly4();else cr(Q);let B=PP(),$=ve();if((!B||$||FK0())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(SG("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(SG("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(PP()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function A9(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;o54("0.0.1777279908-g9ebba6");let Y=bk({storage:A.settings,secretStorage:A.secrets,workspaceRoot:g0.of(Z1.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:uq0,userConfigDir:yZ1});Z7A(Y);let Z=await Y.getLatest();T.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let F=!1;{let m=await A.secrets.get("apiKey",A.ampURL);if(F=Boolean(m),T.info("API key lookup before login",{found:Boolean(m),ampURL:A.ampURL,deferAuth:$}),!m)if($)T.info("No API key found, continuing startup with deferred auth");else{E5.write(`No API key found. Starting login flow...
6138
6138
  `);let p=await Rz8(A),u=await A.secrets.get("apiKey",A.ampURL);if(T.info("Login flow completed",{success:p,storedKeyPresent:Boolean(u),ampURL:A.ampURL}),!p)await MK(),process.exit(1);F=!0}}{let m=await Y.getLatest(),p=m.settings.url,u=m.secrets.isSet?.[p];T.info("Config secrets state after login",{configURL:p,apiKeySet:u?.apiKey??!1})}let X=k1(ZJ(Y).pipe(N5(zz8))),D=$?"pending":await X;if(!$)T.info("Server status resolved",{status:"ready",isAuthenticated:gA(D),isError:GW(D),errorMessage:GW(D)?D.error.message:void 0});let G=X.then((m)=>qz8(m));G.catch(()=>{return});let{toolService:V,dispose:U}=ND0({configService:Y}),K=new Map,E=()=>K.clear(),W=new wm0(Y,A.settings.getWorkspaceRootPath()),H=s$0({configService:Y,filesystem:k8}),z=xF4({configService:Y,trustStore:W,skillMCPServers:H.skillMCPServers,createOAuthProvider:async(m,p,u)=>{let a=`${m}:${p}`,d=K.get(a);if(d)return T.debug("Reusing existing OAuth provider for server",{serverName:m,serverUrl:p}),d;T.debug("Creating OAuth provider for server",{serverName:m,serverUrl:p});let s=(async()=>{let W0=new eL(A.secrets),n=await W0.getClientInfo(m,p),A0=u?.scopes??n?.scopes,D0=Tr4();T.info("OAuth headless mode check",{useHeadless:D0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:E5.isTTY});let z0;if(D0)z0=A.executeMode?_r4():Pr4(m);let B0=new Jb0({storage:W0,serverName:m,serverUrl:p,clientId:u?.clientId??n?.clientId,clientSecret:u?.clientSecret??n?.clientSecret,authUrl:u?.authUrl??n?.authUrl,tokenUrl:u?.tokenUrl??n?.tokenUrl,scopes:A0,headlessAuthHandler:z0});return T.debug("OAuth provider created",{serverName:m,serverUrl:p,hasManualClientId:!!(u?.clientId??n?.clientId),willUseDCR:!(u?.clientId??n?.clientId),scopes:A0,headlessMode:D0,executeMode:A.executeMode}),B0})();return K.set(a,s),s}}),q=Ct0({configService:Y,filesystem:k8,spawn:pX0}),N;if(J)N=new Map;else if(A.executeMode){let m=await Xk4({toolService:V,providers:[z,q],initialTimeout:15000});N=m.registrations;for(let[p,u]of m.initErrors)T.warn(`${p} provider initialization slow or failed:`,u)}else N=wt0({toolService:V,providers:[z,q]});if(Q.jetbrains)lL("JetBrains");else if(Q.ide&&Ks4())lL("VS Code");else if(Q.ide&&Es4())lL("Neovim");else if(Q.ide){let m=await Uz8();if(m){let p=i90(m.ideName);if(p)lL(p)}}if(A.executeMode)r54(!0);let I,C=i8.status.pipe(w1((m)=>Boolean(m.connected&&m.authenticated&&m.ideName&&O84(m.ideName))),m4()).subscribe((m)=>{if(m){if(!I)I=V.registerTool(Fk4)}else I?.dispose(),I=void 0}),w;if(!A.executeMode){let m=await A.settings.get("fuzzy.alwaysIncludePaths")??[];w=new ab(process.cwd(),{alwaysIncludePaths:m},!0)}else w=new class extends ab{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let M=new jd0(cO(Y),{maxThreads:200});T.info("Starting Amp background services");let j=new UB1,P=process.env.PLUGINS??"off",R=Q.headless?c9A():void 0,b=R??new nW0({configService:Y}),g=b instanceof nW0?b:void 0;if(g)g.pluginExecutorKind="local";let f=hm0({configService:Y,fileSystem:k8,platform:b,internalPlugins:iDA,pluginFilter:P}),k=_X4({pluginService:f,toolService:V}),x={configService:Y,toolService:V,mcpService:z,skillService:H,toolboxService:q,trustStore:W,threadService:M,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:w,fileSystem:k8,terminal:j,pluginService:f,pluginPlatform:g,headlessPluginPlatform:R,serverStatus:D,serverStatusPromise:X,viewerUserIDPromise:G,hasAPIKeyAtStartup:F};return{...x,async asyncDispose(){if(x.mcpService.hasAuthenticatingClients())T.info("Waiting for OAuth authentication to complete before exit..."),await x.mcpService.waitForAuthentication();for(let m of N.values())m.dispose();await x.mcpService.dispose(),E(),await x.threadService.asyncDispose(),x.configService.unsubscribe(),U(),x.fuzzyServer.dispose(),x.settingsStorage[Symbol.dispose](),C.unsubscribe(),I?.dispose(),k.dispose(),await x.pluginService.dispose()}}}async function Rz8(A){if(!A.executeMode){if(!await RK0("Would you like to log in to Amp? [(y)es, (n)o]: "))return E5.write(`Login cancelled. Run the command again to retry.
6139
6139
  `),!1}return await oDA(A)}async function oDA(A){let Q=cDA(32).toString("hex"),B=await Ju(A.ampURL,Q),$=new AbortController;try{await UD(B,$.signal)}catch(Y){T.error("Error opening browser",{error:Y})}let J=await Ju(A.ampURL,Q,!1);E5.write(`If your browser does not open automatically, visit:
6140
6140
 
@@ -6142,7 +6142,7 @@ ${n0.blue.bold(J)}
6142
6142
 
6143
6143
  `);try{return await Re4(A.ampURL,Q,A.secrets,$),E5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(Y){return T.error("Login failed",{error:Y}),P$.write(`
6144
6144
  Login failed: ${Y instanceof Error?Y.message:String(Y)}
6145
- `),!1}}function Pz8(A){let Q=new fI().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((E)=>{if(E.code==="commander.help"||E.code==="commander.version"||E.exitCode===0)YP(),process.exit(0);let W=E.originalError??E;Ya4(W)}),l0A(Q,{version:"0.0.1777279521-gff806d",buildTimestamp:"2026-04-27T08:50:02.827Z",buildType:"'release'"}),Q.addHelpText("after",Gs4()),Q.configureHelp({formatHelp:Vs4}),Q.command("logout").description("Log out by removing stored API key").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await xz8(z)}),Q.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await yz8(z,await nt(H,z.settings))}),Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(E,W,H)=>{let z=H.optsWithGlobals(),q=await K8(z);await Ir4(E??"get",q.ampURL,q.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await Cr4(z.ampURL,z.secrets),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(E)=>{await _t4({raw:E.raw===!0}),process.exit(process.exitCode??0)}),Q.command("live-sync [threadIDOrURL]",{hidden:!0}).summary("Mirror live DTW thread changes into the current checkout").description("Experimental: watch a v2 thread URL or ID and mirror its live working-tree changes into your local checkout, or apply the current snapshot once and exit.").addHelpText("after",["","Examples:"," amp live-sync T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync --apply T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync https://ampcode.com/threads/T-5928a90d-d53b-488f-a829-4e36442142ee"].join(`
6145
+ `),!1}}function Pz8(A){let Q=new fI().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((E)=>{if(E.code==="commander.help"||E.code==="commander.version"||E.exitCode===0)YP(),process.exit(0);let W=E.originalError??E;Ya4(W)}),l0A(Q,{version:"0.0.1777279908-g9ebba6",buildTimestamp:"2026-04-27T08:55:43.407Z",buildType:"'release'"}),Q.addHelpText("after",Gs4()),Q.configureHelp({formatHelp:Vs4}),Q.command("logout").description("Log out by removing stored API key").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await xz8(z)}),Q.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await yz8(z,await nt(H,z.settings))}),Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(E,W,H)=>{let z=H.optsWithGlobals(),q=await K8(z);await Ir4(E??"get",q.ampURL,q.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await Cr4(z.ampURL,z.secrets),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(E)=>{await _t4({raw:E.raw===!0}),process.exit(process.exitCode??0)}),Q.command("live-sync [threadIDOrURL]",{hidden:!0}).summary("Mirror live DTW thread changes into the current checkout").description("Experimental: watch a v2 thread URL or ID and mirror its live working-tree changes into your local checkout, or apply the current snapshot once and exit.").addHelpText("after",["","Examples:"," amp live-sync T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync --apply T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync https://ampcode.com/threads/T-5928a90d-d53b-488f-a829-4e36442142ee"].join(`
6146
6146
  `)).option("--apply <threadIDOrURL>","Apply the current DTW thread snapshot once and exit").option("--checkout","Automatically check out the thread commit when it differs").option("--skip-checkout","Skip the startup checkout prompt when commits differ").action(async(E,W,H)=>{if(E&&W.apply)throw new K4("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let z=W.apply??E;if(!z||z.trim().length===0)E5.write(`live-sync watches a v2 thread and mirrors its live changes locally. Use --apply <thread-id> to materialize the current snapshot once and exit.
6147
6147
 
6148
6148
  `),H.outputHelp(),process.exit(0);let q=C3(z)??EB(z),N=H.optsWithGlobals(),I=await K8(N);Y7(H,N);let C=await A9(I,N),w=!1;try{if(W.checkout&&W.skipCheckout)throw new K4("Choose either --checkout or --skip-checkout, not both.",1);if(GW(C.serverStatus))throw vZ1(C.serverStatus,I.ampURL);let M=gA(C.serverStatus)?C.serverStatus.features:void 0;if(!oh(M,Y9.V2))throw new K4("live-sync is not enabled for your user",1);await He4({ampURL:I.ampURL,threadId:q,configService:C.configService,threadService:C.threadService,apiKey:process.env.AMP_API_KEY,applyOnce:typeof W.apply==="string",checkoutMode:W.checkout?"always":W.skipCheckout?"never":"prompt",promptForYesNo:RK0}),w=!0}finally{if(await C.asyncDispose(),w)process.exit(0)}});let B=async(E,W,H)=>{bk({storage:W.settings,secretStorage:W.secrets,workspaceRoot:g0.of(Z1.file(process.cwd())),defaultAmpURL:W.ampURL,homeDir:uq0,userConfigDir:yZ1});let z={...W,executeMode:!1};await hq0(z,{...E,openThreadSwitcher:!0},H,A)},$=Q.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").option("--include-archived","Include archived threads in the list").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await dDA(H,z,W)});$.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await iz8(H,z,W)}),$.command("continue [threadIDOrURL]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, interactive mode shows a picker. Use --last to continue the last thread for the current mode directly.").option("--last","Continue the last thread for the current mode directly").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(E,W,H)=>{let z=H.optsWithGlobals(),q=await K8(z);if(W.pick)P$.write(`${n0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
@@ -6176,8 +6176,8 @@ ${I}
6176
6176
 
6177
6177
  This thread belongs to a different user and cannot be continued for security reasons. Set AMP_RESUME_OTHER_USER_THREADS_INSECURE=1 to bypass this check.`)}}async function _z8(A){if(A.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof A.execute==="string"){let Q=(await rW0()).trimEnd();return{userInput:A.execute,stdinInput:Q||null}}return{userInput:(await rW0()).trimEnd(),stdinInput:null}}function Tz8(A,Q,B){if(A.streamJson&&!Q)throw new K4("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new K4("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new K4("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new K4("The --stats and --stream-json flags are mutually exclusive output formats",1,'Use one or the other: amp --execute "your message" --stats OR amp --execute "your message" --stream-json');if(A.stats&&!Q)throw new K4("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archive&&!Q)throw new K4("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(A.streamJsonInput&&typeof A.execute==="string"&&A.execute.trim()!=="")throw new K4("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Q&&B===""&&!A.streamJsonInput&&!A.headless)throw new K4("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
6178
6178
  Or pipe via stdin: echo "your message" | amp --execute`)}async function hq0(A,Q,B,$){let J=process.hrtime.bigint(),Y=(i,o)=>{let e=Number(process.hrtime.bigint()-o)/1e6,Y0=md4();T.info("Startup phase",{phase:i,phaseMs:Math.round(e),sinceMainMs:Y0===null?void 0:Math.round(Y0)})},{userInput:Z,stdinInput:F}=await _z8(Q),X=!!Q.streamJson||!!Q.streamJsonThinking;Tz8({...Q,streamJson:X},A.executeMode,Z),Y7(B,Q);let D=process.hrtime.bigint(),G=Boolean(await A.secrets.get("apiKey",A.ampURL)),V=!A.executeMode&&!Q.headless&&G;T.info("Interactive auth startup mode",{deferInteractiveAuth:V,hasAPIKeyAtStartup:G,executeMode:A.executeMode,headless:Boolean(Q.headless)});let U=await A9(A,Q,{deferAuth:V});Y("runMainThread:createThreadDependencies",D);let{serverStatus:K}=U;if(!V&&GW(K))throw vZ1(K,A.ampURL);let E=gA(K)?K:null,W=E?.user.email,H=!!(W&&K7(W));if(!V)await uDA(B,Q,K);let z=sh(K),q=z?.features??[],N=z?.team??null,I=RW0(Q,z);if(I instanceof Error)o5(I.message);if(E&&!Hc(Q.mode,W))throw new K4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(Q.headless){if(process.env.AMP_EXECUTOR!=="1"&&(!W||!K7(W)))throw new K4("Headless executor mode is only available for Amp employees",1);let o=await U.secretStorage.get("apiKey",A.ampURL);if(!o)throw new K4("API key required for headless mode. Please run `amp login` first.",1);let e=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(e&&!e$(e))throw new K4(`Invalid thread ID: ${e}`,1);let Y0=e?void 0:await cz8({dependencies:U,apiKey:o,visibility:I??void 0}),$0=e??Y0?.threadId;if(!$0)throw new K4("Failed to resolve headless thread ID",1);let K0=await yr4($0);if(K0.status==="already-running")await U.asyncDispose(),await MK(),process.exit(0);try{await Or4({ampURL:A.ampURL,apiKey:o,workspaceRoot:process.cwd(),threadId:$0,ownerUserId:Y0?.ownerUserId,threadVersion:Y0?.threadVersion,agentMode:Y0?.agentMode,initialToolDiscovery:Promise.all([U.mcpService.initialized,U.toolboxService.initialized]).then(()=>{return}),configService:U.configService,mcpService:U.mcpService,toolService:U.toolService,skillService:U.skillService,fileSystem:U.fileSystem,pluginService:U.pluginService,pluginPlatform:U.headlessPluginPlatform})}finally{await K0.release(),await U.asyncDispose()}await MK(),process.exit(0)}let C=Q.threadId&&e$(Q.threadId)?Q.threadId:void 0,w=Q.observe?C3(Q.observe)??EB(Q.observe):void 0,M=V?await U.serverStatusPromise:K,j=gA(M)&&oh(M.features,Y9.NEO_TUI);if((j||Q.neo||!!w||!1)&&!A.executeMode&&!Q.takeMeBack){if((Q.neo||w)&&!j&&(!gA(M)||!K7(M.user.email)))throw new K4(Q.observe?"--observe is only available for Amp employees":"--neo is only available for Amp employees",1);let i=await U.secretStorage.get("apiKey",A.ampURL);if(!i)throw new K4("API key required. Please run `amp login` first.",1);let o=cO(U.configService),e=new U_(U.fuzzyServer),Y0=process.cwd();await YB1({ampURL:A.ampURL,apiKey:i,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??fJ(A.ampURL),configService:U.configService,toolService:U.toolService,skillService:U.skillService,mcpService:U.mcpService,readFileSystemDirectory:({uri:$0})=>qC({fileSystem:U.fileSystem,workspaceRoot:Y0},$0),completionBuilder:e,workspaceRoot:Y0,listThreads:()=>o.listThreads(),getThreadFromServer:($0)=>o.getThread($0),isInternalUser:gA(M)&&K7(M.user.email),settingsFilePath:U.settingsStorage.getSettingsFilePath()},{initialThreadID:w??C,initialUserInput:Z||void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!w,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0});return}let R=gA(M)&&oh(M.features,Y9.THREAD_ACTORS_TUI);if(A.executeMode&&!Q.takeMeBack&&R){let i=await U.secretStorage.get("apiKey",A.ampURL);if(!i)throw new K4("API key required. Please run `amp login` first.",1);U31(U.mcpService,A.settings);try{let o=await do4({apiKey:i,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:U,userInput:Z,stdinInput:F,stats:!!Q.stats,streamJson:X,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,labels:Q.label,initialThreadID:C});if(await rh(o,"execute"),Q.archive)await U.threadService.archive(o,!0)}finally{await U.asyncDispose()}await MK(),process.exit(0)}if(!A.executeMode&&!Q.headless)U.skillService=Oz8(U.skillService);D=process.hrtime.bigint();let g=await gq0(U);Y("runMainThread:createWorkerDeps",D);let f=A.executeMode?void 0:async(i)=>rh(i,"interactive"),k={threadService:U.threadService,workerDeps:g,createThread:async(i)=>{let o=V?await U.serverStatusPromise:K,e=await XU0(A.settings,process.cwd(),sh(o),I);if(e instanceof Error)o5(e.message);return JY1(g,{threadMeta:e?gG(e):void 0,agentMode:i??Q.mode,onFirstAssistantMessage:f})},validateThreadOwnership:async(i,o)=>{if(o?.nonBlockingOwnershipCheck){mDA(i,U.configService,U.viewerUserIDPromise).catch((e)=>{if(e instanceof K4){if(o.onOwnershipError){o.onOwnershipError(e,i);return}TH(e,i);return}T.warn("Failed to validate thread ownership in CLI, allowing to open",{error:e})});return}try{await mDA(i,U.configService,U.viewerUserIDPromise)}catch(e){if(e instanceof K4)throw e;T.warn("Failed to validate thread ownership in CLI, allowing to open",{error:e})}},switchThreadVisibility:I,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:f,handleError:TH},x=async()=>{try{return UZA(k,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(i){if(i instanceof K4)throw i;throw await TH(i,Q.threadId),Error("handleError should have called process.exit()")}};if(Q.format==="jsonl")P$.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
6179
- `),await MK(),process.exit(1);let m=(async()=>{if(V){T.info("Skipping initial free tier status fetch until auth is complete");return}try{let i=await U.configService.getLatest(),o=Jc(i),e=await lA.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(o)});if(e.ok)return T.info("User free tier status:",e),e.result;return}catch(i){T.error("Failed to fetch free tier status:",i);return}})(),u=!A.executeMode?new wB1:null,a,d=null;if(u)a=u,d=(async()=>{let i=V?await U.serverStatusPromise:U.serverStatus;if(GW(i))throw vZ1(i,A.ampURL);await uDA(B,Q,i);let o=process.hrtime.bigint(),e=await x();if(Y("runMainThread:createThreadPool",o),u.attach(e),Z){let Y0=await k1(e.threadHandles$);if(!Y0)throw new K4("No active thread is available yet.",1);await Y0.sendMessage({content:[{type:"text",text:Z}]})}})(),d.catch(async(i)=>{let o=i instanceof Error?i:Error(String(i));u.setInitError(o),await TH(i,Q.threadId)});else D=process.hrtime.bigint(),a=await x(),Y("runMainThread:createThreadPool",D);let s=Q.notifications!==void 0?Q.notifications:!A.executeMode,W0=E!==null&&oh(E.features,Y9.TUI_VOICE_NOTIF);if(V)U.serverStatusPromise.then((i)=>{W0=gA(i)&&oh(i.features,Y9.TUI_VOICE_NOTIF)}).catch((i)=>{T.debug("Failed to resolve TUI voice notification feature flag",{error:i})});D=process.hrtime.bigint();let n=await U.configService.getLatest();if(Y("runMainThread:configService.getLatest",D),D=process.hrtime.bigint(),jz8({configService:U.configService,threadService:U.threadService,config:n,useNotificationsForService:s,isTUIVoiceNotifEnabled:()=>W0,threadViewStates$:()=>a.threadHandles$.pipe(l4((i)=>{if(!i)return g0.of({});return u6(i.thread$,i.threadViewState$).pipe(w1(([o,e])=>({[o.id]:e})))}))}),Y("runMainThread:createCliNotificationService",D),A.executeMode){U31(U.mcpService,A.settings);let i={userInput:Z,stdinInput:F,dependencies:U,streamJson:X,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:H,agentMode:Q.mode,labels:Q.label},o=await ja4({threadPool:a,...i});if(await rh(o,"execute"),Q.archive)await U.threadService.archive(o,!0);await U.asyncDispose(),process.exit(0)}let A0=!1,D0=!1;if(Q.jetbrains||Q.ide){await n90();let i=await ID({jetbrainsOnly:Q.jetbrains});if(i.length===0){if(Q.jetbrains)A0=!await U.configService.get("jetbrains.skipInstall")}else if(i.length===1){let o=i[0];if(o)i8.selectConfig(o)}else D0=!0}D=process.hrtime.bigint();let z0=k81("0.0.1777279521-gff806d",U.settingsStorage,{startDelayMs:3000});Y("runMainThread:createUpdateService",D),D=process.hrtime.bigint();let B0=new K31(U.mcpService,A.settings.getWorkspaceRootPath());if(Y("runMainThread:createMcpTrustHandler",D),Z&&A.executeMode){let i=await k1(a.threadHandles$);if(!i)throw new K4("No active thread is available yet.",1);await i.sendMessage({content:[{type:"text",text:Z}]})}D=process.hrtime.bigint();let Z0=await Yu();Y("runMainThread:loadSessionState",D),T.info("Loaded session state:",Z0);let c={...Z0,launchCount:Z0.launchCount+1};NZ((i)=>({...i,launchCount:i.launchCount+1}));try{if(D=process.hrtime.bigint(),await DQA({history:new ut,fuzzyServer:U.fuzzyServer,settingsStorage:U.settingsStorage,threadService:U.threadService,skillService:U.skillService,configService:U.configService,secretStorage:U.secretStorage,internalAPIClient:lA,threadPool:a,createSystemPromptDeps:async()=>nDA(U),ideClient:i8,mcpService:U.mcpService,toolboxService:U.toolboxService,mcpTrustHandler:B0,updateService:z0,pluginPlatform:U.pluginPlatform,pluginService:U.pluginService},{initialServerStatus:U.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:U.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:C,showJetBrainsInstaller:A0,showIdePickerHint:D0,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:Vz8,logFile:{path:$},sessionState:c,freeTierStatusPromise:m,workspace:N??null,features:q,isInternalUser:H,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,buildTimestamp:"2026-04-27T08:50:02.827Z"},(i)=>new _B1({...i,threadPool:i.threadPool},(o)=>new BY1({...o,threadState:o.threadState}))),Y("runMainThread:mountApp-returned",D),d)await d}finally{await a.dispose().catch((i)=>{T.error("Failed to dispose thread pool during shutdown",i)})}await U.asyncDispose(),Y("runMainThread:dependencies.asyncDispose",J),process.exit(0)}async function K8(A){if(T.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)P$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6180
- `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;T.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await gF4({get:async(F)=>{if(F!==Xi)return;try{let X=await lDA(SZ1,"utf-8");return JSON.parse(X).installationID}catch{return}},set:async(F,X)=>{if(F!==Xi)return;await Fz8(V40.dirname(SZ1),{recursive:!0}),await Xz8(SZ1,JSON.stringify({installationID:X},null,2),{mode:384})}},{clientType:"cli",platform:yB0()});s54($);let J=await cU0({...A,workspaceTrust:{current:!0,changes:Sx0},getHook:process.env.AMP_URL?(F,X)=>{if(F==="url")return Promise.resolve(process.env.AMP_URL);return X()}:void 0});if(A.mcpConfig){let F=await be4(A.mcpConfig);J=ue4(J,F)}let Y=V40.dirname(J.getSettingsFilePath());cy4(rb,Y),J=T64(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=k9;if(T.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!vq(Z))T.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:vK0(await nt(A,J))}}function Sz8(A){let Q={};for(let B=0;B<A.length;B++){let $=A[B];if($?.startsWith("--")){let Y=$.slice(2).replace(/-([a-z])/g,(F,X)=>X.toUpperCase()),Z=A[B+1];if(Z&&!Z.startsWith("--"))Q[Y]=Z,B++}}return Q}function kz8(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=V40.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?Gz8:Pt));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function vz8(){gd4();let A=Sz8(process.argv),Q=kz8(process.argv,A),B=rn4(Q),$=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)n0.level=0;if(Kz8(T),T.info("Starting Amp CLI.",{version:"0.0.1777279521-gff806d",buildTimestamp:"2026-04-27T08:50:02.827Z"}),process.platform==="win32"&&EP())ks4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new K4(h7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Pz8(B).parseAsync(process.argv)}py4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await vz8().catch(TH)});async function yz8(A,Q){let B=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!B)await A.settings.set("url",process.env.AMP_URL,"global"),E5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6179
+ `),await MK(),process.exit(1);let m=(async()=>{if(V){T.info("Skipping initial free tier status fetch until auth is complete");return}try{let i=await U.configService.getLatest(),o=Jc(i),e=await lA.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(o)});if(e.ok)return T.info("User free tier status:",e),e.result;return}catch(i){T.error("Failed to fetch free tier status:",i);return}})(),u=!A.executeMode?new wB1:null,a,d=null;if(u)a=u,d=(async()=>{let i=V?await U.serverStatusPromise:U.serverStatus;if(GW(i))throw vZ1(i,A.ampURL);await uDA(B,Q,i);let o=process.hrtime.bigint(),e=await x();if(Y("runMainThread:createThreadPool",o),u.attach(e),Z){let Y0=await k1(e.threadHandles$);if(!Y0)throw new K4("No active thread is available yet.",1);await Y0.sendMessage({content:[{type:"text",text:Z}]})}})(),d.catch(async(i)=>{let o=i instanceof Error?i:Error(String(i));u.setInitError(o),await TH(i,Q.threadId)});else D=process.hrtime.bigint(),a=await x(),Y("runMainThread:createThreadPool",D);let s=Q.notifications!==void 0?Q.notifications:!A.executeMode,W0=E!==null&&oh(E.features,Y9.TUI_VOICE_NOTIF);if(V)U.serverStatusPromise.then((i)=>{W0=gA(i)&&oh(i.features,Y9.TUI_VOICE_NOTIF)}).catch((i)=>{T.debug("Failed to resolve TUI voice notification feature flag",{error:i})});D=process.hrtime.bigint();let n=await U.configService.getLatest();if(Y("runMainThread:configService.getLatest",D),D=process.hrtime.bigint(),jz8({configService:U.configService,threadService:U.threadService,config:n,useNotificationsForService:s,isTUIVoiceNotifEnabled:()=>W0,threadViewStates$:()=>a.threadHandles$.pipe(l4((i)=>{if(!i)return g0.of({});return u6(i.thread$,i.threadViewState$).pipe(w1(([o,e])=>({[o.id]:e})))}))}),Y("runMainThread:createCliNotificationService",D),A.executeMode){U31(U.mcpService,A.settings);let i={userInput:Z,stdinInput:F,dependencies:U,streamJson:X,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:H,agentMode:Q.mode,labels:Q.label},o=await ja4({threadPool:a,...i});if(await rh(o,"execute"),Q.archive)await U.threadService.archive(o,!0);await U.asyncDispose(),process.exit(0)}let A0=!1,D0=!1;if(Q.jetbrains||Q.ide){await n90();let i=await ID({jetbrainsOnly:Q.jetbrains});if(i.length===0){if(Q.jetbrains)A0=!await U.configService.get("jetbrains.skipInstall")}else if(i.length===1){let o=i[0];if(o)i8.selectConfig(o)}else D0=!0}D=process.hrtime.bigint();let z0=k81("0.0.1777279908-g9ebba6",U.settingsStorage,{startDelayMs:3000});Y("runMainThread:createUpdateService",D),D=process.hrtime.bigint();let B0=new K31(U.mcpService,A.settings.getWorkspaceRootPath());if(Y("runMainThread:createMcpTrustHandler",D),Z&&A.executeMode){let i=await k1(a.threadHandles$);if(!i)throw new K4("No active thread is available yet.",1);await i.sendMessage({content:[{type:"text",text:Z}]})}D=process.hrtime.bigint();let Z0=await Yu();Y("runMainThread:loadSessionState",D),T.info("Loaded session state:",Z0);let c={...Z0,launchCount:Z0.launchCount+1};NZ((i)=>({...i,launchCount:i.launchCount+1}));try{if(D=process.hrtime.bigint(),await DQA({history:new ut,fuzzyServer:U.fuzzyServer,settingsStorage:U.settingsStorage,threadService:U.threadService,skillService:U.skillService,configService:U.configService,secretStorage:U.secretStorage,internalAPIClient:lA,threadPool:a,createSystemPromptDeps:async()=>nDA(U),ideClient:i8,mcpService:U.mcpService,toolboxService:U.toolboxService,mcpTrustHandler:B0,updateService:z0,pluginPlatform:U.pluginPlatform,pluginService:U.pluginService},{initialServerStatus:U.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:U.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:C,showJetBrainsInstaller:A0,showIdePickerHint:D0,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:Vz8,logFile:{path:$},sessionState:c,freeTierStatusPromise:m,workspace:N??null,features:q,isInternalUser:H,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,buildTimestamp:"2026-04-27T08:55:43.407Z"},(i)=>new _B1({...i,threadPool:i.threadPool},(o)=>new BY1({...o,threadState:o.threadState}))),Y("runMainThread:mountApp-returned",D),d)await d}finally{await a.dispose().catch((i)=>{T.error("Failed to dispose thread pool during shutdown",i)})}await U.asyncDispose(),Y("runMainThread:dependencies.asyncDispose",J),process.exit(0)}async function K8(A){if(T.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)P$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6180
+ `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;T.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await gF4({get:async(F)=>{if(F!==Xi)return;try{let X=await lDA(SZ1,"utf-8");return JSON.parse(X).installationID}catch{return}},set:async(F,X)=>{if(F!==Xi)return;await Fz8(V40.dirname(SZ1),{recursive:!0}),await Xz8(SZ1,JSON.stringify({installationID:X},null,2),{mode:384})}},{clientType:"cli",platform:yB0()});s54($);let J=await cU0({...A,workspaceTrust:{current:!0,changes:Sx0},getHook:process.env.AMP_URL?(F,X)=>{if(F==="url")return Promise.resolve(process.env.AMP_URL);return X()}:void 0});if(A.mcpConfig){let F=await be4(A.mcpConfig);J=ue4(J,F)}let Y=V40.dirname(J.getSettingsFilePath());cy4(rb,Y),J=T64(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=k9;if(T.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!vq(Z))T.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:vK0(await nt(A,J))}}function Sz8(A){let Q={};for(let B=0;B<A.length;B++){let $=A[B];if($?.startsWith("--")){let Y=$.slice(2).replace(/-([a-z])/g,(F,X)=>X.toUpperCase()),Z=A[B+1];if(Z&&!Z.startsWith("--"))Q[Y]=Z,B++}}return Q}function kz8(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=V40.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?Gz8:Pt));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function vz8(){gd4();let A=Sz8(process.argv),Q=kz8(process.argv,A),B=rn4(Q),$=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)n0.level=0;if(Kz8(T),T.info("Starting Amp CLI.",{version:"0.0.1777279908-g9ebba6",buildTimestamp:"2026-04-27T08:55:43.407Z"}),process.platform==="win32"&&EP())ks4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new K4(h7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Pz8(B).parseAsync(process.argv)}py4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await vz8().catch(TH)});async function yz8(A,Q){let B=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!B)await A.settings.set("url",process.env.AMP_URL,"global"),E5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6181
6181
  `);else if(!vq(A.ampURL))E5.write(`Logging in to ${new URL(A.ampURL).hostname}
6182
6182
  `);let $=process.env.AMP_API_KEY;if($)E5.write(`API key found in environment variable, storing...
6183
6183
  `),await Q.set("apiKey",$,A.ampURL),E5.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1777279521-gff806d",
3
+ "version": "0.0.1777279908-g9ebba6",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {