@sourcegraph/amp 0.0.1777680871-g5fc25d → 0.0.1777697948-g1a223c

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
@@ -4735,12 +4735,12 @@ ${E}`))}},error:(K)=>{if(!U)U=!0,F(Error(`Failed to spawn brew: ${K.message}`))}
4735
4735
  ${E}`;if(Y==="pnpm"&&E.includes("Unable to find the global bin directory"))H+=`
4736
4736
 
4737
4737
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
4738
- npm install -g @sourcegraph/amp`;F(Error(H))}},error:(K)=>{if(!V)V=!0,F(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,X()}})})}i0();i0();yI();async function wK0(A,Q){let J=`${Q||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,Y=new AbortController,Z=setTimeout(()=>Y.abort(),5000);try{let X=await fetch(J,{signal:Y.signal});if(!X.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let F=await X.json(),D=F.version??F["dist-tags"]?.latest;if(!D)return{hasUpdate:!1,currentVersion:A,source:"npm"};let G=Le(A,D),V=G<0,U,K;if(F.time){let E=F.time[A],H=F.time[D],W=Date.now();if(E)U=Math.floor((W-new Date(E).getTime())/3600000);if(H)K=Math.floor((W-new Date(H).getTime())/3600000)}return j.info("NPM version comparison",{currentVersion:A,latestVersion:D,compareResult:G,hasUpdate:V,currentVersionAge:U,latestVersionAge:K}),{hasUpdate:V,latestVersion:D,currentVersion:A,currentVersionAge:U,latestVersionAge:K,source:"npm"}}catch(X){return j.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var no5="https://static.ampcode.com/cli/cli-version.txt";async function CK0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${no5}?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=Le(A,J),Z=Y<0;return j.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return j.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var ao5=604800000;function De4(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>ao5)return{ageMs:B};return null}function Le(A,Q){let B=(Z)=>{let[X,F]=Z.split("-");return{parts:X?.split(".").map(Number)||[],label:F}},$=B(A),J=B(Q),Y=Math.max($.parts.length,J.parts.length);for(let Z=0;Z<Y;Z++){let X=$.parts[Z]||0,F=J.parts[Z]||0;if(X<F)return-1;if(X>F)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 B31(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?rU(B):void 0;return{sha:$,age:J}}catch{return null}}j1();i0();import{readFile as oo5,realpath as ro5}from"node:fs/promises";import{homedir as so5}from"node:os";import{dirname as Ge4,join as $31}from"node:path";async function Ve4(A){switch(A){case"binary":case"brew":return to5(Ie());case"npm":case"pnpm":case"yarn":case"bun":return eo5();case"bootstrap":return Ar5()}}async function to5(A){let Q=await hG(A,["--version"],5000);if(Q.reason!=="success")return j.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function eo5(){try{let A=process.argv[1];if(!A)return null;let Q=await ro5(A),B=Ge4(Ge4(Q));return await Ue4($31(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function Ar5(){try{let A=process.env.AMP_HOME??$31(so5(),".amp");return await Ue4($31(A,"package","package.json"))}catch(A){return j.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function Ue4(A){let Q=await oo5(A,"utf8"),B=JSON.parse(Q);if(B.name!=="@sourcegraph/amp")return j.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var Qr5=3600000,Br5=5000;function J31(A,Q,B={}){let $=new r4,J=$.pipe($6({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??Qr5,X=!1,F=()=>{X=!0};return setImmediate(async()=>{let D=new vY().scoped("update");if(Y>0){if(await oU(Y),X)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!X){let U=await $r5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await oU(Br5),X)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!X){let H=Math.min(K,E);await oU(H),E-=H}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:F}}async function $r5(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 NK0(),X=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:X});let F;if(X)F=await CK0(A);else{let V=await xP();F=await wK0(A,V)}if(!(F.latestVersion&&F.hasUpdate))return B.debug("no update available"),J;let D=(V)=>{$.next(V),J.emittedVisibleState=!0};if(Z){let V=await Ve4(Z);if(V&&Le(V,F.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:F.latestVersion}),J.updatedTo=V,Le(A,V)<0){let U=await Bz(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(F.currentVersionAge!==void 0&&F.latestVersionAge!==void 0){let V=F.currentVersionAge-F.latestVersionAge,U=0.5;if(Math.abs(V)<0.5)return B.debug("versions too close together, suppressing update warning",{currentVersionAge:F.currentVersionAge,latestVersionAge:F.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!==Ie()){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 Me(F.latestVersion,Z),J.updatedTo=F.latestVersion;let V=await Bz(F.latestVersion),U={from:F.currentVersion,to:F.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}}yI();import{stderr as gG}from"node:process";function Ke4(A){let Q=new Yw().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 c81($.force||!1,$.verbose||!1,"0.0.1777680871-g5fc25d"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new Yw("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 Yr5($.targetVersion)});A.addCommand(B)}function Jr5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
4738
+ npm install -g @sourcegraph/amp`;F(Error(H))}},error:(K)=>{if(!V)V=!0,F(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,X()}})})}i0();i0();yI();async function wK0(A,Q){let J=`${Q||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,Y=new AbortController,Z=setTimeout(()=>Y.abort(),5000);try{let X=await fetch(J,{signal:Y.signal});if(!X.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let F=await X.json(),D=F.version??F["dist-tags"]?.latest;if(!D)return{hasUpdate:!1,currentVersion:A,source:"npm"};let G=Le(A,D),V=G<0,U,K;if(F.time){let E=F.time[A],H=F.time[D],W=Date.now();if(E)U=Math.floor((W-new Date(E).getTime())/3600000);if(H)K=Math.floor((W-new Date(H).getTime())/3600000)}return j.info("NPM version comparison",{currentVersion:A,latestVersion:D,compareResult:G,hasUpdate:V,currentVersionAge:U,latestVersionAge:K}),{hasUpdate:V,latestVersion:D,currentVersion:A,currentVersionAge:U,latestVersionAge:K,source:"npm"}}catch(X){return j.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var no5="https://static.ampcode.com/cli/cli-version.txt";async function CK0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${no5}?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=Le(A,J),Z=Y<0;return j.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return j.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var ao5=604800000;function De4(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>ao5)return{ageMs:B};return null}function Le(A,Q){let B=(Z)=>{let[X,F]=Z.split("-");return{parts:X?.split(".").map(Number)||[],label:F}},$=B(A),J=B(Q),Y=Math.max($.parts.length,J.parts.length);for(let Z=0;Z<Y;Z++){let X=$.parts[Z]||0,F=J.parts[Z]||0;if(X<F)return-1;if(X>F)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 B31(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?rU(B):void 0;return{sha:$,age:J}}catch{return null}}j1();i0();import{readFile as oo5,realpath as ro5}from"node:fs/promises";import{homedir as so5}from"node:os";import{dirname as Ge4,join as $31}from"node:path";async function Ve4(A){switch(A){case"binary":case"brew":return to5(Ie());case"npm":case"pnpm":case"yarn":case"bun":return eo5();case"bootstrap":return Ar5()}}async function to5(A){let Q=await hG(A,["--version"],5000);if(Q.reason!=="success")return j.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function eo5(){try{let A=process.argv[1];if(!A)return null;let Q=await ro5(A),B=Ge4(Ge4(Q));return await Ue4($31(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function Ar5(){try{let A=process.env.AMP_HOME??$31(so5(),".amp");return await Ue4($31(A,"package","package.json"))}catch(A){return j.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function Ue4(A){let Q=await oo5(A,"utf8"),B=JSON.parse(Q);if(B.name!=="@sourcegraph/amp")return j.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var Qr5=3600000,Br5=5000;function J31(A,Q,B={}){let $=new r4,J=$.pipe($6({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??Qr5,X=!1,F=()=>{X=!0};return setImmediate(async()=>{let D=new vY().scoped("update");if(Y>0){if(await oU(Y),X)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!X){let U=await $r5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await oU(Br5),X)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!X){let H=Math.min(K,E);await oU(H),E-=H}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:F}}async function $r5(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 NK0(),X=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:X});let F;if(X)F=await CK0(A);else{let V=await xP();F=await wK0(A,V)}if(!(F.latestVersion&&F.hasUpdate))return B.debug("no update available"),J;let D=(V)=>{$.next(V),J.emittedVisibleState=!0};if(Z){let V=await Ve4(Z);if(V&&Le(V,F.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:F.latestVersion}),J.updatedTo=V,Le(A,V)<0){let U=await Bz(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(F.currentVersionAge!==void 0&&F.latestVersionAge!==void 0){let V=F.currentVersionAge-F.latestVersionAge,U=0.5;if(Math.abs(V)<0.5)return B.debug("versions too close together, suppressing update warning",{currentVersionAge:F.currentVersionAge,latestVersionAge:F.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!==Ie()){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 Me(F.latestVersion,Z),J.updatedTo=F.latestVersion;let V=await Bz(F.latestVersion),U={from:F.currentVersion,to:F.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}}yI();import{stderr as gG}from"node:process";function Ke4(A){let Q=new Yw().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 c81($.force||!1,$.verbose||!1,"0.0.1777697948-g1a223c"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new Yw("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 Yr5($.targetVersion)});A.addCommand(B)}function Jr5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
4739
4739
  `),$=!1,B=0}function Y(Z){if(!Q)return;let X=Z.padEnd(B," ");A.write(`\r${X}`),$=!0,B=X.length}return{flushProgressLine:J,renderProgress:Y}}async function Yr5(A){let B=process.platform==="win32"&&yP()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:$,renderProgress:J}=Jr5(gG);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")gG.write(r0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4740
4740
 
4741
4741
  `));try{if(!A){gG.write(r0.blue(`Checking for updates...
4742
- `));let X=!1,F;if(yP()){let D=await CK0("0.0.1777680871-g5fc25d");X=D.hasUpdate,F=D.latestVersion}else{let D=await xP(),G=await wK0("0.0.1777680871-g5fc25d",D);X=G.hasUpdate,F=G.latestVersion}if(!X){let D=B31("0.0.1777680871-g5fc25d"),G=D?.age?`released ${D.age} ago`:`built ${rU(new Date("2026-05-02T00:18:10.627Z"))} ago`;gG.write(r0.green(`✓ Amp is already up to date on version ${"0.0.1777680871-g5fc25d"} (${G})
4743
- `));let V=await Bz("0.0.1777680871-g5fc25d",B);if(V.warning)gG.write(`
4742
+ `));let X=!1,F;if(yP()){let D=await CK0("0.0.1777697948-g1a223c");X=D.hasUpdate,F=D.latestVersion}else{let D=await xP(),G=await wK0("0.0.1777697948-g1a223c",D);X=G.hasUpdate,F=G.latestVersion}if(!X){let D=B31("0.0.1777697948-g1a223c"),G=D?.age?`released ${D.age} ago`:`built ${rU(new Date("2026-05-02T05:02:48.212Z"))} ago`;gG.write(r0.green(`✓ Amp is already up to date on version ${"0.0.1777697948-g1a223c"} (${G})
4743
+ `));let V=await Bz("0.0.1777697948-g1a223c",B);if(V.warning)gG.write(`
4744
4744
  `+r0.yellow(V.warning)+`
4745
4745
  `);process.exit(0)}if(!F)gG.write(r0.yellow("[WARN] could not find latest version")),process.exit(0);A=F}gG.write(r0.blue(`Updating to version ${A}...
4746
4746
  `)),await Me(A,void 0,(X)=>{$(),gG.write(r0.dim(`Running: ${X}
@@ -5285,7 +5285,7 @@ Ctrl-X, Y, Z to unlock`;if(E){let $0=G.text.replace(/`([^`]+)`/g,"$1")+`
5285
5285
  * MIT Licence
5286
5286
  */var Sh=9000000000000000,xC=1e9,Z$1="0123456789abcdef",zW0="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",qW0="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",X$1={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Sh,maxE:Sh,crypto:!1},$BA,Iz,Q6=!0,IW0="[DecimalError] ",yC=IW0+"Invalid argument: ",JBA=IW0+"Precision limit exceeded",YBA=IW0+"crypto unavailable",ZBA="[object Decimal]",_B=Math.floor,X7=Math.pow,gY8=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,mY8=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,pY8=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,XBA=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,AV=1e7,hA=7,dY8=9007199254740991,cY8=zW0.length-1,F$1=qW0.length-1,d1={toStringTag:ZBA};d1.absoluteValue=d1.abs=function(){var A=new this.constructor(this);if(A.s<0)A.s=1;return qA(A)};d1.ceil=function(){return qA(new this.constructor(this),this.e+1,2)};d1.clampedTo=d1.clamp=function(A,Q){var B,$=this,J=$.constructor;if(A=new J(A),Q=new J(Q),!A.s||!Q.s)return new J(NaN);if(A.gt(Q))throw Error(yC+Q);return B=$.cmp(A),B<0?A:$.cmp(Q)>0?Q:new J($)};d1.comparedTo=d1.cmp=function(A){var Q,B,$,J,Y=this,Z=Y.d,X=(A=new Y.constructor(A)).d,F=Y.s,D=A.s;if(!Z||!X)return!F||!D?NaN:F!==D?F:Z===X?0:!Z^F<0?1:-1;if(!Z[0]||!X[0])return Z[0]?F:X[0]?-D:0;if(F!==D)return F;if(Y.e!==A.e)return Y.e>A.e^F<0?1:-1;$=Z.length,J=X.length;for(Q=0,B=$<J?$:J;Q<B;++Q)if(Z[Q]!==X[Q])return Z[Q]>X[Q]^F<0?1:-1;return $===J?0:$>J^F<0?1:-1};d1.cosine=d1.cos=function(){var A,Q,B=this,$=B.constructor;if(!B.d)return new $(NaN);if(!B.d[0])return new $(1);return A=$.precision,Q=$.rounding,$.precision=A+Math.max(B.e,B.sd())+hA,$.rounding=1,B=lY8($,UBA($,B)),$.precision=A,$.rounding=Q,qA(Iz==2||Iz==3?B.neg():B,A,Q,!0)};d1.cubeRoot=d1.cbrt=function(){var A,Q,B,$,J,Y,Z,X,F,D,G=this,V=G.constructor;if(!G.isFinite()||G.isZero())return new V(G);if(Q6=!1,Y=G.s*X7(G.s*G,0.3333333333333333),!Y||Math.abs(Y)==1/0){if(B=yQ(G.d),A=G.e,Y=(A-B.length+1)%3)B+=Y==1||Y==-2?"0":"00";if(Y=X7(B,0.3333333333333333),A=_B((A+1)/3)-(A%3==(A<0?-1:2)),Y==1/0)B="5e"+A;else B=Y.toExponential(),B=B.slice(0,B.indexOf("e")+1)+A;$=new V(B),$.s=G.s}else $=new V(Y.toString());Z=(A=V.precision)+3;for(;;)if(X=$,F=X.times(X).times(X),D=F.plus(G),$=h8(D.plus(G).times(X),D.plus(F),Z+2,1),yQ(X.d).slice(0,Z)===(B=yQ($.d)).slice(0,Z))if(B=B.slice(Z-3,Z+1),B=="9999"||!J&&B=="4999"){if(!J){if(qA(X,A+1,0),X.times(X).times(X).eq(G)){$=X;break}}Z+=4,J=1}else{if(!+B||!+B.slice(1)&&B.charAt(0)=="5")qA($,A+1,1),Q=!$.times($).times($).eq(G);break}return Q6=!0,qA($,A,V.rounding,Q)};d1.decimalPlaces=d1.dp=function(){var A,Q=this.d,B=NaN;if(Q){if(A=Q.length-1,B=(A-_B(this.e/hA))*hA,A=Q[A],A)for(;A%10==0;A/=10)B--;if(B<0)B=0}return B};d1.dividedBy=d1.div=function(A){return h8(this,new this.constructor(A))};d1.dividedToIntegerBy=d1.divToInt=function(A){var Q=this,B=Q.constructor;return qA(h8(Q,new B(A),0,1,1),B.precision,B.rounding)};d1.equals=d1.eq=function(A){return this.cmp(A)===0};d1.floor=function(){return qA(new this.constructor(this),this.e+1,3)};d1.greaterThan=d1.gt=function(A){return this.cmp(A)>0};d1.greaterThanOrEqualTo=d1.gte=function(A){var Q=this.cmp(A);return Q==1||Q===0};d1.hyperbolicCosine=d1.cosh=function(){var A,Q,B,$,J,Y=this,Z=Y.constructor,X=new Z(1);if(!Y.isFinite())return new Z(Y.s?1/0:NaN);if(Y.isZero())return X;if(B=Z.precision,$=Z.rounding,Z.precision=B+Math.max(Y.e,Y.sd())+4,Z.rounding=1,J=Y.d.length,J<32)A=Math.ceil(J/3),Q=(1/CW0(4,A)).toString();else A=16,Q="2.3283064365386962890625e-10";Y=kh(Z,1,Y.times(Q),new Z(1),!0);var F,D=A,G=new Z(8);for(;D--;)F=Y.times(Y),Y=X.minus(F.times(G.minus(F.times(G))));return qA(Y,Z.precision=B,Z.rounding=$,!0)};d1.hyperbolicSine=d1.sinh=function(){var A,Q,B,$,J=this,Y=J.constructor;if(!J.isFinite()||J.isZero())return new Y(J);if(Q=Y.precision,B=Y.rounding,Y.precision=Q+Math.max(J.e,J.sd())+4,Y.rounding=1,$=J.d.length,$<3)J=kh(Y,2,J,J,!0);else{A=1.4*Math.sqrt($),A=A>16?16:A|0,J=J.times(1/CW0(5,A)),J=kh(Y,2,J,J,!0);var Z,X=new Y(5),F=new Y(16),D=new Y(20);for(;A--;)Z=J.times(J),J=J.times(X.plus(Z.times(F.times(Z).plus(D))))}return Y.precision=Q,Y.rounding=B,qA(J,Q,B,!0)};d1.hyperbolicTangent=d1.tanh=function(){var A,Q,B=this,$=B.constructor;if(!B.isFinite())return new $(B.s);if(B.isZero())return new $(B);return A=$.precision,Q=$.rounding,$.precision=A+7,$.rounding=1,h8(B.sinh(),B.cosh(),$.precision=A,$.rounding=Q)};d1.inverseCosine=d1.acos=function(){var A=this,Q=A.constructor,B=A.abs().cmp(1),$=Q.precision,J=Q.rounding;if(B!==-1)return B===0?A.isNeg()?FE(Q,$,J):new Q(0):new Q(NaN);if(A.isZero())return FE(Q,$+4,J).times(0.5);return Q.precision=$+6,Q.rounding=1,A=new Q(1).minus(A).div(A.plus(1)).sqrt().atan(),Q.precision=$,Q.rounding=J,A.times(2)};d1.inverseHyperbolicCosine=d1.acosh=function(){var A,Q,B=this,$=B.constructor;if(B.lte(1))return new $(B.eq(1)?0:NaN);if(!B.isFinite())return new $(B);return A=$.precision,Q=$.rounding,$.precision=A+Math.max(Math.abs(B.e),B.sd())+4,$.rounding=1,Q6=!1,B=B.times(B).minus(1).sqrt().plus(B),Q6=!0,$.precision=A,$.rounding=Q,B.ln()};d1.inverseHyperbolicSine=d1.asinh=function(){var A,Q,B=this,$=B.constructor;if(!B.isFinite()||B.isZero())return new $(B);return A=$.precision,Q=$.rounding,$.precision=A+2*Math.max(Math.abs(B.e),B.sd())+6,$.rounding=1,Q6=!1,B=B.times(B).plus(1).sqrt().plus(B),Q6=!0,$.precision=A,$.rounding=Q,B.ln()};d1.inverseHyperbolicTangent=d1.atanh=function(){var A,Q,B,$,J=this,Y=J.constructor;if(!J.isFinite())return new Y(NaN);if(J.e>=0)return new Y(J.abs().eq(1)?J.s/0:J.isZero()?J:NaN);if(A=Y.precision,Q=Y.rounding,$=J.sd(),Math.max($,A)<2*-J.e-1)return qA(new Y(J),A,Q,!0);return Y.precision=B=$-J.e,J=h8(J.plus(1),new Y(1).minus(J),B+A,1),Y.precision=A+4,Y.rounding=1,J=J.ln(),Y.precision=A,Y.rounding=Q,J.times(0.5)};d1.inverseSine=d1.asin=function(){var A,Q,B,$,J=this,Y=J.constructor;if(J.isZero())return new Y(J);if(Q=J.abs().cmp(1),B=Y.precision,$=Y.rounding,Q!==-1){if(Q===0)return A=FE(Y,B+4,$).times(0.5),A.s=J.s,A;return new Y(NaN)}return Y.precision=B+6,Y.rounding=1,J=J.div(new Y(1).minus(J.times(J)).sqrt().plus(1)).atan(),Y.precision=B,Y.rounding=$,J.times(2)};d1.inverseTangent=d1.atan=function(){var A,Q,B,$,J,Y,Z,X,F,D=this,G=D.constructor,V=G.precision,U=G.rounding;if(!D.isFinite()){if(!D.s)return new G(NaN);if(V+4<=F$1)return Z=FE(G,V+4,U).times(0.5),Z.s=D.s,Z}else if(D.isZero())return new G(D);else if(D.abs().eq(1)&&V+4<=F$1)return Z=FE(G,V+4,U).times(0.25),Z.s=D.s,Z;G.precision=X=V+10,G.rounding=1,B=Math.min(28,X/hA+2|0);for(A=B;A;--A)D=D.div(D.times(D).plus(1).sqrt().plus(1));Q6=!1,Q=Math.ceil(X/hA),$=1,F=D.times(D),Z=new G(D),J=D;for(;A!==-1;)if(J=J.times(F),Y=Z.minus(J.div($+=2)),J=J.times(F),Z=Y.plus(J.div($+=2)),Z.d[Q]!==void 0)for(A=Q;Z.d[A]===Y.d[A]&&A--;);if(B)Z=Z.times(2<<B-1);return Q6=!0,qA(Z,G.precision=V,G.rounding=U,!0)};d1.isFinite=function(){return!!this.d};d1.isInteger=d1.isInt=function(){return!!this.d&&_B(this.e/hA)>this.d.length-2};d1.isNaN=function(){return!this.s};d1.isNegative=d1.isNeg=function(){return this.s<0};d1.isPositive=d1.isPos=function(){return this.s>0};d1.isZero=function(){return!!this.d&&this.d[0]===0};d1.lessThan=d1.lt=function(A){return this.cmp(A)<0};d1.lessThanOrEqualTo=d1.lte=function(A){return this.cmp(A)<1};d1.logarithm=d1.log=function(A){var Q,B,$,J,Y,Z,X,F,D=this,G=D.constructor,V=G.precision,U=G.rounding,K=5;if(A==null)A=new G(10),Q=!0;else{if(A=new G(A),B=A.d,A.s<0||!B||!B[0]||A.eq(1))return new G(NaN);Q=A.eq(10)}if(B=D.d,D.s<0||!B||!B[0]||D.eq(1))return new G(B&&!B[0]?-1/0:D.s!=1?NaN:B?0:1/0);if(Q)if(B.length>1)Y=!0;else{for(J=B[0];J%10===0;)J/=10;Y=J!==1}if(Q6=!1,X=V+K,Z=vC(D,X),$=Q?NW0(G,X+10):vC(A,X),F=h8(Z,$,X,1),M10(F.d,J=V,U))do if(X+=10,Z=vC(D,X),$=Q?NW0(G,X+10):vC(A,X),F=h8(Z,$,X,1),!Y){if(+yQ(F.d).slice(J+1,J+15)+1==100000000000000)F=qA(F,V+1,0);break}while(M10(F.d,J+=10,U));return Q6=!0,qA(F,V,U)};d1.minus=d1.sub=function(A){var Q,B,$,J,Y,Z,X,F,D,G,V,U,K=this,E=K.constructor;if(A=new E(A),!K.d||!A.d){if(!K.s||!A.s)A=new E(NaN);else if(K.d)A.s=-A.s;else A=new E(A.d||K.s!==A.s?K:NaN);return A}if(K.s!=A.s)return A.s=-A.s,K.plus(A);if(D=K.d,U=A.d,X=E.precision,F=E.rounding,!D[0]||!U[0]){if(U[0])A.s=-A.s;else if(D[0])A=new E(K);else return new E(F===3?-0:0);return Q6?qA(A,X,F):A}if(B=_B(A.e/hA),G=_B(K.e/hA),D=D.slice(),Y=G-B,Y){if(V=Y<0,V)Q=D,Y=-Y,Z=U.length;else Q=U,B=G,Z=D.length;if($=Math.max(Math.ceil(X/hA),Z)+2,Y>$)Y=$,Q.length=1;Q.reverse();for($=Y;$--;)Q.push(0);Q.reverse()}else{if($=D.length,Z=U.length,V=$<Z,V)Z=$;for($=0;$<Z;$++)if(D[$]!=U[$]){V=D[$]<U[$];break}Y=0}if(V)Q=D,D=U,U=Q,A.s=-A.s;Z=D.length;for($=U.length-Z;$>0;--$)D[Z++]=0;for($=U.length;$>Y;){if(D[--$]<U[$]){for(J=$;J&&D[--J]===0;)D[J]=AV-1;--D[J],D[$]+=AV}D[$]-=U[$]}for(;D[--Z]===0;)D.pop();for(;D[0]===0;D.shift())--B;if(!D[0])return new E(F===3?-0:0);return A.d=D,A.e=wW0(D,B),Q6?qA(A,X,F):A};d1.modulo=d1.mod=function(A){var Q,B=this,$=B.constructor;if(A=new $(A),!B.d||!A.s||A.d&&!A.d[0])return new $(NaN);if(!A.d||B.d&&!B.d[0])return qA(new $(B),$.precision,$.rounding);if(Q6=!1,$.modulo==9)Q=h8(B,A.abs(),0,3,1),Q.s*=A.s;else Q=h8(B,A,0,$.modulo,1);return Q=Q.times(A),Q6=!0,B.minus(Q)};d1.naturalExponential=d1.exp=function(){return D$1(this)};d1.naturalLogarithm=d1.ln=function(){return vC(this)};d1.negated=d1.neg=function(){var A=new this.constructor(this);return A.s=-A.s,qA(A)};d1.plus=d1.add=function(A){var Q,B,$,J,Y,Z,X,F,D,G,V=this,U=V.constructor;if(A=new U(A),!V.d||!A.d){if(!V.s||!A.s)A=new U(NaN);else if(!V.d)A=new U(A.d||V.s===A.s?V:NaN);return A}if(V.s!=A.s)return A.s=-A.s,V.minus(A);if(D=V.d,G=A.d,X=U.precision,F=U.rounding,!D[0]||!G[0]){if(!G[0])A=new U(V);return Q6?qA(A,X,F):A}if(Y=_B(V.e/hA),$=_B(A.e/hA),D=D.slice(),J=Y-$,J){if(J<0)B=D,J=-J,Z=G.length;else B=G,$=Y,Z=D.length;if(Y=Math.ceil(X/hA),Z=Y>Z?Y+1:Z+1,J>Z)J=Z,B.length=1;B.reverse();for(;J--;)B.push(0);B.reverse()}if(Z=D.length,J=G.length,Z-J<0)J=Z,B=G,G=D,D=B;for(Q=0;J;)Q=(D[--J]=D[J]+G[J]+Q)/AV|0,D[J]%=AV;if(Q)D.unshift(Q),++$;for(Z=D.length;D[--Z]==0;)D.pop();return A.d=D,A.e=wW0(D,$),Q6?qA(A,X,F):A};d1.precision=d1.sd=function(A){var Q,B=this;if(A!==void 0&&A!==!!A&&A!==1&&A!==0)throw Error(yC+A);if(B.d){if(Q=FBA(B.d),A&&B.e+1>Q)Q=B.e+1}else Q=NaN;return Q};d1.round=function(){var A=this,Q=A.constructor;return qA(new Q(A),A.e+1,Q.rounding)};d1.sine=d1.sin=function(){var A,Q,B=this,$=B.constructor;if(!B.isFinite())return new $(NaN);if(B.isZero())return new $(B);return A=$.precision,Q=$.rounding,$.precision=A+Math.max(B.e,B.sd())+hA,$.rounding=1,B=nY8($,UBA($,B)),$.precision=A,$.rounding=Q,qA(Iz>2?B.neg():B,A,Q,!0)};d1.squareRoot=d1.sqrt=function(){var A,Q,B,$,J,Y,Z=this,X=Z.d,F=Z.e,D=Z.s,G=Z.constructor;if(D!==1||!X||!X[0])return new G(!D||D<0&&(!X||X[0])?NaN:X?Z:1/0);if(Q6=!1,D=Math.sqrt(+Z),D==0||D==1/0){if(Q=yQ(X),(Q.length+F)%2==0)Q+="0";if(D=Math.sqrt(Q),F=_B((F+1)/2)-(F<0||F%2),D==1/0)Q="5e"+F;else Q=D.toExponential(),Q=Q.slice(0,Q.indexOf("e")+1)+F;$=new G(Q)}else $=new G(D.toString());B=(F=G.precision)+3;for(;;)if(Y=$,$=Y.plus(h8(Z,Y,B+2,1)).times(0.5),yQ(Y.d).slice(0,B)===(Q=yQ($.d)).slice(0,B))if(Q=Q.slice(B-3,B+1),Q=="9999"||!J&&Q=="4999"){if(!J){if(qA(Y,F+1,0),Y.times(Y).eq(Z)){$=Y;break}}B+=4,J=1}else{if(!+Q||!+Q.slice(1)&&Q.charAt(0)=="5")qA($,F+1,1),A=!$.times($).eq(Z);break}return Q6=!0,qA($,F,G.rounding,A)};d1.tangent=d1.tan=function(){var A,Q,B=this,$=B.constructor;if(!B.isFinite())return new $(NaN);if(B.isZero())return new $(B);return A=$.precision,Q=$.rounding,$.precision=A+10,$.rounding=1,B=B.sin(),B.s=1,B=h8(B,new $(1).minus(B.times(B)).sqrt(),A+10,0),$.precision=A,$.rounding=Q,qA(Iz==2||Iz==4?B.neg():B,A,Q,!0)};d1.times=d1.mul=function(A){var Q,B,$,J,Y,Z,X,F,D,G=this,V=G.constructor,U=G.d,K=(A=new V(A)).d;if(A.s*=G.s,!U||!U[0]||!K||!K[0])return new V(!A.s||U&&!U[0]&&!K||K&&!K[0]&&!U?NaN:!U||!K?A.s/0:A.s*0);if(B=_B(G.e/hA)+_B(A.e/hA),F=U.length,D=K.length,F<D)Y=U,U=K,K=Y,Z=F,F=D,D=Z;Y=[],Z=F+D;for($=Z;$--;)Y.push(0);for($=D;--$>=0;){Q=0;for(J=F+$;J>$;)X=Y[J]+K[$]*U[J-$-1]+Q,Y[J--]=X%AV|0,Q=X/AV|0;Y[J]=(Y[J]+Q)%AV|0}for(;!Y[--Z];)Y.pop();if(Q)++B;else Y.shift();return A.d=Y,A.e=wW0(Y,B),Q6?qA(A,V.precision,V.rounding):A};d1.toBinary=function(A,Q){return G$1(this,2,A,Q)};d1.toDecimalPlaces=d1.toDP=function(A,Q){var B=this,$=B.constructor;if(B=new $(B),A===void 0)return B;if(BY(A,0,xC),Q===void 0)Q=$.rounding;else BY(Q,0,8);return qA(B,A+B.e+1,Q)};d1.toExponential=function(A,Q){var B,$=this,J=$.constructor;if(A===void 0)B=DE($,!0);else{if(BY(A,0,xC),Q===void 0)Q=J.rounding;else BY(Q,0,8);$=qA(new J($),A+1,Q),B=DE($,!0,A+1)}return $.isNeg()&&!$.isZero()?"-"+B:B};d1.toFixed=function(A,Q){var B,$,J=this,Y=J.constructor;if(A===void 0)B=DE(J);else{if(BY(A,0,xC),Q===void 0)Q=Y.rounding;else BY(Q,0,8);$=qA(new Y(J),A+J.e+1,Q),B=DE($,!1,A+$.e+1)}return J.isNeg()&&!J.isZero()?"-"+B:B};d1.toFraction=function(A){var Q,B,$,J,Y,Z,X,F,D,G,V,U,K=this,E=K.d,H=K.constructor;if(!E)return new H(K);if(D=B=new H(1),$=F=new H(0),Q=new H($),Y=Q.e=FBA(E)-K.e-1,Z=Y%hA,Q.d[0]=X7(10,Z<0?hA+Z:Z),A==null)A=Y>0?Q:D;else{if(X=new H(A),!X.isInt()||X.lt(D))throw Error(yC+X);A=X.gt(Q)?Y>0?Q:D:X}Q6=!1,X=new H(yQ(E)),G=H.precision,H.precision=Y=E.length*hA*2;for(;;){if(V=h8(X,Q,0,1,1),J=B.plus(V.times($)),J.cmp(A)==1)break;B=$,$=J,J=D,D=F.plus(V.times(J)),F=J,J=Q,Q=X.minus(V.times(J)),X=J}return J=h8(A.minus(B),$,0,1,1),F=F.plus(J.times(D)),B=B.plus(J.times($)),F.s=D.s=K.s,U=h8(D,$,Y,1).minus(K).abs().cmp(h8(F,B,Y,1).minus(K).abs())<1?[D,$]:[F,B],H.precision=G,Q6=!0,U};d1.toHexadecimal=d1.toHex=function(A,Q){return G$1(this,16,A,Q)};d1.toNearest=function(A,Q){var B=this,$=B.constructor;if(B=new $(B),A==null){if(!B.d)return B;A=new $(1),Q=$.rounding}else{if(A=new $(A),Q===void 0)Q=$.rounding;else BY(Q,0,8);if(!B.d)return A.s?B:A;if(!A.d){if(A.s)A.s=B.s;return A}}if(A.d[0])Q6=!1,B=h8(B,A,0,Q,1).times(A),Q6=!0,qA(B);else A.s=B.s,B=A;return B};d1.toNumber=function(){return+this};d1.toOctal=function(A,Q){return G$1(this,8,A,Q)};d1.toPower=d1.pow=function(A){var Q,B,$,J,Y,Z,X=this,F=X.constructor,D=+(A=new F(A));if(!X.d||!A.d||!X.d[0]||!A.d[0])return new F(X7(+X,D));if(X=new F(X),X.eq(1))return X;if($=F.precision,Y=F.rounding,A.eq(1))return qA(X,$,Y);if(Q=_B(A.e/hA),Q>=A.d.length-1&&(B=D<0?-D:D)<=dY8)return J=DBA(F,X,B,$),A.s<0?new F(1).div(J):qA(J,$,Y);if(Z=X.s,Z<0){if(Q<A.d.length-1)return new F(NaN);if((A.d[Q]&1)==0)Z=1;if(X.e==0&&X.d[0]==1&&X.d.length==1)return X.s=Z,X}if(B=X7(+X,D),Q=B==0||!isFinite(B)?_B(D*(Math.log("0."+yQ(X.d))/Math.LN10+X.e+1)):new F(B+"").e,Q>F.maxE+1||Q<F.minE-1)return new F(Q>0?Z/0:0);if(Q6=!1,F.rounding=X.s=1,B=Math.min(12,(Q+"").length),J=D$1(A.times(vC(X,$+B)),$),J.d){if(J=qA(J,$+5,1),M10(J.d,$,Y)){if(Q=$+10,J=qA(D$1(A.times(vC(X,Q+B)),Q),Q+5,1),+yQ(J.d).slice($+1,$+15)+1==100000000000000)J=qA(J,$+1,0)}}return J.s=Z,Q6=!0,F.rounding=Y,qA(J,$,Y)};d1.toPrecision=function(A,Q){var B,$=this,J=$.constructor;if(A===void 0)B=DE($,$.e<=J.toExpNeg||$.e>=J.toExpPos);else{if(BY(A,1,xC),Q===void 0)Q=J.rounding;else BY(Q,0,8);$=qA(new J($),A,Q),B=DE($,A<=$.e||$.e<=J.toExpNeg,A)}return $.isNeg()&&!$.isZero()?"-"+B:B};d1.toSignificantDigits=d1.toSD=function(A,Q){var B=this,$=B.constructor;if(A===void 0)A=$.precision,Q=$.rounding;else if(BY(A,1,xC),Q===void 0)Q=$.rounding;else BY(Q,0,8);return qA(new $(B),A,Q)};d1.toString=function(){var A=this,Q=A.constructor,B=DE(A,A.e<=Q.toExpNeg||A.e>=Q.toExpPos);return A.isNeg()&&!A.isZero()?"-"+B:B};d1.truncated=d1.trunc=function(){return qA(new this.constructor(this),this.e+1,1)};d1.valueOf=d1.toJSON=function(){var A=this,Q=A.constructor,B=DE(A,A.e<=Q.toExpNeg||A.e>=Q.toExpPos);return A.isNeg()?"-"+B:B};function yQ(A){var Q,B,$,J=A.length-1,Y="",Z=A[0];if(J>0){Y+=Z;for(Q=1;Q<J;Q++){if($=A[Q]+"",B=hA-$.length,B)Y+=kC(B);Y+=$}if(Z=A[Q],$=Z+"",B=hA-$.length,B)Y+=kC(B)}else if(Z===0)return"0";for(;Z%10===0;)Z/=10;return Y+Z}function BY(A,Q,B){if(A!==~~A||A<Q||A>B)throw Error(yC+A)}function M10(A,Q,B,$){var J,Y,Z,X;for(Y=A[0];Y>=10;Y/=10)--Q;if(--Q<0)Q+=hA,J=0;else J=Math.ceil((Q+1)/hA),Q%=hA;if(Y=X7(10,hA-Q),X=A[J]%Y|0,$==null)if(Q<3){if(Q==0)X=X/100|0;else if(Q==1)X=X/10|0;Z=B<4&&X==99999||B>3&&X==49999||X==50000||X==0}else Z=(B<4&&X+1==Y||B>3&&X+1==Y/2)&&(A[J+1]/Y/100|0)==X7(10,Q-2)-1||(X==Y/2||X==0)&&(A[J+1]/Y/100|0)==0;else if(Q<4){if(Q==0)X=X/1000|0;else if(Q==1)X=X/100|0;else if(Q==2)X=X/10|0;Z=($||B<4)&&X==9999||!$&&B>3&&X==4999}else Z=(($||B<4)&&X+1==Y||!$&&B>3&&X+1==Y/2)&&(A[J+1]/Y/1000|0)==X7(10,Q-3)-1;return Z}function HW0(A,Q,B){var $,J=[0],Y,Z=0,X=A.length;for(;Z<X;){for(Y=J.length;Y--;)J[Y]*=Q;J[0]+=Z$1.indexOf(A.charAt(Z++));for($=0;$<J.length;$++)if(J[$]>B-1){if(J[$+1]===void 0)J[$+1]=0;J[$+1]+=J[$]/B|0,J[$]%=B}}return J.reverse()}function lY8(A,Q){var B,$,J;if(Q.isZero())return Q;if($=Q.d.length,$<32)B=Math.ceil($/3),J=(1/CW0(4,B)).toString();else B=16,J="2.3283064365386962890625e-10";A.precision+=B,Q=kh(A,1,Q.times(J),new A(1));for(var Y=B;Y--;){var Z=Q.times(Q);Q=Z.times(Z).minus(Z).times(8).plus(1)}return A.precision-=B,Q}var h8=function(){function A($,J,Y){var Z,X=0,F=$.length;for($=$.slice();F--;)Z=$[F]*J+X,$[F]=Z%Y|0,X=Z/Y|0;if(X)$.unshift(X);return $}function Q($,J,Y,Z){var X,F;if(Y!=Z)F=Y>Z?1:-1;else for(X=F=0;X<Y;X++)if($[X]!=J[X]){F=$[X]>J[X]?1:-1;break}return F}function B($,J,Y,Z){var X=0;for(;Y--;)$[Y]-=X,X=$[Y]<J[Y]?1:0,$[Y]=X*Z+$[Y]-J[Y];for(;!$[0]&&$.length>1;)$.shift()}return function($,J,Y,Z,X,F){var D,G,V,U,K,E,H,W,z,q,N,I,w,C,O,P,S,T,f,h,b=$.constructor,y=$.s==J.s?1:-1,u=$.d,m=J.d;if(!u||!u[0]||!m||!m[0])return new b(!$.s||!J.s||(u?m&&u[0]==m[0]:!m)?NaN:u&&u[0]==0||!m?y*0:y/0);if(F)K=1,G=$.e-J.e;else F=AV,K=hA,G=_B($.e/K)-_B(J.e/K);f=m.length,S=u.length,z=new b(y),q=z.d=[];for(V=0;m[V]==(u[V]||0);V++);if(m[V]>(u[V]||0))G--;if(Y==null)C=Y=b.precision,Z=b.rounding;else if(X)C=Y+($.e-J.e)+1;else C=Y;if(C<0)q.push(1),E=!0;else{if(C=C/K+2|0,V=0,f==1){U=0,m=m[0],C++;for(;(V<S||U)&&C--;V++)O=U*F+(u[V]||0),q[V]=O/m|0,U=O%m|0;E=U||V<S}else{if(U=F/(m[0]+1)|0,U>1)m=A(m,U,F),u=A(u,U,F),f=m.length,S=u.length;P=f,N=u.slice(0,f),I=N.length;for(;I<f;)N[I++]=0;if(h=m.slice(),h.unshift(0),T=m[0],m[1]>=F/2)++T;do{if(U=0,D=Q(m,N,f,I),D<0){if(w=N[0],f!=I)w=w*F+(N[1]||0);if(U=w/T|0,U>1){if(U>=F)U=F-1;if(H=A(m,U,F),W=H.length,I=N.length,D=Q(H,N,W,I),D==1)U--,B(H,f<W?h:m,W,F)}else{if(U==0)D=U=1;H=m.slice()}if(W=H.length,W<I)H.unshift(0);if(B(N,H,I,F),D==-1){if(I=N.length,D=Q(m,N,f,I),D<1)U++,B(N,f<I?h:m,I,F)}I=N.length}else if(D===0)U++,N=[0];if(q[V++]=U,D&&N[0])N[I++]=u[P]||0;else N=[u[P]],I=1}while((P++<S||N[0]!==void 0)&&C--);E=N[0]!==void 0}if(!q[0])q.shift()}if(K==1)z.e=G,$BA=E;else{for(V=1,U=q[0];U>=10;U/=10)V++;z.e=V+G*K-1,qA(z,X?Y+z.e+1:Y,Z,E)}return z}}();function qA(A,Q,B,$){var J,Y,Z,X,F,D,G,V,U,K=A.constructor;A:if(Q!=null){if(V=A.d,!V)return A;for(J=1,X=V[0];X>=10;X/=10)J++;if(Y=Q-J,Y<0)Y+=hA,Z=Q,G=V[U=0],F=G/X7(10,J-Z-1)%10|0;else if(U=Math.ceil((Y+1)/hA),X=V.length,U>=X)if($){for(;X++<=U;)V.push(0);G=F=0,J=1,Y%=hA,Z=Y-hA+1}else break A;else{G=X=V[U];for(J=1;X>=10;X/=10)J++;Y%=hA,Z=Y-hA+J,F=Z<0?0:G/X7(10,J-Z-1)%10|0}if($=$||Q<0||V[U+1]!==void 0||(Z<0?G:G%X7(10,J-Z-1)),D=B<4?(F||$)&&(B==0||B==(A.s<0?3:2)):F>5||F==5&&(B==4||$||B==6&&(Y>0?Z>0?G/X7(10,J-Z):0:V[U-1])%10&1||B==(A.s<0?8:7)),Q<1||!V[0]){if(V.length=0,D)Q-=A.e+1,V[0]=X7(10,(hA-Q%hA)%hA),A.e=-Q||0;else V[0]=A.e=0;return A}if(Y==0)V.length=U,X=1,U--;else V.length=U+1,X=X7(10,hA-Y),V[U]=Z>0?(G/X7(10,J-Z)%X7(10,Z)|0)*X:0;if(D)for(;;)if(U==0){for(Y=1,Z=V[0];Z>=10;Z/=10)Y++;Z=V[0]+=X;for(X=1;Z>=10;Z/=10)X++;if(Y!=X){if(A.e++,V[0]==AV)V[0]=1}break}else{if(V[U]+=X,V[U]!=AV)break;V[U--]=0,X=1}for(Y=V.length;V[--Y]===0;)V.pop()}if(Q6){if(A.e>K.maxE)A.d=null,A.e=NaN;else if(A.e<K.minE)A.e=0,A.d=[0]}return A}function DE(A,Q,B){if(!A.isFinite())return VBA(A);var $,J=A.e,Y=yQ(A.d),Z=Y.length;if(Q){if(B&&($=B-Z)>0)Y=Y.charAt(0)+"."+Y.slice(1)+kC($);else if(Z>1)Y=Y.charAt(0)+"."+Y.slice(1);Y=Y+(A.e<0?"e":"e+")+A.e}else if(J<0){if(Y="0."+kC(-J-1)+Y,B&&($=B-Z)>0)Y+=kC($)}else if(J>=Z){if(Y+=kC(J+1-Z),B&&($=B-J-1)>0)Y=Y+"."+kC($)}else{if(($=J+1)<Z)Y=Y.slice(0,$)+"."+Y.slice($);if(B&&($=B-Z)>0){if(J+1===Z)Y+=".";Y+=kC($)}}return Y}function wW0(A,Q){var B=A[0];for(Q*=hA;B>=10;B/=10)Q++;return Q}function NW0(A,Q,B){if(Q>cY8){if(Q6=!0,B)A.precision=B;throw Error(JBA)}return qA(new A(zW0),Q,1,!0)}function FE(A,Q,B){if(Q>F$1)throw Error(JBA);return qA(new A(qW0),Q,B,!0)}function FBA(A){var Q=A.length-1,B=Q*hA+1;if(Q=A[Q],Q){for(;Q%10==0;Q/=10)B--;for(Q=A[0];Q>=10;Q/=10)B++}return B}function kC(A){var Q="";for(;A--;)Q+="0";return Q}function DBA(A,Q,B,$){var J,Y=new A(1),Z=Math.ceil($/hA+4);Q6=!1;for(;;){if(B%2){if(Y=Y.times(Q),QBA(Y.d,Z))J=!0}if(B=_B(B/2),B===0){if(B=Y.d.length-1,J&&Y.d[B]===0)++Y.d[B];break}Q=Q.times(Q),QBA(Q.d,Z)}return Q6=!0,Y}function ABA(A){return A.d[A.d.length-1]&1}function GBA(A,Q,B){var $,J,Y=new A(Q[0]),Z=0;for(;++Z<Q.length;){if(J=new A(Q[Z]),!J.s){Y=J;break}if($=Y.cmp(J),$===B||$===0&&Y.s===B)Y=J}return Y}function D$1(A,Q){var B,$,J,Y,Z,X,F,D=0,G=0,V=0,U=A.constructor,K=U.rounding,E=U.precision;if(!A.d||!A.d[0]||A.e>17)return new U(A.d?!A.d[0]?1:A.s<0?0:1/0:A.s?A.s<0?0:A:NaN);if(Q==null)Q6=!1,F=E;else F=Q;X=new U(0.03125);while(A.e>-2)A=A.times(X),V+=5;$=Math.log(X7(2,V))/Math.LN10*2+5|0,F+=$,B=Y=Z=new U(1),U.precision=F;for(;;){if(Y=qA(Y.times(A),F,1),B=B.times(++G),X=Z.plus(h8(Y,B,F,1)),yQ(X.d).slice(0,F)===yQ(Z.d).slice(0,F)){J=V;while(J--)Z=qA(Z.times(Z),F,1);if(Q==null)if(D<3&&M10(Z.d,F-$,K,D))U.precision=F+=10,B=Y=X=new U(1),G=0,D++;else return qA(Z,U.precision=E,K,Q6=!0);else return U.precision=E,Z}Z=X}}function vC(A,Q){var B,$,J,Y,Z,X,F,D,G,V,U,K=1,E=10,H=A,W=H.d,z=H.constructor,q=z.rounding,N=z.precision;if(H.s<0||!W||!W[0]||!H.e&&W[0]==1&&W.length==1)return new z(W&&!W[0]?-1/0:H.s!=1?NaN:W?0:H);if(Q==null)Q6=!1,G=N;else G=Q;if(z.precision=G+=E,B=yQ(W),$=B.charAt(0),Math.abs(Y=H.e)<1500000000000000){while($<7&&$!=1||$==1&&B.charAt(1)>3)H=H.times(A),B=yQ(H.d),$=B.charAt(0),K++;if(Y=H.e,$>1)H=new z("0."+B),Y++;else H=new z($+"."+B.slice(1))}else return D=NW0(z,G+2,N).times(Y+""),H=vC(new z($+"."+B.slice(1)),G-E).plus(D),z.precision=N,Q==null?qA(H,N,q,Q6=!0):H;V=H,F=Z=H=h8(H.minus(1),H.plus(1),G,1),U=qA(H.times(H),G,1),J=3;for(;;){if(Z=qA(Z.times(U),G,1),D=F.plus(h8(Z,new z(J),G,1)),yQ(D.d).slice(0,G)===yQ(F.d).slice(0,G)){if(F=F.times(2),Y!==0)F=F.plus(NW0(z,G+2,N).times(Y+""));if(F=h8(F,new z(K),G,1),Q==null)if(M10(F.d,G-E,q,X))z.precision=G+=E,D=Z=H=h8(V.minus(1),V.plus(1),G,1),U=qA(H.times(H),G,1),J=X=1;else return qA(F,z.precision=N,q,Q6=!0);else return z.precision=N,F}F=D,J+=2}}function VBA(A){return String(A.s*A.s/0)}function WW0(A,Q){var B,$,J;if((B=Q.indexOf("."))>-1)Q=Q.replace(".","");if(($=Q.search(/e/i))>0){if(B<0)B=$;B+=+Q.slice($+1),Q=Q.substring(0,$)}else if(B<0)B=Q.length;for($=0;Q.charCodeAt($)===48;$++);for(J=Q.length;Q.charCodeAt(J-1)===48;--J);if(Q=Q.slice($,J),Q){if(J-=$,A.e=B=B-$-1,A.d=[],$=(B+1)%hA,B<0)$+=hA;if($<J){if($)A.d.push(+Q.slice(0,$));for(J-=hA;$<J;)A.d.push(+Q.slice($,$+=hA));Q=Q.slice($),$=hA-Q.length}else $-=J;for(;$--;)Q+="0";if(A.d.push(+Q),Q6){if(A.e>A.constructor.maxE)A.d=null,A.e=NaN;else if(A.e<A.constructor.minE)A.e=0,A.d=[0]}}else A.e=0,A.d=[0];return A}function iY8(A,Q){var B,$,J,Y,Z,X,F,D,G;if(Q.indexOf("_")>-1){if(Q=Q.replace(/(\d)_(?=\d)/g,"$1"),XBA.test(Q))return WW0(A,Q)}else if(Q==="Infinity"||Q==="NaN"){if(!+Q)A.s=NaN;return A.e=NaN,A.d=null,A}if(mY8.test(Q))B=16,Q=Q.toLowerCase();else if(gY8.test(Q))B=2;else if(pY8.test(Q))B=8;else throw Error(yC+Q);if(Y=Q.search(/p/i),Y>0)F=+Q.slice(Y+1),Q=Q.substring(2,Y);else Q=Q.slice(2);if(Y=Q.indexOf("."),Z=Y>=0,$=A.constructor,Z)Q=Q.replace(".",""),X=Q.length,Y=X-Y,J=DBA($,new $(B),Y,Y*2);D=HW0(Q,B,AV),G=D.length-1;for(Y=G;D[Y]===0;--Y)D.pop();if(Y<0)return new $(A.s*0);if(A.e=wW0(D,G),A.d=D,Q6=!1,Z)A=h8(A,J,X*4);if(F)A=A.times(Math.abs(F)<54?X7(2,F):L10.pow(2,F));return Q6=!0,A}function nY8(A,Q){var B,$=Q.d.length;if($<3)return Q.isZero()?Q:kh(A,2,Q,Q);B=1.4*Math.sqrt($),B=B>16?16:B|0,Q=Q.times(1/CW0(5,B)),Q=kh(A,2,Q,Q);var J,Y=new A(5),Z=new A(16),X=new A(20);for(;B--;)J=Q.times(Q),Q=Q.times(Y.plus(J.times(Z.times(J).minus(X))));return Q}function kh(A,Q,B,$,J){var Y,Z,X,F,D=1,G=A.precision,V=Math.ceil(G/hA);Q6=!1,F=B.times(B),X=new A($);for(;;){if(Z=h8(X.times(F),new A(Q++*Q++),G,1),X=J?$.plus(Z):$.minus(Z),$=h8(Z.times(F),new A(Q++*Q++),G,1),Z=X.plus($),Z.d[V]!==void 0){for(Y=V;Z.d[Y]===X.d[Y]&&Y--;);if(Y==-1)break}Y=X,X=$,$=Z,Z=Y,D++}return Q6=!0,Z.d.length=V+1,Z}function CW0(A,Q){var B=A;while(--Q)B*=A;return B}function UBA(A,Q){var B,$=Q.s<0,J=FE(A,A.precision,1),Y=J.times(0.5);if(Q=Q.abs(),Q.lte(Y))return Iz=$?4:1,Q;if(B=Q.divToInt(J),B.isZero())Iz=$?3:2;else{if(Q=Q.minus(B.times(J)),Q.lte(Y))return Iz=ABA(B)?$?2:3:$?4:1,Q;Iz=ABA(B)?$?1:4:$?3:2}return Q.minus(J).abs()}function G$1(A,Q,B,$){var J,Y,Z,X,F,D,G,V,U,K=A.constructor,E=B!==void 0;if(E)if(BY(B,1,xC),$===void 0)$=K.rounding;else BY($,0,8);else B=K.precision,$=K.rounding;if(!A.isFinite())G=VBA(A);else{if(G=DE(A),Z=G.indexOf("."),E){if(J=2,Q==16)B=B*4-3;else if(Q==8)B=B*3-2}else J=Q;if(Z>=0)G=G.replace(".",""),U=new K(1),U.e=G.length-Z,U.d=HW0(DE(U),10,J),U.e=U.d.length;V=HW0(G,10,J),Y=F=V.length;for(;V[--F]==0;)V.pop();if(!V[0])G=E?"0p+0":"0";else{if(Z<0)Y--;else A=new K(A),A.d=V,A.e=Y,A=h8(A,U,B,$,0,J),V=A.d,Y=A.e,D=$BA;if(Z=V[B],X=J/2,D=D||V[B+1]!==void 0,D=$<4?(Z!==void 0||D)&&($===0||$===(A.s<0?3:2)):Z>X||Z===X&&($===4||D||$===6&&V[B-1]&1||$===(A.s<0?8:7)),V.length=B,D){for(;++V[--B]>J-1;)if(V[B]=0,!B)++Y,V.unshift(1)}for(F=V.length;!V[F-1];--F);for(Z=0,G="";Z<F;Z++)G+=Z$1.charAt(V[Z]);if(E){if(F>1)if(Q==16||Q==8){Z=Q==16?4:3;for(--F;F%Z;F++)G+="0";V=HW0(G,J,Q);for(F=V.length;!V[F-1];--F);for(Z=1,G="1.";Z<F;Z++)G+=Z$1.charAt(V[Z])}else G=G.charAt(0)+"."+G.slice(1);G=G+(Y<0?"p":"p+")+Y}else if(Y<0){for(;++Y;)G="0"+G;G="0."+G}else if(++Y>F)for(Y-=F;Y--;)G+="0";else if(Y<F)G=G.slice(0,Y)+"."+G.slice(Y)}G=(Q==16?"0x":Q==2?"0b":Q==8?"0o":"")+G}return A.s<0?"-"+G:G}function QBA(A,Q){if(A.length>Q)return A.length=Q,!0}function aY8(A){return new this(A).abs()}function oY8(A){return new this(A).acos()}function rY8(A){return new this(A).acosh()}function sY8(A,Q){return new this(A).plus(Q)}function tY8(A){return new this(A).asin()}function eY8(A){return new this(A).asinh()}function AZ8(A){return new this(A).atan()}function QZ8(A){return new this(A).atanh()}function BZ8(A,Q){A=new this(A),Q=new this(Q);var B,$=this.precision,J=this.rounding,Y=$+4;if(!A.s||!Q.s)B=new this(NaN);else if(!A.d&&!Q.d)B=FE(this,Y,1).times(Q.s>0?0.25:0.75),B.s=A.s;else if(!Q.d||A.isZero())B=Q.s<0?FE(this,$,J):new this(0),B.s=A.s;else if(!A.d||Q.isZero())B=FE(this,Y,1).times(0.5),B.s=A.s;else if(Q.s<0)this.precision=Y,this.rounding=1,B=this.atan(h8(A,Q,Y,1)),Q=FE(this,Y,1),this.precision=$,this.rounding=J,B=A.s<0?B.minus(Q):B.plus(Q);else B=this.atan(h8(A,Q,Y,1));return B}function $Z8(A){return new this(A).cbrt()}function JZ8(A){return qA(A=new this(A),A.e+1,2)}function YZ8(A,Q,B){return new this(A).clamp(Q,B)}function ZZ8(A){if(!A||typeof A!=="object")throw Error(IW0+"Object expected");var Q,B,$,J=A.defaults===!0,Y=["precision",1,xC,"rounding",0,8,"toExpNeg",-Sh,0,"toExpPos",0,Sh,"maxE",0,Sh,"minE",-Sh,0,"modulo",0,9];for(Q=0;Q<Y.length;Q+=3){if(B=Y[Q],J)this[B]=X$1[B];if(($=A[B])!==void 0)if(_B($)===$&&$>=Y[Q+1]&&$<=Y[Q+2])this[B]=$;else throw Error(yC+B+": "+$)}if(B="crypto",J)this[B]=X$1[B];if(($=A[B])!==void 0)if($===!0||$===!1||$===0||$===1)if($)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[B]=!0;else throw Error(YBA);else this[B]=!1;else throw Error(yC+B+": "+$);return this}function XZ8(A){return new this(A).cos()}function FZ8(A){return new this(A).cosh()}function KBA(A){var Q,B,$;function J(Y){var Z,X,F,D=this;if(!(D instanceof J))return new J(Y);if(D.constructor=J,BBA(Y)){if(D.s=Y.s,Q6)if(!Y.d||Y.e>J.maxE)D.e=NaN,D.d=null;else if(Y.e<J.minE)D.e=0,D.d=[0];else D.e=Y.e,D.d=Y.d.slice();else D.e=Y.e,D.d=Y.d?Y.d.slice():Y.d;return}if(F=typeof Y,F==="number"){if(Y===0){D.s=1/Y<0?-1:1,D.e=0,D.d=[0];return}if(Y<0)Y=-Y,D.s=-1;else D.s=1;if(Y===~~Y&&Y<1e7){for(Z=0,X=Y;X>=10;X/=10)Z++;if(Q6)if(Z>J.maxE)D.e=NaN,D.d=null;else if(Z<J.minE)D.e=0,D.d=[0];else D.e=Z,D.d=[Y];else D.e=Z,D.d=[Y];return}if(Y*0!==0){if(!Y)D.s=NaN;D.e=NaN,D.d=null;return}return WW0(D,Y.toString())}if(F==="string"){if((X=Y.charCodeAt(0))===45)Y=Y.slice(1),D.s=-1;else{if(X===43)Y=Y.slice(1);D.s=1}return XBA.test(Y)?WW0(D,Y):iY8(D,Y)}if(F==="bigint"){if(Y<0)Y=-Y,D.s=-1;else D.s=1;return WW0(D,Y.toString())}throw Error(yC+Y)}if(J.prototype=d1,J.ROUND_UP=0,J.ROUND_DOWN=1,J.ROUND_CEIL=2,J.ROUND_FLOOR=3,J.ROUND_HALF_UP=4,J.ROUND_HALF_DOWN=5,J.ROUND_HALF_EVEN=6,J.ROUND_HALF_CEIL=7,J.ROUND_HALF_FLOOR=8,J.EUCLID=9,J.config=J.set=ZZ8,J.clone=KBA,J.isDecimal=BBA,J.abs=aY8,J.acos=oY8,J.acosh=rY8,J.add=sY8,J.asin=tY8,J.asinh=eY8,J.atan=AZ8,J.atanh=QZ8,J.atan2=BZ8,J.cbrt=$Z8,J.ceil=JZ8,J.clamp=YZ8,J.cos=XZ8,J.cosh=FZ8,J.div=DZ8,J.exp=GZ8,J.floor=VZ8,J.hypot=UZ8,J.ln=KZ8,J.log=EZ8,J.log10=WZ8,J.log2=HZ8,J.max=zZ8,J.min=qZ8,J.mod=NZ8,J.mul=IZ8,J.pow=wZ8,J.random=CZ8,J.round=MZ8,J.sign=LZ8,J.sin=OZ8,J.sinh=jZ8,J.sqrt=RZ8,J.sub=PZ8,J.sum=_Z8,J.tan=TZ8,J.tanh=SZ8,J.trunc=kZ8,A===void 0)A={};if(A){if(A.defaults!==!0){$=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"];for(Q=0;Q<$.length;)if(!A.hasOwnProperty(B=$[Q++]))A[B]=this[B]}}return J.config(A),J}function DZ8(A,Q){return new this(A).div(Q)}function GZ8(A){return new this(A).exp()}function VZ8(A){return qA(A=new this(A),A.e+1,3)}function UZ8(){var A,Q,B=new this(0);Q6=!1;for(A=0;A<arguments.length;)if(Q=new this(arguments[A++]),!Q.d){if(Q.s)return Q6=!0,new this(1/0);B=Q}else if(B.d)B=B.plus(Q.times(Q));return Q6=!0,B.sqrt()}function BBA(A){return A instanceof L10||A&&A.toStringTag===ZBA||!1}function KZ8(A){return new this(A).ln()}function EZ8(A,Q){return new this(A).log(Q)}function HZ8(A){return new this(A).log(2)}function WZ8(A){return new this(A).log(10)}function zZ8(){return GBA(this,arguments,-1)}function qZ8(){return GBA(this,arguments,1)}function NZ8(A,Q){return new this(A).mod(Q)}function IZ8(A,Q){return new this(A).mul(Q)}function wZ8(A,Q){return new this(A).pow(Q)}function CZ8(A){var Q,B,$,J,Y=0,Z=new this(1),X=[];if(A===void 0)A=this.precision;else BY(A,1,xC);if($=Math.ceil(A/hA),!this.crypto)for(;Y<$;)X[Y++]=Math.random()*1e7|0;else if(crypto.getRandomValues){Q=crypto.getRandomValues(new Uint32Array($));for(;Y<$;)if(J=Q[Y],J>=4290000000)Q[Y]=crypto.getRandomValues(new Uint32Array(1))[0];else X[Y++]=J%1e7}else if(crypto.randomBytes){Q=crypto.randomBytes($*=4);for(;Y<$;)if(J=Q[Y]+(Q[Y+1]<<8)+(Q[Y+2]<<16)+((Q[Y+3]&127)<<24),J>=2140000000)crypto.randomBytes(4).copy(Q,Y);else X.push(J%1e7),Y+=4;Y=$/4}else throw Error(YBA);if($=X[--Y],A%=hA,$&&A)J=X7(10,hA-A),X[Y]=($/J|0)*J;for(;X[Y]===0;Y--)X.pop();if(Y<0)B=0,X=[0];else{B=-1;for(;X[0]===0;B-=hA)X.shift();for($=1,J=X[0];J>=10;J/=10)$++;if($<hA)B-=hA-$}return Z.e=B,Z.d=X,Z}function MZ8(A){return qA(A=new this(A),A.e+1,this.rounding)}function LZ8(A){return A=new this(A),A.d?A.d[0]?A.s:0*A.s:A.s||NaN}function OZ8(A){return new this(A).sin()}function jZ8(A){return new this(A).sinh()}function RZ8(A){return new this(A).sqrt()}function PZ8(A,Q){return new this(A).sub(Q)}function _Z8(){var A=0,Q=arguments,B=new this(Q[A]);Q6=!1;for(;B.s&&++A<Q.length;)B=B.plus(Q[A]);return Q6=!0,qA(B,this.precision,this.rounding)}function TZ8(A){return new this(A).tan()}function SZ8(A){return new this(A).tanh()}function kZ8(A){return qA(A=new this(A),A.e+1,1)}d1[Symbol.for("nodejs.util.inspect.custom")]=d1.toString;d1[Symbol.toStringTag]="Decimal";var L10=d1.constructor=KBA(X$1);zW0=new L10(zW0);qW0=new L10(qW0);var V$1=2;function vZ8(A,Q){let B=Q.decimalPlaces==="more-if-tiny"?Math.abs(A)<0.01?V$1+1:V$1:Q.decimalPlaces??V$1,$=Q.intent==="balance"?A<0?"expand":"trunc":"halfExpand";return{decimalPlaces:B,roundingMode:$}}function fC(A,Q){let{decimalPlaces:B,roundingMode:$}=vZ8(A,Q),J=A%1===0&&!Q.alwaysShowCents?A.toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:0,roundingMode:$}):A.toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:B,maximumFractionDigits:B,roundingMode:$});return Q.includeCurrencyCode?`${J} USD`:J}function O10(A){if(A>=1e6)return`${Math.round(A/1e6)}M`;if(A>=1000)return`${Math.round(A/1000)}k`;return A.toString()}function yZ8(A){if(!A)return"";let Q=A.split("-");if(Q.length>=2)return Q.slice(0,2).join("-");return A}function EBA(A){let Q=[],B=(A.inputTokens??0)+(A.cacheCreationInputTokens??0),$=A.cacheReadInputTokens??0;if(B>0)Q.push(`${O10(B)} in`);if($>0)Q.push(`${O10($)} cache read`);if(A.outputTokens)Q.push(`${O10(A.outputTokens)} out`);if(A.model)Q.push(yZ8(A.model));if(Q.length>0)return`(${Q.join(", ")})`;return""}function bC(A,Q){let{colors:B,dim:$}=Q,J=[];if(A.totalCostUSD===null)return J;let Y=A.costBreakdown,Z=Y?.freeUSD??0,X=Y?.paidUSD??0;if(Z===0&&X===0)return J;let D={decimalPlaces:"more-if-tiny",intent:"cost"};if(X===0)J.push(new M(fC(Z,D),new x({color:B.foreground,dim:$}))),J.push(new M(" (free)",new x({color:B.foreground,dim:$})));else if(Z>0)J.push(new M(fC(Z,D),new x({color:B.foreground,dim:$}))),J.push(new M(" (free)",new x({color:B.foreground,dim:$}))),J.push(new M(" + ",new x({color:B.foreground,dim:$}))),J.push(new M(fC(X,D),new x({color:B.foreground,dim:$,bold:!$})));else J.push(new M(fC(X,D),new x({color:B.foreground,dim:$,bold:!$})));return J}class U$1 extends GA{}class K$1 extends GA{}function xZ8(A,Q){if(Q.code==="auth-required")return"You must be logged in to view thread usage. Run `amp login` first.";if(Q.code==="thread-not-found")return`Thread ${A} not found.`;return`Failed to load thread usage: ${Q.message??Q.code}`}function fZ8(A,Q){let B=_0.of(Q),{colors:$}=B,J=bC(A,{colors:{foreground:$.foreground}}),Y=[];if(J.length>0)Y.push(new M("Total: ",new x({color:$.mutedForeground}))),Y.push(...J);else if(A.totalCostUSD===null)Y.push(new M("Usage information is currently unavailable."));else Y.push(new M("No usage recorded for this thread yet."));if(A.costBreakdownURL)Y.push(new M(`
5287
5287
 
5288
- `)),Y.push(new M("Details: ",new x({color:$.mutedForeground}))),Y.push(new M(A.costBreakdownURL,new x({color:B.app.link})));return new i({text:new M("",void 0,Y)})}function bZ8(A,Q,B){let $=fZ8(A,Q);if(!A.costBreakdownURL)return new cA({header:"Thread Cost",minWidth:80,maxWidth:100,onDismiss:B,child:$});let J=A.costBreakdownURL,Y=new N4(()=>{return MA.maybeInvoke(Q,new P$(J,"Cost breakdown URL copied to clipboard","Failed to copy cost breakdown URL")),"handled"}),Z=new N4(()=>{return L6(Q,J),"handled"});return new cA({header:"Thread Cost",minWidth:80,maxWidth:100,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["o"],label:"open in browser"},{keys:["y"],label:"copy url"}],onDismiss:B,child:new MA({actions:new Map([[U$1,Y],[K$1,Z]]),child:new V8({debugLabel:"ThreadCostShortcuts",shortcuts:new Map([[b1.key("o"),new K$1],[b1.key("y"),new U$1]]),child:new s4({autofocus:!0,debugLabel:"ThreadCostBody",child:$})})})})}function HBA(A){return{noun:"thread",verb:"show cost",description:"Show usage cost for the active thread",keywords:["usage","credits","billing","spend"],get status(){return A.getActiveThreadID()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(Q,B,$)=>{let J=A.getActiveThreadID();if(!J)return;try{let Y=await yA.threadDisplayCostInfo({threadID:J},{config:A.configService});if(!Y.ok){A.toastController.show(xZ8(J,Y.error),"error",5000),$();return}Q.push(bZ8(Y.result,B,$))}catch(Y){j.error("Failed to load Neo thread cost",{error:Y,threadID:J}),A.toastController.show(`Failed to show thread cost: ${Y instanceof Error?Y.message:String(Y)}`,"error",5000),$()}}}}var uZ8=250,hZ8=2000;class E$1 extends y0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;showNeoWelcome;onNeoWelcomeDismissed;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.showNeoWelcome=A.showNeoWelcome??!1,this.onNeoWelcomeDismissed=A.onNeoWelcomeDismissed,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.initialUserInput=A.initialUserInput,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new zBA}}class zBA extends v0{editorController=new k3;commandPalette=new Z00(this);commandRegistry=new yQ1;toastController=new z21;exitHintTimer=new du(this,1000);ideStatus=new s3(this,{});threadNavigationHistory=new PQ1;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;debugOverlayVisible=!1;focusDebugVisible=!1;agentModeCostInfo=null;unregisterCommands=null;pluginIntegration=null;configReloadSubscription=null;configReloadToastTimer=null;pendingConfigReloadToastType=null;lastConfigReloadToast=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.connectToExistingThread(A,{recordNavigation:!0})};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 J9A({configService:this.widget.configService},A,Q,B)};setThreadVisibility=(A,Q)=>{return Y9A({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await G5A({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await V5A({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 U5A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(C$.getInstance().interceptConsole(),this.widget.showNeoWelcome)this.neoWelcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:Q,error:B})=>{if(j.error("Neo failed to connect to thread",{threadID:Q,error:B}),!Q)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configReloadSubscription=this.widget.configService.configReloadEvents.subscribe((Q)=>this.scheduleConfigReloadToast(Q)),this.configSubscription=this.widget.configService.config.subscribe((Q)=>{this.applyDraftThreadSettingsSeed(c90(Q.settings))}),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID){let Q={};if(A)Q.initialUserInput=A;this.connectToExistingThread(this.widget.initialThreadID,Q)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.pluginIntegration=new RQ1({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,neoContext:this.widget.neoContext,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread}),this.pluginIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=d4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}scheduleConfigReloadToast(A){if(this.pendingConfigReloadToastType=this.pendingConfigReloadToastType==="failed"||A.type==="failed"?"failed":"succeeded",this.configReloadToastTimer)clearTimeout(this.configReloadToastTimer);this.configReloadToastTimer=setTimeout(()=>{this.flushConfigReloadToast()},uZ8),this.configReloadToastTimer.unref()}flushConfigReloadToast(){let A=this.pendingConfigReloadToastType;if(this.pendingConfigReloadToastType=null,this.configReloadToastTimer=null,!A)return;let Q=Date.now();if(this.lastConfigReloadToast?.type===A&&Q-this.lastConfigReloadToast.shownAt<hZ8)return;switch(this.lastConfigReloadToast={type:A,shownAt:Q},A){case"succeeded":this.toastController.show("Config reloaded","success",1500);break;case"failed":this.toastController.show("Config reload failed","error",5000);break}}registerAppCommands(){let A=this,Q=this.widget.neoContext.pluginService?Q9A({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,toastController:this.toastController}):[],$=[{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(J,Y,Z)=>{J.pushWithDismiss((X)=>kB1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:X,onThreadSelected:Z}))}},{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(J,Y,Z)=>{A.navigateBack(),Z()}},HBA({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(J,Y,Z)=>{A.navigateForward(),Z()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new cQ1({mcpServers:this.widget.neoContext.mcpServers,onDismiss:Z}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",keywords:["tools","toolbox"],status:{type:"enabled"},run:(J)=>{J.pushWithDismiss((Y)=>new A$1({toolboxes:this.widget.neoContext.toolboxes,onDismiss:Y}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async(J,Y,Z)=>{try{await L6(Y,"https://ampcode.com/chronicle")}finally{Z()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{oJ(this.widget.neoContext.settingsFilePath).catch((J)=>{j.error("Failed to open settings file in editor",{error:J})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(J,Y,Z)=>{J.pushWithDismiss((X)=>new pQ1({onCancel:X,onSelect:(F)=>{this.handleIdeSelection(F),Z()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new hQ1({commands:_$.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show neo welcome",description:"Show the Neo welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(J,Y,Z)=>{Z(),A.showNeoWelcome()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new cA({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new i({text:new M(G21({version:"0.0.1777680871-g5fc25d",buildTimestamp:"2026-05-02T00:18:10.627Z",buildType:"'release'"}))})}))}},{noun:"amp",verb:"reconnect",description:"Disconnect and reconnect the active thread",keywords:["connection","disconnect","socket","debug"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: reconnect with no active thread"}},run:(J,Y,Z)=>{A.reconnectActiveThread(),Z()}},{noun:"amp",verb:"disconnect",description:"Disconnect the active thread without reconnecting",keywords:["connection","socket","debug","dev"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: disconnect with no active thread"}},run:(J,Y,Z)=>{A.disconnectActiveThread(),Z()}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:b1.ctrl("c"),status:{type:"enabled"},run:(J,Y)=>{MA.maybeInvoke(Y,new wh)}},...Q,...c2A(this.widget.neoContext.logFilePath)].map((J)=>this.commandRegistry.register(J));return()=>{for(let J of $)J()}}build(A){let Q=this.buildHints(),B=this.ideStatus.getValue(),$=new eB1({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,hints:Q,ideStatus:B}),J=J4.of(A),Z=[new d0({constraints:L1.tight(J.size.width,J.size.height),child:$})];if(this.commandPalette.isEnabled())Z.push(new QA({debugLabel:"CommandPaletteOverlay",child:new xQ1({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)Z.push(kB1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)Z.push(new QA({debugLabel:"NeoWelcomeDialogOverlay",child:new J$1({onDismiss:this.dismissNeoWelcome})}));if(Z.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.agentModeCostInfo)Z.push(new QA({debugLabel:"AgentModeCostModalOverlay",child:this.buildAgentModeCostModal(this.agentModeCostInfo)}));if(this.widget.neoContext.isInternalUser)Z.push(new gQ1({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:j10.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)Z.push(new mQ1);return new _9({neoContext:this.widget.neoContext,child:new _$({commandRegistry:this.commandRegistry,child:new OC({completionBuilder:this.widget.completionBuilder,child:new S3({controller:this.toastController,child:new MA({actions:this.buildActions(),child:new V8({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[b1.ctrl("c"),new iH0],[b1.ctrl("o"),new nH0],[b1.alt("i"),new oH0],[b1.alt("p"),new JC],[b1.ctrl("t"),new rH0]]),child:new s4({debugLabel:"AppShellFocus",child:new q21({controller:this.toastController,child:new HA({children:Z})})})})})})})})})}buildActions(){let A=new N4(()=>{if(aJ.hasAnyCopyableSelection())return aJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new N4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new N4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new N4(()=>{let V=this.activeThreadContext?.client.getThreadId();return this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(V),this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.writeTerminalTitle(void 0),this.activeThreadContext=null,this.connectingToThreadID=null}),"handled"}),J=new N4(()=>{return d4.instance.stop(),"handled"}),Y=new N4((V)=>{if(!V.text)return"ignored";return d4.instance.tuiInstance.clipboard.writeText(V.text).then(()=>{this.toastController.show(V.successMessage,"success",2000)}).catch((U)=>{j.error("Failed to copy Neo text to clipboard",{error:U}),this.toastController.show(V.failureMessage,"error",2000)}),"handled"}),Z=new N4(()=>{return d4.instance.toggleFrameStatsOverlay(),"handled"}),X=new N4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),F=new N4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";let V=this.activeThreadContext?.client.getThreadId();if(!V)return this.toastController.show("No active thread","error",2000),"handled";return j51(V).then((U)=>{this.toastController.show(ba4(U),"success",2000)}).catch((U)=>{let K=U instanceof Error?U.message:String(U);j.error("Failed to copy thread log",{error:U}),this.toastController.show(`Failed to copy thread log: ${K}`,"error",2000)}),"handled"}),D=new N4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"}),G=new N4((V)=>{return this.setState(()=>{this.agentModeCostInfo={agentMode:V.agentMode,speedCostMultiplier:V.speedCostMultiplier}}),"handled"});return new Map([[iH0,A],[B10,$],[wh,J],[P$,Y],[Y10,B],[nH0,Q],[oH0,X],[C_,F],[Z10,G],[JC,Z],[rH0,D]])}dismissAgentModeCostModal=()=>{if(!this.agentModeCostInfo)return;this.setState(()=>{this.agentModeCostInfo=null})};buildAgentModeCostModal(A){let Q=(S8(A.agentMode)?.displayName??A.agentMode).toLowerCase();return new cA({header:"Fast Mode Enabled",minWidth:54,maxWidth:72,footer:[{keys:["Esc"],label:"close"}],onDismiss:this.dismissAgentModeCostModal,child:new i({text:new M(`This agent mode now runs in fast mode.
5288
+ `)),Y.push(new M("Details: ",new x({color:$.mutedForeground}))),Y.push(new M(A.costBreakdownURL,new x({color:B.app.link})));return new i({text:new M("",void 0,Y)})}function bZ8(A,Q,B){let $=fZ8(A,Q);if(!A.costBreakdownURL)return new cA({header:"Thread Cost",minWidth:80,maxWidth:100,onDismiss:B,child:$});let J=A.costBreakdownURL,Y=new N4(()=>{return MA.maybeInvoke(Q,new P$(J,"Cost breakdown URL copied to clipboard","Failed to copy cost breakdown URL")),"handled"}),Z=new N4(()=>{return L6(Q,J),"handled"});return new cA({header:"Thread Cost",minWidth:80,maxWidth:100,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["o"],label:"open in browser"},{keys:["y"],label:"copy url"}],onDismiss:B,child:new MA({actions:new Map([[U$1,Y],[K$1,Z]]),child:new V8({debugLabel:"ThreadCostShortcuts",shortcuts:new Map([[b1.key("o"),new K$1],[b1.key("y"),new U$1]]),child:new s4({autofocus:!0,debugLabel:"ThreadCostBody",child:$})})})})}function HBA(A){return{noun:"thread",verb:"show cost",description:"Show usage cost for the active thread",keywords:["usage","credits","billing","spend"],get status(){return A.getActiveThreadID()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(Q,B,$)=>{let J=A.getActiveThreadID();if(!J)return;try{let Y=await yA.threadDisplayCostInfo({threadID:J},{config:A.configService});if(!Y.ok){A.toastController.show(xZ8(J,Y.error),"error",5000),$();return}Q.push(bZ8(Y.result,B,$))}catch(Y){j.error("Failed to load Neo thread cost",{error:Y,threadID:J}),A.toastController.show(`Failed to show thread cost: ${Y instanceof Error?Y.message:String(Y)}`,"error",5000),$()}}}}var uZ8=250,hZ8=2000;class E$1 extends y0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;showNeoWelcome;onNeoWelcomeDismissed;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.showNeoWelcome=A.showNeoWelcome??!1,this.onNeoWelcomeDismissed=A.onNeoWelcomeDismissed,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.initialUserInput=A.initialUserInput,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new zBA}}class zBA extends v0{editorController=new k3;commandPalette=new Z00(this);commandRegistry=new yQ1;toastController=new z21;exitHintTimer=new du(this,1000);ideStatus=new s3(this,{});threadNavigationHistory=new PQ1;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;debugOverlayVisible=!1;focusDebugVisible=!1;agentModeCostInfo=null;unregisterCommands=null;pluginIntegration=null;configReloadSubscription=null;configReloadToastTimer=null;pendingConfigReloadToastType=null;lastConfigReloadToast=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.connectToExistingThread(A,{recordNavigation:!0})};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 J9A({configService:this.widget.configService},A,Q,B)};setThreadVisibility=(A,Q)=>{return Y9A({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await G5A({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await V5A({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 U5A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(C$.getInstance().interceptConsole(),this.widget.showNeoWelcome)this.neoWelcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:Q,error:B})=>{if(j.error("Neo failed to connect to thread",{threadID:Q,error:B}),!Q)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configReloadSubscription=this.widget.configService.configReloadEvents.subscribe((Q)=>this.scheduleConfigReloadToast(Q)),this.configSubscription=this.widget.configService.config.subscribe((Q)=>{this.applyDraftThreadSettingsSeed(c90(Q.settings))}),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID){let Q={};if(A)Q.initialUserInput=A;this.connectToExistingThread(this.widget.initialThreadID,Q)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.pluginIntegration=new RQ1({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,neoContext:this.widget.neoContext,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread}),this.pluginIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=d4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}scheduleConfigReloadToast(A){if(this.pendingConfigReloadToastType=this.pendingConfigReloadToastType==="failed"||A.type==="failed"?"failed":"succeeded",this.configReloadToastTimer)clearTimeout(this.configReloadToastTimer);this.configReloadToastTimer=setTimeout(()=>{this.flushConfigReloadToast()},uZ8),this.configReloadToastTimer.unref()}flushConfigReloadToast(){let A=this.pendingConfigReloadToastType;if(this.pendingConfigReloadToastType=null,this.configReloadToastTimer=null,!A)return;let Q=Date.now();if(this.lastConfigReloadToast?.type===A&&Q-this.lastConfigReloadToast.shownAt<hZ8)return;switch(this.lastConfigReloadToast={type:A,shownAt:Q},A){case"succeeded":this.toastController.show("Config reloaded","success",1500);break;case"failed":this.toastController.show("Config reload failed","error",5000);break}}registerAppCommands(){let A=this,Q=this.widget.neoContext.pluginService?Q9A({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,toastController:this.toastController}):[],$=[{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(J,Y,Z)=>{J.pushWithDismiss((X)=>kB1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:X,onThreadSelected:Z}))}},{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(J,Y,Z)=>{A.navigateBack(),Z()}},HBA({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(J,Y,Z)=>{A.navigateForward(),Z()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new cQ1({mcpServers:this.widget.neoContext.mcpServers,onDismiss:Z}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",keywords:["tools","toolbox"],status:{type:"enabled"},run:(J)=>{J.pushWithDismiss((Y)=>new A$1({toolboxes:this.widget.neoContext.toolboxes,onDismiss:Y}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async(J,Y,Z)=>{try{await L6(Y,"https://ampcode.com/chronicle")}finally{Z()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{oJ(this.widget.neoContext.settingsFilePath).catch((J)=>{j.error("Failed to open settings file in editor",{error:J})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(J,Y,Z)=>{J.pushWithDismiss((X)=>new pQ1({onCancel:X,onSelect:(F)=>{this.handleIdeSelection(F),Z()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new hQ1({commands:_$.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show neo welcome",description:"Show the Neo welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(J,Y,Z)=>{Z(),A.showNeoWelcome()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new cA({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new i({text:new M(G21({version:"0.0.1777697948-g1a223c",buildTimestamp:"2026-05-02T05:02:48.212Z",buildType:"'release'"}))})}))}},{noun:"amp",verb:"reconnect",description:"Disconnect and reconnect the active thread",keywords:["connection","disconnect","socket","debug"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: reconnect with no active thread"}},run:(J,Y,Z)=>{A.reconnectActiveThread(),Z()}},{noun:"amp",verb:"disconnect",description:"Disconnect the active thread without reconnecting",keywords:["connection","socket","debug","dev"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: disconnect with no active thread"}},run:(J,Y,Z)=>{A.disconnectActiveThread(),Z()}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:b1.ctrl("c"),status:{type:"enabled"},run:(J,Y)=>{MA.maybeInvoke(Y,new wh)}},...Q,...c2A(this.widget.neoContext.logFilePath)].map((J)=>this.commandRegistry.register(J));return()=>{for(let J of $)J()}}build(A){let Q=this.buildHints(),B=this.ideStatus.getValue(),$=new eB1({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,hints:Q,ideStatus:B}),J=J4.of(A),Z=[new d0({constraints:L1.tight(J.size.width,J.size.height),child:$})];if(this.commandPalette.isEnabled())Z.push(new QA({debugLabel:"CommandPaletteOverlay",child:new xQ1({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)Z.push(kB1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)Z.push(new QA({debugLabel:"NeoWelcomeDialogOverlay",child:new J$1({onDismiss:this.dismissNeoWelcome})}));if(Z.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.agentModeCostInfo)Z.push(new QA({debugLabel:"AgentModeCostModalOverlay",child:this.buildAgentModeCostModal(this.agentModeCostInfo)}));if(this.widget.neoContext.isInternalUser)Z.push(new gQ1({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:j10.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)Z.push(new mQ1);return new _9({neoContext:this.widget.neoContext,child:new _$({commandRegistry:this.commandRegistry,child:new OC({completionBuilder:this.widget.completionBuilder,child:new S3({controller:this.toastController,child:new MA({actions:this.buildActions(),child:new V8({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[b1.ctrl("c"),new iH0],[b1.ctrl("o"),new nH0],[b1.alt("i"),new oH0],[b1.alt("p"),new JC],[b1.ctrl("t"),new rH0]]),child:new s4({debugLabel:"AppShellFocus",child:new q21({controller:this.toastController,child:new HA({children:Z})})})})})})})})})}buildActions(){let A=new N4(()=>{if(aJ.hasAnyCopyableSelection())return aJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new N4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new N4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new N4(()=>{let V=this.activeThreadContext?.client.getThreadId();return this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(V),this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.writeTerminalTitle(void 0),this.activeThreadContext=null,this.connectingToThreadID=null}),"handled"}),J=new N4(()=>{return d4.instance.stop(),"handled"}),Y=new N4((V)=>{if(!V.text)return"ignored";return d4.instance.tuiInstance.clipboard.writeText(V.text).then(()=>{this.toastController.show(V.successMessage,"success",2000)}).catch((U)=>{j.error("Failed to copy Neo text to clipboard",{error:U}),this.toastController.show(V.failureMessage,"error",2000)}),"handled"}),Z=new N4(()=>{return d4.instance.toggleFrameStatsOverlay(),"handled"}),X=new N4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),F=new N4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";let V=this.activeThreadContext?.client.getThreadId();if(!V)return this.toastController.show("No active thread","error",2000),"handled";return j51(V).then((U)=>{this.toastController.show(ba4(U),"success",2000)}).catch((U)=>{let K=U instanceof Error?U.message:String(U);j.error("Failed to copy thread log",{error:U}),this.toastController.show(`Failed to copy thread log: ${K}`,"error",2000)}),"handled"}),D=new N4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"}),G=new N4((V)=>{return this.setState(()=>{this.agentModeCostInfo={agentMode:V.agentMode,speedCostMultiplier:V.speedCostMultiplier}}),"handled"});return new Map([[iH0,A],[B10,$],[wh,J],[P$,Y],[Y10,B],[nH0,Q],[oH0,X],[C_,F],[Z10,G],[JC,Z],[rH0,D]])}dismissAgentModeCostModal=()=>{if(!this.agentModeCostInfo)return;this.setState(()=>{this.agentModeCostInfo=null})};buildAgentModeCostModal(A){let Q=(S8(A.agentMode)?.displayName??A.agentMode).toLowerCase();return new cA({header:"Fast Mode Enabled",minWidth:54,maxWidth:72,footer:[{keys:["Esc"],label:"close"}],onDismiss:this.dismissAgentModeCostModal,child:new i({text:new M(`This agent mode now runs in fast mode.
5289
5289
 
5290
5290
  `+`↯${Q} costs ${A.speedCostMultiplier} the standard rate for this mode.
5291
5291
 
@@ -6054,7 +6054,7 @@ ${J}`,Q);this.line=B,this.column=$,this.codeblock=J}}/*!
6054
6054
  `),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 M(G.slice(1,-1),new x({color:$.app.keybind,bold:!0})));else Y.push(new M(G,new x({color:B.colorScheme.foreground})));if(Z<J.length-1)Y.push(new M(`
6055
6055
  `))}return new d0({decoration:{color:B.colorScheme.background,border:e1.all(new A4($.app.keybind,1,"rounded"))},child:new b0({padding:w0.symmetric(0,1),child:new i({text:new M(void 0,void 0,Y)})})})}}class IJ1 extends a3{chartData;highlightIndex;showAxes;colors;constructor({key:A,chartData:Q,highlightIndex:B=null,showAxes:$=!0,colors:J=fz0}){super(A?{key:A}:{});this.chartData=Q,this.highlightIndex=B,this.showAxes=$,this.colors=J}createRenderObject(){return new qJ1({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 xYA(A,Q,B,$,J,Y,Z){if(Y<=0)return null;switch(A){case"horizontal-bar":{let X=B;return X>=0&&X<Y?X:null}case"bar":case"stacked-bar":{let X=Z?A2:0,F=$-X;if(F<=0)return null;let D=Q-X;if(D<0||D>=F)return null;let G=Math.max(1,Math.floor(F/Y)),V=Math.floor(D/G);return V>=0&&V<Y?V:null}case"line":case"sparkline":case"stacked-area":{let X=Z?A2:0,F=$-X;if(F<=0)return null;let D=Math.max(0,Math.min(F-1,Q-X));if(Y===1)return 0;let G=F/(Y-1),V=Math.round(D/G);return Math.max(0,Math.min(Y-1,V))}default:return null}}function eU8(A,Q,B,$,J,Y,Z,X){if(J<=0||Q<0||Q>=J)return null;let F=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?F: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=X>0?Z/X:0,H=Math.round((1-E)*(V-1));return{x:K,y:H}}case"line":case"sparkline":case"stacked-area":{let D=Y?A2:0,G=B-D,V=$-(Y?F: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=X>0?Z/X:0,E=Math.round((1-K)*(V-1));return{x:U,y:E}}default:return null}}function AK8(A){let Q=0;for(let B of A)for(let $ of B.points)if($.value>Q)Q=$.value;return Q||1}function QK8(A,Q,B,$,J){if(B.length<=1){let X=$(A.value),F=A.meta?` (${A.meta})`:"";return A.label.length+2+X.length+F.length}let Y=A.label.length,Z=0;for(let X of B){let F=X.points[Q];if(!F)continue;Z+=F.value;let D=2+X.name.length+2+$(F.value).length;Y=Math.max(Y,D)}if(J){let X=9+$(Z).length;Y=Math.max(Y,X)}return Y}function BK8(A,Q,B,$,J,Y,Z){let X;try{let E=S1.of(A),H=_0.of(A);X={foreground:E.colorScheme.foreground,background:E.colorScheme.background,border:H.app.keybind}}catch{X={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let F=new x({color:X.foreground,bold:!0}),D=new x({color:X.foreground}),G=new x({color:X.foreground,dim:!0}),V=[],U=new x({color:X.foreground,underline:!0}),K=(E,H)=>new M(H,U,void 0,_K0(E),()=>{L6(A,E)});if($.length<=1){if(V.push(new M(`${Q.label}: `,F)),Q.link)V.push(K(Q.link,Y(Q.value)));else V.push(new M(Y(Q.value),D));if(Q.meta)V.push(new M(` (${Q.meta})`,G))}else{let E=Z==="stacked-bar"||Z==="stacked-area";V.push(new M(`${Q.label}
6056
6056
  `,F));let H=0;for(let W=0;W<$.length;W++){let z=$[W],q=z.points[B];if(!q)continue;H+=q.value;let N=z.color??J[W%J.length]??X.foreground;if(V.push(new M("● ",new x({color:N}))),V.push(new M(`${z.name}: `,G)),q.link)V.push(K(q.link,Y(q.value)));else V.push(new M(Y(q.value),D));if(W<$.length-1||E)V.push(new M(`
6057
- `))}if(E)V.push(new M(" ",G)),V.push(new M("Total: ",G)),V.push(new M(Y(H),D))}return new d0({decoration:{color:X.background,border:e1.all(new A4(X.border,1,"rounded"))},child:new i({text:new M(void 0,void 0,V)})})}i0();T8();KO();x2();F8();oQ();Qr();OX();KQ();x9();Q$();TU();e4();Xx();fk();j1();i0();KQ();class wJ1{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.1777680871-g5fc25d"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await a70(Q,this.configService)}catch(Q){j.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class oC extends y0{props;constructor(A){super();this.props=A}createState(){return new fYA}}class fYA 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)}}class bYA extends v0{controller=new k3;focusNode=new H6({debugLabel:"CommandArgumentPrompt",onKey:(A)=>{if(A.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(A){let Q=_0.of(A),{colors:B,app:$}=Q,J=this.widget.props.isRequiredArg??!0,Y=this.controller.text.trim().length>0,Z=!J||Y,X=e1.all(new A4(B.foreground,1,"solid")),F=new M$({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(K)=>{let E=K.trim();if(J&&E.length===0)return;this.widget.props.onSubmit(E)},autofocus:!0,style:{textColor:B.foreground,border:null},maxLines:1}),D=new Q1({children:[new d0({decoration:{color:B.background},child:new i({text:new M(">",new x({color:B.foreground}))})}),new T1({child:F})]}),G=new d0({padding:w0.symmetric(1,0),child:new i({text:this.widget.props.title?new M(this.widget.props.title,new x({color:$.command,bold:!0})):new M("",void 0,[new M("Command: ",new x({color:B.foreground})),new M(this.widget.props.commandName,new x({color:$.command,bold:!0}))])})}),V=[];if(Z)V.push(new M("Enter",new x({color:$.keybind}))),V.push(new M(" to submit, ",new x({color:B.foreground,dim:!0})));V.push(new M("Esc",new x({color:$.keybind}))),V.push(new M(" to cancel",new x({color:B.foreground,dim:!0})));let U=new d0({padding:w0.symmetric(1,0),child:new i({text:new M("",void 0,V)})});return new d0({decoration:{border:X,color:B.background},padding:w0.all(1),child:new f0({children:[G,new M0({height:1}),D,new H5,U]})})}}class d10 extends y0{props;constructor(A){super();this.props=A}createState(){return new bYA}}Q$();class uYA extends v0{controller=new k3;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new H6({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>=C7)return!1;let Q=await uF(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=_0.of(A),{colors:B,app:$}=Q,Y=J4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),X=new eG({controller:this.controller,triggers:[new QY],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:d4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),F=new s4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:X}),D=new d0({constraints:new L1({maxHeight:Z}),padding:w0.symmetric(1,0),child:F}),G=new d0({padding:w0.symmetric(1,0),child:new i({text:new M("",void 0,[new M("Command: ",new x({color:B.foreground})),new M(this.widget.props.commandName,new x({color:$.command,bold:!0}))])})}),V=new d0({padding:w0.symmetric(1,0),child:new i({text:this.isConfirmingClearInput?new M("",void 0,[new M("Esc",new x({color:$.keybind})),new M(" again to clear input",new x({color:B.foreground,dim:!0}))]):new M("",void 0,[new M("Press ",new x({color:B.foreground,dim:!0})),new M("Enter",new x({color:$.keybind})),new M(" to submit, ",new x({color:B.foreground,dim:!0})),new M("Esc",new x({color:$.keybind})),new M(" to clear",new x({color:B.foreground,dim:!0}))])})}),U=[G,new M0({height:1}),new T1({child:D}),new M0({height:1}),V];return new d0({decoration:{border:e1.all(new A4(B.foreground,1,"solid")),color:B.background},padding:w0.all(1),child:new f0({children:U})})}}class CJ1 extends y0{props;constructor(A){super();this.props=A}createState(){return new uYA}}function hYA(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 MJ1 extends M1{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)=>hYA(J.pubDate).length));return new t6({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,X)=>{let F=_0.of(X),{colors:D}=F,G=F.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(H,W)=>new M0({width:W,child:Q1.end([new i({text:new M(H,new x({color:K}))})])});return new d0({decoration:V?{color:V}:void 0,padding:w0.symmetric(2,0),child:new Q1({children:[new T1({child:new i({text:new M(J.title,new x({color:U})),overflow:"ellipsis",maxLines:1})}),new M0({width:2}),E(hYA(J.pubDate),B)]})})}})}}class yB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!yB._instance)yB._instance=new yB;return yB._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()}}i0();class gYA extends v0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){j.error("Failed to load labels",A.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=A.result,this.isLoading=!1,this.setState()}catch(A){j.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let B=this.widget.props.currentLabels||[],$=this.labels.some((Y)=>Y.name===Q),J=B.includes(Q);return!$&&!J}build(A){let Q=_0.of(A),{app:B,colors:$}=Q,J=this.currentQuery.trim().toLowerCase(),Y=J.length>0?this.getValidationError(J):null,Z=this.getAvailableLabels(),F=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...Z];return new t6({title:"Add Label",items:F,getLabel:(D)=>{if("__isCreateMarker"in D)return this.currentQuery.trim().toLowerCase();return D.name},onAccept:(D)=>{if("__isCreateMarker"in D)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(D.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:Y||"Type to create a new label",renderItem:(D,G,V,U)=>{let K=G?B.selectionBackground:void 0,E=G?B.selectionForeground:$.foreground;if("__isCreateMarker"in D&&D.__isCreateMarker){let W=this.currentQuery.trim().toLowerCase();return new d0({decoration:K?{color:K}:void 0,padding:w0.symmetric(2,0),child:new i({text:new M("",void 0,[new M("Create new label: ",new x({color:E})),new M(W,new x({color:E,bold:!0}))])})})}return new d0({decoration:K?{color:K}:void 0,padding:w0.symmetric(2,0),child:new i({text:new M(D.name,new x({color:E}))})})},filterItem:(D,G)=>{if(this.currentQuery!==G)this.currentQuery=G,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in D&&D.__isCreateMarker)return this.shouldShowCreateMarker(G);let U=G.trim().toLowerCase();return U.length===0||D.name.includes(U)},sortItems:(D,G,V)=>{let U="__isCreateMarker"in D.item&&D.item.__isCreateMarker,K="__isCreateMarker"in G.item&&G.item.__isCreateMarker;if(U&&!K)return-1;if(!U&&K)return 1;return G.score-D.score}})}}class LJ1 extends y0{props;constructor(A){super();this.props=A}createState(){return new gYA}}class BV extends y0{props;constructor(A){super();this.props=A}createState(){return new mYA}}class mYA extends v0{_spinner=new C6;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(A){let Q=_0.of(A),{colors:B,app:$}=Q,J=e1.all(new A4(B.foreground,1,"solid")),Y=this._spinner.toBraille(),Z=new i({textAlign:"center",text:new M("",void 0,[new M(Y,new x({color:$.processing})),new M(" ",void 0),new M(this.widget.props.message,new x({color:B.foreground}))])}),F=[new T1({child:new f0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)F.push(new M0({height:2,child:new d0({padding:w0.symmetric(2,0),child:new i({text:new M("",new x({dim:!0}),[new M("Press ",new x({color:B.foreground})),new M("Esc",new x({color:B.info})),new M(" to cancel",new x({color:B.foreground}))])})})}));let D=new d0({decoration:new t4(B.background,J),child:new M0({width:60,height:7,child:new f0({mainAxisAlignment:"start",children:F})})});if(this.widget.props.onAbort)return new QA({debugLabel:"LoadingDialog",child:new s4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class UE extends y0{props;constructor(A){super();this.props=A}createState(){return new pYA}}class pYA extends v0{scrollController=new Z6;scrollAreaKey=new N2("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(A){return A instanceof r2}resolveFooterStyle(A){if(this.isWidgetMessage(A))return A.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let B=Q.size;if(typeof B.height==="number"&&B.height>0)return this.viewportHeight=B.height,B.height}return this.viewportHeight}build(A){let Q=_0.of(A),B=this.widget.props.message,$=(()=>{if(this.isWidgetMessage(B))return{title:B.title,type:B.type};if(B instanceof Error&&B.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:B.message};if(B instanceof Error&&B.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:B.message};let G=iE0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=e1.all(new A4(Q.colors.border,1,"solid")),Z=new d0({padding:w0.symmetric(1,0),child:new i({text:new M($.title,new x({color:J,bold:!0}))})}),X=this.isWidgetMessage(B)?B.widget:new i({text:new M($.description,new x({color:Q.colors.foreground})),selectable:!0}),F=new T1({child:new a2({child:new d0({padding:w0.symmetric(1,0),child:new Q1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new uA({controller:this.scrollController,autofocus:!0,child:X})}),new C2({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let G=this.scrollController.maxScrollExtent,V=this.scrollController.offset,U=this.getViewportHeight(),K=G+U;return{totalContentHeight:Math.max(K,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(V,0)}}})]})})})}),D=new d0({padding:w0.symmetric(1,0),child:new i({text:(()=>{if(this.widget.props.onRetry)return new M("",void 0,[new M("Press ",new x({color:Q.colors.foreground,dim:!0})),new M("R",new x({color:Q.app.keybind})),new M(" to retry, ",new x({color:Q.colors.foreground,dim:!0})),new M("Esc",new x({color:Q.app.keybind})),new M(" to cancel",new x({color:Q.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new M("",new x({color:Q.colors.foreground,dim:!0}));if(G==="help"){let V=new x({color:Q.app.keybind}),U=new x({color:Q.colors.foreground,dim:!0});return new M("",U,[new M("Press ",U),new M("Escape",V),new M(" to close • Use ",U),new M("↑↓",V),new M(" or ",U),new M("j/k",V),new M(" to scroll",U)])}return new M("Press any key to close",new x({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new QA({debugLabel:"MessageDialog",child:new HA({fit:"expand",children:[new l1({onClick:()=>{},child:new M0}),new s4({onKey:(G)=>{if(this.widget.props.onRetry&&G.key==="r")return this.widget.props.onRetry(),"handled";if(G.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new d0({decoration:{border:Y,color:Q.colors.background},padding:w0.all(1),child:new f0({mainAxisAlignment:"center",children:[Z,new M0({height:1}),F,D]})})})]})})}}T8();class dYA extends y0{props;constructor(A){super();this.props=A}createState(){return new cYA}}class cYA 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=t3.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=_0.of(A),{app:B}=Q;if(this.plugins.length===0)return new i({text:new M("No plugins found.",new x({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((F)=>F.status==="active").length,Z=this.plugins.reduce((F,D)=>F+D.registeredCommands.length,0),X=this.plugins.reduce((F,D)=>F+D.registeredTools.length,0);if($.push(new M(`${Y}/${J} ${E4(J,"plugin")} active`,new x({bold:!0}))),Z>0||X>0)$.push(new M(` (${Z} ${E4(Z,"command")}, ${X} ${E4(X,"tool")})`,new x({dim:!0})));$.push(new M(`
6057
+ `))}if(E)V.push(new M(" ",G)),V.push(new M("Total: ",G)),V.push(new M(Y(H),D))}return new d0({decoration:{color:X.background,border:e1.all(new A4(X.border,1,"rounded"))},child:new i({text:new M(void 0,void 0,V)})})}i0();T8();KO();x2();F8();oQ();Qr();OX();KQ();x9();Q$();TU();e4();Xx();fk();j1();i0();KQ();class wJ1{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.1777697948-g1a223c"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await a70(Q,this.configService)}catch(Q){j.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class oC extends y0{props;constructor(A){super();this.props=A}createState(){return new fYA}}class fYA 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)}}class bYA extends v0{controller=new k3;focusNode=new H6({debugLabel:"CommandArgumentPrompt",onKey:(A)=>{if(A.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(A){let Q=_0.of(A),{colors:B,app:$}=Q,J=this.widget.props.isRequiredArg??!0,Y=this.controller.text.trim().length>0,Z=!J||Y,X=e1.all(new A4(B.foreground,1,"solid")),F=new M$({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(K)=>{let E=K.trim();if(J&&E.length===0)return;this.widget.props.onSubmit(E)},autofocus:!0,style:{textColor:B.foreground,border:null},maxLines:1}),D=new Q1({children:[new d0({decoration:{color:B.background},child:new i({text:new M(">",new x({color:B.foreground}))})}),new T1({child:F})]}),G=new d0({padding:w0.symmetric(1,0),child:new i({text:this.widget.props.title?new M(this.widget.props.title,new x({color:$.command,bold:!0})):new M("",void 0,[new M("Command: ",new x({color:B.foreground})),new M(this.widget.props.commandName,new x({color:$.command,bold:!0}))])})}),V=[];if(Z)V.push(new M("Enter",new x({color:$.keybind}))),V.push(new M(" to submit, ",new x({color:B.foreground,dim:!0})));V.push(new M("Esc",new x({color:$.keybind}))),V.push(new M(" to cancel",new x({color:B.foreground,dim:!0})));let U=new d0({padding:w0.symmetric(1,0),child:new i({text:new M("",void 0,V)})});return new d0({decoration:{border:X,color:B.background},padding:w0.all(1),child:new f0({children:[G,new M0({height:1}),D,new H5,U]})})}}class d10 extends y0{props;constructor(A){super();this.props=A}createState(){return new bYA}}Q$();class uYA extends v0{controller=new k3;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new H6({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>=C7)return!1;let Q=await uF(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=_0.of(A),{colors:B,app:$}=Q,Y=J4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),X=new eG({controller:this.controller,triggers:[new QY],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:d4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),F=new s4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:X}),D=new d0({constraints:new L1({maxHeight:Z}),padding:w0.symmetric(1,0),child:F}),G=new d0({padding:w0.symmetric(1,0),child:new i({text:new M("",void 0,[new M("Command: ",new x({color:B.foreground})),new M(this.widget.props.commandName,new x({color:$.command,bold:!0}))])})}),V=new d0({padding:w0.symmetric(1,0),child:new i({text:this.isConfirmingClearInput?new M("",void 0,[new M("Esc",new x({color:$.keybind})),new M(" again to clear input",new x({color:B.foreground,dim:!0}))]):new M("",void 0,[new M("Press ",new x({color:B.foreground,dim:!0})),new M("Enter",new x({color:$.keybind})),new M(" to submit, ",new x({color:B.foreground,dim:!0})),new M("Esc",new x({color:$.keybind})),new M(" to clear",new x({color:B.foreground,dim:!0}))])})}),U=[G,new M0({height:1}),new T1({child:D}),new M0({height:1}),V];return new d0({decoration:{border:e1.all(new A4(B.foreground,1,"solid")),color:B.background},padding:w0.all(1),child:new f0({children:U})})}}class CJ1 extends y0{props;constructor(A){super();this.props=A}createState(){return new uYA}}function hYA(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 MJ1 extends M1{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)=>hYA(J.pubDate).length));return new t6({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,X)=>{let F=_0.of(X),{colors:D}=F,G=F.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(H,W)=>new M0({width:W,child:Q1.end([new i({text:new M(H,new x({color:K}))})])});return new d0({decoration:V?{color:V}:void 0,padding:w0.symmetric(2,0),child:new Q1({children:[new T1({child:new i({text:new M(J.title,new x({color:U})),overflow:"ellipsis",maxLines:1})}),new M0({width:2}),E(hYA(J.pubDate),B)]})})}})}}class yB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!yB._instance)yB._instance=new yB;return yB._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()}}i0();class gYA extends v0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){j.error("Failed to load labels",A.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=A.result,this.isLoading=!1,this.setState()}catch(A){j.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let B=this.widget.props.currentLabels||[],$=this.labels.some((Y)=>Y.name===Q),J=B.includes(Q);return!$&&!J}build(A){let Q=_0.of(A),{app:B,colors:$}=Q,J=this.currentQuery.trim().toLowerCase(),Y=J.length>0?this.getValidationError(J):null,Z=this.getAvailableLabels(),F=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...Z];return new t6({title:"Add Label",items:F,getLabel:(D)=>{if("__isCreateMarker"in D)return this.currentQuery.trim().toLowerCase();return D.name},onAccept:(D)=>{if("__isCreateMarker"in D)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(D.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:Y||"Type to create a new label",renderItem:(D,G,V,U)=>{let K=G?B.selectionBackground:void 0,E=G?B.selectionForeground:$.foreground;if("__isCreateMarker"in D&&D.__isCreateMarker){let W=this.currentQuery.trim().toLowerCase();return new d0({decoration:K?{color:K}:void 0,padding:w0.symmetric(2,0),child:new i({text:new M("",void 0,[new M("Create new label: ",new x({color:E})),new M(W,new x({color:E,bold:!0}))])})})}return new d0({decoration:K?{color:K}:void 0,padding:w0.symmetric(2,0),child:new i({text:new M(D.name,new x({color:E}))})})},filterItem:(D,G)=>{if(this.currentQuery!==G)this.currentQuery=G,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in D&&D.__isCreateMarker)return this.shouldShowCreateMarker(G);let U=G.trim().toLowerCase();return U.length===0||D.name.includes(U)},sortItems:(D,G,V)=>{let U="__isCreateMarker"in D.item&&D.item.__isCreateMarker,K="__isCreateMarker"in G.item&&G.item.__isCreateMarker;if(U&&!K)return-1;if(!U&&K)return 1;return G.score-D.score}})}}class LJ1 extends y0{props;constructor(A){super();this.props=A}createState(){return new gYA}}class BV extends y0{props;constructor(A){super();this.props=A}createState(){return new mYA}}class mYA extends v0{_spinner=new C6;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(A){let Q=_0.of(A),{colors:B,app:$}=Q,J=e1.all(new A4(B.foreground,1,"solid")),Y=this._spinner.toBraille(),Z=new i({textAlign:"center",text:new M("",void 0,[new M(Y,new x({color:$.processing})),new M(" ",void 0),new M(this.widget.props.message,new x({color:B.foreground}))])}),F=[new T1({child:new f0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)F.push(new M0({height:2,child:new d0({padding:w0.symmetric(2,0),child:new i({text:new M("",new x({dim:!0}),[new M("Press ",new x({color:B.foreground})),new M("Esc",new x({color:B.info})),new M(" to cancel",new x({color:B.foreground}))])})})}));let D=new d0({decoration:new t4(B.background,J),child:new M0({width:60,height:7,child:new f0({mainAxisAlignment:"start",children:F})})});if(this.widget.props.onAbort)return new QA({debugLabel:"LoadingDialog",child:new s4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class UE extends y0{props;constructor(A){super();this.props=A}createState(){return new pYA}}class pYA extends v0{scrollController=new Z6;scrollAreaKey=new N2("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(A){return A instanceof r2}resolveFooterStyle(A){if(this.isWidgetMessage(A))return A.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let B=Q.size;if(typeof B.height==="number"&&B.height>0)return this.viewportHeight=B.height,B.height}return this.viewportHeight}build(A){let Q=_0.of(A),B=this.widget.props.message,$=(()=>{if(this.isWidgetMessage(B))return{title:B.title,type:B.type};if(B instanceof Error&&B.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:B.message};if(B instanceof Error&&B.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:B.message};let G=iE0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=e1.all(new A4(Q.colors.border,1,"solid")),Z=new d0({padding:w0.symmetric(1,0),child:new i({text:new M($.title,new x({color:J,bold:!0}))})}),X=this.isWidgetMessage(B)?B.widget:new i({text:new M($.description,new x({color:Q.colors.foreground})),selectable:!0}),F=new T1({child:new a2({child:new d0({padding:w0.symmetric(1,0),child:new Q1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new uA({controller:this.scrollController,autofocus:!0,child:X})}),new C2({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let G=this.scrollController.maxScrollExtent,V=this.scrollController.offset,U=this.getViewportHeight(),K=G+U;return{totalContentHeight:Math.max(K,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(V,0)}}})]})})})}),D=new d0({padding:w0.symmetric(1,0),child:new i({text:(()=>{if(this.widget.props.onRetry)return new M("",void 0,[new M("Press ",new x({color:Q.colors.foreground,dim:!0})),new M("R",new x({color:Q.app.keybind})),new M(" to retry, ",new x({color:Q.colors.foreground,dim:!0})),new M("Esc",new x({color:Q.app.keybind})),new M(" to cancel",new x({color:Q.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new M("",new x({color:Q.colors.foreground,dim:!0}));if(G==="help"){let V=new x({color:Q.app.keybind}),U=new x({color:Q.colors.foreground,dim:!0});return new M("",U,[new M("Press ",U),new M("Escape",V),new M(" to close • Use ",U),new M("↑↓",V),new M(" or ",U),new M("j/k",V),new M(" to scroll",U)])}return new M("Press any key to close",new x({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new QA({debugLabel:"MessageDialog",child:new HA({fit:"expand",children:[new l1({onClick:()=>{},child:new M0}),new s4({onKey:(G)=>{if(this.widget.props.onRetry&&G.key==="r")return this.widget.props.onRetry(),"handled";if(G.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new d0({decoration:{border:Y,color:Q.colors.background},padding:w0.all(1),child:new f0({mainAxisAlignment:"center",children:[Z,new M0({height:1}),F,D]})})})]})})}}T8();class dYA extends y0{props;constructor(A){super();this.props=A}createState(){return new cYA}}class cYA 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=t3.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=_0.of(A),{app:B}=Q;if(this.plugins.length===0)return new i({text:new M("No plugins found.",new x({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((F)=>F.status==="active").length,Z=this.plugins.reduce((F,D)=>F+D.registeredCommands.length,0),X=this.plugins.reduce((F,D)=>F+D.registeredTools.length,0);if($.push(new M(`${Y}/${J} ${E4(J,"plugin")} active`,new x({bold:!0}))),Z>0||X>0)$.push(new M(` (${Z} ${E4(Z,"command")}, ${X} ${E4(X,"tool")})`,new x({dim:!0})));$.push(new M(`
6058
6058
 
6059
6059
  `));for(let F of this.plugins){let{icon:D,color:G}=this.statusIcon(F.status),V=this.getRelativePath(F.uri.toString());if($.push(new M(`${D} `,new x({color:G}))),$.push(new M(V,new x({bold:!0}))),$.push(new M(` ${F.status}`,new x({dim:!0}))),$.push(new M(`
6060
6060
  `)),F.status==="active"&&F.registeredEvents.length>0)$.push(new M(" Events: ",new x({dim:!0}))),$.push(new M(F.registeredEvents.join(", "),new x({color:B.link}))),$.push(new M(`
@@ -6232,7 +6232,7 @@ ${s.content||""}`:s.content||"",C0=[],h0=s.baseDir.startsWith("file://")?Vq0(s.b
6232
6232
  `)}function jFA(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"),X=J84({settings:{url:Y.ampURL,proxy:Z},secrets:{getToken:(D,G)=>Y.secrets.get(D,G)}}),F=await yA.userDisplayBalanceInfo({},{config:X});if(!F.ok){if(F.error.code==="auth-required")process.stderr.write(r0.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(r0.red("Error: ")+F.error.message+`
6233
6233
  `),process.exit(1)}process.stdout.write(await qW8(F.result.displayText)+`
6234
6234
  `),process.exit(0)})}var hI8=j40.join(LX,"logs","headless.log"),PX1=j40.join(wu,"device-id.json"),gI8=`cli-tui-${eVA(16).toString("hex")}`;async function mI8(){for(let A of WO)try{if((await A.listConfigs()).length>0)return A}catch(Q){j.debug("Failed to detect query-based IDE integration",{ideName:A.ideName,error:Q})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => w4(wg(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){DY.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
6235
- `)}function pI8(A){process.emitWarning=(Q,B,$,J)=>{let Y=typeof Q==="string"?Q:Q.message||String(Q),Z=B||"Warning",X=!1;A.warn(Y,{name:Z,code:$})}}function A9(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")sB("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")sB("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)sB("internal.model",lI8(Q.model))}function nVA(A){let Q=A.indexOf(":");if(Q===-1)throw new X4(`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 X4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function dI8(A){if(A===void 0)return;let Q=A.trim();if(Ef0(Q))return Q;throw new X4(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function cI8(A,Q){if(WH(A,Q))return;let B=XJ(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new X4(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function lI8(A){if(!A.includes("="))return nVA(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new X4(`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 X4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new X4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);nVA(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new X4("No valid model overrides found in --model flag value.",1);return Q}function iI8(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 nI8(A){try{return await AUA(A,"utf-8")}catch{return A}}async function _X1(A,Q,B){let $=iI8(A,Q);if(!$)return;let J=gA(B)?B.features:[],Y=gA(B)?B.user.email:void 0;if(!R40(J,Z9.HARNESS_SYSTEM_PROMPT)&&!(Y&&ZQ(Y)))throw new X4("You are not allowed to do this.",1);sB("systemPrompt",await nI8($))}function R40(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function aI8(A){return A!=="pending"}function t_(A){if(!gA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function oI8(A){let Q=t_(A);if(Q)return Q.id;if(SD(A))throw Error(A.error.message);throw Error("unreachable")}function rI8(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 sI8(A){let $=rI8(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 X4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function P40(A,Q){let B=P51(Error(A.error.message));if(B.message===g7.networkOffline||B.message===g7.networkTimeout)return sI8(Q);if(B.message!==g7.internalBug)return new X4(B.message,1,B.suggestion);return new X4(A.error.message.replace(/^Error: /,""),1)}var aVA=[{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??_F,description:`Custom settings file path (overrides the default location ${_F})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${it})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:j9(),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:UO.SMART.key,description:`Set the agent mode (${YJ({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(YJ().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neoOrb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"showNeoWelcome",long:"show-neo-welcome",type:"switch",description:"Show the Neo welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],oVA=(A)=>("deprecated"in A)&&A.deprecated===!0,tI8=(A)=>("hidden"in A)&&A.hidden===!0,eI8=(A)=>("default"in A),Aw8=(A)=>("default"in A)?A.default:void 0;function AN0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=dI8(Q.effort);if(B!==void 0)cI8(Q.mode,B);return B}function Qw8(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((X)=>B.includes(X)||X.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 X4(g7.unknownCommand(B),1,Z)}}async function $N0(A){return{...A,getThreadEnvironment:fW,getEnvironmentData:(Q,B)=>nD({filesystem:A.fileSystem},Q,B),osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new Fj(A.fileSystem),generateThreadTitle:eE4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>tQ(A.configService),pluginService:A.pluginService}}function QUA(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:fW,getEnvironmentData:(Q,B)=>nD({filesystem:A.fileSystem},Q,B),filesystem:A.fileSystem,threadService:A.threadService}}var QN0=Y1.file(uI8.homedir()),TX1=process.env.XDG_CONFIG_HOME?Y1.file(process.env.XDG_CONFIG_HOME):V1.joinPath(QN0,".config");function Bw8(A){return Px4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(DK0())GK0();else if(process.platform==="darwin"&&Q==="idle"&&A.isTUIVoiceNotifEnabled())Rx4();else Xs(Q);let B=iP(),$=te();if((!B||$||Lu())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(pG("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(pG("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(iP()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function Q2(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;g84("0.0.1777680871-g5fc25d");let Y=Jv({storage:A.settings,secretStorage:A.secrets,workspaceRoot:g0.of(Y1.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:QN0,userConfigDir:TX1});pBA(Y);let Z=await Y.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let X=!1;{let m=await A.secrets.get("apiKey",A.ampURL);if(X=Boolean(m),j.info("API key lookup before login",{found:Boolean(m),ampURL:A.ampURL,deferAuth:$}),!m)if($)j.info("No API key found, continuing startup with deferred auth");else{N5.write(`No API key found. Starting login flow...
6235
+ `)}function pI8(A){process.emitWarning=(Q,B,$,J)=>{let Y=typeof Q==="string"?Q:Q.message||String(Q),Z=B||"Warning",X=!1;A.warn(Y,{name:Z,code:$})}}function A9(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")sB("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")sB("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)sB("internal.model",lI8(Q.model))}function nVA(A){let Q=A.indexOf(":");if(Q===-1)throw new X4(`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 X4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function dI8(A){if(A===void 0)return;let Q=A.trim();if(Ef0(Q))return Q;throw new X4(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function cI8(A,Q){if(WH(A,Q))return;let B=XJ(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new X4(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function lI8(A){if(!A.includes("="))return nVA(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new X4(`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 X4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new X4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);nVA(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new X4("No valid model overrides found in --model flag value.",1);return Q}function iI8(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 nI8(A){try{return await AUA(A,"utf-8")}catch{return A}}async function _X1(A,Q,B){let $=iI8(A,Q);if(!$)return;let J=gA(B)?B.features:[],Y=gA(B)?B.user.email:void 0;if(!R40(J,Z9.HARNESS_SYSTEM_PROMPT)&&!(Y&&ZQ(Y)))throw new X4("You are not allowed to do this.",1);sB("systemPrompt",await nI8($))}function R40(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function aI8(A){return A!=="pending"}function t_(A){if(!gA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function oI8(A){let Q=t_(A);if(Q)return Q.id;if(SD(A))throw Error(A.error.message);throw Error("unreachable")}function rI8(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 sI8(A){let $=rI8(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 X4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function P40(A,Q){let B=P51(Error(A.error.message));if(B.message===g7.networkOffline||B.message===g7.networkTimeout)return sI8(Q);if(B.message!==g7.internalBug)return new X4(B.message,1,B.suggestion);return new X4(A.error.message.replace(/^Error: /,""),1)}var aVA=[{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??_F,description:`Custom settings file path (overrides the default location ${_F})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${it})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:j9(),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:UO.SMART.key,description:`Set the agent mode (${YJ({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(YJ().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neoOrb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"showNeoWelcome",long:"show-neo-welcome",type:"switch",description:"Show the Neo welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],oVA=(A)=>("deprecated"in A)&&A.deprecated===!0,tI8=(A)=>("hidden"in A)&&A.hidden===!0,eI8=(A)=>("default"in A),Aw8=(A)=>("default"in A)?A.default:void 0;function AN0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=dI8(Q.effort);if(B!==void 0)cI8(Q.mode,B);return B}function Qw8(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((X)=>B.includes(X)||X.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 X4(g7.unknownCommand(B),1,Z)}}async function $N0(A){return{...A,getThreadEnvironment:fW,getEnvironmentData:(Q,B)=>nD({filesystem:A.fileSystem},Q,B),osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new Fj(A.fileSystem),generateThreadTitle:eE4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>tQ(A.configService),pluginService:A.pluginService}}function QUA(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:fW,getEnvironmentData:(Q,B)=>nD({filesystem:A.fileSystem},Q,B),filesystem:A.fileSystem,threadService:A.threadService}}var QN0=Y1.file(uI8.homedir()),TX1=process.env.XDG_CONFIG_HOME?Y1.file(process.env.XDG_CONFIG_HOME):V1.joinPath(QN0,".config");function Bw8(A){return Px4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(DK0())GK0();else if(process.platform==="darwin"&&Q==="idle"&&A.isTUIVoiceNotifEnabled())Rx4();else Xs(Q);let B=iP(),$=te();if((!B||$||Lu())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(pG("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(pG("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(iP()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function Q2(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;g84("0.0.1777697948-g1a223c");let Y=Jv({storage:A.settings,secretStorage:A.secrets,workspaceRoot:g0.of(Y1.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:QN0,userConfigDir:TX1});pBA(Y);let Z=await Y.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let X=!1;{let m=await A.secrets.get("apiKey",A.ampURL);if(X=Boolean(m),j.info("API key lookup before login",{found:Boolean(m),ampURL:A.ampURL,deferAuth:$}),!m)if($)j.info("No API key found, continuing startup with deferred auth");else{N5.write(`No API key found. Starting login flow...
6236
6236
  `);let d=await $w8(A),g=await A.secrets.get("apiKey",A.ampURL);if(j.info("Login flow completed",{success:d,storedKeyPresent:Boolean(g),ampURL:A.ampURL}),!d)await tW(),process.exit(1);X=!0}}{let m=await Y.getLatest(),d=m.settings.url,g=m.secrets.isSet?.[d];j.info("Config secrets state after login",{configURL:d,apiKeySet:g?.apiKey??!1})}let F=k1(tQ(Y).pipe(L5(aI8))),D=$?"pending":await F;if(!$)j.info("Server status resolved",{status:"ready",isAuthenticated:gA(D),isError:SD(D),errorMessage:SD(D)?D.error.message:void 0});let G=F.then((m)=>oI8(m));G.catch(()=>{return});let{toolService:V,dispose:U}=hD0({configService:Y}),K=new Map,E=()=>K.clear(),H=new mm0(Y,A.settings.getWorkspaceRootPath()),W=IJ0({configService:Y,filesystem:e5}),z=RF4({configService:Y,trustStore:H,skillMCPServers:W.skillMCPServers,createOAuthProvider:async(m,d,g)=>{let n=`${m}:${d}`,c=K.get(n);if(c)return j.debug("Reusing existing OAuth provider for server",{serverName:m,serverUrl:d}),c;j.debug("Creating OAuth provider for server",{serverName:m,serverUrl:d});let $0=(async()=>{let j0=new CO(A.secrets),l=await j0.getClientInfo(m,d),B0=g?.scopes??l?.scopes,K0=ts4();j.info("OAuth headless mode check",{useHeadless:K0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:N5.isTTY});let z0;if(K0)z0=A.executeMode?ss4():rs4(m);let A0=new wb0({storage:j0,serverName:m,serverUrl:d,clientId:g?.clientId??l?.clientId,clientSecret:g?.clientSecret??l?.clientSecret,authUrl:g?.authUrl??l?.authUrl,tokenUrl:g?.tokenUrl??l?.tokenUrl,scopes:B0,headlessAuthHandler:z0});return j.debug("OAuth provider created",{serverName:m,serverUrl:d,hasManualClientId:!!(g?.clientId??l?.clientId),willUseDCR:!(g?.clientId??l?.clientId),scopes:B0,headlessMode:K0,executeMode:A.executeMode}),A0})();return K.set(n,$0),$0}}),q=sr({configService:Y,filesystem:e5,spawn:af}),N;if(J)N=new Map;else if(A.executeMode){let m=await ek4({toolService:V,providers:[z,q],initialTimeout:15000});N=m.registrations;for(let[d,g]of m.initErrors)j.warn(`${d} provider initialization slow or failed:`,g)}else N=tr({toolService:V,providers:[z,q]});if(Q.jetbrains)EO("JetBrains");else if(Q.ide&&xt4())EO("VS Code");else if(Q.ide&&ft4())EO("Neovim");else if(Q.ide){let m=await mI8();if(m){let d=G70(m.ideName);if(d)EO(d)}}if(A.executeMode)m84(!0);let I,w=a8.status.pipe(O1((m)=>Boolean(m.connected&&m.authenticated&&m.ideName&&W34(m.ideName))),m4()).subscribe((m)=>{if(m){if(!I)I=V.registerTool(tk4)}else I?.dispose(),I=void 0}),C;if(!A.executeMode){let m=await A.settings.get("fuzzy.alwaysIncludePaths")??[];C=new Nu(process.cwd(),{alwaysIncludePaths:m},!0)}else C=new class extends Nu{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let O=new $l0(Oj(Y,{usesThreadActors:!1}),{maxThreads:200});j.info("Starting Amp background services");let P=new w$1,S=process.env.PLUGINS??"permissions",T=Q.headless?D1A():void 0,f=T??new ku({configService:Y}),h=f instanceof ku?f:void 0;if(h)h.pluginExecutorKind="local";let b=bi({configService:Y,fileSystem:e5,platform:f,internalPlugins:Oe,pluginFilter:S}),y=w$0({pluginService:b,toolService:V}),u={configService:Y,toolService:V,mcpService:z,skillService:W,toolboxService:q,trustStore:H,threadService:O,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:C,fileSystem:e5,terminal:P,pluginService:b,pluginPlatform:h,headlessPluginPlatform:T,serverStatus:D,serverStatusPromise:F,viewerUserIDPromise:G,hasAPIKeyAtStartup:X};return{...u,async asyncDispose(){if(u.mcpService.hasAuthenticatingClients())j.info("Waiting for OAuth authentication to complete before exit..."),await u.mcpService.waitForAuthentication();for(let m of N.values())m.dispose();await u.mcpService.dispose(),E(),await u.threadService.asyncDispose(),u.configService.unsubscribe(),U(),u.fuzzyServer.dispose(),u.settingsStorage[Symbol.dispose](),w.unsubscribe(),I?.dispose(),y.dispose(),await u.pluginService.dispose()}}}async function $w8(A){if(!A.executeMode){if(!await AE0("Would you like to log in to Amp? [(y)es, (n)o]: "))return N5.write(`Login cancelled. Run the command again to retry.
6237
6237
  `),!1}return await BUA(A)}async function BUA(A){let Q=eVA(32).toString("hex"),B=await Su(A.ampURL,Q),$=new AbortController;try{await ID(B,$.signal)}catch(Y){j.error("Error opening browser",{error:Y})}let J=await Su(A.ampURL,Q,!1);N5.write(`If your browser does not open automatically, visit:
6238
6238
 
@@ -6240,7 +6240,7 @@ ${r0.blue.bold(J)}
6240
6240
 
6241
6241
  `);try{return await r0A(A.ampURL,Q,A.secrets,$),N5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(Y){return j.error("Login failed",{error:Y}),DY.write(`
6242
6242
  Login failed: ${Y instanceof Error?Y.message:String(Y)}
6243
- `),!1}}function Jw8(A){let Q=new Yw().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)OP(),process.exit(0);let H=E.originalError??E;la4(H)}),Z4A(Q,{version:"0.0.1777680871-g5fc25d",buildTimestamp:"2026-05-02T00:18:10.627Z",buildType:"'release'"}),Q.addHelpText("after",kt4()),Q.configureHelp({formatHelp:vt4}),Q.command("logout").description("Log out by removing stored API key").action(async(E,H)=>{let W=H.optsWithGlobals(),z=await E8(W);await Kw8(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,H)=>{let W=H.optsWithGlobals(),z=await E8(W);await Uw8(z,await Ke(W,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,H,W)=>{let z=W.optsWithGlobals(),q=await E8(z);await ps4(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,H)=>{let W=H.optsWithGlobals(),z=await E8(W);await ds4(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 se4({raw:E.raw===!0}),process.exit(process.exitCode??0)}),Q.command("cplog <threadIDOrURL>",{hidden:!0}).summary("Copy a thread-scoped log file to the clipboard").description("Internal: snapshot <cwd>/.amp/in/<threadID>.log (written by the CLI for thread-scoped logs) to a timestamped JSONL file in the OS temp directory and copy that file to the clipboard for Slack paste.").action(async(E)=>{await fa4(E),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(`
6243
+ `),!1}}function Jw8(A){let Q=new Yw().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)OP(),process.exit(0);let H=E.originalError??E;la4(H)}),Z4A(Q,{version:"0.0.1777697948-g1a223c",buildTimestamp:"2026-05-02T05:02:48.212Z",buildType:"'release'"}),Q.addHelpText("after",kt4()),Q.configureHelp({formatHelp:vt4}),Q.command("logout").description("Log out by removing stored API key").action(async(E,H)=>{let W=H.optsWithGlobals(),z=await E8(W);await Kw8(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,H)=>{let W=H.optsWithGlobals(),z=await E8(W);await Uw8(z,await Ke(W,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,H,W)=>{let z=W.optsWithGlobals(),q=await E8(z);await ps4(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,H)=>{let W=H.optsWithGlobals(),z=await E8(W);await ds4(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 se4({raw:E.raw===!0}),process.exit(process.exitCode??0)}),Q.command("cplog <threadIDOrURL>",{hidden:!0}).summary("Copy a thread-scoped log file to the clipboard").description("Internal: snapshot <cwd>/.amp/in/<threadID>.log (written by the CLI for thread-scoped logs) to a timestamped JSONL file in the OS temp directory and copy that file to the clipboard for Slack paste.").action(async(E)=>{await fa4(E),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(`
6244
6244
  `)).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,H,W)=>{if(E&&H.apply)throw new X4("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let z=H.apply??E;if(!z||z.trim().length===0)N5.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.
6245
6245
 
6246
6246
  `),W.outputHelp(),process.exit(0);let q=i8(z)??WB(z),N=W.optsWithGlobals(),I=await E8(N);A9(W,N);let w=await Q2(I,N),C=!1;try{if(H.checkout&&H.skipCheckout)throw new X4("Choose either --checkout or --skip-checkout, not both.",1);if(SD(w.serverStatus))throw P40(w.serverStatus,I.ampURL);let O=gA(w.serverStatus)?w.serverStatus.features:void 0;if(!R40(O,Z9.V2))throw new X4("live-sync is not enabled for your user",1);await h0A({ampURL:I.ampURL,threadId:q,configService:w.configService,threadService:w.threadService,apiKey:process.env.AMP_API_KEY,applyOnce:typeof H.apply==="string",checkoutMode:H.checkout?"always":H.skipCheckout?"never":"prompt",promptForYesNo:AE0}),C=!0}finally{if(await w.asyncDispose(),C)process.exit(0)}});let B=async(E,H,W)=>{Jv({storage:H.settings,secretStorage:H.secrets,workspaceRoot:g0.of(Y1.file(process.cwd())),defaultAmpURL:H.ampURL,homeDir:QN0,userConfigDir:TX1});let z={...H,executeMode:!1};await BN0(z,{...E,openThreadSwitcher:!0},W,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,H)=>{let W=H.optsWithGlobals(),z=await E8(W);await tVA(W,z,H)});$.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,H)=>{let W=H.optsWithGlobals(),z=await E8(W);await Lw8(W,z,H)}),$.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,H,W)=>{let z=W.optsWithGlobals(),q=await E8(z);if(H.pick)DY.write(`${r0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
@@ -6273,8 +6273,8 @@ ${I}
6273
6273
  `))}),H.args.length>0)Qw8(z,H);await BN0(z,W,H,A)}),Ke4(Q),Q}async function Cg(A,Q){await kZ((B)=>YE0(B,A,Q))}async function rVA(A,Q,B){let $=Date.now(),[J,Y]=await Promise.all([yA.getThreadLinkInfo({thread:A},{config:Q}),B]);if(j.info(`[fetchAndStartThread] Ownership check in ${Date.now()-$}ms`),J.ok){let Z=J.result.creatorUserID;if(Z&&Z!==Y&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new X4(`Cannot resume thread created by another user.
6274
6274
 
6275
6275
  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 $UA(A){if(A.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof A.execute==="string"){let Q=(await OW0()).trimEnd();return{userInput:A.execute,stdinInput:Q||null}}return{userInput:(await OW0()).trimEnd(),stdinInput:null}}function JUA(A,Q,B){if(A.streamJson&&!Q)throw new X4("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new X4("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new X4("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new X4("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 X4("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archive&&!Q)throw new X4("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 X4("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 X4("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"
6276
- Or pipe via stdin: echo "your message" | amp --execute`)}function Yw8(A,Q){if(VQ4([O90.parse({tool:"*",action:"allow"})]),_BA(A.settings))j.debug("Enabling permissions plugin"),Q.registerInternalPlugin({name:"permissions",entryPoint:W$1})}async function BN0(A,Q,B,$){if(Q.headless)return Zw8(A,Q,B);let J=await Q2(A,Q),Y=await J.serverStatusPromise,Z=await J.configService.getLatest(),X=gA(Y)&&R40(Y.features,Z9.THREAD_ACTORS_TUI),F=X&&!Q.takeMeBack;if(Q.showNeoWelcome&&!X)throw await J.asyncDispose(),new X4("--show-neo-welcome is only available with the Neo TUI feature flag",1);if(F)return Yw8(Z,J.pluginService),Xw8(A,Q,B,J);else{if(Q.threadId&&W7(Q.threadId)){let D=await yA.getThreadLinkInfo({thread:Q.threadId},{config:J.configService}).catch(()=>null);if(D?.ok&&D.result.usesThreadActors)throw await J.asyncDispose(),new X4(`Thread ${Q.threadId} was created with the Neo TUI and cannot be continued in the legacy CLI.`,1,"Re-run without --take-me-back to continue this thread.")}return Fw8(A,Q,B,$,{dependencies:J})}}async function Zw8(A,Q,B){let $=(z,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=gA1();j.info("Startup phase",{phase:z,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};A9(B,Q);let J=process.hrtime.bigint(),Y=await Q2(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(SD(Z))throw P40(Z,A.ampURL);let X=gA(Z)?Z:null,F=X?.user.email;await _X1(B,Q,Z);let D=t_(Z),G=Y00(Q,D);if(G instanceof Error)l5(G.message);if(X&&!Bv(Q.mode,F))throw new X4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!F||!ZQ(F)))throw new X4("Headless executor mode is only available for Amp employees",1);RU0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new X4("API key required for headless mode. Please run `amp login` first.",1);let K=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(K&&!W7(K))throw new X4(`Invalid thread ID: ${K}`,1);let E=K?void 0:await Cw8({dependencies:Y,apiKey:U,visibility:G??void 0}),H=K??E?.threadId;if(!H)throw new X4("Failed to resolve headless thread ID",1);let W=await Bt4(H);if(W.status==="already-running")await Y.asyncDispose(),await tW(),process.exit(0);try{await ns4({ampURL:A.ampURL,apiKey:U,workspaceRoot:process.cwd(),threadId:H,ownerUserId:E?.ownerUserId,threadVersion:E?.threadVersion,agentMode:E?.agentMode,initialToolDiscovery:Promise.all([Y.mcpService.initialized,Y.toolboxService.initialized]).then(()=>{return}),configService:Y.configService,mcpService:Y.mcpService,toolService:Y.toolService,skillService:Y.skillService,fileSystem:Y.fileSystem,pluginService:Y.pluginService,pluginPlatform:Y.headlessPluginPlatform})}finally{await W.release(),await Y.asyncDispose()}await tW(),process.exit(0)}async function Xw8(A,Q,B,$){let{userInput:J,stdinInput:Y}=await $UA(Q),Z=!!Q.streamJson||!!Q.streamJsonThinking;JUA({...Q,streamJson:Z},A.executeMode,J),A9(B,Q);let X=Q.threadId&&W7(Q.threadId)?Q.threadId:void 0,F=Q.observe?i8(Q.observe)??WB(Q.observe):void 0,D=await $.serverStatusPromise;if(SD(D))throw P40(D,A.ampURL);let G=await $.secretStorage.get("apiKey",A.ampURL);if(!G)throw new X4("API key required. Please run `amp login` first.",1);let V=gA(D)&&ZQ(D.user.email);if(V)RU0();if(A.executeMode){h31($.mcpService,A.settings);try{let U=AN0(B,Q),K=await BC(),E=X?U:QE0({agentMode:Q.mode,explicitEffort:U,sessionState:K}),H=X?void 0:BE0(await vu($.configService),{agentMode:Q.mode,explicitEffort:U,sessionState:K}),W=await Vs4({apiKey:G,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:$,userInput:J,stdinInput:Y,stats:!!Q.stats,streamJson:Z,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:E,labels:Q.label,initialThreadID:X,initialSettings:H});if(await Cg(W,"execute"),Q.archive)await $.threadService.archive(W,!0)}finally{await $.asyncDispose()}await tW(),process.exit(0)}else{let U=AN0(B,Q),K=Oj($.configService,{usesThreadActors:!0}),E=new k_($.fuzzyServer),H=process.cwd();await H$1({ampURL:A.ampURL,apiKey:G,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??pJ(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:W})=>hw({fileSystem:$.fileSystem,workspaceRoot:H},W),completionBuilder:E,workspaceRoot:H,listThreads:()=>K.listThreads(),getThreadFromServer:(W)=>K.getThread(W),toolboxes:$.toolboxService.toolboxes,isInternalUser:V,settingsFilePath:$.settingsStorage.getSettingsFilePath()},{initialThreadID:F??X,initialUserInput:J||void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!F,splashOrbVisualStyle:"neo",showNeoWelcome:Q.showNeoWelcome,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:U}),process.exit(0)}}async function Fw8(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(z0,A0)=>{let Y0=Number(process.hrtime.bigint()-A0)/1e6,a=gA1();j.info("Startup phase",{phase:z0,phaseMs:Math.round(Y0),sinceMainMs:a===null?void 0:Math.round(a)})},{userInput:X,stdinInput:F}=await $UA(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;JUA({...Q,streamJson:D},A.executeMode,X),A9(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await Q2(A,Q),U=V.hasAPIKeyAtStartup,K=V.serverStatus==="pending";if(j.info("Interactive auth startup mode",{deferInteractiveAuth:K,hasAPIKeyAtStartup:U,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!J)Z("runMainThread:createThreadDependencies",G);let{serverStatus:E}=V;if(!K&&SD(E))throw P40(E,A.ampURL);let H=gA(E)?E:null,W=H?.user.email,z=!!(W&&ZQ(W));if(z)RU0();if(!K)await _X1(B,Q,E);let q=t_(E),N=q?.features??[],I=q?.team??null,w=Y00(Q,q);if(w instanceof Error)l5(w.message);if(H&&!Bv(Q.mode,W))throw new X4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let C=Q.threadId&&W7(Q.threadId)?Q.threadId:void 0;G=process.hrtime.bigint();let O=await $N0(V);Z("runMainThread:createWorkerDeps",G);let P=A.executeMode?void 0:async(z0)=>Cg(z0,"interactive"),S={threadService:V.threadService,workerDeps:O,createThread:async(z0)=>{let A0=K?await V.serverStatusPromise:E,Y0=await PU0(A.settings,process.cwd(),t_(A0),w);if(Y0 instanceof Error)l5(Y0.message);return QZ1(O,{threadMeta:Y0?xZ(Y0):void 0,agentMode:z0??Q.mode,onFirstAssistantMessage:P})},validateThreadOwnership:async(z0,A0)=>{if(A0?.nonBlockingOwnershipCheck){rVA(z0,V.configService,V.viewerUserIDPromise).catch((Y0)=>{if(Y0 instanceof X4){if(A0.onOwnershipError){A0.onOwnershipError(Y0,z0);return}eW(Y0,z0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Y0})});return}try{await rVA(z0,V.configService,V.viewerUserIDPromise)}catch(Y0){if(Y0 instanceof X4)throw Y0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Y0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:P,handleError:eW},T=async()=>{try{return CFA(S,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(z0){if(z0 instanceof X4)throw z0;throw await eW(z0,Q.threadId),Error("handleError should have called process.exit()")}},f=(async()=>{if(K){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await V.configService.getLatest(),A0=jc(z0),Y0=await yA.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(A0)});if(Y0.ok)return j.info("User free tier status:",Y0),Y0.result;return}catch(z0){j.error("Failed to fetch free tier status:",z0);return}})(),b=!A.executeMode?new O$1:null,y,u=null;if(b)y=b,u=(async()=>{let z0=K?await V.serverStatusPromise:V.serverStatus;if(SD(z0))throw P40(z0,A.ampURL);await _X1(B,Q,z0);let A0=process.hrtime.bigint(),Y0=await T();if(Z("runMainThread:createThreadPool",A0),b.attach(Y0),X){let a=await k1(Y0.threadHandles$);if(!a)throw new X4("No active thread is available yet.",1);await a.sendMessage({content:[{type:"text",text:X}]})}})(),u.catch(async(z0)=>{let A0=z0 instanceof Error?z0:Error(String(z0));b.setInitError(A0),await eW(z0,Q.threadId)});else G=process.hrtime.bigint(),y=await T(),Z("runMainThread:createThreadPool",G);let m=Q.notifications!==void 0?Q.notifications:!A.executeMode,d=H!==null&&R40(H.features,Z9.TUI_VOICE_NOTIF);if(K)V.serverStatusPromise.then((z0)=>{d=gA(z0)&&R40(z0.features,Z9.TUI_VOICE_NOTIF)}).catch((z0)=>{j.debug("Failed to resolve TUI voice notification feature flag",{error:z0})});G=process.hrtime.bigint();let g=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),Bw8({configService:V.configService,threadService:V.threadService,config:g,useNotificationsForService:m,isTUIVoiceNotifEnabled:()=>d,threadViewStates$:()=>y.threadHandles$.pipe(i4((z0)=>{if(!z0)return g0.of({});return u6(z0.thread$,z0.threadViewState$).pipe(O1(([A0,Y0])=>({[A0.id]:Y0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){h31(V.mcpService,A.settings);let z0=AN0(B,Q),A0=await BC(),Y0=C?z0:QE0({agentMode:Q.mode,explicitEffort:z0,sessionState:A0}),a={userInput:X,stdinInput:F,dependencies:V,streamJson:D,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:z,agentMode:Q.mode,reasoningEffort:Y0,labels:Q.label},r=await Uo4({threadPool:y,...a});if(await Cg(r,"execute"),Q.archive)await V.threadService.archive(r,!0);await V.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Q.jetbrains||Q.ide){await V70();let z0=await PD({jetbrainsOnly:Q.jetbrains});if(z0.length===0){if(Q.jetbrains)n=!await V.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let A0=z0[0];if(A0)a8.selectConfig(A0)}else c=!0}G=process.hrtime.bigint();let $0=J31("0.0.1777680871-g5fc25d",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let j0=new g31(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),X&&A.executeMode){let z0=await k1(y.threadHandles$);if(!z0)throw new X4("No active thread is available yet.",1);await z0.sendMessage({content:[{type:"text",text:X}]})}G=process.hrtime.bigint();let l=await BC();Z("runMainThread:loadSessionState",G),j.info("Loaded session state:",l);let B0=AN0(B,Q),K0={...l,launchCount:l.launchCount+1,lastReasoningEffortByMode:B0?{...l.lastReasoningEffortByMode,[Q.mode]:B0}:l.lastReasoningEffortByMode};kZ((z0)=>({...z0,launchCount:z0.launchCount+1}));try{if(G=process.hrtime.bigint(),await x$A({history:new Je,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:yA,threadPool:y,createSystemPromptDeps:async()=>QUA(V),ideClient:a8,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:j0,updateService:$0,pluginPlatform:V.pluginPlatform,pluginService:V.pluginService},{initialServerStatus:V.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:V.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:C,showJetBrainsInstaller:n,showIdePickerHint:c,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:gI8,logFile:{path:$},sessionState:K0,freeTierStatusPromise:f,workspace:I??null,features:N,isInternalUser:z,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-02T00:18:10.627Z"},(z0)=>new k$1({...z0,threadPool:z0.threadPool},(A0)=>new eY1({...A0,threadState:A0.threadState}))),Z("runMainThread:mountApp-returned",G),u)await u}finally{await y.dispose().catch((z0)=>{j.error("Failed to dispose thread pool during shutdown",z0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function E8(A){if(j.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)DY.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6277
- `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await kF4({get:async(X)=>{if(X!==ji)return;try{let F=await AUA(PX1,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(X,F)=>{if(X!==ji)return;await fI8(j40.dirname(PX1),{recursive:!0}),await bI8(PX1,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:sB0()});p84($);let J=await HK0({...A,workspaceTrust:{current:!0,changes:ax0},getHook:process.env.AMP_URL?(X,F)=>{if(X==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(A.mcpConfig){let X=await Z1A(A.mcpConfig);J=X1A(J,X)}let Y=j40.dirname(J.getSettingsFilePath());jx4(wu,Y),J=j54(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=v9;if(j.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!QN(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:JE0(await Ke(A,J))}}function Dw8(A){let Q={};for(let B=0;B<A.length;B++){let $=A[B];if($?.startsWith("--")){let Y=$.slice(2).replace(/-([a-z])/g,(X,F)=>F.toUpperCase()),Z=A[B+1];if(Z&&!Z.startsWith("--"))Q[Y]=Z,B++}}return Q}function Gw8(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=j40.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?hI8:it));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function Vw8(){Cc4();let A=Dw8(process.argv),Q=Gw8(process.argv,A),B=Ta4(Q),$=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)r0.level=0;if(pI8(j),j.info("Starting Amp CLI.",{version:"0.0.1777680871-g5fc25d",buildTimestamp:"2026-05-02T00:18:10.627Z"}),process.platform==="win32"&&yP())Ae4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new X4(g7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Jw8(B).parseAsync(process.argv)}Lx4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await Vw8().catch(eW)});async function Uw8(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"),N5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6276
+ Or pipe via stdin: echo "your message" | amp --execute`)}function Yw8(A,Q){if(VQ4([O90.parse({tool:"*",action:"allow"})]),_BA(A.settings))j.debug("Enabling permissions plugin"),Q.registerInternalPlugin({name:"permissions",entryPoint:W$1})}async function BN0(A,Q,B,$){if(Q.headless)return Zw8(A,Q,B);let J=await Q2(A,Q),Y=await J.serverStatusPromise,Z=await J.configService.getLatest(),X=gA(Y)&&R40(Y.features,Z9.THREAD_ACTORS_TUI),F=X&&!Q.takeMeBack;if(Q.showNeoWelcome&&!X)throw await J.asyncDispose(),new X4("--show-neo-welcome is only available with the Neo TUI feature flag",1);if(F)return Yw8(Z,J.pluginService),Xw8(A,Q,B,J);else{if(Q.threadId&&W7(Q.threadId)){let D=await yA.getThreadLinkInfo({thread:Q.threadId},{config:J.configService}).catch(()=>null);if(D?.ok&&D.result.usesThreadActors)throw await J.asyncDispose(),new X4(`Thread ${Q.threadId} was created with the Neo TUI and cannot be continued in the legacy CLI.`,1,"Re-run without --take-me-back to continue this thread.")}return Fw8(A,Q,B,$,{dependencies:J})}}async function Zw8(A,Q,B){let $=(z,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=gA1();j.info("Startup phase",{phase:z,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};A9(B,Q);let J=process.hrtime.bigint(),Y=await Q2(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(SD(Z))throw P40(Z,A.ampURL);let X=gA(Z)?Z:null,F=X?.user.email;await _X1(B,Q,Z);let D=t_(Z),G=Y00(Q,D);if(G instanceof Error)l5(G.message);if(X&&!Bv(Q.mode,F))throw new X4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!F||!ZQ(F)))throw new X4("Headless executor mode is only available for Amp employees",1);RU0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new X4("API key required for headless mode. Please run `amp login` first.",1);let K=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(K&&!W7(K))throw new X4(`Invalid thread ID: ${K}`,1);let E=K?void 0:await Cw8({dependencies:Y,apiKey:U,visibility:G??void 0}),H=K??E?.threadId;if(!H)throw new X4("Failed to resolve headless thread ID",1);let W=await Bt4(H);if(W.status==="already-running")await Y.asyncDispose(),await tW(),process.exit(0);try{await ns4({ampURL:A.ampURL,apiKey:U,workspaceRoot:process.cwd(),threadId:H,ownerUserId:E?.ownerUserId,threadVersion:E?.threadVersion,agentMode:E?.agentMode,initialToolDiscovery:Promise.all([Y.mcpService.initialized,Y.toolboxService.initialized]).then(()=>{return}),configService:Y.configService,mcpService:Y.mcpService,toolService:Y.toolService,skillService:Y.skillService,fileSystem:Y.fileSystem,pluginService:Y.pluginService,pluginPlatform:Y.headlessPluginPlatform})}finally{await W.release(),await Y.asyncDispose()}await tW(),process.exit(0)}async function Xw8(A,Q,B,$){let{userInput:J,stdinInput:Y}=await $UA(Q),Z=!!Q.streamJson||!!Q.streamJsonThinking;JUA({...Q,streamJson:Z},A.executeMode,J),A9(B,Q);let X=Q.threadId&&W7(Q.threadId)?Q.threadId:void 0,F=Q.observe?i8(Q.observe)??WB(Q.observe):void 0,D=await $.serverStatusPromise;if(SD(D))throw P40(D,A.ampURL);let G=await $.secretStorage.get("apiKey",A.ampURL);if(!G)throw new X4("API key required. Please run `amp login` first.",1);let V=gA(D)&&ZQ(D.user.email);if(V)RU0();if(A.executeMode){h31($.mcpService,A.settings);try{let U=AN0(B,Q),K=await BC(),E=X?U:QE0({agentMode:Q.mode,explicitEffort:U,sessionState:K}),H=X?void 0:BE0(await vu($.configService),{agentMode:Q.mode,explicitEffort:U,sessionState:K}),W=await Vs4({apiKey:G,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:$,userInput:J,stdinInput:Y,stats:!!Q.stats,streamJson:Z,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:E,labels:Q.label,initialThreadID:X,initialSettings:H});if(await Cg(W,"execute"),Q.archive)await $.threadService.archive(W,!0)}finally{await $.asyncDispose()}await tW(),process.exit(0)}else{let U=AN0(B,Q),K=Oj($.configService,{usesThreadActors:!0}),E=new k_($.fuzzyServer),H=process.cwd();await H$1({ampURL:A.ampURL,apiKey:G,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??pJ(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:W})=>hw({fileSystem:$.fileSystem,workspaceRoot:H},W),completionBuilder:E,workspaceRoot:H,listThreads:()=>K.listThreads(),getThreadFromServer:(W)=>K.getThread(W),toolboxes:$.toolboxService.toolboxes,isInternalUser:V,settingsFilePath:$.settingsStorage.getSettingsFilePath()},{initialThreadID:F??X,initialUserInput:J||void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!F,splashOrbVisualStyle:"neo",showNeoWelcome:Q.showNeoWelcome,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:U}),process.exit(0)}}async function Fw8(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(z0,A0)=>{let Y0=Number(process.hrtime.bigint()-A0)/1e6,a=gA1();j.info("Startup phase",{phase:z0,phaseMs:Math.round(Y0),sinceMainMs:a===null?void 0:Math.round(a)})},{userInput:X,stdinInput:F}=await $UA(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;JUA({...Q,streamJson:D},A.executeMode,X),A9(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await Q2(A,Q),U=V.hasAPIKeyAtStartup,K=V.serverStatus==="pending";if(j.info("Interactive auth startup mode",{deferInteractiveAuth:K,hasAPIKeyAtStartup:U,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!J)Z("runMainThread:createThreadDependencies",G);let{serverStatus:E}=V;if(!K&&SD(E))throw P40(E,A.ampURL);let H=gA(E)?E:null,W=H?.user.email,z=!!(W&&ZQ(W));if(z)RU0();if(!K)await _X1(B,Q,E);let q=t_(E),N=q?.features??[],I=q?.team??null,w=Y00(Q,q);if(w instanceof Error)l5(w.message);if(H&&!Bv(Q.mode,W))throw new X4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let C=Q.threadId&&W7(Q.threadId)?Q.threadId:void 0;G=process.hrtime.bigint();let O=await $N0(V);Z("runMainThread:createWorkerDeps",G);let P=A.executeMode?void 0:async(z0)=>Cg(z0,"interactive"),S={threadService:V.threadService,workerDeps:O,createThread:async(z0)=>{let A0=K?await V.serverStatusPromise:E,Y0=await PU0(A.settings,process.cwd(),t_(A0),w);if(Y0 instanceof Error)l5(Y0.message);return QZ1(O,{threadMeta:Y0?xZ(Y0):void 0,agentMode:z0??Q.mode,onFirstAssistantMessage:P})},validateThreadOwnership:async(z0,A0)=>{if(A0?.nonBlockingOwnershipCheck){rVA(z0,V.configService,V.viewerUserIDPromise).catch((Y0)=>{if(Y0 instanceof X4){if(A0.onOwnershipError){A0.onOwnershipError(Y0,z0);return}eW(Y0,z0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Y0})});return}try{await rVA(z0,V.configService,V.viewerUserIDPromise)}catch(Y0){if(Y0 instanceof X4)throw Y0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Y0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:P,handleError:eW},T=async()=>{try{return CFA(S,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(z0){if(z0 instanceof X4)throw z0;throw await eW(z0,Q.threadId),Error("handleError should have called process.exit()")}},f=(async()=>{if(K){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await V.configService.getLatest(),A0=jc(z0),Y0=await yA.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(A0)});if(Y0.ok)return j.info("User free tier status:",Y0),Y0.result;return}catch(z0){j.error("Failed to fetch free tier status:",z0);return}})(),b=!A.executeMode?new O$1:null,y,u=null;if(b)y=b,u=(async()=>{let z0=K?await V.serverStatusPromise:V.serverStatus;if(SD(z0))throw P40(z0,A.ampURL);await _X1(B,Q,z0);let A0=process.hrtime.bigint(),Y0=await T();if(Z("runMainThread:createThreadPool",A0),b.attach(Y0),X){let a=await k1(Y0.threadHandles$);if(!a)throw new X4("No active thread is available yet.",1);await a.sendMessage({content:[{type:"text",text:X}]})}})(),u.catch(async(z0)=>{let A0=z0 instanceof Error?z0:Error(String(z0));b.setInitError(A0),await eW(z0,Q.threadId)});else G=process.hrtime.bigint(),y=await T(),Z("runMainThread:createThreadPool",G);let m=Q.notifications!==void 0?Q.notifications:!A.executeMode,d=H!==null&&R40(H.features,Z9.TUI_VOICE_NOTIF);if(K)V.serverStatusPromise.then((z0)=>{d=gA(z0)&&R40(z0.features,Z9.TUI_VOICE_NOTIF)}).catch((z0)=>{j.debug("Failed to resolve TUI voice notification feature flag",{error:z0})});G=process.hrtime.bigint();let g=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),Bw8({configService:V.configService,threadService:V.threadService,config:g,useNotificationsForService:m,isTUIVoiceNotifEnabled:()=>d,threadViewStates$:()=>y.threadHandles$.pipe(i4((z0)=>{if(!z0)return g0.of({});return u6(z0.thread$,z0.threadViewState$).pipe(O1(([A0,Y0])=>({[A0.id]:Y0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){h31(V.mcpService,A.settings);let z0=AN0(B,Q),A0=await BC(),Y0=C?z0:QE0({agentMode:Q.mode,explicitEffort:z0,sessionState:A0}),a={userInput:X,stdinInput:F,dependencies:V,streamJson:D,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:z,agentMode:Q.mode,reasoningEffort:Y0,labels:Q.label},r=await Uo4({threadPool:y,...a});if(await Cg(r,"execute"),Q.archive)await V.threadService.archive(r,!0);await V.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Q.jetbrains||Q.ide){await V70();let z0=await PD({jetbrainsOnly:Q.jetbrains});if(z0.length===0){if(Q.jetbrains)n=!await V.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let A0=z0[0];if(A0)a8.selectConfig(A0)}else c=!0}G=process.hrtime.bigint();let $0=J31("0.0.1777697948-g1a223c",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let j0=new g31(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),X&&A.executeMode){let z0=await k1(y.threadHandles$);if(!z0)throw new X4("No active thread is available yet.",1);await z0.sendMessage({content:[{type:"text",text:X}]})}G=process.hrtime.bigint();let l=await BC();Z("runMainThread:loadSessionState",G),j.info("Loaded session state:",l);let B0=AN0(B,Q),K0={...l,launchCount:l.launchCount+1,lastReasoningEffortByMode:B0?{...l.lastReasoningEffortByMode,[Q.mode]:B0}:l.lastReasoningEffortByMode};kZ((z0)=>({...z0,launchCount:z0.launchCount+1}));try{if(G=process.hrtime.bigint(),await x$A({history:new Je,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:yA,threadPool:y,createSystemPromptDeps:async()=>QUA(V),ideClient:a8,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:j0,updateService:$0,pluginPlatform:V.pluginPlatform,pluginService:V.pluginService},{initialServerStatus:V.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:V.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:C,showJetBrainsInstaller:n,showIdePickerHint:c,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:gI8,logFile:{path:$},sessionState:K0,freeTierStatusPromise:f,workspace:I??null,features:N,isInternalUser:z,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-02T05:02:48.212Z"},(z0)=>new k$1({...z0,threadPool:z0.threadPool},(A0)=>new eY1({...A0,threadState:A0.threadState}))),Z("runMainThread:mountApp-returned",G),u)await u}finally{await y.dispose().catch((z0)=>{j.error("Failed to dispose thread pool during shutdown",z0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function E8(A){if(j.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)DY.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6277
+ `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await kF4({get:async(X)=>{if(X!==ji)return;try{let F=await AUA(PX1,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(X,F)=>{if(X!==ji)return;await fI8(j40.dirname(PX1),{recursive:!0}),await bI8(PX1,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:sB0()});p84($);let J=await HK0({...A,workspaceTrust:{current:!0,changes:ax0},getHook:process.env.AMP_URL?(X,F)=>{if(X==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(A.mcpConfig){let X=await Z1A(A.mcpConfig);J=X1A(J,X)}let Y=j40.dirname(J.getSettingsFilePath());jx4(wu,Y),J=j54(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=v9;if(j.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!QN(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:JE0(await Ke(A,J))}}function Dw8(A){let Q={};for(let B=0;B<A.length;B++){let $=A[B];if($?.startsWith("--")){let Y=$.slice(2).replace(/-([a-z])/g,(X,F)=>F.toUpperCase()),Z=A[B+1];if(Z&&!Z.startsWith("--"))Q[Y]=Z,B++}}return Q}function Gw8(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=j40.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?hI8:it));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function Vw8(){Cc4();let A=Dw8(process.argv),Q=Gw8(process.argv,A),B=Ta4(Q),$=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)r0.level=0;if(pI8(j),j.info("Starting Amp CLI.",{version:"0.0.1777697948-g1a223c",buildTimestamp:"2026-05-02T05:02:48.212Z"}),process.platform==="win32"&&yP())Ae4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new X4(g7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Jw8(B).parseAsync(process.argv)}Lx4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await Vw8().catch(eW)});async function Uw8(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"),N5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6278
6278
  `);else if(!QN(A.ampURL))N5.write(`Logging in to ${new URL(A.ampURL).hostname}
6279
6279
  `);let $=process.env.AMP_API_KEY;if($)N5.write(`API key found in environment variable, storing...
6280
6280
  `),await Q.set("apiKey",$,A.ampURL),N5.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1777680871-g5fc25d",
3
+ "version": "0.0.1777697948-g1a223c",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {