@sourcegraph/amp 0.0.1777910718-gcdf3ba → 0.0.1777912178-gd6d908
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +9 -9
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -4820,12 +4820,12 @@ ${E}`))}},error:(K)=>{if(!U)U=!0,F(Error(`Failed to spawn brew: ${K.message}`))}
|
|
|
4820
4820
|
${E}`;if(Y==="pnpm"&&E.includes("Unable to find the global bin directory"))H+=`
|
|
4821
4821
|
|
|
4822
4822
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
4823
|
-
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()}})})}o0();o0();fI();async function NK0(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=_e(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 Er5="https://static.ampcode.com/cli/cli-version.txt";async function IK0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${Er5}?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=_e(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 Hr5=604800000;function Ce4(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>Hr5)return{ageMs:B};return null}function _e(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();o0();import{readFile as Wr5,realpath as zr5}from"node:fs/promises";import{homedir as qr5}from"node:os";import{dirname as Me4,join as $31}from"node:path";async function Le4(A){switch(A){case"binary":case"brew":return Nr5(Oe());case"npm":case"pnpm":case"yarn":case"bun":return Ir5();case"bootstrap":return wr5()}}async function Nr5(A){let Q=await gG(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 Ir5(){try{let A=process.argv[1];if(!A)return null;let Q=await zr5(A),B=Me4(Me4(Q));return await Oe4($31(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function wr5(){try{let A=process.env.AMP_HOME??$31(qr5(),".amp");return await Oe4($31(A,"package","package.json"))}catch(A){return j.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function Oe4(A){let Q=await Wr5(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 Cr5=3600000,Mr5=5000;function J31(A,Q,B={}){let $=new o4,J=$.pipe($6({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??Cr5,X=!1,F=()=>{X=!0};return setImmediate(async()=>{let D=new xY().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 Lr5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await oU(Mr5),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 Lr5(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 zK0(),X=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:X});let F;if(X)F=await IK0(A);else{let V=await fP();F=await NK0(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 Le4(Z);if(V&&_e(V,F.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:F.latestVersion}),J.updatedTo=V,_e(A,V)<0){let U=await $z(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!==Oe()){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 Pe(F.latestVersion,Z),J.updatedTo=F.latestVersion;let V=await $z(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}}fI();import{stderr as mG}from"node:process";function je4(A){let Q=new Xw().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.
|
|
4823
|
+
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()}})})}o0();o0();fI();async function NK0(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=_e(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 Er5="https://static.ampcode.com/cli/cli-version.txt";async function IK0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${Er5}?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=_e(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 Hr5=604800000;function Ce4(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>Hr5)return{ageMs:B};return null}function _e(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();o0();import{readFile as Wr5,realpath as zr5}from"node:fs/promises";import{homedir as qr5}from"node:os";import{dirname as Me4,join as $31}from"node:path";async function Le4(A){switch(A){case"binary":case"brew":return Nr5(Oe());case"npm":case"pnpm":case"yarn":case"bun":return Ir5();case"bootstrap":return wr5()}}async function Nr5(A){let Q=await gG(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 Ir5(){try{let A=process.argv[1];if(!A)return null;let Q=await zr5(A),B=Me4(Me4(Q));return await Oe4($31(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function wr5(){try{let A=process.env.AMP_HOME??$31(qr5(),".amp");return await Oe4($31(A,"package","package.json"))}catch(A){return j.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function Oe4(A){let Q=await Wr5(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 Cr5=3600000,Mr5=5000;function J31(A,Q,B={}){let $=new o4,J=$.pipe($6({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??Cr5,X=!1,F=()=>{X=!0};return setImmediate(async()=>{let D=new xY().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 Lr5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await oU(Mr5),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 Lr5(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 zK0(),X=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:X});let F;if(X)F=await IK0(A);else{let V=await fP();F=await NK0(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 Le4(Z);if(V&&_e(V,F.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:F.latestVersion}),J.updatedTo=V,_e(A,V)<0){let U=await $z(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!==Oe()){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 Pe(F.latestVersion,Z),J.updatedTo=F.latestVersion;let V=await $z(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}}fI();import{stderr as mG}from"node:process";function je4(A){let Q=new Xw().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.1777912178-gd6d908"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new Xw("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 jr5($.targetVersion)});A.addCommand(B)}function Or5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
|
|
4824
4824
|
`),$=!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 jr5(A){let B=process.platform==="win32"&&xP()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:$,renderProgress:J}=Or5(mG);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")mG.write(s0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
4825
4825
|
|
|
4826
4826
|
`));try{if(!A){mG.write(s0.blue(`Checking for updates...
|
|
4827
|
-
`));let X=!1,F;if(xP()){let D=await IK0("0.0.
|
|
4828
|
-
`));let V=await $z("0.0.
|
|
4827
|
+
`));let X=!1,F;if(xP()){let D=await IK0("0.0.1777912178-gd6d908");X=D.hasUpdate,F=D.latestVersion}else{let D=await fP(),G=await NK0("0.0.1777912178-gd6d908",D);X=G.hasUpdate,F=G.latestVersion}if(!X){let D=B31("0.0.1777912178-gd6d908"),G=D?.age?`released ${D.age} ago`:`built ${rU(new Date("2026-05-04T16:33:09.749Z"))} ago`;mG.write(s0.green(`✓ Amp is already up to date on version ${"0.0.1777912178-gd6d908"} (${G})
|
|
4828
|
+
`));let V=await $z("0.0.1777912178-gd6d908",B);if(V.warning)mG.write(`
|
|
4829
4829
|
`+s0.yellow(V.warning)+`
|
|
4830
4830
|
`);process.exit(0)}if(!F)mG.write(s0.yellow("[WARN] could not find latest version")),process.exit(0);A=F}mG.write(s0.blue(`Updating to version ${A}...
|
|
4831
4831
|
`)),await Pe(A,void 0,(X)=>{$(),mG.write(s0.dim(`Running: ${X}
|
|
@@ -5370,7 +5370,7 @@ Ctrl-X, Y, Z to unlock`;if(E){let B0=G.text.replace(/`([^`]+)`/g,"$1")+`
|
|
|
5370
5370
|
* MIT Licence
|
|
5371
5371
|
*/var Sh=9000000000000000,fC=1e9,V$1="0123456789abcdef",zW0="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",qW0="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",U$1={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Sh,maxE:Sh,crypto:!1},CBA,wz,Q6=!0,IW0="[DecimalError] ",xC=IW0+"Invalid argument: ",MBA=IW0+"Precision limit exceeded",LBA=IW0+"crypto unavailable",OBA="[object Decimal]",_B=Math.floor,X7=Math.pow,CZ8=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,MZ8=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,LZ8=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,jBA=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,QV=1e7,mA=7,OZ8=9007199254740991,jZ8=zW0.length-1,K$1=qW0.length-1,c1={toStringTag:OBA};c1.absoluteValue=c1.abs=function(){var A=new this.constructor(this);if(A.s<0)A.s=1;return NA(A)};c1.ceil=function(){return NA(new this.constructor(this),this.e+1,2)};c1.clampedTo=c1.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(xC+Q);return B=$.cmp(A),B<0?A:$.cmp(Q)>0?Q:new J($)};c1.comparedTo=c1.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};c1.cosine=c1.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())+mA,$.rounding=1,B=RZ8($,SBA($,B)),$.precision=A,$.rounding=Q,NA(wz==2||wz==3?B.neg():B,A,Q,!0)};c1.cubeRoot=c1.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),$=u8(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(NA(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")NA($,A+1,1),Q=!$.times($).times($).eq(G);break}return Q6=!0,NA($,A,V.rounding,Q)};c1.decimalPlaces=c1.dp=function(){var A,Q=this.d,B=NaN;if(Q){if(A=Q.length-1,B=(A-_B(this.e/mA))*mA,A=Q[A],A)for(;A%10==0;A/=10)B--;if(B<0)B=0}return B};c1.dividedBy=c1.div=function(A){return u8(this,new this.constructor(A))};c1.dividedToIntegerBy=c1.divToInt=function(A){var Q=this,B=Q.constructor;return NA(u8(Q,new B(A),0,1,1),B.precision,B.rounding)};c1.equals=c1.eq=function(A){return this.cmp(A)===0};c1.floor=function(){return NA(new this.constructor(this),this.e+1,3)};c1.greaterThan=c1.gt=function(A){return this.cmp(A)>0};c1.greaterThanOrEqualTo=c1.gte=function(A){var Q=this.cmp(A);return Q==1||Q===0};c1.hyperbolicCosine=c1.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 NA(Y,Z.precision=B,Z.rounding=$,!0)};c1.hyperbolicSine=c1.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,NA(J,Q,B,!0)};c1.hyperbolicTangent=c1.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,u8(B.sinh(),B.cosh(),$.precision=A,$.rounding=Q)};c1.inverseCosine=c1.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()?DE(Q,$,J):new Q(0):new Q(NaN);if(A.isZero())return DE(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)};c1.inverseHyperbolicCosine=c1.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()};c1.inverseHyperbolicSine=c1.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()};c1.inverseHyperbolicTangent=c1.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 NA(new Y(J),A,Q,!0);return Y.precision=B=$-J.e,J=u8(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)};c1.inverseSine=c1.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=DE(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)};c1.inverseTangent=c1.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<=K$1)return Z=DE(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<=K$1)return Z=DE(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/mA+2|0);for(A=B;A;--A)D=D.div(D.times(D).plus(1).sqrt().plus(1));Q6=!1,Q=Math.ceil(X/mA),$=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,NA(Z,G.precision=V,G.rounding=U,!0)};c1.isFinite=function(){return!!this.d};c1.isInteger=c1.isInt=function(){return!!this.d&&_B(this.e/mA)>this.d.length-2};c1.isNaN=function(){return!this.s};c1.isNegative=c1.isNeg=function(){return this.s<0};c1.isPositive=c1.isPos=function(){return this.s>0};c1.isZero=function(){return!!this.d&&this.d[0]===0};c1.lessThan=c1.lt=function(A){return this.cmp(A)<0};c1.lessThanOrEqualTo=c1.lte=function(A){return this.cmp(A)<1};c1.logarithm=c1.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=yC(D,X),$=Q?NW0(G,X+10):yC(A,X),F=u8(Z,$,X,1),L10(F.d,J=V,U))do if(X+=10,Z=yC(D,X),$=Q?NW0(G,X+10):yC(A,X),F=u8(Z,$,X,1),!Y){if(+yQ(F.d).slice(J+1,J+15)+1==100000000000000)F=NA(F,V+1,0);break}while(L10(F.d,J+=10,U));return Q6=!0,NA(F,V,U)};c1.minus=c1.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?NA(A,X,F):A}if(B=_B(A.e/mA),G=_B(K.e/mA),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/mA),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]=QV-1;--D[J],D[$]+=QV}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?NA(A,X,F):A};c1.modulo=c1.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 NA(new $(B),$.precision,$.rounding);if(Q6=!1,$.modulo==9)Q=u8(B,A.abs(),0,3,1),Q.s*=A.s;else Q=u8(B,A,0,$.modulo,1);return Q=Q.times(A),Q6=!0,B.minus(Q)};c1.naturalExponential=c1.exp=function(){return E$1(this)};c1.naturalLogarithm=c1.ln=function(){return yC(this)};c1.negated=c1.neg=function(){var A=new this.constructor(this);return A.s=-A.s,NA(A)};c1.plus=c1.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?NA(A,X,F):A}if(Y=_B(V.e/mA),$=_B(A.e/mA),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/mA),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)/QV|0,D[J]%=QV;if(Q)D.unshift(Q),++$;for(Z=D.length;D[--Z]==0;)D.pop();return A.d=D,A.e=wW0(D,$),Q6?NA(A,X,F):A};c1.precision=c1.sd=function(A){var Q,B=this;if(A!==void 0&&A!==!!A&&A!==1&&A!==0)throw Error(xC+A);if(B.d){if(Q=RBA(B.d),A&&B.e+1>Q)Q=B.e+1}else Q=NaN;return Q};c1.round=function(){var A=this,Q=A.constructor;return NA(new Q(A),A.e+1,Q.rounding)};c1.sine=c1.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())+mA,$.rounding=1,B=_Z8($,SBA($,B)),$.precision=A,$.rounding=Q,NA(wz>2?B.neg():B,A,Q,!0)};c1.squareRoot=c1.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(u8(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(NA(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")NA($,F+1,1),A=!$.times($).eq(Z);break}return Q6=!0,NA($,F,G.rounding,A)};c1.tangent=c1.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=u8(B,new $(1).minus(B.times(B)).sqrt(),A+10,0),$.precision=A,$.rounding=Q,NA(wz==2||wz==4?B.neg():B,A,Q,!0)};c1.times=c1.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/mA)+_B(A.e/mA),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%QV|0,Q=X/QV|0;Y[J]=(Y[J]+Q)%QV|0}for(;!Y[--Z];)Y.pop();if(Q)++B;else Y.shift();return A.d=Y,A.e=wW0(Y,B),Q6?NA(A,V.precision,V.rounding):A};c1.toBinary=function(A,Q){return H$1(this,2,A,Q)};c1.toDecimalPlaces=c1.toDP=function(A,Q){var B=this,$=B.constructor;if(B=new $(B),A===void 0)return B;if(JY(A,0,fC),Q===void 0)Q=$.rounding;else JY(Q,0,8);return NA(B,A+B.e+1,Q)};c1.toExponential=function(A,Q){var B,$=this,J=$.constructor;if(A===void 0)B=GE($,!0);else{if(JY(A,0,fC),Q===void 0)Q=J.rounding;else JY(Q,0,8);$=NA(new J($),A+1,Q),B=GE($,!0,A+1)}return $.isNeg()&&!$.isZero()?"-"+B:B};c1.toFixed=function(A,Q){var B,$,J=this,Y=J.constructor;if(A===void 0)B=GE(J);else{if(JY(A,0,fC),Q===void 0)Q=Y.rounding;else JY(Q,0,8);$=NA(new Y(J),A+J.e+1,Q),B=GE($,!1,A+$.e+1)}return J.isNeg()&&!J.isZero()?"-"+B:B};c1.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=RBA(E)-K.e-1,Z=Y%mA,Q.d[0]=X7(10,Z<0?mA+Z:Z),A==null)A=Y>0?Q:D;else{if(X=new H(A),!X.isInt()||X.lt(D))throw Error(xC+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*mA*2;for(;;){if(V=u8(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=u8(A.minus(B),$,0,1,1),F=F.plus(J.times(D)),B=B.plus(J.times($)),F.s=D.s=K.s,U=u8(D,$,Y,1).minus(K).abs().cmp(u8(F,B,Y,1).minus(K).abs())<1?[D,$]:[F,B],H.precision=G,Q6=!0,U};c1.toHexadecimal=c1.toHex=function(A,Q){return H$1(this,16,A,Q)};c1.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 JY(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=u8(B,A,0,Q,1).times(A),Q6=!0,NA(B);else A.s=B.s,B=A;return B};c1.toNumber=function(){return+this};c1.toOctal=function(A,Q){return H$1(this,8,A,Q)};c1.toPower=c1.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 NA(X,$,Y);if(Q=_B(A.e/mA),Q>=A.d.length-1&&(B=D<0?-D:D)<=OZ8)return J=PBA(F,X,B,$),A.s<0?new F(1).div(J):NA(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=E$1(A.times(yC(X,$+B)),$),J.d){if(J=NA(J,$+5,1),L10(J.d,$,Y)){if(Q=$+10,J=NA(E$1(A.times(yC(X,Q+B)),Q),Q+5,1),+yQ(J.d).slice($+1,$+15)+1==100000000000000)J=NA(J,$+1,0)}}return J.s=Z,Q6=!0,F.rounding=Y,NA(J,$,Y)};c1.toPrecision=function(A,Q){var B,$=this,J=$.constructor;if(A===void 0)B=GE($,$.e<=J.toExpNeg||$.e>=J.toExpPos);else{if(JY(A,1,fC),Q===void 0)Q=J.rounding;else JY(Q,0,8);$=NA(new J($),A,Q),B=GE($,A<=$.e||$.e<=J.toExpNeg,A)}return $.isNeg()&&!$.isZero()?"-"+B:B};c1.toSignificantDigits=c1.toSD=function(A,Q){var B=this,$=B.constructor;if(A===void 0)A=$.precision,Q=$.rounding;else if(JY(A,1,fC),Q===void 0)Q=$.rounding;else JY(Q,0,8);return NA(new $(B),A,Q)};c1.toString=function(){var A=this,Q=A.constructor,B=GE(A,A.e<=Q.toExpNeg||A.e>=Q.toExpPos);return A.isNeg()&&!A.isZero()?"-"+B:B};c1.truncated=c1.trunc=function(){return NA(new this.constructor(this),this.e+1,1)};c1.valueOf=c1.toJSON=function(){var A=this,Q=A.constructor,B=GE(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=mA-$.length,B)Y+=vC(B);Y+=$}if(Z=A[Q],$=Z+"",B=mA-$.length,B)Y+=vC(B)}else if(Z===0)return"0";for(;Z%10===0;)Z/=10;return Y+Z}function JY(A,Q,B){if(A!==~~A||A<Q||A>B)throw Error(xC+A)}function L10(A,Q,B,$){var J,Y,Z,X;for(Y=A[0];Y>=10;Y/=10)--Q;if(--Q<0)Q+=mA,J=0;else J=Math.ceil((Q+1)/mA),Q%=mA;if(Y=X7(10,mA-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]+=V$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 RZ8(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 u8=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,k,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=QV,K=mA,G=_B($.e/K)-_B(J.e/K);f=m.length,k=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<k||U)&&C--;V++)O=U*F+(u[V]||0),q[V]=O/m|0,U=O%m|0;E=U||V<k}else{if(U=F/(m[0]+1)|0,U>1)m=A(m,U,F),u=A(u,U,F),f=m.length,k=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++<k||N[0]!==void 0)&&C--);E=N[0]!==void 0}if(!q[0])q.shift()}if(K==1)z.e=G,CBA=E;else{for(V=1,U=q[0];U>=10;U/=10)V++;z.e=V+G*K-1,NA(z,X?Y+z.e+1:Y,Z,E)}return z}}();function NA(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+=mA,Z=Q,G=V[U=0],F=G/X7(10,J-Z-1)%10|0;else if(U=Math.ceil((Y+1)/mA),X=V.length,U>=X)if($){for(;X++<=U;)V.push(0);G=F=0,J=1,Y%=mA,Z=Y-mA+1}else break A;else{G=X=V[U];for(J=1;X>=10;X/=10)J++;Y%=mA,Z=Y-mA+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,(mA-Q%mA)%mA),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,mA-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]==QV)V[0]=1}break}else{if(V[U]+=X,V[U]!=QV)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 GE(A,Q,B){if(!A.isFinite())return TBA(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)+vC($);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."+vC(-J-1)+Y,B&&($=B-Z)>0)Y+=vC($)}else if(J>=Z){if(Y+=vC(J+1-Z),B&&($=B-J-1)>0)Y=Y+"."+vC($)}else{if(($=J+1)<Z)Y=Y.slice(0,$)+"."+Y.slice($);if(B&&($=B-Z)>0){if(J+1===Z)Y+=".";Y+=vC($)}}return Y}function wW0(A,Q){var B=A[0];for(Q*=mA;B>=10;B/=10)Q++;return Q}function NW0(A,Q,B){if(Q>jZ8){if(Q6=!0,B)A.precision=B;throw Error(MBA)}return NA(new A(zW0),Q,1,!0)}function DE(A,Q,B){if(Q>K$1)throw Error(MBA);return NA(new A(qW0),Q,B,!0)}function RBA(A){var Q=A.length-1,B=Q*mA+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 vC(A){var Q="";for(;A--;)Q+="0";return Q}function PBA(A,Q,B,$){var J,Y=new A(1),Z=Math.ceil($/mA+4);Q6=!1;for(;;){if(B%2){if(Y=Y.times(Q),IBA(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),IBA(Q.d,Z)}return Q6=!0,Y}function NBA(A){return A.d[A.d.length-1]&1}function _BA(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 E$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=NA(Y.times(A),F,1),B=B.times(++G),X=Z.plus(u8(Y,B,F,1)),yQ(X.d).slice(0,F)===yQ(Z.d).slice(0,F)){J=V;while(J--)Z=NA(Z.times(Z),F,1);if(Q==null)if(D<3&&L10(Z.d,F-$,K,D))U.precision=F+=10,B=Y=X=new U(1),G=0,D++;else return NA(Z,U.precision=E,K,Q6=!0);else return U.precision=E,Z}Z=X}}function yC(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=yC(new z($+"."+B.slice(1)),G-E).plus(D),z.precision=N,Q==null?NA(H,N,q,Q6=!0):H;V=H,F=Z=H=u8(H.minus(1),H.plus(1),G,1),U=NA(H.times(H),G,1),J=3;for(;;){if(Z=NA(Z.times(U),G,1),D=F.plus(u8(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=u8(F,new z(K),G,1),Q==null)if(L10(F.d,G-E,q,X))z.precision=G+=E,D=Z=H=u8(V.minus(1),V.plus(1),G,1),U=NA(H.times(H),G,1),J=X=1;else return NA(F,z.precision=N,q,Q6=!0);else return z.precision=N,F}F=D,J+=2}}function TBA(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)%mA,B<0)$+=mA;if($<J){if($)A.d.push(+Q.slice(0,$));for(J-=mA;$<J;)A.d.push(+Q.slice($,$+=mA));Q=Q.slice($),$=mA-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 PZ8(A,Q){var B,$,J,Y,Z,X,F,D,G;if(Q.indexOf("_")>-1){if(Q=Q.replace(/(\d)_(?=\d)/g,"$1"),jBA.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(MZ8.test(Q))B=16,Q=Q.toLowerCase();else if(CZ8.test(Q))B=2;else if(LZ8.test(Q))B=8;else throw Error(xC+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=PBA($,new $(B),Y,Y*2);D=HW0(Q,B,QV),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=u8(A,J,X*4);if(F)A=A.times(Math.abs(F)<54?X7(2,F):O10.pow(2,F));return Q6=!0,A}function _Z8(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/mA);Q6=!1,F=B.times(B),X=new A($);for(;;){if(Z=u8(X.times(F),new A(Q++*Q++),G,1),X=J?$.plus(Z):$.minus(Z),$=u8(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 SBA(A,Q){var B,$=Q.s<0,J=DE(A,A.precision,1),Y=J.times(0.5);if(Q=Q.abs(),Q.lte(Y))return wz=$?4:1,Q;if(B=Q.divToInt(J),B.isZero())wz=$?3:2;else{if(Q=Q.minus(B.times(J)),Q.lte(Y))return wz=NBA(B)?$?2:3:$?4:1,Q;wz=NBA(B)?$?1:4:$?3:2}return Q.minus(J).abs()}function H$1(A,Q,B,$){var J,Y,Z,X,F,D,G,V,U,K=A.constructor,E=B!==void 0;if(E)if(JY(B,1,fC),$===void 0)$=K.rounding;else JY($,0,8);else B=K.precision,$=K.rounding;if(!A.isFinite())G=TBA(A);else{if(G=GE(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(GE(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=u8(A,U,B,$,0,J),V=A.d,Y=A.e,D=CBA;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+=V$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+=V$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 IBA(A,Q){if(A.length>Q)return A.length=Q,!0}function TZ8(A){return new this(A).abs()}function SZ8(A){return new this(A).acos()}function kZ8(A){return new this(A).acosh()}function vZ8(A,Q){return new this(A).plus(Q)}function yZ8(A){return new this(A).asin()}function xZ8(A){return new this(A).asinh()}function fZ8(A){return new this(A).atan()}function bZ8(A){return new this(A).atanh()}function uZ8(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=DE(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?DE(this,$,J):new this(0),B.s=A.s;else if(!A.d||Q.isZero())B=DE(this,Y,1).times(0.5),B.s=A.s;else if(Q.s<0)this.precision=Y,this.rounding=1,B=this.atan(u8(A,Q,Y,1)),Q=DE(this,Y,1),this.precision=$,this.rounding=J,B=A.s<0?B.minus(Q):B.plus(Q);else B=this.atan(u8(A,Q,Y,1));return B}function hZ8(A){return new this(A).cbrt()}function gZ8(A){return NA(A=new this(A),A.e+1,2)}function mZ8(A,Q,B){return new this(A).clamp(Q,B)}function pZ8(A){if(!A||typeof A!=="object")throw Error(IW0+"Object expected");var Q,B,$,J=A.defaults===!0,Y=["precision",1,fC,"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]=U$1[B];if(($=A[B])!==void 0)if(_B($)===$&&$>=Y[Q+1]&&$<=Y[Q+2])this[B]=$;else throw Error(xC+B+": "+$)}if(B="crypto",J)this[B]=U$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(LBA);else this[B]=!1;else throw Error(xC+B+": "+$);return this}function dZ8(A){return new this(A).cos()}function cZ8(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,wBA(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 jBA.test(Y)?WW0(D,Y):PZ8(D,Y)}if(F==="bigint"){if(Y<0)Y=-Y,D.s=-1;else D.s=1;return WW0(D,Y.toString())}throw Error(xC+Y)}if(J.prototype=c1,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=pZ8,J.clone=kBA,J.isDecimal=wBA,J.abs=TZ8,J.acos=SZ8,J.acosh=kZ8,J.add=vZ8,J.asin=yZ8,J.asinh=xZ8,J.atan=fZ8,J.atanh=bZ8,J.atan2=uZ8,J.cbrt=hZ8,J.ceil=gZ8,J.clamp=mZ8,J.cos=dZ8,J.cosh=cZ8,J.div=lZ8,J.exp=iZ8,J.floor=nZ8,J.hypot=aZ8,J.ln=oZ8,J.log=rZ8,J.log10=tZ8,J.log2=sZ8,J.max=eZ8,J.min=AX8,J.mod=QX8,J.mul=BX8,J.pow=$X8,J.random=JX8,J.round=YX8,J.sign=ZX8,J.sin=XX8,J.sinh=FX8,J.sqrt=DX8,J.sub=GX8,J.sum=VX8,J.tan=UX8,J.tanh=KX8,J.trunc=EX8,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 lZ8(A,Q){return new this(A).div(Q)}function iZ8(A){return new this(A).exp()}function nZ8(A){return NA(A=new this(A),A.e+1,3)}function aZ8(){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 wBA(A){return A instanceof O10||A&&A.toStringTag===OBA||!1}function oZ8(A){return new this(A).ln()}function rZ8(A,Q){return new this(A).log(Q)}function sZ8(A){return new this(A).log(2)}function tZ8(A){return new this(A).log(10)}function eZ8(){return _BA(this,arguments,-1)}function AX8(){return _BA(this,arguments,1)}function QX8(A,Q){return new this(A).mod(Q)}function BX8(A,Q){return new this(A).mul(Q)}function $X8(A,Q){return new this(A).pow(Q)}function JX8(A){var Q,B,$,J,Y=0,Z=new this(1),X=[];if(A===void 0)A=this.precision;else JY(A,1,fC);if($=Math.ceil(A/mA),!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(LBA);if($=X[--Y],A%=mA,$&&A)J=X7(10,mA-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-=mA)X.shift();for($=1,J=X[0];J>=10;J/=10)$++;if($<mA)B-=mA-$}return Z.e=B,Z.d=X,Z}function YX8(A){return NA(A=new this(A),A.e+1,this.rounding)}function ZX8(A){return A=new this(A),A.d?A.d[0]?A.s:0*A.s:A.s||NaN}function XX8(A){return new this(A).sin()}function FX8(A){return new this(A).sinh()}function DX8(A){return new this(A).sqrt()}function GX8(A,Q){return new this(A).sub(Q)}function VX8(){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,NA(B,this.precision,this.rounding)}function UX8(A){return new this(A).tan()}function KX8(A){return new this(A).tanh()}function EX8(A){return NA(A=new this(A),A.e+1,1)}c1[Symbol.for("nodejs.util.inspect.custom")]=c1.toString;c1[Symbol.toStringTag]="Decimal";var O10=c1.constructor=kBA(U$1);zW0=new O10(zW0);qW0=new O10(qW0);var W$1=2;function HX8(A,Q){let B=Q.decimalPlaces==="more-if-tiny"?Math.abs(A)<0.01?W$1+1:W$1:Q.decimalPlaces??W$1,$=Q.intent==="balance"?A<0?"expand":"trunc":"halfExpand";return{decimalPlaces:B,roundingMode:$}}function bC(A,Q){let{decimalPlaces:B,roundingMode:$}=HX8(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 j10(A){if(A>=1e6)return`${Math.round(A/1e6)}M`;if(A>=1000)return`${Math.round(A/1000)}k`;return A.toString()}function WX8(A){if(!A)return"";let Q=A.split("-");if(Q.length>=2)return Q.slice(0,2).join("-");return A}function vBA(A){let Q=[],B=(A.inputTokens??0)+(A.cacheCreationInputTokens??0),$=A.cacheReadInputTokens??0;if(B>0)Q.push(`${j10(B)} in`);if($>0)Q.push(`${j10($)} cache read`);if(A.outputTokens)Q.push(`${j10(A.outputTokens)} out`);if(A.model)Q.push(WX8(A.model));if(Q.length>0)return`(${Q.join(", ")})`;return""}function uC(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(bC(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(bC(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(bC(X,D),new x({color:B.foreground,dim:$,bold:!$})));else J.push(new M(bC(X,D),new x({color:B.foreground,dim:$,bold:!$})));return J}class z$1 extends WA{}class q$1 extends WA{}function zX8(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 qX8(A,Q){let B=_0.of(Q),{colors:$}=B,J=uC(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(`
|
|
5372
5372
|
|
|
5373
|
-
`)),Y.push(new M("Details: ",new x({color:$.mutedForeground}))),Y.push(new M(A.costBreakdownURL,new x({color:B.app.link})));return new l({text:new M("",void 0,Y)})}function NX8(A,Q,B){let $=qX8(A,Q);if(!A.costBreakdownURL)return new nA({header:"Thread Cost",minWidth:80,maxWidth:100,onDismiss:B,child:$});let J=A.costBreakdownURL,Y=new O4(()=>{return SA.maybeInvoke(Q,new _$(J,"Cost breakdown URL copied to clipboard","Failed to copy cost breakdown URL")),"handled"}),Z=new O4(()=>{return L6(Q,J),"handled"});return new nA({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 SA({actions:new Map([[z$1,Y],[q$1,Z]]),child:new U8({debugLabel:"ThreadCostShortcuts",shortcuts:new Map([[g1.key("o"),new q$1],[g1.key("y"),new z$1]]),child:new s4({autofocus:!0,debugLabel:"ThreadCostBody",child:$})})})})}function yBA(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 OA.threadDisplayCostInfo({threadID:J},{config:A.configService});if(!Y.ok){A.toastController.show(zX8(J,Y.error),"error",5000),$();return}Q.push(NX8(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 IX8=250,wX8=2000;class N$1 extends v0{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 fBA}}class fBA extends k0{editorController=new v3;commandPalette=new D00(this);commandRegistry=new yQ1;toastController=new W21;exitHintTimer=new du(this,1000);ideStatus=new t3(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;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 z9A({configService:this.widget.configService},A,Q,B)};setThreadVisibility=(A,Q)=>{return q9A({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await M5A({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await L5A({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 O5A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(M$.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(V70(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()},IX8),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<wX8)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?E9A({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)=>fB1({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()}},yBA({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 J$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:()=>{sJ(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:T$.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(J,Y,Z)=>{Z(),A.showNeoWelcome()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new nA({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new l({text:new M(D21({version:"0.0.1777910718-gcdf3ba",buildTimestamp:"2026-05-04T16:08:54.852Z",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:g1.ctrl("c"),status:{type:"enabled"},run:(J,Y)=>{SA.maybeInvoke(Y,new wh)}},...Q,...$9A(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 $$1({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=Y4.of(A),Z=[new l0({constraints:L1.tight(J.size.width,J.size.height),child:$})];if(this.commandPalette.isEnabled())Z.push(new QA({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new xQ1({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)Z.push(fB1({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 D$1({onDismiss:this.dismissNeoWelcome})}));if(Z.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)Z.push(new gQ1({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:R10.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)Z.push(new mQ1);return new R2({neoContext:this.widget.neoContext,child:new T$({commandRegistry:this.commandRegistry,child:new jC({completionBuilder:this.widget.completionBuilder,child:new e8({controller:this.toastController,child:new SA({actions:this.buildActions(),child:new U8({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[g1.ctrl("c"),new cH0],[g1.ctrl("o"),new lH0],[g1.alt("i"),new nH0],[g1.alt("p"),new YC],[g1.ctrl("t"),new aH0]]),child:new s4({debugLabel:"AppShellFocus",child:new z21({controller:this.toastController,child:new XA({children:Z})})})})})})})})})}buildActions(){let A=new O4(()=>{if(rJ.hasAnyCopyableSelection())return rJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new O4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new O4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new O4(()=>{let G=this.activeThreadContext?.client.getThreadId();return this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(G),this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.writeTerminalTitle(void 0),this.activeThreadContext=null,this.connectingToThreadID=null}),"handled"}),J=new O4(()=>{return d4.instance.stop(),"handled"}),Y=new O4((G)=>{if(!G.text)return"ignored";return d4.instance.tuiInstance.clipboard.writeText(G.text).then(()=>{this.toastController.show(G.successMessage,"success",2000)}).catch((V)=>{j.error("Failed to copy Neo text to clipboard",{error:V}),this.toastController.show(G.failureMessage,"error",2000)}),"handled"}),Z=new O4(()=>{return d4.instance.toggleFrameStatsOverlay(),"handled"}),X=new O4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),F=new O4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";let G=this.activeThreadContext?.client.getThreadId();if(!G)return this.toastController.show("No active thread","error",2000),"handled";return O51(G).then((V)=>{this.toastController.show(aa4(V),"success",2000)}).catch((V)=>{let U=V instanceof Error?V.message:String(V);j.error("Failed to copy thread log",{error:V}),this.toastController.show(`Failed to copy thread log: ${U}`,"error",2000)}),"handled"}),D=new O4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[cH0,A],[Y10,$],[wh,J],[_$,Y],[F10,B],[lH0,Q],[nH0,X],[M_,F],[YC,Z],[aH0,D]])}closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=AE0(await ku(this.widget.configService),{agentMode:this.widget.neoContext.sessionAgentMode,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext});this.applyDraftThreadSettingsSeed(A)}catch(A){j.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=xBA(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(RX(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=xBA(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(OC);if(this.exitHintTimer.isActive())A.add(Hh);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),d4.instance.stop();else this.exitHintTimer.activate()};dismissNeoWelcome=()=>{if(!this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!1}),this.widget.onNeoWelcomeDismissed?.()};showNeoWelcome=()=>{if(this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!0})};closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,B=null)=>{await this.ensureDraftThreadSettingsInitialized();let $=this.activeThreadContext?.client.getThreadId(),J=A.find((Z)=>Z.type==="text");if(J&&J.type==="text")this.widget.history.add(J.text,R10.cwd()),this.widget.history.reset();let Y=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,B?xZ(B):void 0);this.sendUserMessage(Y,A,Q),this.threadNavigationHistory.recordNavigation($),this.setActiveClient(Y)};sendUserMessage(A,Q,B){let $=$D0(this.ideStatus.getValue());A.client.sendUserMessage(Q,B,{userState:$})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};appendPluginMessagesToThread=async(A,Q)=>{let B=this.activeThreadContext;if(!B)throw Error("appendToThread is not available - no active thread");let $=B.client.getThreadId();if(Q&&$!==Q)throw Error("thread.append is only available for the active executor thread");for(let J of A)this.sendUserMessage(B,[{type:"text",text:J.content}])};async connectToExistingThread(A,Q={}){let B=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let $=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly});if(this.setActiveClient($),Q.recordNavigation&&B!==A)this.threadNavigationHistory.recordNavigation(B);if(Q.initialUserInput)this.sendUserMessage($,[{type:"text",text:Q.initialUserInput}])}catch($){if(j.error("Failed to load thread",{error:$,threadID:A}),this.toastController.show(`Failed to load ${A}: ${$ instanceof Error?$.message:String($)}`,"error",4000),Q.rethrowError)throw $}finally{this.setState(()=>{this.connectingToThreadID=null})}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}async reconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to reconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Reconnecting ${Q}...`:"Reconnecting thread...","warning",60000);try{let $=await this.widget.clientPool.reconnectClient(A.client);this.toastController.update(B,`Reconnected ${$}`,"success",2000)}catch($){j.error("Failed to reconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Reconnect failed: ${J}`,"error",4000)}}async disconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to disconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Disconnecting ${Q}...`:"Disconnecting thread...","warning",60000);try{let $=await this.widget.clientPool.disconnectClient(A.client);this.toastController.update(B,`Disconnected ${$}`,"success",2000)}catch($){j.error("Failed to disconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Disconnect failed: ${J}`,"error",4000)}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q},this.subscribeTitleUpdates(Q),this.subscribeNotifications(Q)})}subscribeTitleUpdates(A){this.titleSubscription?.unsubscribe(),this.titleSubscription=A.title().subscribe({next:(Q)=>{this.writeTerminalTitle(Q)}})}subscribeNotifications(A){this.widget.notificationService.attach(A.agentState())}writeTerminalTitle(A){let Q=R10.cwd().replace(R10.env.HOME||"","~"),B=A?`amp - ${A} - ${Q}`:"";R10.stdout.write(ow(B))}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){j.error("Failed to connect to IDE",{error:Q});let B=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${B}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.titleSubscription?.unsubscribe(),this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.configReloadSubscription?.unsubscribe(),this.configReloadSubscription=null,this.configReloadToastTimer)clearTimeout(this.configReloadToastTimer),this.configReloadToastTimer=null;this.pendingConfigReloadToastType=null,this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.neoWelcomeVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function xBA(A,Q,B){let $={...A};for(let J of CX8(Q,B)){if(!RX(A[J],Q[J]))continue;let Y=B[J];if(Y===void 0)delete $[J];else $[J]=Y}return $}function CX8(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}AA();function bBA(A,Q,B,$){let J=Kv(A),Y="\x1B[0m",Z="\x1B[34m",X="\x1B[90m",F="\x1B[2m",D=[];if(A.archived)D.push("\x1B[90m\x1B[2mArchived\x1B[0m");D.push(`${J}`),D.push(`\x1B[34m${Q}\x1B[0m`),D.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let G=14,V=7,U=new _Z(G,V),K=new A7(42),E=new tw(G,V,G,V,G,V,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,H0.default(),K);E.layout(L1.tight(G,V)),E.paint(U,0,0);let H=U.getBuffer().getCells(),W=0;for(let P=0;P<V;P++)if(H[P].some((k)=>k.char!==" ")){W=P;break}let z=V-1;for(let P=V-1;P>=0;P--)if(H[P].some((k)=>k.char!==" ")){z=P;break}function q(P,k){if(!P)return"";if(P.type==="rgb"){let{r:T,g:f,b:h}=P.value;if(B.getColorDepth()>=24)return`\x1B[${k?38:48};2;${T};${f};${h}m`;let b=gP(T,f,h);return`\x1B[${k?38:48};5;${b}m`}return""}let N=[];if(z>=W)for(let P=W;P<=z;P++){let k="";for(let T=0;T<G;T++){let f=H[P][T],h=f.char,b=q(f.style.fg,!0);k+=b+h+"\x1B[0m"}N.push(k)}let I=N.length,w=Math.max(I,D.length),C=Math.floor((w-I)/2),O=Math.floor((w-D.length)/2);for(let P=0;P<w;P++){let k=" ".repeat(G);if(P>=C&&P<C+I)k=N[P-C];let T=" ",f="";if(P>=O&&P<O+D.length)f=D[P-O];B.write(k+T+f+`
|
|
5373
|
+
`)),Y.push(new M("Details: ",new x({color:$.mutedForeground}))),Y.push(new M(A.costBreakdownURL,new x({color:B.app.link})));return new l({text:new M("",void 0,Y)})}function NX8(A,Q,B){let $=qX8(A,Q);if(!A.costBreakdownURL)return new nA({header:"Thread Cost",minWidth:80,maxWidth:100,onDismiss:B,child:$});let J=A.costBreakdownURL,Y=new O4(()=>{return SA.maybeInvoke(Q,new _$(J,"Cost breakdown URL copied to clipboard","Failed to copy cost breakdown URL")),"handled"}),Z=new O4(()=>{return L6(Q,J),"handled"});return new nA({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 SA({actions:new Map([[z$1,Y],[q$1,Z]]),child:new U8({debugLabel:"ThreadCostShortcuts",shortcuts:new Map([[g1.key("o"),new q$1],[g1.key("y"),new z$1]]),child:new s4({autofocus:!0,debugLabel:"ThreadCostBody",child:$})})})})}function yBA(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 OA.threadDisplayCostInfo({threadID:J},{config:A.configService});if(!Y.ok){A.toastController.show(zX8(J,Y.error),"error",5000),$();return}Q.push(NX8(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 IX8=250,wX8=2000;class N$1 extends v0{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 fBA}}class fBA extends k0{editorController=new v3;commandPalette=new D00(this);commandRegistry=new yQ1;toastController=new W21;exitHintTimer=new du(this,1000);ideStatus=new t3(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;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 z9A({configService:this.widget.configService},A,Q,B)};setThreadVisibility=(A,Q)=>{return q9A({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await M5A({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await L5A({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 O5A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(M$.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(V70(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()},IX8),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<wX8)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?E9A({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)=>fB1({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()}},yBA({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 J$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:()=>{sJ(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:T$.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(J,Y,Z)=>{Z(),A.showNeoWelcome()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new nA({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new l({text:new M(D21({version:"0.0.1777912178-gd6d908",buildTimestamp:"2026-05-04T16:33:09.749Z",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:g1.ctrl("c"),status:{type:"enabled"},run:(J,Y)=>{SA.maybeInvoke(Y,new wh)}},...Q,...$9A(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 $$1({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=Y4.of(A),Z=[new l0({constraints:L1.tight(J.size.width,J.size.height),child:$})];if(this.commandPalette.isEnabled())Z.push(new QA({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new xQ1({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)Z.push(fB1({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 D$1({onDismiss:this.dismissNeoWelcome})}));if(Z.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)Z.push(new gQ1({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:R10.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)Z.push(new mQ1);return new R2({neoContext:this.widget.neoContext,child:new T$({commandRegistry:this.commandRegistry,child:new jC({completionBuilder:this.widget.completionBuilder,child:new e8({controller:this.toastController,child:new SA({actions:this.buildActions(),child:new U8({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[g1.ctrl("c"),new cH0],[g1.ctrl("o"),new lH0],[g1.alt("i"),new nH0],[g1.alt("p"),new YC],[g1.ctrl("t"),new aH0]]),child:new s4({debugLabel:"AppShellFocus",child:new z21({controller:this.toastController,child:new XA({children:Z})})})})})})})})})}buildActions(){let A=new O4(()=>{if(rJ.hasAnyCopyableSelection())return rJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new O4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new O4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new O4(()=>{let G=this.activeThreadContext?.client.getThreadId();return this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(G),this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.writeTerminalTitle(void 0),this.activeThreadContext=null,this.connectingToThreadID=null}),"handled"}),J=new O4(()=>{return d4.instance.stop(),"handled"}),Y=new O4((G)=>{if(!G.text)return"ignored";return d4.instance.tuiInstance.clipboard.writeText(G.text).then(()=>{this.toastController.show(G.successMessage,"success",2000)}).catch((V)=>{j.error("Failed to copy Neo text to clipboard",{error:V}),this.toastController.show(G.failureMessage,"error",2000)}),"handled"}),Z=new O4(()=>{return d4.instance.toggleFrameStatsOverlay(),"handled"}),X=new O4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),F=new O4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";let G=this.activeThreadContext?.client.getThreadId();if(!G)return this.toastController.show("No active thread","error",2000),"handled";return O51(G).then((V)=>{this.toastController.show(aa4(V),"success",2000)}).catch((V)=>{let U=V instanceof Error?V.message:String(V);j.error("Failed to copy thread log",{error:V}),this.toastController.show(`Failed to copy thread log: ${U}`,"error",2000)}),"handled"}),D=new O4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[cH0,A],[Y10,$],[wh,J],[_$,Y],[F10,B],[lH0,Q],[nH0,X],[M_,F],[YC,Z],[aH0,D]])}closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=AE0(await ku(this.widget.configService),{agentMode:this.widget.neoContext.sessionAgentMode,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext});this.applyDraftThreadSettingsSeed(A)}catch(A){j.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=xBA(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(RX(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=xBA(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(OC);if(this.exitHintTimer.isActive())A.add(Hh);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),d4.instance.stop();else this.exitHintTimer.activate()};dismissNeoWelcome=()=>{if(!this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!1}),this.widget.onNeoWelcomeDismissed?.()};showNeoWelcome=()=>{if(this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!0})};closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,B=null)=>{await this.ensureDraftThreadSettingsInitialized();let $=this.activeThreadContext?.client.getThreadId(),J=A.find((Z)=>Z.type==="text");if(J&&J.type==="text")this.widget.history.add(J.text,R10.cwd()),this.widget.history.reset();let Y=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,B?xZ(B):void 0);this.sendUserMessage(Y,A,Q),this.threadNavigationHistory.recordNavigation($),this.setActiveClient(Y)};sendUserMessage(A,Q,B){let $=$D0(this.ideStatus.getValue());A.client.sendUserMessage(Q,B,{userState:$})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};appendPluginMessagesToThread=async(A,Q)=>{let B=this.activeThreadContext;if(!B)throw Error("appendToThread is not available - no active thread");let $=B.client.getThreadId();if(Q&&$!==Q)throw Error("thread.append is only available for the active executor thread");for(let J of A)this.sendUserMessage(B,[{type:"text",text:J.content}])};async connectToExistingThread(A,Q={}){let B=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let $=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly});if(this.setActiveClient($),Q.recordNavigation&&B!==A)this.threadNavigationHistory.recordNavigation(B);if(Q.initialUserInput)this.sendUserMessage($,[{type:"text",text:Q.initialUserInput}])}catch($){if(j.error("Failed to load thread",{error:$,threadID:A}),this.toastController.show(`Failed to load ${A}: ${$ instanceof Error?$.message:String($)}`,"error",4000),Q.rethrowError)throw $}finally{this.setState(()=>{this.connectingToThreadID=null})}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}async reconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to reconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Reconnecting ${Q}...`:"Reconnecting thread...","warning",60000);try{let $=await this.widget.clientPool.reconnectClient(A.client);this.toastController.update(B,`Reconnected ${$}`,"success",2000)}catch($){j.error("Failed to reconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Reconnect failed: ${J}`,"error",4000)}}async disconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to disconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Disconnecting ${Q}...`:"Disconnecting thread...","warning",60000);try{let $=await this.widget.clientPool.disconnectClient(A.client);this.toastController.update(B,`Disconnected ${$}`,"success",2000)}catch($){j.error("Failed to disconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Disconnect failed: ${J}`,"error",4000)}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q},this.subscribeTitleUpdates(Q),this.subscribeNotifications(Q)})}subscribeTitleUpdates(A){this.titleSubscription?.unsubscribe(),this.titleSubscription=A.title().subscribe({next:(Q)=>{this.writeTerminalTitle(Q)}})}subscribeNotifications(A){this.widget.notificationService.attach(A.agentState())}writeTerminalTitle(A){let Q=R10.cwd().replace(R10.env.HOME||"","~"),B=A?`amp - ${A} - ${Q}`:"";R10.stdout.write(ow(B))}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){j.error("Failed to connect to IDE",{error:Q});let B=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${B}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.titleSubscription?.unsubscribe(),this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.configReloadSubscription?.unsubscribe(),this.configReloadSubscription=null,this.configReloadToastTimer)clearTimeout(this.configReloadToastTimer),this.configReloadToastTimer=null;this.pendingConfigReloadToastType=null,this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.neoWelcomeVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function xBA(A,Q,B){let $={...A};for(let J of CX8(Q,B)){if(!RX(A[J],Q[J]))continue;let Y=B[J];if(Y===void 0)delete $[J];else $[J]=Y}return $}function CX8(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}AA();function bBA(A,Q,B,$){let J=Kv(A),Y="\x1B[0m",Z="\x1B[34m",X="\x1B[90m",F="\x1B[2m",D=[];if(A.archived)D.push("\x1B[90m\x1B[2mArchived\x1B[0m");D.push(`${J}`),D.push(`\x1B[34m${Q}\x1B[0m`),D.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let G=14,V=7,U=new _Z(G,V),K=new A7(42),E=new tw(G,V,G,V,G,V,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,H0.default(),K);E.layout(L1.tight(G,V)),E.paint(U,0,0);let H=U.getBuffer().getCells(),W=0;for(let P=0;P<V;P++)if(H[P].some((k)=>k.char!==" ")){W=P;break}let z=V-1;for(let P=V-1;P>=0;P--)if(H[P].some((k)=>k.char!==" ")){z=P;break}function q(P,k){if(!P)return"";if(P.type==="rgb"){let{r:T,g:f,b:h}=P.value;if(B.getColorDepth()>=24)return`\x1B[${k?38:48};2;${T};${f};${h}m`;let b=gP(T,f,h);return`\x1B[${k?38:48};5;${b}m`}return""}let N=[];if(z>=W)for(let P=W;P<=z;P++){let k="";for(let T=0;T<G;T++){let f=H[P][T],h=f.char,b=q(f.style.fg,!0);k+=b+h+"\x1B[0m"}N.push(k)}let I=N.length,w=Math.max(I,D.length),C=Math.floor((w-I)/2),O=Math.floor((w-D.length)/2);for(let P=0;P<w;P++){let k=" ".repeat(G);if(P>=C&&P<C+I)k=N[P-C];let T=" ",f="";if(P>=O&&P<O+D.length)f=D[P-O];B.write(k+T+f+`
|
|
5374
5374
|
`)}if($)B.write(`
|
|
5375
5375
|
\x1B[90m${$}\x1B[0m
|
|
5376
5376
|
`)}o0();GE0();var MX8=2000;function uBA(A){let Q=!0,B=!0,$=A.configService.config.subscribe((V)=>{Q=V.settings["notifications.enabled"]??!0,B=V.settings["notifications.system.enabled"]!==!1}),J=0,Y=(V)=>{if(!Q)return;let U=Date.now();if(U-J<MX8)return;if(J=U,nP())return;if(XK0())FK0();else Vs(V)},Z=(V)=>{if(!Q||!B)return;if(nP()&&!Q00()&&!Mu())return;process.stdout.write(dG(`\x1B]777;notify;Amp;${V}\x1B\\`))},X=null,F=null,D=()=>{X?.unsubscribe(),X=null,F=null};return{attach:(V)=>{D(),X=V.subscribe({next:(U)=>{try{let K=F!==null&&w$(F),E=F==="awaiting_approval";if(U==="awaiting_approval"&&!E)Y("requires-user-input"),Z("Waiting for approval");else if((U==="idle"||U==="error")&&(K||E))Y("idle"),Z("Agent is ready")}catch(K){j.debug("Neo notification handling failed",{error:K})}finally{F=U}},error:(U)=>{j.debug("Neo notification agent state stream errored",{error:U})}})},detach:D,unsubscribe(){D(),$.unsubscribe()}}}o0();PH();H4();j1();function hBA(A,Q){if(!Q)return A;let B=Q.toLowerCase(),$=[];for(let J of A){let Y=LX8(J,B);if(Y>0)$.push({...J,score:Y})}return $.sort((J,Y)=>{let Z=Y.score-J.score;if(Z!==0)return Z;return A.indexOf(J)-A.indexOf(Y)}),$}function LX8(A,Q){let B=OX8(A,Q),$=jX8(A.message.toLowerCase(),Q);return Math.max(B,$)}function OX8(A,Q){let B=A.hash.toLowerCase(),$=A.shortHash.toLowerCase();if($===Q)return 1000;if($.startsWith(Q))return 900;if(B.startsWith(Q))return 850;if(B.includes(Q)||$.includes(Q))return 400;return 0}function jX8(A,Q){if(A===Q)return 800;if(A.startsWith(Q))return 700;let B=A.indexOf(Q);if(B!==-1)return 600-Math.min(B,500);let $=RX8(A,Q);if($>0)return $;return 0}function RX8(A,Q){let B=0,$=0,J=-1;while(B<A.length&&$<Q.length){if(A[B]===Q[$]){if(J===-1)J=B;$++}B++}if($===Q.length)return 250-Math.min(J,150);return 0}var gBA=":";function k_(A,Q){if(!kP())return;j.debug("[file mention completions]",{event:A,...Q})}function vh(A){return A.length<=80?A:`${A.slice(0,77)}...`}class v_{fuzzyClient;cachedDirtyFiles=[];cachedCommits=[];refreshPromise;refreshCommitsPromise;constructor(A){this.fuzzyClient=A;this.refreshDirtyFilesInBackground(),this.refreshCommitsInBackground()}async buildOptions(A){if(A.trigger==="@"){let Q=A.query;if(Q.toLowerCase().startsWith(gBA)){let Z=Q.slice(gBA.length);return k_("commit_query_detected",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:Z.length,queryPreview:vh(Z)}),this.buildCommitOptions(Z)}let $=Q.length===0?18:20,J=await this.buildFileOptions(Q,$),Y=this.appendHintOptions(Q,J);return k_("build_options_completed",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:Q.length,queryPreview:vh(Q),maxResults:$,fileOptionCount:J.filter((Z)=>Z.type==="file").length,hintOptionCount:Y.filter((Z)=>Z.type==="hint").length,finalOptionCount:Y.length,firstFilePaths:Y.filter((Z)=>Z.type==="file").slice(0,5).map((Z)=>Z.path)}),Y}return[]}async buildFileOptions(A,Q){try{let B=await this.getOpenFiles(),$=this.cachedDirtyFiles;this.refreshDirtyFilesInBackground();let J=await this.fuzzyClient.queryCompletions(A,Q,B,$),Y=J.map((Z)=>H7A(Z));return k_("file_options_built",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:vh(A),maxResults:Q,openFilesCount:B?.length??0,dirtyFilesCount:$.length,completionItemCount:J.length,fileOptionCount:Y.length,firstPaths:Y.slice(0,5).map((Z)=>Z.path)}),Y}catch(B){return k_("file_options_failed",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:vh(A),maxResults:Q,error:B instanceof Error?B.message:String(B)}),[]}}async getOpenFiles(){let A=await v1(n8.status);if(!A.connected)return;let Q=[];if(A.openFile)Q.push(Z1.parse(A.openFile).fsPath);if(A.visibleFiles)for(let B of A.visibleFiles){let $=Z1.parse(B).fsPath;if(!Q.includes($))Q.push($)}if(Q.length===0)return;return Q}refreshDirtyFilesInBackground(){if(this.refreshPromise!==void 0)return;this.refreshPromise=_v4(this.fuzzyClient.workspaceRoot).then((A)=>{this.cachedDirtyFiles=A}).catch(()=>{}).finally(()=>{this.refreshPromise=void 0})}async buildCommitOptions(A){this.refreshCommitsInBackground();let Q=this.cachedCommits;if(!Q.length)return k_("commit_options_empty_cache",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:vh(A)}),[];let B=hBA(Q,A).slice(0,20);return k_("commit_options_built",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:vh(A),commitCacheCount:Q.length,resultCount:B.length,firstCommitHashes:B.slice(0,5).map(($)=>$.shortHash)}),B.map(($)=>({type:"commit",hash:$.hash,shortHash:$.shortHash,message:$.message,relativeDate:$.relativeDate}))}refreshCommitsInBackground(){if(this.refreshCommitsPromise!==void 0)return;this.refreshCommitsPromise=Tv4(this.fuzzyClient.workspaceRoot).then((A)=>{this.cachedCommits=A}).catch(()=>{}).finally(()=>{this.refreshCommitsPromise=void 0})}appendHintOptions(A,Q){if(A.length>0)return Q;let B=[{type:"hint",kind:"commit",message:"mention a commit"},{type:"hint",kind:"thread",message:"mention a thread"}];return k_("hint_options_appended",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,fileOptionCount:Q.filter(($)=>$.type==="file").length,hintOptionCount:B.length,hintOnly:Q.length===0,firstFilePaths:Q.filter(($)=>$.type==="file").slice(0,5).map(($)=>$.path)}),[...Q,...B]}}var _X8=[{long:"neo",description:"Use the Neo TUI",type:"boolean",default:!1},{long:"url",short:"u",description:"Amp server URL",type:"string",default:""},{long:"dangerously-allow-all",description:"Disable all command confirmation prompts (agent will execute all commands without asking)",type:"boolean",default:!1},{long:"observe",description:"Connect to an existing thread as observer only (no local executor). Accepts a thread ID or thread URL.",type:"string",default:""}],_i2=z4A({name:"amp neo",description:"Start the Neo TUI",options:_X8,positionals:[],action:async({options:A})=>{let Q=mBA(A);if(A.observe){let B=l8(A.observe)??WB(A.observe);await MW0(Q,{initialThreadID:B,observerOnly:!0});return}await MW0(Q)},subcommands:[{name:"threads",alias:"t",description:"List and manage threads",options:[],positionals:[],subcommands:[{name:"continue",alias:"c",description:"Continue an existing thread",options:[],positionals:[{name:"thread-id",description:"Thread ID to continue"}],action:async({globalOptions:A,positionals:Q})=>{let $=mBA(A);if(!Q["thread-id"]){await MW0($,{openThreadPickerOnStart:!0});return}let J=l8(Q["thread-id"]);if(!J)throw"invalid thread ID";await MW0($,{initialThreadID:J})}}]}]});function TX8(A){if(A)return A;if(process.env.AMP_URL)return process.env.AMP_URL;return x9}function SX8(A){if(process.env.RIVET_PUBLIC_ENDPOINT)return process.env.RIVET_PUBLIC_ENDPOINT;return cJ(A)}var pBA=Z1.file(PX8.homedir()),kX8=process.env.XDG_CONFIG_HOME?Z1.file(process.env.XDG_CONFIG_HOME):K1.joinPath(pBA,".config");function vX8({initialUserInput:A,showNeoWelcome:Q,neoWelcomeDismissed:B}){if(Q)return{show:!0,markDismissedOnDismiss:!0};let $=!A&&!B;return{show:$,markDismissedOnDismiss:$}}async function yX8(A){await kZ((Q)=>$E0(Q,A,"interactive"))}function mBA(A){return{url:A.url,dangerouslyAllowAll:A["dangerously-allow-all"]}}async function MW0(A,Q={}){let{initialThreadID:B,openThreadPickerOnStart:$=!1,observerOnly:J=!1}=Q,Y=TX8(A.url),Z={dataDir:void 0,getHook:(k,T)=>{if(k==="url")return Promise.resolve(Y);return T()}},X=await KK0(Z),F=BE0(await qe(Z,X)),D=SX8(Y);if(A.dangerouslyAllowAll)sB("dangerouslyAllowAll",!0);let G=await F.get("apiKey",Y);if(!G)throw new D4("API key required. Please run `amp login` first.",1);let V=Nv({storage:X,secretStorage:F,workspaceRoot:m0.of(Z1.file(process.cwd())),defaultAmpURL:Y,homeDir:pBA,userConfigDir:kX8}),U=jj(V,{usesThreadActors:!0}),K=bD0({configService:V}),E=new Su({configService:V});E.pluginExecutorKind="local";let H=mi({configService:V,fileSystem:A8,platform:E,loadGlobalPlugins:Ee(V),pluginFilter:"all"}),W=N$0({pluginService:H,toolService:K.toolService}),z=Qs({configService:V,filesystem:A8,spawn:nf}),q=Bs({toolService:K.toolService,providers:[z]}),N=qJ0({configService:V,filesystem:A8}),I={registerToolsWithToolService:()=>({dispose:()=>{}}),getClient:()=>{return},servers:m0.of([]),getPrompt:async()=>null,searchResources:async()=>[],searchPrompts:()=>m0.of([]),getToolsForServer:async()=>{return}},w=process.cwd(),C=async({uri:k})=>{return gw({fileSystem:A8,workspaceRoot:w},k)},O=new qu(w,{},!0),P=new v_(O);await I$1({ampURL:Y,apiKey:G,rivetEndpoint:D,configService:V,toolService:K.toolService,pluginPlatform:E,pluginService:H,skillService:N,mcpService:I,readFileSystemDirectory:C,completionBuilder:P,workspaceRoot:w,listThreads:()=>U.listThreads(),getThreadFromServer:(k)=>U.getThread(k),toolboxes:z.toolboxes,isInternalUser:!1,settingsFilePath:X.getSettingsFilePath(),dispose:()=>{for(let k of q.values())k.dispose();return z.dispose(),O.dispose(),W.dispose(),K.dispose(),H.dispose()}},{initialThreadID:B,openThreadPickerOnStart:$,observerOnly:J})}async function I$1(A,Q={}){let{initialThreadID:B,initialUserInput:$,openThreadPickerOnStart:J=!1,observerOnly:Y=!1,initialAgentMode:Z,initialReasoningEffort:X,showNeoWelcome:F=!1}=Q,D=async(I)=>{let w=await A.getThreadFromServer(I);if(!w)return null;return cU0(w)},G=async(I)=>{let w=await A.getThreadFromServer(I);if(!w)throw Error(`Thread ${I} not found`);let C=await jZ(I,A.configService,A.apiKey,{usesThreadActors:!0}),k=await yK({endpoint:A.rivetEndpoint}).threadActor.getOrCreate([I],{params:{wsToken:C.wsToken},createWithInput:{threadId:C.threadId,threadVersion:C.threadVersion,ownerUserId:C.ownerUserId,...C.agentMode?{agentMode:C.agentMode}:{}}}).fetch("/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({thread:lr4(w)})});if(k.ok||k.status===409)return;throw Error(`Thread import failed (${k.status}): ${await k.text()}`)},V=new p31(A.rivetEndpoint,A.apiKey,A.configService,{clientID:uw.parse(`neo-${crypto.randomUUID()}`),toolService:A.toolService,skillService:A.skillService,requestPluginToolCall:(I)=>A.pluginService.event.toolCall(I),requestPluginToolResult:(I)=>A.pluginService.event.toolResult(I),pluginService:A.pluginService,invokeTool:async(I,w)=>{let C=typeof w.args==="object"&&w.args!==null?w.args:{},O=await pw({toolName:w.toolName,configService:A.configService,toolService:A.toolService,mcpService:A.mcpService,skillService:A.skillService,toolUseID:w.toolCallId,threadID:I});return A.toolService.invokeTool(w.toolName,{args:C},O)},persistLastThreadID:yX8,readFileSystemDirectory:A.readFileSystemDirectory},D,G),U=await $C(),K=vX8({initialUserInput:$,showNeoWelcome:F,neoWelcomeDismissed:U.neoWelcomeDismissed}),E={ampURL:A.ampURL,configService:A.configService,getThreadMarkdown:async(I)=>{let w=await A.getThreadFromServer(I);return w?SU(w):null},isInternalUser:A.isInternalUser,listThreads:A.listThreads,logFilePath:rt,mcpServers:A.mcpService.servers,pluginPlatform:A.pluginPlatform,pluginService:A.pluginService,toolboxes:A.toolboxes,observerOnly:Y,sessionAgentMode:Z??U.agentMode,explicitReasoningEffort:X,lastReasoningEffortByMode:U.lastReasoningEffortByMode,settingsFilePath:A.settingsFilePath,splashOrbVisualStyle:Q.splashOrbVisualStyle??"neo",workspaceRoot:A.workspaceRoot},H=(I,w)=>{return db({ampURL:A.ampURL,configService:A.configService,threadID:I,signal:w})},W=(I,w)=>{return L1A({ampURL:A.ampURL,configService:A.configService,threadID:I,signal:w})},z=new F21,q=uBA({configService:A.configService}),N=new Set;try{await B00(new N$1({clientPool:V,analyzeContextForThread:H,listSkillsForThread:W,completionBuilder:A.completionBuilder,history:new Fe,ideManager:z,configService:A.configService,initialThreadID:B,notificationService:q,initialUserInput:$,openThreadPickerOnStart:J,neoContext:E,showNeoWelcome:K.show,onNeoWelcomeDismissed:K.markDismissedOnDismiss?()=>{kZ(P1A).catch((w)=>{j.warn("Failed to mark Neo welcome as dismissed",{error:w})})}:void 0,onThreadArchived:(w)=>{N.add(w)}}));let I=V.lastActiveObservingClient;if(I){let{client:w,observer:C}=I,O=w.getThreadId();if(O){let P={id:O,title:C.title().getValue(),agentMode:C.agentMode,archived:N.has(O)},k=`${A.ampURL.replace(/\/$/,"")}/threads/${O}`;bBA(P,k,process.stdout)}}}finally{process.stdout.write(ow("")),q.unsubscribe(),V.dispose(),await A.dispose?.()}process.exit(0)}yl();EH();async function xX8(A,Q,B){let $=s70(A);if(!$.success)throw Error(`Invalid permission format: ${$.error.message}`);if($.data.length===0)throw Error("No permission entry provided");let J=$N($.data);if(!J.success){let F=J.error.issues.map((D)=>D.message).join(", ");throw Error(`Invalid permission entry: ${F}`)}let Y=await Q.get("permissions",B)??[],X=[$.data[0],...Y];await Q.set("permissions",X,B)}async function dBA(A){try{let Q=A.args.map((B)=>{if(/[\s/\\*?[\]{}()"]/.test(B))return`"${B}"`;return B}).join(" ");await xX8(Q,A.settings,A.scope),A.exit(0)}catch(Q){let B=Q instanceof Error?Q.message:"Unknown error";A.stderr.write(`Error: ${B}
|
|
@@ -6139,7 +6139,7 @@ ${J}`,Q);this.line=B,this.column=$,this.codeblock=J}}/*!
|
|
|
6139
6139
|
`),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(`
|
|
6140
6140
|
`))}return new l0({decoration:{color:B.colorScheme.background,border:e1.all(new A4($.app.keybind,1,"rounded"))},child:new u0({padding:N0.symmetric(0,1),child:new l({text:new M(void 0,void 0,Y)})})})}}class OJ1 extends o3{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 MJ1({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 AZA(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?Q2: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?Q2: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 xK8(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?Q2: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?Q2: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 fK8(A){let Q=0;for(let B of A)for(let $ of B.points)if($.value>Q)Q=$.value;return Q||1}function bK8(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 uK8(A,Q,B,$,J,Y,Z){let X;try{let E=y1.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,RK0(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}
|
|
6141
6141
|
`,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(`
|
|
6142
|
-
`))}if(E)V.push(new M(" ",G)),V.push(new M("Total: ",G)),V.push(new M(Y(H),D))}return new l0({decoration:{color:X.background,border:e1.all(new A4(X.border,1,"rounded"))},child:new l({text:new M(void 0,void 0,V)})})}o0();S8();JN();G2();D8();tQ();Yr();jX();VQ();K9();Q$();TU();AA();Zx();bk();j1();o0();VQ();class jJ1{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.1777910718-gcdf3ba"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await Z70(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 rC extends v0{props;constructor(A){super();this.props=A}createState(){return new QZA}}class QZA extends k0{_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 BZA extends k0{controller=new v3;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 L$({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 Y1({children:[new l0({decoration:{color:B.background},child:new l({text:new M(">",new x({color:B.foreground}))})}),new k1({child:F})]}),G=new l0({padding:N0.symmetric(1,0),child:new l({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 l0({padding:N0.symmetric(1,0),child:new l({text:new M("",void 0,V)})});return new l0({decoration:{border:X,color:B.background},padding:N0.all(1),child:new b0({children:[G,new w0({height:1}),D,new H5,U]})})}}class d10 extends v0{props;constructor(A){super();this.props=A}createState(){return new BZA}}Q$();class $ZA extends k0{controller=new v3;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 hF(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=Y4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),X=new AV({controller:this.controller,triggers:[new $Y],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 l0({constraints:new L1({maxHeight:Z}),padding:N0.symmetric(1,0),child:F}),G=new l0({padding:N0.symmetric(1,0),child:new l({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 l0({padding:N0.symmetric(1,0),child:new l({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 w0({height:1}),new k1({child:D}),new w0({height:1}),V];return new l0({decoration:{border:e1.all(new A4(B.foreground,1,"solid")),color:B.background},padding:N0.all(1),child:new b0({children:U})})}}class RJ1 extends v0{props;constructor(A){super();this.props=A}createState(){return new $ZA}}function JZA(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 PJ1 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)=>JZA(J.pubDate).length));return new e6({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 w0({width:W,child:Y1.end([new l({text:new M(H,new x({color:K}))})])});return new l0({decoration:V?{color:V}:void 0,padding:N0.symmetric(2,0),child:new Y1({children:[new k1({child:new l({text:new M(J.title,new x({color:U})),overflow:"ellipsis",maxLines:1})}),new w0({width:2}),E(JZA(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()}}o0();class YZA extends k0{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 e6({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 l0({decoration:K?{color:K}:void 0,padding:N0.symmetric(2,0),child:new l({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 l0({decoration:K?{color:K}:void 0,padding:N0.symmetric(2,0),child:new l({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 _J1 extends v0{props;constructor(A){super();this.props=A}createState(){return new YZA}}class $V extends v0{props;constructor(A){super();this.props=A}createState(){return new ZZA}}class ZZA extends k0{_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 l({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 k1({child:new b0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)F.push(new w0({height:2,child:new l0({padding:N0.symmetric(2,0),child:new l({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 l0({decoration:new t4(B.background,J),child:new w0({width:60,height:7,child:new b0({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 KE extends v0{props;constructor(A){super();this.props=A}createState(){return new XZA}}class XZA extends k0{scrollController=new Z6;scrollAreaKey=new C2("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 e2}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=cE0(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 l0({padding:N0.symmetric(1,0),child:new l({text:new M($.title,new x({color:J,bold:!0}))})}),X=this.isWidgetMessage(B)?B.widget:new l({text:new M($.description,new x({color:Q.colors.foreground})),selectable:!0}),F=new k1({child:new s3({child:new l0({padding:N0.symmetric(1,0),child:new Y1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new k1({child:new gA({controller:this.scrollController,autofocus:!0,child:X})}),new j2({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 l0({padding:N0.symmetric(1,0),child:new l({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 XA({fit:"expand",children:[new i1({onClick:()=>{},child:new w0}),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 l0({decoration:{border:Y,color:Q.colors.background},padding:N0.all(1),child:new b0({mainAxisAlignment:"center",children:[Z,new w0({height:1}),F,D]})})})]})})}}S8();class FZA extends v0{props;constructor(A){super();this.props=A}createState(){return new DZA}}class DZA extends k0{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=e3.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 l({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} ${W4(J,"plugin")} active`,new x({bold:!0}))),Z>0||X>0)$.push(new M(` (${Z} ${W4(Z,"command")}, ${X} ${W4(X,"tool")})`,new x({dim:!0})));$.push(new M(`
|
|
6142
|
+
`))}if(E)V.push(new M(" ",G)),V.push(new M("Total: ",G)),V.push(new M(Y(H),D))}return new l0({decoration:{color:X.background,border:e1.all(new A4(X.border,1,"rounded"))},child:new l({text:new M(void 0,void 0,V)})})}o0();S8();JN();G2();D8();tQ();Yr();jX();VQ();K9();Q$();TU();AA();Zx();bk();j1();o0();VQ();class jJ1{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.1777912178-gd6d908"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await Z70(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 rC extends v0{props;constructor(A){super();this.props=A}createState(){return new QZA}}class QZA extends k0{_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 BZA extends k0{controller=new v3;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 L$({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 Y1({children:[new l0({decoration:{color:B.background},child:new l({text:new M(">",new x({color:B.foreground}))})}),new k1({child:F})]}),G=new l0({padding:N0.symmetric(1,0),child:new l({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 l0({padding:N0.symmetric(1,0),child:new l({text:new M("",void 0,V)})});return new l0({decoration:{border:X,color:B.background},padding:N0.all(1),child:new b0({children:[G,new w0({height:1}),D,new H5,U]})})}}class d10 extends v0{props;constructor(A){super();this.props=A}createState(){return new BZA}}Q$();class $ZA extends k0{controller=new v3;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 hF(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=Y4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),X=new AV({controller:this.controller,triggers:[new $Y],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 l0({constraints:new L1({maxHeight:Z}),padding:N0.symmetric(1,0),child:F}),G=new l0({padding:N0.symmetric(1,0),child:new l({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 l0({padding:N0.symmetric(1,0),child:new l({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 w0({height:1}),new k1({child:D}),new w0({height:1}),V];return new l0({decoration:{border:e1.all(new A4(B.foreground,1,"solid")),color:B.background},padding:N0.all(1),child:new b0({children:U})})}}class RJ1 extends v0{props;constructor(A){super();this.props=A}createState(){return new $ZA}}function JZA(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 PJ1 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)=>JZA(J.pubDate).length));return new e6({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 w0({width:W,child:Y1.end([new l({text:new M(H,new x({color:K}))})])});return new l0({decoration:V?{color:V}:void 0,padding:N0.symmetric(2,0),child:new Y1({children:[new k1({child:new l({text:new M(J.title,new x({color:U})),overflow:"ellipsis",maxLines:1})}),new w0({width:2}),E(JZA(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()}}o0();class YZA extends k0{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 e6({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 l0({decoration:K?{color:K}:void 0,padding:N0.symmetric(2,0),child:new l({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 l0({decoration:K?{color:K}:void 0,padding:N0.symmetric(2,0),child:new l({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 _J1 extends v0{props;constructor(A){super();this.props=A}createState(){return new YZA}}class $V extends v0{props;constructor(A){super();this.props=A}createState(){return new ZZA}}class ZZA extends k0{_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 l({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 k1({child:new b0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)F.push(new w0({height:2,child:new l0({padding:N0.symmetric(2,0),child:new l({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 l0({decoration:new t4(B.background,J),child:new w0({width:60,height:7,child:new b0({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 KE extends v0{props;constructor(A){super();this.props=A}createState(){return new XZA}}class XZA extends k0{scrollController=new Z6;scrollAreaKey=new C2("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 e2}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=cE0(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 l0({padding:N0.symmetric(1,0),child:new l({text:new M($.title,new x({color:J,bold:!0}))})}),X=this.isWidgetMessage(B)?B.widget:new l({text:new M($.description,new x({color:Q.colors.foreground})),selectable:!0}),F=new k1({child:new s3({child:new l0({padding:N0.symmetric(1,0),child:new Y1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new k1({child:new gA({controller:this.scrollController,autofocus:!0,child:X})}),new j2({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 l0({padding:N0.symmetric(1,0),child:new l({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 XA({fit:"expand",children:[new i1({onClick:()=>{},child:new w0}),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 l0({decoration:{border:Y,color:Q.colors.background},padding:N0.all(1),child:new b0({mainAxisAlignment:"center",children:[Z,new w0({height:1}),F,D]})})})]})})}}S8();class FZA extends v0{props;constructor(A){super();this.props=A}createState(){return new DZA}}class DZA extends k0{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=e3.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 l({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} ${W4(J,"plugin")} active`,new x({bold:!0}))),Z>0||X>0)$.push(new M(` (${Z} ${W4(Z,"command")}, ${X} ${W4(X,"tool")})`,new x({dim:!0})));$.push(new M(`
|
|
6143
6143
|
|
|
6144
6144
|
`));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(`
|
|
6145
6145
|
`)),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(`
|
|
@@ -6317,7 +6317,7 @@ ${s.content||""}`:s.content||"",f0=[],Q1=s.baseDir.startsWith("file://")?Vq0(s.b
|
|
|
6317
6317
|
`)}function lFA(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=N24({settings:{url:Y.ampURL,proxy:Z},secrets:{getToken:(D,G)=>Y.secrets.get(D,G)}}),F=await OA.userDisplayBalanceInfo({},{config:X});if(!F.ok){if(F.error.code==="auth-required")process.stderr.write(s0.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(s0.red("Error: ")+F.error.message+`
|
|
6318
6318
|
`),process.exit(1)}process.stdout.write(await Az8(F.result.displayText)+`
|
|
6319
6319
|
`),process.exit(0)})}var ww8=j40.join(OX,"logs","headless.log"),vX1=j40.join(Iu,"device-id.json"),Cw8=`cli-tui-${qUA(16).toString("hex")}`;async function Mw8(){for(let A of jO)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(() => M4(Cg(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){VY.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
|
|
6320
|
-
`)}function Lw8(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 J9(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",Rw8(Q.model))}function UUA(A){let Q=A.indexOf(":");if(Q===-1)throw new D4(`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 D4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function Ow8(A){if(A===void 0)return;let Q=A.trim();if(Z24(Q))return Q;throw new D4(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function jw8(A,Q){if(PD(A,Q))return;let B=UJ(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new D4(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function Rw8(A){if(!A.includes("="))return UUA(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new D4(`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 D4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new D4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);UUA(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new D4("No valid model overrides found in --model flag value.",1);return Q}function Pw8(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 _w8(A){try{return await NUA(A,"utf-8")}catch{return A}}async function yX1(A,Q,B){let $=Pw8(A,Q);if(!$)return;let J=fA(B)?B.features:[],Y=fA(B)?B.user.email:void 0;if(!Mg(J,X2.HARNESS_SYSTEM_PROMPT)&&!(Y&&ZQ(Y)))throw new D4("You are not allowed to do this.",1);sB("systemPrompt",await _w8($))}function Mg(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function Tw8(A){return A!=="pending"}function e_(A){if(!fA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function Sw8(A){let Q=e_(A);if(Q)return Q.id;if(jD(A))throw Error(A.error.message);throw Error("unreachable")}function kw8(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 vw8(A){let $=kw8(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 D4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function R40(A,Q){let B=R51(Error(A.error.message));if(B.message===g7.networkOffline||B.message===g7.networkTimeout)return vw8(Q);if(B.message!==g7.internalBug)return new D4(B.message,1,B.suggestion);return new D4(A.error.message.replace(/^Error: /,""),1)}var KUA=[{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??TF,description:`Custom settings file path (overrides the default location ${TF})`},{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 ${rt})`},{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:_9(),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:LO.SMART.key,description:`Set the agent mode (${GJ({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(GJ().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:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],EUA=(A)=>("deprecated"in A)&&A.deprecated===!0,yw8=(A)=>("hidden"in A)&&A.hidden===!0,xw8=(A)=>("default"in A),fw8=(A)=>("default"in A)?A.default:void 0;function AN0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=Ow8(Q.effort);if(B!==void 0)jw8(Q.mode,B);return B}function bw8(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 D4(g7.unknownCommand(B),1,Z)}}async function $N0(A){return{...A,getThreadEnvironment:bW,getEnvironmentData:(Q,B)=>oD({filesystem:A.fileSystem},Q,B),osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new Dj(A.fileSystem),generateThreadTitle:GH4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>sQ(A.configService),pluginService:A.pluginService}}function IUA(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:bW,getEnvironmentData:(Q,B)=>oD({filesystem:A.fileSystem},Q,B),filesystem:A.fileSystem,threadService:A.threadService}}var QN0=Z1.file(Iw8.homedir()),xX1=process.env.XDG_CONFIG_HOME?Z1.file(process.env.XDG_CONFIG_HOME):K1.joinPath(QN0,".config");function uw8(A){return hx4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(XK0())FK0();else if(process.platform==="darwin"&&Q==="idle"&&A.isTUIVoiceNotifEnabled())ux4();else Vs(Q);let B=nP(),$=Q00();if((!B||$||Mu())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(dG("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(dG("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(nP()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function B2(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;s34("0.0.
|
|
6320
|
+
`)}function Lw8(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 J9(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",Rw8(Q.model))}function UUA(A){let Q=A.indexOf(":");if(Q===-1)throw new D4(`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 D4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function Ow8(A){if(A===void 0)return;let Q=A.trim();if(Z24(Q))return Q;throw new D4(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function jw8(A,Q){if(PD(A,Q))return;let B=UJ(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new D4(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function Rw8(A){if(!A.includes("="))return UUA(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new D4(`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 D4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new D4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);UUA(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new D4("No valid model overrides found in --model flag value.",1);return Q}function Pw8(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 _w8(A){try{return await NUA(A,"utf-8")}catch{return A}}async function yX1(A,Q,B){let $=Pw8(A,Q);if(!$)return;let J=fA(B)?B.features:[],Y=fA(B)?B.user.email:void 0;if(!Mg(J,X2.HARNESS_SYSTEM_PROMPT)&&!(Y&&ZQ(Y)))throw new D4("You are not allowed to do this.",1);sB("systemPrompt",await _w8($))}function Mg(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function Tw8(A){return A!=="pending"}function e_(A){if(!fA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function Sw8(A){let Q=e_(A);if(Q)return Q.id;if(jD(A))throw Error(A.error.message);throw Error("unreachable")}function kw8(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 vw8(A){let $=kw8(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 D4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function R40(A,Q){let B=R51(Error(A.error.message));if(B.message===g7.networkOffline||B.message===g7.networkTimeout)return vw8(Q);if(B.message!==g7.internalBug)return new D4(B.message,1,B.suggestion);return new D4(A.error.message.replace(/^Error: /,""),1)}var KUA=[{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??TF,description:`Custom settings file path (overrides the default location ${TF})`},{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 ${rt})`},{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:_9(),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:LO.SMART.key,description:`Set the agent mode (${GJ({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(GJ().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:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],EUA=(A)=>("deprecated"in A)&&A.deprecated===!0,yw8=(A)=>("hidden"in A)&&A.hidden===!0,xw8=(A)=>("default"in A),fw8=(A)=>("default"in A)?A.default:void 0;function AN0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=Ow8(Q.effort);if(B!==void 0)jw8(Q.mode,B);return B}function bw8(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 D4(g7.unknownCommand(B),1,Z)}}async function $N0(A){return{...A,getThreadEnvironment:bW,getEnvironmentData:(Q,B)=>oD({filesystem:A.fileSystem},Q,B),osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new Dj(A.fileSystem),generateThreadTitle:GH4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>sQ(A.configService),pluginService:A.pluginService}}function IUA(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:bW,getEnvironmentData:(Q,B)=>oD({filesystem:A.fileSystem},Q,B),filesystem:A.fileSystem,threadService:A.threadService}}var QN0=Z1.file(Iw8.homedir()),xX1=process.env.XDG_CONFIG_HOME?Z1.file(process.env.XDG_CONFIG_HOME):K1.joinPath(QN0,".config");function uw8(A){return hx4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(XK0())FK0();else if(process.platform==="darwin"&&Q==="idle"&&A.isTUIVoiceNotifEnabled())ux4();else Vs(Q);let B=nP(),$=Q00();if((!B||$||Mu())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(dG("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(dG("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(nP()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function B2(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;s34("0.0.1777912178-gd6d908");let Y=Nv({storage:A.settings,secretStorage:A.secrets,workspaceRoot:m0.of(Z1.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:QN0,userConfigDir:xX1});X$A(Y);let Z=await Y.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let X=!1;{let d=await A.secrets.get("apiKey",A.ampURL);if(X=Boolean(d),j.info("API key lookup before login",{found:Boolean(d),ampURL:A.ampURL,deferAuth:$}),!d)if($)j.info("No API key found, continuing startup with deferred auth");else{N5.write(`No API key found. Starting login flow...
|
|
6321
6321
|
`);let g=await hw8(A),n=await A.secrets.get("apiKey",A.ampURL);if(j.info("Login flow completed",{success:g,storedKeyPresent:Boolean(n),ampURL:A.ampURL}),!g)await eW(),process.exit(1);X=!0}}{let d=await Y.getLatest(),g=d.settings.url,n=d.secrets.isSet?.[g];j.info("Config secrets state after login",{configURL:g,apiKeySet:n?.apiKey??!1})}let F=v1(sQ(Y).pipe(L5(Tw8))),D=$?"pending":await F;if(!$)j.info("Server status resolved",{status:"ready",isAuthenticated:fA(D),isError:jD(D),errorMessage:jD(D)?D.error.message:void 0});let G=F.then((d)=>Sw8(d));G.catch(()=>{return});let U=!A.executeMode&&!Q.takeMeBack&&fA(D)&&Mg(D.features,X2.THREAD_ACTORS_TUI)?"all":process.env.PLUGINS??"permissions",{toolService:K,dispose:E}=bD0({configService:Y}),H=new Map,W=()=>H.clear(),z=new gm0(Y,A.settings.getWorkspaceRootPath()),q=qJ0({configService:Y,filesystem:A8}),N=xF4({configService:Y,trustStore:z,skillMCPServers:q.skillMCPServers,createOAuthProvider:async(d,g,n)=>{let c=`${d}:${g}`,B0=H.get(c);if(B0)return j.debug("Reusing existing OAuth provider for server",{serverName:d,serverUrl:g}),B0;j.debug("Creating OAuth provider for server",{serverName:d,serverUrl:g});let O0=(async()=>{let i=new kO(A.secrets),Q0=await i.getClientInfo(d,g),K0=n?.scopes??Q0?.scopes,E0=Vt4();j.info("OAuth headless mode check",{useHeadless:E0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:N5.isTTY});let A0;if(E0)A0=A.executeMode?Gt4():Dt4(d);let Y0=new rb0({storage:i,serverName:d,serverUrl:g,clientId:n?.clientId??Q0?.clientId,clientSecret:n?.clientSecret??Q0?.clientSecret,authUrl:n?.authUrl??Q0?.authUrl,tokenUrl:n?.tokenUrl??Q0?.tokenUrl,scopes:K0,headlessAuthHandler:A0});return j.debug("OAuth provider created",{serverName:d,serverUrl:g,hasManualClientId:!!(n?.clientId??Q0?.clientId),willUseDCR:!(n?.clientId??Q0?.clientId),scopes:K0,headlessMode:E0,executeMode:A.executeMode}),Y0})();return H.set(c,O0),O0}}),I=Qs({configService:Y,filesystem:A8,spawn:nf}),w;if(J)w=new Map;else if(A.executeMode){let d=await Gv4({toolService:K,providers:[N,I],initialTimeout:15000});w=d.registrations;for(let[g,n]of d.initErrors)j.warn(`${g} provider initialization slow or failed:`,n)}else w=Bs({toolService:K,providers:[N,I]});if(Q.jetbrains)IO("JetBrains");else if(Q.ide&&at4())IO("VS Code");else if(Q.ide&&ot4())IO("Neovim");else if(Q.ide){let d=await Mw8();if(d){let g=C70(d.ideName);if(g)IO(g)}}if(A.executeMode)t34(!0);let C,O=n8.status.pipe(O1((d)=>Boolean(d.connected&&d.authenticated&&d.ideName&&o24(d.ideName))),m4()).subscribe((d)=>{if(d){if(!C)C=K.registerTool(Dv4)}else C?.dispose(),C=void 0}),P;if(!A.executeMode){let d=await A.settings.get("fuzzy.alwaysIncludePaths")??[];P=new qu(process.cwd(),{alwaysIncludePaths:d},!0)}else P=new class extends qu{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let k=new Bl0(jj(Y,{usesThreadActors:!1}),{maxThreads:200});j.info("Starting Amp background services");let T=new j$1,f=Q.headless?C1A():void 0,h=f??new Su({configService:Y}),b=h instanceof Su?h:void 0;if(b)b.pluginExecutorKind="local";let y=mi({configService:Y,fileSystem:A8,platform:h,loadGlobalPlugins:Ee(Y),pluginFilter:U}),u=N$0({pluginService:y,toolService:K}),m={configService:Y,toolService:K,mcpService:N,skillService:q,toolboxService:I,trustStore:z,threadService:k,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:P,fileSystem:A8,terminal:T,pluginService:y,pluginPlatform:b,headlessPluginPlatform:f,serverStatus:D,serverStatusPromise:F,viewerUserIDPromise:G,hasAPIKeyAtStartup:X};return{...m,async asyncDispose(){if(m.mcpService.hasAuthenticatingClients())j.info("Waiting for OAuth authentication to complete before exit..."),await m.mcpService.waitForAuthentication();for(let d of w.values())d.dispose();await m.mcpService.dispose(),W(),await m.threadService.asyncDispose(),m.configService.unsubscribe(),E(),m.fuzzyServer.dispose(),m.settingsStorage[Symbol.dispose](),O.unsubscribe(),C?.dispose(),u.dispose(),await m.pluginService.dispose()}}}async function hw8(A){if(!A.executeMode){if(!await tK0("Would you like to log in to Amp? [(y)es, (n)o]: "))return N5.write(`Login cancelled. Run the command again to retry.
|
|
6322
6322
|
`),!1}return await wUA(A)}async function wUA(A){let Q=qUA(32).toString("hex"),B=await Tu(A.ampURL,Q),$=new AbortController;try{await ID(B,$.signal)}catch(Y){j.error("Error opening browser",{error:Y})}let J=await Tu(A.ampURL,Q,!1);N5.write(`If your browser does not open automatically, visit:
|
|
6323
6323
|
|
|
@@ -6325,7 +6325,7 @@ ${s0.blue.bold(J)}
|
|
|
6325
6325
|
|
|
6326
6326
|
`);try{return await D1A(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}),VY.write(`
|
|
6327
6327
|
Login failed: ${Y instanceof Error?Y.message:String(Y)}
|
|
6328
|
-
`),!1}}function gw8(A){let Q=new Xw().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)jP(),process.exit(0);let H=E.originalError??E;Bo4(H)}),N4A(Q,{version:"0.0.
|
|
6328
|
+
`),!1}}function gw8(A){let Q=new Xw().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)jP(),process.exit(0);let H=E.originalError??E;Bo4(H)}),N4A(Q,{version:"0.0.1777912178-gd6d908",buildTimestamp:"2026-05-04T16:33:09.749Z",buildType:"'release'"}),Q.addHelpText("after",lt4()),Q.configureHelp({formatHelp:it4}),Q.command("logout").description("Log out by removing stored API key").action(async(E,H)=>{let W=H.optsWithGlobals(),z=await H8(W);await ow8(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 H8(W);await aw8(z,await qe(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 H8(z);await Qt4(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 H8(W);await Bt4(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 G0A({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 na4(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(`
|
|
6329
6329
|
`)).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 D4("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.
|
|
6330
6330
|
|
|
6331
6331
|
`),W.outputHelp(),process.exit(0);let q=l8(z)??WB(z),N=W.optsWithGlobals(),I=await H8(N);J9(W,N);let w=await B2(I,N),C=!1;try{if(H.checkout&&H.skipCheckout)throw new D4("Choose either --checkout or --skip-checkout, not both.",1);if(jD(w.serverStatus))throw R40(w.serverStatus,I.ampURL);let O=fA(w.serverStatus)?w.serverStatus.features:void 0;if(!Mg(O,X2.V2))throw new D4("live-sync is not enabled for your user",1);await t0A({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:tK0}),C=!0}finally{if(await w.asyncDispose(),C)process.exit(0)}});let B=async(E,H,W)=>{Nv({storage:H.settings,secretStorage:H.secrets,workspaceRoot:m0.of(Z1.file(process.cwd())),defaultAmpURL:H.ampURL,homeDir:QN0,userConfigDir:xX1});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 H8(W);await zUA(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 H8(W);await ZC8(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 H8(z);if(H.pick)VY.write(`${s0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
|
|
@@ -6358,8 +6358,8 @@ ${I}
|
|
|
6358
6358
|
`))}),H.args.length>0)bw8(z,H);await BN0(z,W,H,A)}),je4(Q),Q}async function Lg(A,Q){await kZ((B)=>$E0(B,A,Q))}async function HUA(A,Q,B){let $=Date.now(),[J,Y]=await Promise.all([OA.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 D4(`Cannot resume thread created by another user.
|
|
6359
6359
|
|
|
6360
6360
|
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 CUA(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 MUA(A,Q,B){if(A.streamJson&&!Q)throw new D4("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new D4("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new D4("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new D4("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 D4("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archive&&!Q)throw new D4("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 D4("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 D4("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"
|
|
6361
|
-
Or pipe via stdin: echo "your message" | amp --execute`)}function mw8(A,Q){if(NQ4([L90.parse({tool:"*",action:"allow"})]),aBA(A.settings))j.debug("Enabling permissions plugin"),Q.registerInternalPlugin({name:"permissions",entryPoint:w$1})}async function BN0(A,Q,B,$){if(Q.headless)return pw8(A,Q,B);let J=await B2(A,Q),Y=await J.serverStatusPromise,Z=await J.configService.getLatest(),X=fA(Y)&&Mg(Y.features,X2.THREAD_ACTORS_TUI),F=X&&!Q.takeMeBack;if(Q.showWelcome&&!X)throw await J.asyncDispose(),new D4("--show-welcome is only available with the new Amp CLI feature flag",1);if(F)return mw8(Z,J.pluginService),dw8(A,Q,B,J);else{if(Q.threadId&&z7(Q.threadId)){let D=await OA.getThreadLinkInfo({thread:Q.threadId},{config:J.configService}).catch(()=>null);if(D?.ok&&D.result.usesThreadActors)throw await J.asyncDispose(),new D4(`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 cw8(A,Q,B,$,{dependencies:J})}}async function pw8(A,Q,B){let $=(z,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=hA1();j.info("Startup phase",{phase:z,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};J9(B,Q);let J=process.hrtime.bigint(),Y=await B2(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(jD(Z))throw R40(Z,A.ampURL);let X=fA(Z)?Z:null,F=X?.user.email;await yX1(B,Q,Z);let D=e_(Z),G=F00(Q,D);if(G instanceof Error)c5(G.message);if(X&&!zv(Q.mode,F))throw new D4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!F||!ZQ(F)))throw new D4("Headless executor mode is only available for Amp employees",1);OU0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new D4("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&&!z7(K))throw new D4(`Invalid thread ID: ${K}`,1);let E=K?void 0:await JC8({dependencies:Y,apiKey:U,visibility:G??void 0}),H=K??E?.threadId;if(!H)throw new D4("Failed to resolve headless thread ID",1);let W=await Ht4(H);if(W.status==="already-running")await Y.asyncDispose(),await eW(),process.exit(0);try{await Zt4({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 eW(),process.exit(0)}async function dw8(A,Q,B,$){let{userInput:J,stdinInput:Y}=await CUA(Q),Z=!!Q.streamJson||!!Q.streamJsonThinking;MUA({...Q,streamJson:Z},A.executeMode,J),J9(B,Q);let X=Q.threadId&&z7(Q.threadId)?Q.threadId:void 0,F=Q.observe?l8(Q.observe)??WB(Q.observe):void 0,D=await $.serverStatusPromise;if(jD(D))throw R40(D,A.ampURL);let G=await $.secretStorage.get("apiKey",A.ampURL);if(!G)throw new D4("API key required. Please run `amp login` first.",1);let V=fA(D)&&ZQ(D.user.email);if(V)OU0();if(A.executeMode){u31($.mcpService,A.settings);try{let U=AN0(B,Q),K=await $C(),E=X?U:eK0({agentMode:Q.mode,explicitEffort:U,sessionState:K}),H=X?void 0:AE0(await ku($.configService),{agentMode:Q.mode,explicitEffort:U,sessionState:K}),W=await Ls4({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 Lg(W,"execute"),Q.archive)await $.threadService.archive(W,!0)}finally{await $.asyncDispose()}await eW(),process.exit(0)}else{let U=AN0(B,Q),K=jj($.configService,{usesThreadActors:!0}),E=new v_($.fuzzyServer),H=process.cwd();await I$1({ampURL:A.ampURL,apiKey:G,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??cJ(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:W})=>gw({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.showWelcome,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:U}),process.exit(0)}}async function cw8(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(E0,A0)=>{let Y0=Number(process.hrtime.bigint()-A0)/1e6,a=hA1();j.info("Startup phase",{phase:E0,phaseMs:Math.round(Y0),sinceMainMs:a===null?void 0:Math.round(a)})},{userInput:X,stdinInput:F}=await CUA(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;MUA({...Q,streamJson:D},A.executeMode,X),J9(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await B2(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&&jD(E))throw R40(E,A.ampURL);let H=fA(E)?E:null,W=H?.user.email,z=!!(W&&ZQ(W));if(z)OU0();if(!K)await yX1(B,Q,E);let q=e_(E),N=q?.features??[],I=q?.team??null,w=F00(Q,q);if(w instanceof Error)c5(w.message);if(H&&!zv(Q.mode,W))throw new D4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let C=Q.threadId&&z7(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(E0)=>Lg(E0,"interactive"),k={threadService:V.threadService,workerDeps:O,createThread:async(E0)=>{let A0=K?await V.serverStatusPromise:E,Y0=await jU0(A.settings,process.cwd(),e_(A0),w);if(Y0 instanceof Error)c5(Y0.message);return ZZ1(O,{threadMeta:Y0?xZ(Y0):void 0,agentMode:E0??Q.mode,onFirstAssistantMessage:P})},validateThreadOwnership:async(E0,A0)=>{if(A0?.nonBlockingOwnershipCheck){HUA(E0,V.configService,V.viewerUserIDPromise).catch((Y0)=>{if(Y0 instanceof D4){if(A0.onOwnershipError){A0.onOwnershipError(Y0,E0);return}Az(Y0,E0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Y0})});return}try{await HUA(E0,V.configService,V.viewerUserIDPromise)}catch(Y0){if(Y0 instanceof D4)throw Y0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Y0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:P,handleError:Az},T=async()=>{try{return mFA(k,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(E0){if(E0 instanceof D4)throw E0;throw await Az(E0,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 E0=await V.configService.getLatest(),A0=Pc(E0),Y0=await OA.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(A0)});if(Y0.ok)return j.info("User free tier status:",Y0),Y0.result;return}catch(E0){j.error("Failed to fetch free tier status:",E0);return}})(),b=!A.executeMode?new T$1:null,y,u=null;if(b)y=b,u=(async()=>{let E0=K?await V.serverStatusPromise:V.serverStatus;if(jD(E0))throw R40(E0,A.ampURL);await yX1(B,Q,E0);let A0=process.hrtime.bigint(),Y0=await T();if(Z("runMainThread:createThreadPool",A0),b.attach(Y0),X){let a=await v1(Y0.threadHandles$);if(!a)throw new D4("No active thread is available yet.",1);await a.sendMessage({content:[{type:"text",text:X}]})}})(),u.catch(async(E0)=>{let A0=E0 instanceof Error?E0:Error(String(E0));b.setInitError(A0),await Az(E0,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&&Mg(H.features,X2.TUI_VOICE_NOTIF);if(K)V.serverStatusPromise.then((E0)=>{d=fA(E0)&&Mg(E0.features,X2.TUI_VOICE_NOTIF)}).catch((E0)=>{j.debug("Failed to resolve TUI voice notification feature flag",{error:E0})});G=process.hrtime.bigint();let g=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),uw8({configService:V.configService,threadService:V.threadService,config:g,useNotificationsForService:m,isTUIVoiceNotifEnabled:()=>d,threadViewStates$:()=>y.threadHandles$.pipe(a4((E0)=>{if(!E0)return m0.of({});return u6(E0.thread$,E0.threadViewState$).pipe(O1(([A0,Y0])=>({[A0.id]:Y0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){u31(V.mcpService,A.settings);let E0=AN0(B,Q),A0=await $C(),Y0=C?E0:eK0({agentMode:Q.mode,explicitEffort:E0,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 Mo4({threadPool:y,...a});if(await Lg(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 M70();let E0=await SD({jetbrainsOnly:Q.jetbrains});if(E0.length===0){if(Q.jetbrains)n=!await V.configService.get("jetbrains.skipInstall")}else if(E0.length===1){let A0=E0[0];if(A0)n8.selectConfig(A0)}else c=!0}G=process.hrtime.bigint();let B0=J31("0.0.1777910718-gcdf3ba",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let O0=new h31(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),X&&A.executeMode){let E0=await v1(y.threadHandles$);if(!E0)throw new D4("No active thread is available yet.",1);await E0.sendMessage({content:[{type:"text",text:X}]})}G=process.hrtime.bigint();let i=await $C();Z("runMainThread:loadSessionState",G),j.info("Loaded session state:",i);let Q0=AN0(B,Q),K0={...i,launchCount:i.launchCount+1,lastReasoningEffortByMode:Q0?{...i.lastReasoningEffortByMode,[Q.mode]:Q0}:i.lastReasoningEffortByMode};kZ((E0)=>({...E0,launchCount:E0.launchCount+1}));try{if(G=process.hrtime.bigint(),await AJA({history:new Fe,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:OA,threadPool:y,createSystemPromptDeps:async()=>IUA(V),ideClient:n8,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:O0,updateService:B0,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:Cw8,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-04T16:08:54.852Z"},(E0)=>new b$1({...E0,threadPool:E0.threadPool},(A0)=>new JZ1({...A0,threadState:A0.threadState}))),Z("runMainThread:mountApp-returned",G),u)await u}finally{await y.dispose().catch((E0)=>{j.error("Failed to dispose thread pool during shutdown",E0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function H8(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)VY.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
6362
|
-
`);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 gF4({get:async(X)=>{if(X!==Ti)return;try{let F=await NUA(vX1,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(X,F)=>{if(X!==Ti)return;await qw8(j40.dirname(vX1),{recursive:!0}),await Nw8(vX1,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:oB0()});e34($);let J=await KK0({...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 N1A(A.mcpConfig);J=I1A(J,X)}let Y=j40.dirname(J.getSettingsFilePath());bx4(Iu,Y),J=S54(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=x9;if(j.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!BN(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:BE0(await qe(A,J))}}function lw8(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 iw8(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=j40.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?ww8:rt));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function nw8(){vc4();let A=lw8(process.argv),Q=iw8(process.argv,A),B=ma4(Q),$=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)s0.level=0;if(Lw8(j),j.info("Starting Amp CLI.",{version:"0.0.
|
|
6361
|
+
Or pipe via stdin: echo "your message" | amp --execute`)}function mw8(A,Q){if(NQ4([L90.parse({tool:"*",action:"allow"})]),aBA(A.settings))j.debug("Enabling permissions plugin"),Q.registerInternalPlugin({name:"permissions",entryPoint:w$1})}async function BN0(A,Q,B,$){if(Q.headless)return pw8(A,Q,B);let J=await B2(A,Q),Y=await J.serverStatusPromise,Z=await J.configService.getLatest(),X=fA(Y)&&Mg(Y.features,X2.THREAD_ACTORS_TUI),F=X&&!Q.takeMeBack;if(Q.showWelcome&&!X)throw await J.asyncDispose(),new D4("--show-welcome is only available with the new Amp CLI feature flag",1);if(F)return mw8(Z,J.pluginService),dw8(A,Q,B,J);else{if(Q.threadId&&z7(Q.threadId)){let D=await OA.getThreadLinkInfo({thread:Q.threadId},{config:J.configService}).catch(()=>null);if(D?.ok&&D.result.usesThreadActors)throw await J.asyncDispose(),new D4(`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 cw8(A,Q,B,$,{dependencies:J})}}async function pw8(A,Q,B){let $=(z,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=hA1();j.info("Startup phase",{phase:z,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};J9(B,Q);let J=process.hrtime.bigint(),Y=await B2(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(jD(Z))throw R40(Z,A.ampURL);let X=fA(Z)?Z:null,F=X?.user.email;await yX1(B,Q,Z);let D=e_(Z),G=F00(Q,D);if(G instanceof Error)c5(G.message);if(X&&!zv(Q.mode,F))throw new D4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!F||!ZQ(F)))throw new D4("Headless executor mode is only available for Amp employees",1);OU0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new D4("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&&!z7(K))throw new D4(`Invalid thread ID: ${K}`,1);let E=K?void 0:await JC8({dependencies:Y,apiKey:U,visibility:G??void 0}),H=K??E?.threadId;if(!H)throw new D4("Failed to resolve headless thread ID",1);let W=await Ht4(H);if(W.status==="already-running")await Y.asyncDispose(),await eW(),process.exit(0);try{await Zt4({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 eW(),process.exit(0)}async function dw8(A,Q,B,$){let{userInput:J,stdinInput:Y}=await CUA(Q),Z=!!Q.streamJson||!!Q.streamJsonThinking;MUA({...Q,streamJson:Z},A.executeMode,J),J9(B,Q);let X=Q.threadId&&z7(Q.threadId)?Q.threadId:void 0,F=Q.observe?l8(Q.observe)??WB(Q.observe):void 0,D=await $.serverStatusPromise;if(jD(D))throw R40(D,A.ampURL);let G=await $.secretStorage.get("apiKey",A.ampURL);if(!G)throw new D4("API key required. Please run `amp login` first.",1);let V=fA(D)&&ZQ(D.user.email);if(V)OU0();if(A.executeMode){u31($.mcpService,A.settings);try{let U=AN0(B,Q),K=await $C(),E=X?U:eK0({agentMode:Q.mode,explicitEffort:U,sessionState:K}),H=X?void 0:AE0(await ku($.configService),{agentMode:Q.mode,explicitEffort:U,sessionState:K}),W=await Ls4({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 Lg(W,"execute"),Q.archive)await $.threadService.archive(W,!0)}finally{await $.asyncDispose()}await eW(),process.exit(0)}else{let U=AN0(B,Q),K=jj($.configService,{usesThreadActors:!0}),E=new v_($.fuzzyServer),H=process.cwd();await I$1({ampURL:A.ampURL,apiKey:G,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??cJ(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:W})=>gw({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.showWelcome,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:U}),process.exit(0)}}async function cw8(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(E0,A0)=>{let Y0=Number(process.hrtime.bigint()-A0)/1e6,a=hA1();j.info("Startup phase",{phase:E0,phaseMs:Math.round(Y0),sinceMainMs:a===null?void 0:Math.round(a)})},{userInput:X,stdinInput:F}=await CUA(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;MUA({...Q,streamJson:D},A.executeMode,X),J9(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await B2(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&&jD(E))throw R40(E,A.ampURL);let H=fA(E)?E:null,W=H?.user.email,z=!!(W&&ZQ(W));if(z)OU0();if(!K)await yX1(B,Q,E);let q=e_(E),N=q?.features??[],I=q?.team??null,w=F00(Q,q);if(w instanceof Error)c5(w.message);if(H&&!zv(Q.mode,W))throw new D4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let C=Q.threadId&&z7(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(E0)=>Lg(E0,"interactive"),k={threadService:V.threadService,workerDeps:O,createThread:async(E0)=>{let A0=K?await V.serverStatusPromise:E,Y0=await jU0(A.settings,process.cwd(),e_(A0),w);if(Y0 instanceof Error)c5(Y0.message);return ZZ1(O,{threadMeta:Y0?xZ(Y0):void 0,agentMode:E0??Q.mode,onFirstAssistantMessage:P})},validateThreadOwnership:async(E0,A0)=>{if(A0?.nonBlockingOwnershipCheck){HUA(E0,V.configService,V.viewerUserIDPromise).catch((Y0)=>{if(Y0 instanceof D4){if(A0.onOwnershipError){A0.onOwnershipError(Y0,E0);return}Az(Y0,E0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Y0})});return}try{await HUA(E0,V.configService,V.viewerUserIDPromise)}catch(Y0){if(Y0 instanceof D4)throw Y0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Y0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:P,handleError:Az},T=async()=>{try{return mFA(k,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(E0){if(E0 instanceof D4)throw E0;throw await Az(E0,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 E0=await V.configService.getLatest(),A0=Pc(E0),Y0=await OA.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(A0)});if(Y0.ok)return j.info("User free tier status:",Y0),Y0.result;return}catch(E0){j.error("Failed to fetch free tier status:",E0);return}})(),b=!A.executeMode?new T$1:null,y,u=null;if(b)y=b,u=(async()=>{let E0=K?await V.serverStatusPromise:V.serverStatus;if(jD(E0))throw R40(E0,A.ampURL);await yX1(B,Q,E0);let A0=process.hrtime.bigint(),Y0=await T();if(Z("runMainThread:createThreadPool",A0),b.attach(Y0),X){let a=await v1(Y0.threadHandles$);if(!a)throw new D4("No active thread is available yet.",1);await a.sendMessage({content:[{type:"text",text:X}]})}})(),u.catch(async(E0)=>{let A0=E0 instanceof Error?E0:Error(String(E0));b.setInitError(A0),await Az(E0,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&&Mg(H.features,X2.TUI_VOICE_NOTIF);if(K)V.serverStatusPromise.then((E0)=>{d=fA(E0)&&Mg(E0.features,X2.TUI_VOICE_NOTIF)}).catch((E0)=>{j.debug("Failed to resolve TUI voice notification feature flag",{error:E0})});G=process.hrtime.bigint();let g=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),uw8({configService:V.configService,threadService:V.threadService,config:g,useNotificationsForService:m,isTUIVoiceNotifEnabled:()=>d,threadViewStates$:()=>y.threadHandles$.pipe(a4((E0)=>{if(!E0)return m0.of({});return u6(E0.thread$,E0.threadViewState$).pipe(O1(([A0,Y0])=>({[A0.id]:Y0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){u31(V.mcpService,A.settings);let E0=AN0(B,Q),A0=await $C(),Y0=C?E0:eK0({agentMode:Q.mode,explicitEffort:E0,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 Mo4({threadPool:y,...a});if(await Lg(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 M70();let E0=await SD({jetbrainsOnly:Q.jetbrains});if(E0.length===0){if(Q.jetbrains)n=!await V.configService.get("jetbrains.skipInstall")}else if(E0.length===1){let A0=E0[0];if(A0)n8.selectConfig(A0)}else c=!0}G=process.hrtime.bigint();let B0=J31("0.0.1777912178-gd6d908",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let O0=new h31(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),X&&A.executeMode){let E0=await v1(y.threadHandles$);if(!E0)throw new D4("No active thread is available yet.",1);await E0.sendMessage({content:[{type:"text",text:X}]})}G=process.hrtime.bigint();let i=await $C();Z("runMainThread:loadSessionState",G),j.info("Loaded session state:",i);let Q0=AN0(B,Q),K0={...i,launchCount:i.launchCount+1,lastReasoningEffortByMode:Q0?{...i.lastReasoningEffortByMode,[Q.mode]:Q0}:i.lastReasoningEffortByMode};kZ((E0)=>({...E0,launchCount:E0.launchCount+1}));try{if(G=process.hrtime.bigint(),await AJA({history:new Fe,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:OA,threadPool:y,createSystemPromptDeps:async()=>IUA(V),ideClient:n8,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:O0,updateService:B0,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:Cw8,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-04T16:33:09.749Z"},(E0)=>new b$1({...E0,threadPool:E0.threadPool},(A0)=>new JZ1({...A0,threadState:A0.threadState}))),Z("runMainThread:mountApp-returned",G),u)await u}finally{await y.dispose().catch((E0)=>{j.error("Failed to dispose thread pool during shutdown",E0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function H8(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)VY.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
6362
|
+
`);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 gF4({get:async(X)=>{if(X!==Ti)return;try{let F=await NUA(vX1,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(X,F)=>{if(X!==Ti)return;await qw8(j40.dirname(vX1),{recursive:!0}),await Nw8(vX1,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:oB0()});e34($);let J=await KK0({...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 N1A(A.mcpConfig);J=I1A(J,X)}let Y=j40.dirname(J.getSettingsFilePath());bx4(Iu,Y),J=S54(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=x9;if(j.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!BN(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:BE0(await qe(A,J))}}function lw8(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 iw8(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=j40.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?ww8:rt));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function nw8(){vc4();let A=lw8(process.argv),Q=iw8(process.argv,A),B=ma4(Q),$=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)s0.level=0;if(Lw8(j),j.info("Starting Amp CLI.",{version:"0.0.1777912178-gd6d908",buildTimestamp:"2026-05-04T16:33:09.749Z"}),process.platform==="win32"&&xP())Ke4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new D4(g7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await gw8(B).parseAsync(process.argv)}xx4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await nw8().catch(Az)});async function aw8(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}
|
|
6363
6363
|
`);else if(!BN(A.ampURL))N5.write(`Logging in to ${new URL(A.ampURL).hostname}
|
|
6364
6364
|
`);let $=process.env.AMP_API_KEY;if($)N5.write(`API key found in environment variable, storing...
|
|
6365
6365
|
`),await Q.set("apiKey",$,A.ampURL),N5.write(`API key successfully stored.
|