@sourcegraph/amp 0.0.1777706852-g76c1b8 → 0.0.1777710388-ge5e9da
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +10 -10
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -4736,12 +4736,12 @@ ${E}`))}},error:(K)=>{if(!U)U=!0,F(Error(`Failed to spawn brew: ${K.message}`))}
|
|
|
4736
4736
|
${E}`;if(Y==="pnpm"&&E.includes("Unable to find the global bin directory"))H+=`
|
|
4737
4737
|
|
|
4738
4738
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
4739
|
-
npm install -g @sourcegraph/amp`;F(Error(H))}},error:(K)=>{if(!V)V=!0,F(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,X()}})})}i0();i0();xI();async function wK0(A,Q){let J=`${Q||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,Y=new AbortController,Z=setTimeout(()=>Y.abort(),5000);try{let X=await fetch(J,{signal:Y.signal});if(!X.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let F=await X.json(),D=F.version??F["dist-tags"]?.latest;if(!D)return{hasUpdate:!1,currentVersion:A,source:"npm"};let G=je(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 io5="https://static.ampcode.com/cli/cli-version.txt";async function CK0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${io5}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!$.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let J=(await $.text()).trim();if(!J||!/^\d+\.\d+\.\d+/.test(J))return{hasUpdate:!1,currentVersion:A,source:"bin"};let Y=je(A,J),Z=Y<0;return 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 no5=604800000;function Ve4(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>no5)return{ageMs:B};return null}function je(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 A31(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Q)return null;let B=parseInt(Q[1],10)*1000,$=Q[2],J=B!==0?rU(B):void 0;return{sha:$,age:J}}catch{return null}}j1();i0();import{readFile as ao5,realpath as oo5}from"node:fs/promises";import{homedir as ro5}from"node:os";import{dirname as Ue4,join as Q31}from"node:path";async function Ke4(A){switch(A){case"binary":case"brew":return so5(Ce());case"npm":case"pnpm":case"yarn":case"bun":return to5();case"bootstrap":return eo5()}}async function so5(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 to5(){try{let A=process.argv[1];if(!A)return null;let Q=await oo5(A),B=Ue4(Ue4(Q));return await Ee4(Q31(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function eo5(){try{let A=process.env.AMP_HOME??Q31(ro5(),".amp");return await Ee4(Q31(A,"package","package.json"))}catch(A){return j.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function Ee4(A){let Q=await ao5(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 Ar5=3600000,Qr5=5000;function B31(A,Q,B={}){let $=new r4,J=$.pipe($6({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??Ar5,X=!1,F=()=>{X=!0};return setImmediate(async()=>{let D=new vY().scoped("update");if(Y>0){if(await oU(Y),X)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!X){let U=await Br5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await oU(Qr5),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 Br5(A,Q,B,$){let J={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return B.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),J.stop=!0,J;let Y=await Q.get("updates.mode");if(Y==="disabled")return B.debug("checking disabled"),J.stop=!0,J;let Z=await NK0(),X=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:X});let F;if(X)F=await CK0(A);else{let V=await xP();F=await wK0(A,V)}if(!(F.latestVersion&&F.hasUpdate))return B.debug("no update available"),J;let D=(V)=>{$.next(V),J.emittedVisibleState=!0};if(Z){let V=await Ke4(Z);if(V&&je(V,F.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:F.latestVersion}),J.updatedTo=V,je(A,V)<0){let U=await Bz(V),K={from:A,to:V,externallyUpdated:!0,...U};if(U.status==="same")B.info("on-disk already updated by another instance",K),D("updated");else B.warn("on-disk already updated by another instance, with PATH warning",K),D("updated-with-warning")}return J}}let G=()=>{if(F.currentVersionAge!==void 0&&F.latestVersionAge!==void 0){let V=F.currentVersionAge-F.latestVersionAge,U=0.5;if(Math.abs(V)<0.5)return B.debug("versions too close together, suppressing update warning",{currentVersionAge:F.currentVersionAge,latestVersionAge:F.latestVersionAge,ageDifferenceHours:V}),!0}return!1};if(!Y)Y=Z==="pnpm"?"warn":"auto",B.debug("no configured update mode; selected default based on package manager",{packageManager:Z,mode:Y});if(Z==="brew"){if(!G())D("update-available-brew");return J}if(Z==="binary"&&process.execPath!==Ce()){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 Oe(F.latestVersion,Z),J.updatedTo=F.latestVersion;let V=await Bz(F.latestVersion),U={from:F.currentVersion,to:F.latestVersion,...V};if(V.status==="same")B.info("success",U),D("updated");else B.warn("success with warning",U),D("updated-with-warning")}catch(V){D("update-error")}return J}catch(Y){return B.debug("check failed",{error:Y}),J}}xI();import{stderr as mG}from"node:process";function He4(A){let Q=new Zw().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 p81($.force||!1,$.verbose||!1,"0.0.
|
|
4739
|
+
npm install -g @sourcegraph/amp`;F(Error(H))}},error:(K)=>{if(!V)V=!0,F(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,X()}})})}i0();i0();xI();async function wK0(A,Q){let J=`${Q||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,Y=new AbortController,Z=setTimeout(()=>Y.abort(),5000);try{let X=await fetch(J,{signal:Y.signal});if(!X.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let F=await X.json(),D=F.version??F["dist-tags"]?.latest;if(!D)return{hasUpdate:!1,currentVersion:A,source:"npm"};let G=je(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 io5="https://static.ampcode.com/cli/cli-version.txt";async function CK0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${io5}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!$.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let J=(await $.text()).trim();if(!J||!/^\d+\.\d+\.\d+/.test(J))return{hasUpdate:!1,currentVersion:A,source:"bin"};let Y=je(A,J),Z=Y<0;return 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 no5=604800000;function Ve4(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>no5)return{ageMs:B};return null}function je(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 A31(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Q)return null;let B=parseInt(Q[1],10)*1000,$=Q[2],J=B!==0?rU(B):void 0;return{sha:$,age:J}}catch{return null}}j1();i0();import{readFile as ao5,realpath as oo5}from"node:fs/promises";import{homedir as ro5}from"node:os";import{dirname as Ue4,join as Q31}from"node:path";async function Ke4(A){switch(A){case"binary":case"brew":return so5(Ce());case"npm":case"pnpm":case"yarn":case"bun":return to5();case"bootstrap":return eo5()}}async function so5(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 to5(){try{let A=process.argv[1];if(!A)return null;let Q=await oo5(A),B=Ue4(Ue4(Q));return await Ee4(Q31(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function eo5(){try{let A=process.env.AMP_HOME??Q31(ro5(),".amp");return await Ee4(Q31(A,"package","package.json"))}catch(A){return j.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function Ee4(A){let Q=await ao5(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 Ar5=3600000,Qr5=5000;function B31(A,Q,B={}){let $=new r4,J=$.pipe($6({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??Ar5,X=!1,F=()=>{X=!0};return setImmediate(async()=>{let D=new vY().scoped("update");if(Y>0){if(await oU(Y),X)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!X){let U=await Br5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await oU(Qr5),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 Br5(A,Q,B,$){let J={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return B.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),J.stop=!0,J;let Y=await Q.get("updates.mode");if(Y==="disabled")return B.debug("checking disabled"),J.stop=!0,J;let Z=await NK0(),X=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:X});let F;if(X)F=await CK0(A);else{let V=await xP();F=await wK0(A,V)}if(!(F.latestVersion&&F.hasUpdate))return B.debug("no update available"),J;let D=(V)=>{$.next(V),J.emittedVisibleState=!0};if(Z){let V=await Ke4(Z);if(V&&je(V,F.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:F.latestVersion}),J.updatedTo=V,je(A,V)<0){let U=await Bz(V),K={from:A,to:V,externallyUpdated:!0,...U};if(U.status==="same")B.info("on-disk already updated by another instance",K),D("updated");else B.warn("on-disk already updated by another instance, with PATH warning",K),D("updated-with-warning")}return J}}let G=()=>{if(F.currentVersionAge!==void 0&&F.latestVersionAge!==void 0){let V=F.currentVersionAge-F.latestVersionAge,U=0.5;if(Math.abs(V)<0.5)return B.debug("versions too close together, suppressing update warning",{currentVersionAge:F.currentVersionAge,latestVersionAge:F.latestVersionAge,ageDifferenceHours:V}),!0}return!1};if(!Y)Y=Z==="pnpm"?"warn":"auto",B.debug("no configured update mode; selected default based on package manager",{packageManager:Z,mode:Y});if(Z==="brew"){if(!G())D("update-available-brew");return J}if(Z==="binary"&&process.execPath!==Ce()){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 Oe(F.latestVersion,Z),J.updatedTo=F.latestVersion;let V=await Bz(F.latestVersion),U={from:F.currentVersion,to:F.latestVersion,...V};if(V.status==="same")B.info("success",U),D("updated");else B.warn("success with warning",U),D("updated-with-warning")}catch(V){D("update-error")}return J}catch(Y){return B.debug("check failed",{error:Y}),J}}xI();import{stderr as mG}from"node:process";function He4(A){let Q=new Zw().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 p81($.force||!1,$.verbose||!1,"0.0.1777710388-ge5e9da"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new Zw("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 $r5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
|
|
4740
4740
|
`),$=!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"&&yP()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:$,renderProgress:J}=$r5(mG);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")mG.write(o0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
4741
4741
|
|
|
4742
4742
|
`));try{if(!A){mG.write(o0.blue(`Checking for updates...
|
|
4743
|
-
`));let X=!1,F;if(yP()){let D=await CK0("0.0.
|
|
4744
|
-
`));let V=await Bz("0.0.
|
|
4743
|
+
`));let X=!1,F;if(yP()){let D=await CK0("0.0.1777710388-ge5e9da");X=D.hasUpdate,F=D.latestVersion}else{let D=await xP(),G=await wK0("0.0.1777710388-ge5e9da",D);X=G.hasUpdate,F=G.latestVersion}if(!X){let D=A31("0.0.1777710388-ge5e9da"),G=D?.age?`released ${D.age} ago`:`built ${rU(new Date("2026-05-02T08:30:18.646Z"))} ago`;mG.write(o0.green(`✓ Amp is already up to date on version ${"0.0.1777710388-ge5e9da"} (${G})
|
|
4744
|
+
`));let V=await Bz("0.0.1777710388-ge5e9da",B);if(V.warning)mG.write(`
|
|
4745
4745
|
`+o0.yellow(V.warning)+`
|
|
4746
4746
|
`);process.exit(0)}if(!F)mG.write(o0.yellow("[WARN] could not find latest version")),process.exit(0);A=F}mG.write(o0.blue(`Updating to version ${A}...
|
|
4747
4747
|
`)),await Oe(A,void 0,(X)=>{$(),mG.write(o0.dim(`Running: ${X}
|
|
@@ -5039,7 +5039,7 @@ Selection requested: ${A.title}
|
|
|
5039
5039
|
Error asking AI: ${Q instanceof Error?Q.message:String(Q)}
|
|
5040
5040
|
|
|
5041
5041
|
`),{result:"uncertain",probability:0.5,reason:"Error calling AI"}}}async appendToThread(A,Q){if(this.appendToThreadHandler)await this.appendToThreadHandler(A,Q);else throw Error("appendToThread is not available - no active thread")}}function V1A(){let A=null;return{pluginExecutorKind:"remote",setNotifyForwarder(Q){A=Q},async notify(Q){if(j.debug("headless plugin notification: %s",Q),!A)return;try{await A(Q)}catch(B){j.error("headless plugin notify forwarder failed",{error:B})}},async open(Q){throw Error("pluginPlatform.open is not supported in headless mode")},async input(Q){throw Error("pluginPlatform.input is not supported in headless mode")},async confirm(Q){throw Error("pluginPlatform.confirm is not supported in headless mode")},async select(Q){throw Error("pluginPlatform.select is not supported in headless mode")},async ask(Q){throw Error("pluginPlatform.ask is not supported in headless mode")}}}i0();j1();WH();X2();async function vu(A){let Q=await A.getLatest();return c90(Q.settings)}function q08(A){let Q=l8(A)?.reasoningEffort;return Q&&jD(A,Q)?Q:void 0}function h31(A,Q){let B=A.lastReasoningEffortByMode?.[Q];return B&&jD(Q,B)?B:void 0}function QE0(A){return A.explicitEffort??h31(A.sessionState,A.agentMode)??q08(A.agentMode)}function BE0(A,Q){let B=QE0(Q);if(B===void 0)return A;return{...A,"reasoning.effort":B}}function g31(A,Q,B={}){let $={},J=Q["internal.model"]??B["internal.model"];if(J!==void 0)$["internal.model"]=J;if(Q["reasoning.effort"]!==void 0)$["reasoning.effort"]=Q["reasoning.effort"];return $v(A,$)}i0();j1();var N08=8000,I08="T-00000000-0000-0000-0000-000000000000";class $E0{projection=new pU0(I08);transcriptEntries=[];transcriptListeners=new Set;transcriptReader={read:()=>this.transcriptEntries,subscribe:(A)=>{return this.transcriptListeners.add(A),()=>this.transcriptListeners.delete(A)}};_agentMode;observerState;activeErrorPayload=null;activeErrorSeq=null;transientErrorMessage=null;transientErrorTimeoutID=null;errorMessageSubject=new D4(null);connectionErrorSubject=new D4(null);activeErrorSubject=new D4(null);pendingSendSubject=new D4(!1);agentMessageIdSubject=new D4(null);cancelledSubject=new r4;transcriptRebuildBatchDepth=0;pendingTranscriptRebuildPreviousLength=null;log=j;constructor(A,Q=null){this._agentMode=A,this.observerState=new cU0({initialAgentLoopState:"idle",initialThreadSettings:Q,dedupeQueuedMessageAdds:!1,compactionRecordsState:"idle"})}get agentMode(){return this._agentMode}set agentMode(A){if(this._agentMode===A)return;if(this._agentMode=A,this.transcriptEntries.length>0)this.requestTranscriptRebuild(this.transcriptEntries.length)}reader(){return this.transcriptReader}agentState(){return this.observerState.agentLoopState}agentMessageId(){return this.agentMessageIdSubject}connectionInfo(){return this.observerState.connectionInfo}connectionError(){return this.connectionErrorSubject}setConnectionError(A){if(this.connectionErrorSubject.getValue()===A)return;this.connectionErrorSubject.next(A)}threadId(){return this.observerState.threadId}pendingSend(){return this.pendingSendSubject}errorMessage(){return this.errorMessageSubject}activeError(){return this.activeErrorSubject}cancelled(){return this.cancelledSubject}getActiveErrorSeq(){return this.activeErrorSeq}title(){return this.observerState.threadTitle}queuedMessages(){return this.observerState.queuedMessages}threadSettings(){return this.observerState.threadSettings}compactionState(){return this.observerState.compactionState}beginTranscriptRebuildBatch(){this.transcriptRebuildBatchDepth+=1}endTranscriptRebuildBatch(){if(this.transcriptRebuildBatchDepth===0)return;if(this.transcriptRebuildBatchDepth-=1,this.transcriptRebuildBatchDepth>0)return;let A=this.pendingTranscriptRebuildPreviousLength;if(this.pendingTranscriptRebuildPreviousLength=null,A!==null)this.rebuildTranscriptEntries(A)}dismissActiveError(){if(this.activeErrorPayload===null)return;this.activeErrorPayload=null,this.activeErrorSeq=null,this.activeErrorSubject.next(null),this.syncErrorMessage()}markMessageSent(){this.pendingSendSubject.next(!0)}onMessageAdded(A){this.log.info("[observer] onMessageAdded",{data:A}),this.applyThreadMessageEvent(A)}onMessageUpdated(A){this.log.info("[observer] onMessageUpdated",{data:A}),this.applyThreadMessageEvent(A)}onDelta(A){this.log.info("[observer] onDelta",{data:A}),this.applyThreadMessageEvent(A)}onTruncate(A){this.log.info("[observer] onTruncate",{data:A}),this.applyThreadMessageEvent(A)}onAgentState(A){this.log.info("[observer] onAgentState",{data:A});let Q=OZ(this.observerState.agentLoopState.getValue());if(OZ(A.state))this.pendingSendSubject.next(!1);this.agentMessageIdSubject.next(A.messageId??null),this.observerState.onAgentState(A);let B=OZ(this.observerState.agentLoopState.getValue());if(Q!==B&&this.transcriptEntries.length>0)this.requestTranscriptRebuild(this.transcriptEntries.length)}onThreadSettings(A){this.log.info("[observer] onThreadSettings",{data:A}),this.observerState.onThreadSettings(A)}onThreadId(A){this.log.info("[observer] onThreadId",{data:{threadId:A}}),this.log=DO(A),this.projection.setThreadID(A),this.observerState.onThreadId(A),this.observerState.threadId.complete()}onConnectionChanged(A){if(this.log.info("[observer] onConnectionChanged",{data:A}),this.observerState.onConnectionChanged(A),A.state==="connected")this.setConnectionError(null)}onQueuedMessages(A){this.log.info("[observer] onQueuedMessages",{data:A}),this.observerState.onQueuedMessages(A)}onUserActionMessageDeliveryStatusChanged(A,Q,B){this.log.info("[observer] onUserActionMessageDeliveryStatusChanged",{data:{messageId:A,status:Q,sentAt:B}}),this.observerState.onUserActionMessageDeliveryStatusChanged(A,Q,B)}onErrorNotice(A){if(this.log.info("[observer] onErrorNotice",{data:A}),this.activeErrorPayload!==null)return;this.clearPendingSendIfIdle(),this.transientErrorMessage=A.message,this.syncErrorMessage(),this.scheduleTransientErrorClear()}onActiveError(A){if(this.log.info("[observer] onActiveError",{data:A}),A.type==="error_set")this.clearPendingSendIfIdle(),this.activeErrorPayload=A.error,this.activeErrorSeq=A.seq,this.clearTransientError();else this.activeErrorPayload=null,this.activeErrorSeq=null;this.activeErrorSubject.next(this.activeErrorPayload),this.syncErrorMessage()}onCancelled(A){this.log.info("[observer] onCancelled",{data:A}),this.observerState.onCancelled(A),this.cancelledSubject.next(A)}onToolProgress(A){this.log.info("[observer] onToolProgress",{data:A}),this.applyThreadMessageEvent(A)}onThreadTitle(A){this.log.info("[observer] onThreadTitle",{data:A}),this.observerState.onThreadTitle(A)}onCompactionEvent(A){this.log.info("[observer] onCompactionEvent",{data:A});let Q=A.type==="compaction_started"?"compacting":"idle";if(A.type==="compaction_started"&&this.observerState.compactionState.getValue()===Q)return;let B=this.transcriptEntries.length;if(this.observerState.onCompactionEvent(A),A.type==="compaction_complete"||A.type==="compaction_records")this.requestTranscriptRebuild(B)}applyThreadMessageEvent(A){let Q=this.transcriptEntries.length;if(!this.projection.apply(A).changed)return;this.requestTranscriptRebuild(Q)}requestTranscriptRebuild(A){if(this.transcriptRebuildBatchDepth===0){this.rebuildTranscriptEntries(A);return}this.pendingTranscriptRebuildPreviousLength=Math.min(this.pendingTranscriptRebuildPreviousLength??A,A)}rebuildTranscriptEntries(A){let Q=this.projection.buildTranscriptEntries({...Ro4(this._agentMode),isWorking:OZ(this.observerState.agentLoopState.getValue()),compactionCutMessageIDs:this.observerState.compactionRecords.getValue().map((B)=>B.cutMessageId)});this.transcriptEntries.length=0,this.transcriptEntries.push(...Q),this.notifyTranscriptReaders(w08(A,Q.length))}notifyTranscriptReaders(A){for(let Q of this.transcriptListeners)Q(A)}clearPendingSendIfIdle(){if(this.pendingSendSubject.getValue()&&this.observerState.agentLoopState.getValue()==="idle")this.pendingSendSubject.next(!1)}syncErrorMessage(){let A=this.activeErrorPayload?.message??this.transientErrorMessage;if(this.errorMessageSubject.getValue()===A)return;this.errorMessageSubject.next(A)}scheduleTransientErrorClear(){this.clearTransientErrorTimer(),this.transientErrorTimeoutID=setTimeout(()=>{this.transientErrorTimeoutID=null,this.transientErrorMessage=null,this.syncErrorMessage()},N08)}clearTransientError(){this.clearTransientErrorTimer(),this.transientErrorMessage=null}clearTransientErrorTimer(){if(this.transientErrorTimeoutID===null)return;clearTimeout(this.transientErrorTimeoutID),this.transientErrorTimeoutID=null}}function w08(A,Q){return Array.from({length:Math.max(A,Q)},(B,$)=>$)}var U1A=45000;class m31{rivetEndpoint;apiKey;configService;runtimeDependencies;loadThreadHistory;observingClients=[];_lastActiveObservingClient=null;connectionErrorSubject=new r4;constructor(A,Q,B,$,J){this.rivetEndpoint=A;this.apiKey=Q;this.configService=B;this.runtimeDependencies=$;this.loadThreadHistory=J}get lastActiveObservingClient(){return this._lastActiveObservingClient}get connectionErrors$(){return this.connectionErrorSubject}async connectToThread(A,Q={}){let B=Q.observerOnly??!1,$=this.observingClients.find((F)=>F.observerOnly===B&&(F.threadID===A||F.client.getThreadId()===A));if($)return this._lastActiveObservingClient=$,this.persistLastThreadID(A),$;let J=this.createClient({threadID:A}),Y=await J.loadThreadHistory(A);if(!Y)throw J.dispose(),new j9("Thread not found");let Z=new $E0(Y.agentMode);Z.beginTranscriptRebuildBatch();try{J.setObserverCallbacks(Z)}finally{Z.endTranscriptRebuildBatch()}let X={client:J,observer:Z,threadID:A,logger:DO(A),observerOnly:B,connectionSubscription:dU0(J,{onError:({threadID:F,error:D})=>this.emitConnectionError(Z,D,F)})};return this.connectAndResume(J,Y.version,{observerOnly:B}).catch((F)=>{this.emitConnectionError(Z,F,A),this.removeObservingClient(X)}),this.persistLastThreadID(A),this.observingClients.push(X),this._lastActiveObservingClient=X,X}createNewThread(A,Q,B){let $=this.createClient({agentMode:A,initialThreadMeta:B}),J=new $E0(A,Q??null);$.setObserverCallbacks(J);let Y={client:$,observer:J,threadID:null,logger:j,observerOnly:!1,connectionSubscription:dU0($,{onError:({threadID:Z,error:X})=>this.emitConnectionError(J,X,Z)})};if(Q)$.sendClientUpdateThreadSettings(Q);else vu(this.configService).then((Z)=>{$.sendClientUpdateThreadSettings(Z)}).catch((Z)=>{j.warn("Failed to seed thread settings",{threadID:$.getThreadId(),error:Z instanceof Error?Z.message:String(Z)})});return this.observingClients.push(Y),this.connectAndResume($,0).then(({client:Z})=>{let X=Z.getThreadId();if(Y.threadID=X,X)Y.logger=DO(X),this.persistLastThreadID(X)}).catch((Z)=>{this.emitConnectionError(J,Z),this.removeObservingClient(Y)}),this._lastActiveObservingClient=Y,Y}async reconnectClient(A){let Q=this.observingClients.find(($)=>$.client===A);if(!Q)throw new j9("Thread client is not managed by this pool");let B=await L08(Q,{onConnected:($)=>{this.persistLastThreadID($)},onError:($,J)=>{this.emitConnectionError(Q.observer,$,J)}});return this._lastActiveObservingClient=Q,B}async disconnectClient(A){let Q=this.observingClients.find(($)=>$.client===A);if(!Q)throw new j9("Thread client is not managed by this pool");let B=await M08(Q);return this._lastActiveObservingClient=Q,B}dispose(){for(let{client:A,connectionSubscription:Q}of this.observingClients.values())Q.unsubscribe(),A.dispose();this.observingClients.length=0,this._lastActiveObservingClient=null,this.connectionErrorSubject.complete()}createClient(A={}){let{threadID:Q,agentMode:B,initialThreadMeta:$}=A,J=Fu(async(Y)=>{try{let Z={agentMode:B,executorType:"local-client"};if(!Y&&$)Z.threadMeta=$;return await uG(Y,this.configService,this.apiKey,Z)}catch(Z){throw ce(Z)}},Q);return new gK({transport:Du({rivetEndpoint:this.rivetEndpoint,credentialsProvider:J,initialThreadID:Q,pingIntervalMs:5000}),threadHistoryLoader:this.loadThreadHistory})}async connectAndResume(A,Q,B={}){let $=B.observerOnly??!1,J=null;try{await A.connect();let Y=A.getThreadId();if(!Y)throw A.disconnect(),new j9("Thread client connected without a thread ID");if($)return A.resumeFromVersion(Q),{client:A,executor:null};return J=this.createExecutor(A,Y),await C08(J,A),A.resumeFromVersion(Q),{client:A,executor:J}}catch(Y){if(A.disconnect(),J)J.dispose();throw ce(Y)}}createExecutor(A,Q){return new _P({transport:A,toolService:this.runtimeDependencies.toolService,configService:this.configService,clientID:this.runtimeDependencies.clientID,threadID:Q,invokeTool:(B)=>this.runtimeDependencies.invokeTool(Q,B),requestPluginToolCall:this.runtimeDependencies.requestPluginToolCall,requestPluginToolResult:this.runtimeDependencies.requestPluginToolResult,pluginService:this.runtimeDependencies.pluginService,readFileSystemDirectory:this.runtimeDependencies.readFileSystemDirectory,skillService:this.runtimeDependencies.skillService,sendGitSnapshot:!1,executorType:"local-client",workspaceRoot:process.cwd()})}emitConnectionError(A,Q,B){let $=ce(Q);A.setConnectionError($.message),this.connectionErrorSubject.next({threadID:B??void 0,error:$})}removeObservingClient(A){A.connectionSubscription.unsubscribe();let Q=this.observingClients.indexOf(A);if(Q!==-1)this.observingClients.splice(Q,1);if(this._lastActiveObservingClient?.client===A.client)this._lastActiveObservingClient=null}persistLastThreadID(A){this.runtimeDependencies.persistLastThreadID(A).catch((Q)=>{j.warn("Failed to persist last active thread ID",{threadID:A,error:Q instanceof Error?Q.message:String(Q)})})}}async function C08(A,Q){A.attachTransportExecutorCallbacks({includeConnectionChanges:!0}),A.handleConnectionChange(Q.getConnectionInfo()),await A.ensureReady({timeoutMs:U1A,timeoutMessage:`Timed out waiting for executor handshake after ${U1A}ms`})}function ce(A){if(A instanceof j9)return A;if(A instanceof Error){let Q=A.message||"Unknown connection error";return new j9(Q,A)}if(typeof A==="string"&&A.length>0)return new j9(A,A);return new j9("Unknown connection error",A)}async function M08(A){let Q=A.threadID??A.client.getThreadId();if(!Q)throw new j9("No active thread to disconnect");A.observer.setConnectionError(null);try{return await A.client.disconnectAndWait(),Q}catch(B){throw ce(B)}}async function L08(A,Q={}){let B=A.threadID??A.client.getThreadId();if(!B)throw new j9("No active thread to reconnect");A.observer.setConnectionError(null);try{await A.client.disconnectAndWait(),await A.client.connect();let $=A.client.getThreadId()??B;return A.threadID=$,Q.onConnected?.($),$}catch($){throw Q.onError?.($,B),ce($)}}async function K1A(A){let Q=pJ(A.ampURL),B=Sw({endpoint:Q}),$=await A.configService.getLatest(A.signal),J=await $.secrets.getToken("apiKey",$.settings.url);if(!J)throw Error("API key required. Please run `amp login` first.");let Y=await B.threadActor.get([A.threadID]).fetch("/skills",{method:"GET",headers:{Authorization:`Bearer ${J}`},signal:A.signal});if(!Y.ok){let X=await Y.text();throw Error(`Skills request failed (${Y.status}): ${X}`)}let Z=await Y.json();if(!Z.ok)throw Error(Z.error);return{skills:Z.skills,errors:Z.errors}}function JE0(A,Q=O08){function B($){let J=Q[$];return J?process.env[J]:void 0}return{async get($,J){let Y=B($);return Y!==void 0&&Y!==""?Y:A.get($,J)},async set($,J,Y){let Z=B($);if(Z!==void 0&&Z!=="")return;await A.set($,J,Y)},changes:A.changes}}var O08={apiKey:"AMP_API_KEY","github-access-token":"AMP_GITHUB_TOKEN"};i0();V9();function le(A){return async()=>{let Q=await OA.loadPlugins({},{config:A});if(!Q.ok)return j.debug("Failed to load server plugins from internal API",{error:Q.error}),[];return Q.result}}ID();i0();q4();j1();i0();eQ();function E1A(A,Q,B){let $=new r4,Y=(()=>{let K=new Map;return(E,H)=>{let z=(K.get(E)?.catch(()=>{})||Promise.resolve()).then(()=>H()).finally(()=>{if(K.get(E)===z)K.delete(E)});return K.set(E,z),z}})(),Z=B?K1.joinPath(Q,B):Q;function X(K){return K1.joinPath(Z,`${K.toString()}.json`)}async function F(K){let E=X(K);try{let H=await A.readBinaryFile(E),W=52428800;if(H.length>52428800){let z=Math.round(H.length/1048576);j.warn(`File too large to load safely: ${String(K)} (${z}MB)`,{key:String(K),size:H.length,maxSize:52428800});return}try{let z=H instanceof Uint8Array?H:new Uint8Array(H);return JSON.parse(new TextDecoder().decode(z))}catch(z){let q=z,{contentLength:N,contentPreview:I}=j08(H);j.warn("Corrupted JSON detected.",{key:String(K),storageUri:Z.toString(),error:q.message,contentLength:N,contentPreview:I});return}}catch(H){if(p3(H))return;throw H}}async function D(K,E){let H=X(K),W=H.with({path:H.path+".amptmp"}),z=JSON.stringify(E,null,2);await A.mkdirp(K1.joinPath(H,"..")),await Y(K,async()=>{await A.writeFile(W,z),await A.rename(W,H)}),$.next(K)}async function G(K){let E=X(K);await Y(K,async()=>{await A.delete(E)}),$.next(K)}async function V(){let K;try{K=await A.readdir(Z)}catch(W){if(p3(W))return[];throw W}let E=K.filter((W)=>{let z=W.uri.path.split("/").pop()||"";return!W.isDirectory&&z.endsWith(".json")});return(await Promise.all(E.map(async(W)=>{let q=(W.uri.path.split("/").pop()||"").slice(0,-5);try{let N=await A.getMtime(W.uri);return{key:q,mtime:N}}catch(N){if(!p3(N))throw N;return null}}))).filter((W)=>W!==null).toSorted((W,z)=>z.mtime-W.mtime).map((W)=>W.key)}async function U(K){return X(K).fsPath}return{get:F,set:D,delete:G,keys:V,path:U,changes:$}}function j08(A){try{let Q=A instanceof Uint8Array?A:new Uint8Array(A),B=new TextDecoder().decode(Q);return{contentLength:A.length,contentPreview:B.slice(0,128)}}catch{let Q=A instanceof Uint8Array?A:new Uint8Array(A),$=Array.from(Q.slice(0,64)).map((J)=>{if(J>=32&&J<=126)return String.fromCharCode(J);return`\\x${J.toString(16).padStart(2,"0")}`}).join("");return{contentLength:A.length,contentPreview:`${$}${A.length>64?"...":""}`}}}q4();var nG={agentMode:"smart",launchCount:0,shortcutsHintUsed:!1,neoWelcomeDismissed:!1};function W1A(A,Q){if(Q==="execute")return A.lastExecuteThreadId??A.lastThreadId;return A.lastThreadId}function YE0(A,Q,B){if(B==="execute")return{...A,lastExecuteThreadId:Q};return{...A,lastThreadId:Q}}function z1A(A){return{...A,neoWelcomeDismissed:!0}}function p31(A={}){let Q=A.fs??e5,B=A.dataDir??hk;return E1A(Q,Z1.file(B))}var q1A=p31(),H1A=Promise.resolve();async function $C(A={}){let Q=A.dataDir||A.fs?p31(A):q1A;try{let B=await Q.get("session"),$={...nG,agentMode:B?.agentMode??nG.agentMode,launchCount:B?.launchCount??nG.launchCount,neoWelcomeDismissed:B?.neoWelcomeDismissed??nG.neoWelcomeDismissed,shortcutsHintUsed:B?.shortcutsHintUsed??nG.shortcutsHintUsed,lastThreadId:B?.lastThreadId,lastExecuteThreadId:B?.lastExecuteThreadId},J={...B?.lastReasoningEffortByMode};if(Object.keys(J).length>0)$.lastReasoningEffortByMode=J;return $}catch{return{...nG}}}async function R08(A,Q){try{await Q.set("session",A)}catch(B){j.warn("Failed to save session state.",{error:B instanceof Error?B.message:String(B)})}}function P08(A={}){return A.dataDir||A.fs?p31(A):q1A}async function SZ(A,Q={}){let B=P08(Q),$={...nG},J=H1A.catch(()=>{return}).then(async()=>{let Y=await $C(Q);$={...nG,...A(Y)},await R08($,B)});return H1A=J.then(()=>{return},()=>{return}),await J,$}class d31{constructor(){}isEnabled(A){return!0}consumesKey(A){return!0}toString(){return`${this.constructor.name}()`}}class I4 extends d31{onInvoke;constructor(A){super();this.onInvoke=A}invoke(A){return this.onInvoke(A)}}function _08(A){return"state"in A}function N1A(A,Q){let B=A.element.parent;while(B){if(_08(B)&&B.state instanceof ZE0){if(Q(B.state))return}B=B.parent}}class XE0{invokeAction(A,Q){let B=this.findAction(A,Q);if(B&&B.enabled)return B.action.invoke(A);return null}findAction(A,Q){let B=null;return N1A(Q,($)=>{let J=$.getActionForIntent(A);if(!J)return!1;return B={action:J,enabled:J.isEnabled(A)},!0}),B}}class MA extends x0{actions;child;dispatcher;constructor({actions:A,child:Q,dispatcher:B,key:$}){super({key:$});this.actions=A,this.child=Q,this.dispatcher=B}createState(){return new ZE0}static invoke(A,Q){return MA.of(A).invokeAction(Q,A)}static maybeInvoke(A,Q){try{return MA.invoke(A,Q)}catch{return null}}static find(A,Q){let B=MA.maybeFind(A,Q);if(!B){let $=Q?.constructor.name||"unknown";throw Error(`No action found for intent type: ${$}`)}return B}static maybeFind(A,Q){if(!Q)return null;let B=null;return N1A(A,($)=>{let J=$.getActionForIntent(Q);if(!J)return!1;return B=J,!0}),B}static of(A){let Q=A.findAncestorStateOfType(ZE0);if(!Q)throw Error("No Actions widget found in context");return Q.dispatcher}static handler(A,Q){let B=MA.of(A).findAction(Q,A);if(B&&B.enabled)return()=>B.action.invoke(Q);return null}}class ZE0 extends y0{dispatcher=new XE0;getActionForIntent(A){let Q=A.constructor;return this.widget.actions.get(Q)}build(A){return this.widget.child}}class GA{constructor(){}toString(){return`${this.constructor.name}()`}}class JC extends GA{constructor(){super()}}class ie extends GA{constructor(){super()}}class ne extends GA{constructor(){super()}}class ae extends GA{constructor(){super()}}class oe extends GA{constructor(){super()}}class YC extends GA{constructor(){super()}}class FE0 extends GA{constructor(){super()}}class re extends GA{constructor(){super()}}class yu extends GA{constructor(){super()}}class se extends GA{constructor(){super()}}class xu extends GA{constructor(){super()}}class fu extends GA{direction;constructor(A){super();this.direction=A}toString(){return`NavigateToPromptHistoryIntent(direction: ${this.direction})`}}class cP extends GA{constructor(){super()}}class Zz extends GA{constructor(){super()}}function T08(A){let Q=[];if(A.ctrlKey)Q.push("ctrl");if(A.metaKey)Q.push("meta");if(A.altKey)Q.push("alt");if(A.shiftKey)Q.push("shift");let B=A.key.toLowerCase();if(["control","meta","alt","shift"].includes(B))return"";if(B===" ")B="space";return Q.push(B),Q.join("+")}function I1A(A){let Q=A.toLowerCase().split("+"),B=Q.pop()||"";return{modifiers:new Set(Q),key:B}}function w1A(A,Q){let B=I1A(A),$=I1A(Q);if(B.key!==$.key)return!1;for(let J of $.modifiers)if(!B.modifiers.has(J))return!1;if($.modifiers.size===0&&B.modifiers.size>0)return!1;return!0}class bu{sequence;timeout;matchedKeys=[];timeoutId=null;constructor(A,Q={}){this.sequence=A,this.timeout=Q.timeout??2000}getProgress(){return{matched:[...this.matchedKeys],remaining:this.sequence.slice(this.matchedKeys.length)}}isInProgress(){return this.matchedKeys.length>0}reset(){if(this.matchedKeys=[],this.timeoutId)clearTimeout(this.timeoutId),this.timeoutId=null}handleKeyEvent(A){let Q=T08(A);if(!Q)return"none";let B=this.matchedKeys.length,$=this.sequence[B];if($&&w1A(Q,$)){if(this.matchedKeys.push($),this.timeoutId)clearTimeout(this.timeoutId),this.timeoutId=null;if(this.matchedKeys.length===this.sequence.length)return this.reset(),"matched";return this.timeoutId=setTimeout(()=>this.reset(),this.timeout),"progress"}else if(this.matchedKeys.length>0){this.reset();let J=this.sequence[0];if(J&&w1A(Q,J))return this.matchedKeys.push(J),this.timeoutId=setTimeout(()=>this.reset(),this.timeout),"progress"}return"none"}dispose(){this.reset()}toString(){return this.sequence.map((A)=>{return A.replace("ctrl+","C-").replace("meta+","M-").replace("alt+","A-")}).join(" ")}}class uu{sequences;activeSequence=null;constructor(A=new Map){this.sequences=A}handleKeyEvent(A){if(this.activeSequence){let Q=this.activeSequence.handleKeyEvent(A);if(Q==="matched"){let B=this.sequences.get(this.activeSequence);return this.activeSequence=null,{intent:B,consumed:!0,progress:null}}else if(Q==="progress")return{intent:null,consumed:!0,progress:this.activeSequence.getProgress()};else this.activeSequence=null}for(let[Q,B]of this.sequences){let $=Q.handleKeyEvent(A);if($==="matched")return{intent:B,consumed:!0,progress:null};else if($==="progress")return this.activeSequence=Q,{intent:null,consumed:!0,progress:Q.getProgress()}}return{intent:null,consumed:!1,progress:null}}isInProgress(){return this.activeSequence!==null}getProgress(){return this.activeSequence?.getProgress()??null}reset(){this.activeSequence=null;for(let A of this.sequences.keys())A.reset()}dispose(){for(let A of this.sequences.keys())A.dispose()}}class H6{static _nextDebugId=0;_debugId;_parent=null;_children=[];_hasPrimaryFocus=!1;_canRequestFocus=!0;_skipTraversal=!1;_keyHandlers=[];_onPasteCallback=null;_listeners=new Set;_debugLabel=null;_manager=null;constructor(A={}){if(this._debugId=`focus-${H6._nextDebugId++}`,this._debugLabel=A.debugLabel??null,this._canRequestFocus=A.canRequestFocus??!0,this._skipTraversal=A.skipTraversal??!1,A.onKey)this._keyHandlers.push(A.onKey);this._onPasteCallback=A.onPaste??null}get debugId(){return this._debugId}get hasPrimaryFocus(){return this._hasPrimaryFocus}get hasFocus(){let A=this._manager?.primaryFocus;return this._hasPrimaryFocus||(A?._isDecendantOf(this)??!1)}get canRequestFocus(){return this._canRequestFocus}set canRequestFocus(A){if(this._canRequestFocus!==A){if(this._canRequestFocus=A,!A&&this._hasPrimaryFocus)this.unfocus()}}get skipTraversal(){return this._skipTraversal}set skipTraversal(A){this._skipTraversal=A}get parent(){return this._parent}get children(){return this._children}get debugLabel(){return this._debugLabel}get onPaste(){return this._onPasteCallback}set onPaste(A){this._onPasteCallback=A}get enclosingScope(){let A=this._parent;while(A!==null){if(c31(A))return A;A=A._parent}return null}get ancestors(){let A=[],Q=this._parent;while(Q!==null)A.push(Q),Q=Q._parent;return A}requestFocus(){if(!this._canRequestFocus)return!1;return this._doRequestFocus({findFirstFocus:!0}),this._manager!==null}unfocus(A="scope"){if(!this.hasFocus&&this._manager?._markedForFocus!==this)return;let Q=this.enclosingScope;if(Q===null)return;switch(A){case"scope":{let B=Q;B._clearFocusedChildren();let $=B.enclosingScope;while(!B.canRequestFocus&&$!==null)$._removeFromHistory(B),B=$,B._clearFocusedChildren(),$=B.enclosingScope;B._doRequestFocus({findFirstFocus:!1});break}case"previouslyFocusedChild":{let B=Q;B._removeFromHistory(this);let $=B.enclosingScope;while(B.focusedChild===null&&!B.canRequestFocus&&$!==null)$._removeFromHistory(B),B=$,$=B.enclosingScope;B._doRequestFocus({findFirstFocus:!0});break}}}_doRequestFocus({findFirstFocus:A}){if(!this._canRequestFocus)return;if(this._hasPrimaryFocus&&this._manager?._markedForFocus===null)return;this._setAsFocusedChildForScope(),this._manager?._markNextFocus(this)}_setAsFocusedChildForScope(){let A=this;for(let Q of this.ancestors)if(c31(Q))Q._pushFocusedChild(A),A=Q}_isDecendantOf(A){if(A===null)return!1;if(this._parent===A)return!0;return this._parent?._isDecendantOf(A)??!1}_isAncestorTo(A){return A?._isDecendantOf(this)??!1}_reparent(A){if(A._parent===this)return;let Q=A.enclosingScope,B=Q!==null&&Q===this.enclosingScope;if(A._parent?._removeChild(A,!B),this._children.push(A),A._parent=this,A._updateManager(this._manager),A._requestFocusWhenReparented)A._doRequestFocus({findFirstFocus:!0}),A._requestFocusWhenReparented=!1}_removeChild(A,Q=!0){let B=this._children.indexOf(A);if(B!==-1)this._children.splice(B,1);if(Q){let $=A.enclosingScope;if($!==null)$._removeFromHistory(A),A._collectDescendants().forEach((J)=>$._removeFromHistory(J))}A._parent=null}_collectDescendants(){let A=[],Q=[...this._children];while(Q.length>0){let B=Q.pop();A.push(B);for(let $ of B._children)Q.push($)}return A}_updateManager(A){this._manager=A;for(let Q of this._children)Q._updateManager(A)}_requestFocusWhenReparented=!1;_setFocus(A){if(this._hasPrimaryFocus===A)return;let Q=this.hasFocus;this._hasPrimaryFocus=A;let B=this.hasFocus;if(this._notifyListeners(),Q!==B)this._notifyAncestorListeners()}addListener(A){this._listeners.add(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A(this)}_notifyAncestorListeners(){let A=this._parent;while(A)A._notifyListeners(),A=A._parent}_handleKeyEvent(A){return this.handleKeyEvent(A)}_handlePasteEvent(A){if(this._onPasteCallback)return this._onPasteCallback(A);return"ignored"}toStringShort(){let A=this._debugLabel?`"${this._debugLabel}"`:"",Q=this._hasPrimaryFocus?" FOCUSED":"",B=this._canRequestFocus?"":" (can't focus)";return`Focus${c31(this)?"Scope":""}Node${A}${Q}${B}`}toStringDeep(A="",Q=!0){let B=A+this.toStringShort();if(Q&&this._children.length>0){let $=A+" ";for(let J of this._children)B+=`
|
|
5042
|
-
`+J.toStringDeep($,!0)}return B}addKeyHandler(A){this._keyHandlers.push(A)}removeKeyHandler(A){let Q=this._keyHandlers.indexOf(A);if(Q!==-1)this._keyHandlers.splice(Q,1)}handleKeyEvent(A){for(let Q of this._keyHandlers)if(Q(A)==="handled")return"handled";return"ignored"}dispose(){this._parent?._removeChild(this,!0),this._children.length=0,this._keyHandlers=[]}}function c31(A){return A._isFocusScopeNode===!0}class hu extends H6{_isFocusScopeNode=!0;_focusedChildren=[];constructor(A={}){super({canRequestFocus:A.canRequestFocus??!0,skipTraversal:A.skipTraversal??!0,...A})}get focusedChild(){return this._focusedChildren.length===0?null:this._focusedChildren[this._focusedChildren.length-1]}autofocus(A){if(A.parent===null)this._reparent(A);let Q=this._manager;if(Q===null){A._requestFocusWhenReparented=!0;return}Q._enqueueAutofocus(this,A)}_doRequestFocus({findFirstFocus:A}){while(this._focusedChildren.length>0&&(!this._focusedChildren[this._focusedChildren.length-1].canRequestFocus||this._focusedChildren[this._focusedChildren.length-1].enclosingScope===null))this._focusedChildren.pop();let Q=this.focusedChild;if(!A||Q===null){if(this.canRequestFocus)this._setAsFocusedChildForScope(),this._manager?._markNextFocus(this);return}Q._doRequestFocus({findFirstFocus:!0})}_pushFocusedChild(A){let Q=this._focusedChildren.indexOf(A);if(Q!==-1)this._focusedChildren.splice(Q,1);this._focusedChildren.push(A)}_removeFromHistory(A){let Q=this._focusedChildren.indexOf(A);if(Q!==-1)this._focusedChildren.splice(Q,1)}_clearFocusedChildren(){this._focusedChildren.length=0}get focusedChildren(){return this._focusedChildren}}class o3{static _instance=null;static _keystrokes=[];static _MAX_KEYSTROKES=100;_rootScope;_primaryFocus=null;_markedForFocus=null;_pendingAutofocuses=[];_haveScheduledUpdate=!1;constructor(){this._rootScope=new hu({debugLabel:"Root Focus Scope",canRequestFocus:!1}),this._rootScope._updateManager(this)}static getRecentKeystrokes(){return[...o3._keystrokes]}static _recordKeystroke(A,Q,B){if(o3._keystrokes.push({timestamp:Date.now(),key:A,focusPath:Q,handled:B}),o3._keystrokes.length>o3._MAX_KEYSTROKES)o3._keystrokes.shift()}static get instance(){if(!o3._instance)o3._instance=new o3;return o3._instance}get primaryFocus(){return this._primaryFocus}get rootScope(){return this._rootScope}requestFocus(A){if(!A.canRequestFocus)return!1;return A._doRequestFocus({findFirstFocus:!0}),!0}_markNextFocus(A){if(this._primaryFocus===A){this._markedForFocus=null;return}this._commitFocus(A)}_commitFocus(A){if(this._primaryFocus===A)return;this._primaryFocus?._setFocus(!1),this._primaryFocus=A,A?._setFocus(!0)}_enqueueAutofocus(A,Q){this._pendingAutofocuses.push({scope:A,node:Q}),this._scheduleUpdate()}_scheduleUpdate(){if(this._haveScheduledUpdate)return;this._haveScheduledUpdate=!0,queueMicrotask(()=>{this._haveScheduledUpdate=!1,this._applyFocusChangesIfNeeded()})}_applyFocusChangesIfNeeded(){let A=this._pendingAutofocuses;this._pendingAutofocuses=[];for(let Q of A)this._applyAutofocusIfValid(Q)}_applyAutofocusIfValid(A){let{scope:Q,node:B}=A;if((Q.parent!==null||Q===this._rootScope)&&Q._manager===this&&Q.focusedChild===null&&B.ancestors.includes(Q))B._doRequestFocus({findFirstFocus:!0})}flushAutofocus(){this._haveScheduledUpdate=!1,this._applyFocusChangesIfNeeded()}handleKeyEvent(A){if(!this._primaryFocus)return!1;let Q=void 0,B=this._primaryFocus;while(B){let J=B._handleKeyEvent(A)==="handled";if(Q)Q.push({id:B.debugId,debugLabel:B.debugLabel,handled:J});if(J){if(Q)o3._recordKeystroke(this.formatKeyEvent(A),Q,!0);return!0}B=B.parent}if(Q)o3._recordKeystroke(this.formatKeyEvent(A),Q,!1);return!1}formatKeyEvent(A){let Q=[];if(A.ctrlKey)Q.push("Ctrl");if(A.altKey)Q.push("Alt");if(A.shiftKey)Q.push("Shift");if(A.metaKey)Q.push("Meta");if(A.key)Q.push(A.key);return Q.join("+")}handlePasteEvent(A){if(!this._primaryFocus)return!1;let Q=this._primaryFocus;while(Q){if(Q._handlePasteEvent(A)==="handled")return!0;Q=Q.parent}return!1}registerNode(A,Q=null){O4(A!==Q,"Focus node cannot be its own parent"),(Q??this._rootScope)._reparent(A)}unregisterNode(A){if(A.hasPrimaryFocus||this._markedForFocus===A)A.unfocus("previouslyFocusedChild");if(this._pendingAutofocuses=this._pendingAutofocuses.filter((B)=>B.node!==A&&B.scope!==A),A.parent?._removeChild(A,!0),this._primaryFocus===A)this._commitFocus(null);A._updateManager(null)}_focusNodeToDebugInfo(A){let Q=A instanceof hu,B=Q?A:null;return{id:A.debugId,debugLabel:A.debugLabel,hasPrimaryFocus:A.hasPrimaryFocus,hasFocus:A.hasFocus,canRequestFocus:A.canRequestFocus,skipTraversal:A.skipTraversal,isPrimaryFocus:this._primaryFocus===A,isScope:Q,focusedChildIds:B?B.focusedChildren.map(($)=>$.debugId):[],children:A.children.map(($)=>this._focusNodeToDebugInfo($))}}debugDumpFocusTree(){return{timestamp:Date.now(),rootScope:this._focusNodeToDebugInfo(this._rootScope),primaryFocusId:this._primaryFocus?.debugId??null,focusStack:this._rootScope.focusedChildren.map((A)=>({id:A.debugId,debugLabel:A.debugLabel}))}}dispose(){this._primaryFocus=null,this._markedForFocus=null,this._pendingAutofocuses=[],this._haveScheduledUpdate=!1,this._rootScope.dispose(),o3._instance=null}}class s4 extends x0{focusNode;child;autofocus;canRequestFocus;skipTraversal;onKey;onPaste;onFocusChange;debugLabel;constructor({key:A,focusNode:Q,child:B,autofocus:$=!1,canRequestFocus:J=!0,skipTraversal:Y=!1,onKey:Z,onPaste:X,onFocusChange:F,debugLabel:D}){super({key:A});this.focusNode=Q,this.child=B,this.autofocus=$,this.canRequestFocus=J,this.skipTraversal=Y,this.onKey=Z||null,this.onPaste=X||null,this.onFocusChange=F||null,this.debugLabel=D||null}createState(){return new gu}}class gu extends y0{_internalFocusNode=null;_isDisposed=!1;_focusChangeHandler=null;_didAutofocus=!1;get effectiveFocusNode(){return this.widget.focusNode??this._internalFocusNode}createFocusNode(A){return new H6(A)}initState(){if(super.initState(),!this.widget.focusNode){let B={canRequestFocus:this.widget.canRequestFocus,skipTraversal:this.widget.skipTraversal};if(this.widget.onKey)B.onKey=this.widget.onKey;if(this.widget.onPaste)B.onPaste=this.widget.onPaste;if(this.widget.debugLabel)B.debugLabel=this.widget.debugLabel;this._internalFocusNode=this.createFocusNode(B)}if(this.widget.onKey&&this.widget.focusNode)this.effectiveFocusNode.addKeyHandler(this.widget.onKey);if(this.widget.onPaste)this.effectiveFocusNode.onPaste=this.widget.onPaste;if(this.widget.onFocusChange)this._focusChangeHandler=(B)=>{if(!this._isDisposed&&this.widget.onFocusChange)this.widget.onFocusChange(B.hasFocus)},this.effectiveFocusNode.addListener(this._focusChangeHandler);let Q=this.context.findAncestorStateOfType(gu)?.effectiveFocusNode||null;if(o3.instance.registerNode(this.effectiveFocusNode,Q),this.widget.autofocus&&!this._didAutofocus)this._didAutofocus=!0,this.findEnclosingScope().autofocus(this.effectiveFocusNode)}findEnclosingScope(){return this.effectiveFocusNode.enclosingScope??o3.instance.rootScope}dispose(){if(this._didAutofocus=!1,this.widget.onKey)this.effectiveFocusNode.removeKeyHandler(this.widget.onKey);if(o3.instance.unregisterNode(this.effectiveFocusNode),this._isDisposed=!0,this._focusChangeHandler)this.effectiveFocusNode.removeListener(this._focusChangeHandler),this._focusChangeHandler=null;if(this._internalFocusNode)this._internalFocusNode.dispose(),this._internalFocusNode=null;super.dispose()}build(A){return this.widget.child}}function C1A(A){let Q=A.key;if(Q.length===1&&Q>="a"&&Q<="z")return Q;if(A.code!==void 0)return A.code;return Q}class g1{key;shift;ctrl;alt;meta;constructor(A,Q={}){this.key=A;this.shift=Q.shift??!1,this.ctrl=Q.ctrl??!1,this.alt=Q.alt??!1,this.meta=Q.meta??!1}accepts(A){return C1A(A)===this.key&&A.shiftKey===this.shift&&A.ctrlKey===this.ctrl&&A.altKey===this.alt&&A.metaKey===this.meta}static key(A){return new g1(A)}static ctrl(A){return new g1(A,{ctrl:!0})}static shift(A){return new g1(A,{shift:!0})}static alt(A){return new g1(A,{alt:!0})}static meta(A){return new g1(A,{meta:!0})}modifiers(){let A=[];if(this.meta)A.push("Meta");if(this.ctrl)A.push("Ctrl");if(this.alt)A.push("Alt");if(this.shift)A.push("Shift");return A}toString(){let A=this.modifiers();return A.length>0?`${A.join("+")}+${this.key}`:this.key}}class l31{shortcuts=new Map;constructor(A=new Map){this.shortcuts=new Map(A)}handleKeyEvent(A){for(let[Q,B]of this.shortcuts)if(Q.accepts(A))return B;return null}addShortcut(A,Q){this.shortcuts.set(A,Q)}removeShortcut(A){return this.shortcuts.delete(A)}getAllShortcuts(){return new Map(this.shortcuts)}copyWith(A){let Q=new Map([...this.shortcuts,...A]);return new l31(Q)}}class V8 extends x0{shortcuts;child;manager;debugLabel;focusNode;constructor({shortcuts:A,child:Q,manager:B,debugLabel:$,focusNode:J,key:Y}){super({key:Y});this.shortcuts=A,this.child=Q,this.manager=B,this.debugLabel=$,this.focusNode=J}createState(){return new M1A}}class M1A extends y0{manager=null;initState(){if(super.initState(),this.createManager(),this.widget.focusNode)this.widget.focusNode.addKeyHandler(this.handleKeyEvent)}didUpdateWidget(A){if(super.didUpdateWidget(A),A.shortcuts!==this.widget.shortcuts||A.manager!==this.widget.manager)this.createManager()}createManager(){if(this.widget.manager)this.manager=this.widget.manager;else this.manager=new l31(this.widget.shortcuts)}dispose(){if(this.widget.focusNode)this.widget.focusNode.removeKeyHandler(this.handleKeyEvent);super.dispose()}handleKeyEvent=(A)=>{if(!this.manager)return"ignored";let Q=this.manager.handleKeyEvent(A);if(Q){if(this.invokeIntent(Q)==="handled")return"handled"}return"ignored"};invokeIntent(A){let B=new XE0().findAction(A,this.context);if(B&&B.enabled){if(B.action.invoke(A)==="ignored")return null;return"handled"}return null}build(A){if(this.widget.focusNode)return this.widget.child;else return new s4({onKey:this.handleKeyEvent,autofocus:!1,canRequestFocus:!0,skipTraversal:!1,debugLabel:this.widget.debugLabel,child:this.widget.child})}}i0();i0();import{execSync as L1A}from"node:child_process";function i31(){let A=S08();if(A)return A;let Q=k08();if(Q)return{...Q,pixelWidth:0,pixelHeight:0};return null}function S08(){try{let A=(()=>{throw new Error("Cannot require module "+"ffi-napi");})(),Q=(()=>{throw new Error("Cannot require module "+"ref-napi");})(),$=(()=>{throw new Error("Cannot require module "+"ref-struct-di");})()(Q)({ws_row:Q.types.ushort,ws_col:Q.types.ushort,ws_xpixel:Q.types.ushort,ws_ypixel:Q.types.ushort}),J=A.Library("libc",{ioctl:["int",["int","ulong","pointer"]]}),Y=process.platform==="darwin"?1074295912:21523,Z=new $;if(J.ioctl(process.stdout.fd,Y,Z.ref())===0)return{rows:Z.ws_row,columns:Z.ws_col,pixelWidth:Z.ws_xpixel,pixelHeight:Z.ws_ypixel};return null}catch(A){return null}}function k08(){try{if(process.stdout.isTTY&&process.stdout.columns&&process.stdout.rows)return{columns:process.stdout.columns,rows:process.stdout.rows};let A=process.stdin;if(process.stdin.isTTY&&A.columns&&A.rows)return{columns:A.columns,rows:A.rows};let Q=process.stdout;if(typeof Q.getWindowSize==="function"){let B=Q.getWindowSize();if(B[0]>0&&B[1]>0)return{columns:B[0],rows:B[1]}}return null}catch(A){return null}}function te(A){return{syncOutput:!1,emojiWidth:!1,pixelMouse:!1,pixelDimensions:!1,xtversion:null,canRgb:!0,supportsCursorShape:!0,animationSupport:"fast",kittyKeyboard:!1,osc52:!1,kittyGraphics:!1,background:"unknown",colorPaletteNotifications:!1,kittyExplicitWidth:!1,underlineSupport:P9()?"none":"standard",scrollStep:()=>3,...A}}var O1A=[{sequence:"\x1B[?1049h\x1B[H\x1B]66;w=1; \x1B\\\x1B[6n\x1B[?1049l",description:"Query Kitty explicit width support"},{sequence:"\x1B]10;?\x07",description:"Query terminal foreground color (OSC 10)"},{sequence:"\x1B]11;?\x07",description:"Query terminal background color (OSC 11)"},{sequence:"\x1B]12;?\x07",description:"Query terminal cursor color (OSC 12)"},{sequence:"\x1B]4;0;?\x07",description:"Query terminal color 0 (OSC 4)"},{sequence:"\x1B]4;1;?\x07",description:"Query terminal color 1 (OSC 4)"},{sequence:"\x1B]4;2;?\x07",description:"Query terminal color 2 (OSC 4)"},{sequence:"\x1B]4;3;?\x07",description:"Query terminal color 3 (OSC 4)"},{sequence:"\x1B]4;4;?\x07",description:"Query terminal color 4 (OSC 4)"},{sequence:"\x1B]4;5;?\x07",description:"Query terminal color 5 (OSC 4)"},{sequence:"\x1B]4;6;?\x07",description:"Query terminal color 6 (OSC 4)"},{sequence:"\x1B]4;7;?\x07",description:"Query terminal color 7 (OSC 4)"},{sequence:"\x1B[?2026$p",description:"Query synchronized output support"},{sequence:"\x1B[?2027$p",description:"Query emoji width mode support"},{sequence:"\x1B[?1016$p",description:"Query pixel mouse mode support"},{sequence:"\x1B[?2031$p",description:"Query color palette change notifications support (mode 2031)"},{sequence:"\x1B[?u",description:"Query Kitty keyboard protocol support"},{sequence:"\x1B[>0q",description:"Query terminal version (XTVERSION)"},{sequence:"\x1BP+q4d73\x1B\\",description:"Query OSC 52 clipboard support (XTGETTCAP Ms)"},{sequence:dG("\x1B_Gi=1,a=q\x1B\\"),description:"Query Kitty graphics protocol support",shouldSend:()=>{return!P9()&&process.env.TERM_PROGRAM!=="Apple_Terminal"&&!Lu()}},{sequence:"\x1B[c",description:"Device Attributes (DA1)",isFinal:!0}];class DE0{options;capabilities;constructor(A={}){this.options=A;this.capabilities={syncOutput:!1,emojiWidth:!1,pixelMouse:!1,pixelDimensions:!1,xtversion:null,canRgb:this.detectRgbSupport(),supportsCursorShape:this.detectCursorShapeSupport(),animationSupport:this.detectAnimationSupport(),kittyKeyboard:!1,osc52:!1,kittyGraphics:this.detectKittyGraphicsFromEnv(),background:"unknown",colorPaletteNotifications:!1,kittyExplicitWidth:!1,underlineSupport:P9()?"none":"standard",scrollStep:()=>this.getScrollStep()}}complete=!1;colorUpdateTimer=null;onColorPaletteChange;inbandPixelData=null;kittyWidthQuerySent=!1;rgbColors={foreground:null,background:null,cursor:null,indices:[null,null,null,null,null,null,null,null]};processDecrqss(A,Q){if(A==="?2026")this.capabilities.syncOutput=Q==="1"||Q==="2";if(A==="?2027")this.capabilities.emojiWidth=Q==="1"||Q==="2";if(A==="?1016")this.capabilities.pixelMouse=Q==="1"||Q==="2";if(A==="?2031")this.capabilities.colorPaletteNotifications=Q==="1"||Q==="2";if(A==="u")this.capabilities.kittyKeyboard=!0;return!1}processDeviceAttributes(A,Q){if(this.checkPixelDimensions(),this.detectJetBrains()||this.detectTmux())this.capabilities.emojiWidth=!0;return this.complete=!0,!0}processXtversion(A){this.capabilities.xtversion=A;let Q=["ghostty","kitty","wezterm","foot","alacritty","iterm2","tmux"],B=A.toLowerCase();if(Q.some(($)=>B.includes($)))this.capabilities.osc52=!0;return!1}processXtgettcap(A,Q){if(A.toLowerCase()==="4d73")this.capabilities.osc52=Q.length>0;return!1}processKittyGraphics(){if(this.isITerm2())return this.capabilities.kittyGraphics=!1,!1;return this.capabilities.kittyGraphics=!0,!1}processCursorPositionReport(A,Q){if(this.kittyWidthQuerySent){if(A===1&&Q===2)this.capabilities.kittyExplicitWidth=!0,j.info("Kitty explicit width support detected");this.kittyWidthQuerySent=!1}return!1}markKittyWidthQuerySent(){this.kittyWidthQuerySent=!0}processOsc10(A){let Q=A.match(/^10;rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!Q||!Q[1]||!Q[2]||!Q[3])return!1;let B=Q[1],$=Q[2],J=Q[3],Y=(D)=>{let G=Number.parseInt(D,16),V=D.length*4;return G/(2**V-1)*255},Z=Math.round(Y(B)),X=Math.round(Y($)),F=Math.round(Y(J));return this.rgbColors.foreground={r:Z,g:X,b:F},!1}processOsc11(A){let Q=A.match(/^11;rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!Q||!Q[1]||!Q[2]||!Q[3])return!1;let B=Q[1],$=Q[2],J=Q[3],Y=(G)=>{let V=Number.parseInt(G,16),U=G.length*4;return V/(2**U-1)*255},Z=Math.round(Y(B)),X=Math.round(Y($)),F=Math.round(Y(J));this.rgbColors.background={r:Z,g:X,b:F};let D=0.299*Z+0.587*X+0.114*F;return this.capabilities.background=D<128?"dark":"light",!1}processOsc12(A){let Q=A.match(/^12;rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!Q||!Q[1]||!Q[2]||!Q[3])return!1;let B=Q[1],$=Q[2],J=Q[3],Y=(D)=>{let G=Number.parseInt(D,16),V=D.length*4;return G/(2**V-1)*255},Z=Math.round(Y(B)),X=Math.round(Y($)),F=Math.round(Y(J));return this.rgbColors.cursor={r:Z,g:X,b:F},!1}processOsc4(A){let Q=A.match(/^4;(\d+);rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!Q||!Q[1]||!Q[2]||!Q[3]||!Q[4])return!1;let B=Number.parseInt(Q[1],10),$=Q[2],J=Q[3],Y=Q[4],Z=(G)=>{let V=Number.parseInt(G,16),U=G.length*4;return V/(2**U-1)*255},X=Math.round(Z($)),F=Math.round(Z(J)),D=Math.round(Z(Y));if(B>=0&&B<=7)this.rgbColors.indices[B]={r:X,g:F,b:D};return!1}setColorPaletteChangeCallback(A){this.onColorPaletteChange=A}handleColorPaletteChangeNotification(){if(j.info("Color palette changed, re-querying colors..."),this.rgbColors={foreground:null,background:null,cursor:null,indices:[null,null,null,null,null,null,null,null]},this.colorUpdateTimer)clearTimeout(this.colorUpdateTimer);this.colorUpdateTimer=setTimeout(()=>{let A=this.getRgbColors();if(this.onColorPaletteChange&&A)j.info("Color re-query complete, notifying callback"),this.onColorPaletteChange();this.colorUpdateTimer=null},200)}getColorQuerySequences(){return["\x1B]10;?\x07","\x1B]11;?\x07","\x1B]12;?\x07","\x1B]4;0;?\x07","\x1B]4;1;?\x07","\x1B]4;2;?\x07","\x1B]4;3;?\x07","\x1B]4;4;?\x07","\x1B]4;5;?\x07","\x1B]4;6;?\x07","\x1B]4;7;?\x07"]}updateInbandPixelData(A,Q,B,$){if(B&&$&&B>0&&$>0)this.inbandPixelData={pixelWidth:B,pixelHeight:$,columns:A,rows:Q},this.capabilities.pixelDimensions=!0}checkPixelDimensions(){if(this.inbandPixelData){this.capabilities.pixelDimensions=!0;return}let A=i31();this.capabilities.pixelDimensions=!!(A&&A.pixelWidth>0&&A.pixelHeight>0)}isComplete(){return this.complete}getCapabilities(){return{...this.capabilities}}getRgbColors(){if(!this.rgbColors.foreground||!this.rgbColors.background||!this.rgbColors.cursor)return j.info("Missing fg, bg, or cursor color",{fg:!!this.rgbColors.foreground,bg:!!this.rgbColors.background,cursor:!!this.rgbColors.cursor}),null;for(let A=0;A<8;A++)if(!this.rgbColors.indices[A])return j.info(`Missing palette color ${A}`),null;return j.info("All RGB colors available",{fg:this.rgbColors.foreground,bg:this.rgbColors.background,cursor:this.rgbColors.cursor,indicesCount:this.rgbColors.indices.filter((A)=>A!==null).length}),{fg:this.rgbColors.foreground,bg:this.rgbColors.background,cursor:this.rgbColors.cursor,indices:this.rgbColors.indices}}shouldUsePixelMouse(){return this.capabilities.pixelMouse&&this.capabilities.pixelDimensions}getPixelDimensions(){if(this.inbandPixelData)return this.inbandPixelData;let A=i31();if(A&&A.pixelWidth>0&&A.pixelHeight>0)return{pixelWidth:A.pixelWidth,pixelHeight:A.pixelHeight,columns:A.columns,rows:A.rows};return null}getPendingQueries(){return this.complete?[]:["\x1B[c"]}detectKittyGraphicsFromEnv(){let A=["kitty","ghostty","wezterm"];if(pG())try{let Q="",B="";try{Q=L1A("tmux show-environment -g TERM 2>/dev/null",{encoding:"utf8",timeout:1000}).trim().replace(/^TERM=/,"").toLowerCase()}catch{}try{B=L1A("tmux show-environment -g TERM_PROGRAM 2>/dev/null",{encoding:"utf8",timeout:1000}).trim().replace(/^TERM_PROGRAM=/,"").toLowerCase()}catch{}for(let $ of A)if(Q.includes($)||B.includes($))return j.debug("Detected Kitty graphics support from tmux environment",{term:Q,termProgram:B}),!0}catch{}return!1}detectRgbSupport(){if(process.env.TERM_PROGRAM==="Apple_Terminal")return!1;return!0}detectCursorShapeSupport(){return!this.detectEmacs()&&!this.detectJetBrains()}detectAnimationSupport(){if(this.options.animationDisabled)return"disabled";if(process.env.NO_ANIMATION==="1"||process.env.NO_ANIMATIONS==="1")return"disabled";if(this.detectEmacs()||this.detectSSH())return"disabled";if(this.detectAppleTerminalUnderTmux())return"disabled";if(this.detectJetBrains())return"slow";return"fast"}detectEmacs(){return!!process.env.INSIDE_EMACS}detectJetBrains(){return process.env.TERMINAL_EMULATOR?.includes("JetBrains")??!1}detectSSH(){return!!(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)}detectTmux(){return!!process.env.TMUX}detectAppleTerminalUnderTmux(){return!!process.env.TMUX&&process.env.__CFBundleIdentifier==="com.apple.Terminal"}isITerm2(){if(this.capabilities.xtversion?.toLowerCase().includes("iterm2"))return!0;return process.env.TERM_PROGRAM==="iTerm.app"}getScrollStep(){if(this.capabilities.xtversion?.startsWith("ghostty"))return 1;if(P9())return 1;return 3}}i0();import{execFile as lP}from"node:child_process";import{existsSync as v08}from"node:fs";import{platform as GE0}from"node:os";import{promisify as y08}from"node:util";var ee=y08(lP);function j1A(){if(GE0()!=="linux")return!1;return Boolean(process.env.WSL_DISTRO_NAME)||v08("/proc/sys/fs/binfmt_misc/WSLInterop")}var x08=(A)=>`\x1B]52;c;${A}\x1B\\`,f08="\x1B]52;c;?\x1B\\",b08="\x1B]52;p;?\x1B\\";class R1A{capabilities=null;pendingReadPromise=null;readResolve=null;readTimeout=null;tmuxSetClipboard="unknown";setCapabilities(A){if(this.capabilities=A,pG())this.detectTmuxSetClipboard()}detectTmuxSetClipboard(){lP("tmux",["show-options","-s","-v","set-clipboard"],{timeout:1000},(A,Q)=>{if(!A){let B=Q.trim();if(B==="on"||B==="external"||B==="off")this.tmuxSetClipboard=B}})}isTmuxOsc52Allowed(){return this.tmuxSetClipboard==="on"||this.tmuxSetClipboard==="unknown"}isOsc52Supported(){return this.capabilities?.osc52??!1}async commandExists(A){try{return await ee("which",[A]),!0}catch{return!1}}async writeToPbcopy(A){try{let Q=lP("pbcopy");return Q.stdin?.write(A),Q.stdin?.end(),await new Promise((B,$)=>{Q.on("close",(J)=>{if(J===0)B();else $(Error(`pbcopy exited with code ${J}`))})}),!0}catch{return!1}}async writeToWlCopy(A){try{let Q=lP("wl-copy");return Q.stdin?.write(A),Q.stdin?.end(),await new Promise((B,$)=>{Q.on("close",(J)=>{if(J===0)B();else $(Error(`wl-copy exited with code ${J}`))})}),!0}catch{return!1}}async writeToXclip(A){try{let Q=lP("xclip",["-selection","clipboard"]);return Q.stdin?.write(A),Q.stdin?.end(),await new Promise((B,$)=>{Q.on("close",(J)=>{if(J===0)B();else $(Error(`xclip exited with code ${J}`))})}),!0}catch{return!1}}async writeToClipExe(A){try{let Q=lP("clip.exe");return Q.stdin?.write(A),Q.stdin?.end(),await new Promise((B,$)=>{Q.on("close",(J)=>{if(J===0)B();else $(Error(`clip.exe exited with code ${J}`))})}),!0}catch{return!1}}async writeToPowerShell(A){try{let Q=lP("powershell.exe",["-NoProfile","-Command","$Input | Set-Clipboard"]);return Q.stdin?.write(A),Q.stdin?.end(),await new Promise((B,$)=>{Q.on("close",(J)=>{if(J===0)B();else $(Error(`powershell.exe exited with code ${J}`))})}),!0}catch{return!1}}async readFromOSC52WithQuery(A){if(!this.isOsc52Supported())return null;if(this.pendingReadPromise!==void 0)return this.pendingReadPromise;this.pendingReadPromise=new Promise((B)=>{this.readResolve=B,this.readTimeout=setTimeout(()=>{this.readResolve=null,this.pendingReadPromise=null,B(null)},2000),process.stdout.write(A)});let Q=await this.pendingReadPromise;return this.pendingReadPromise=null,Q}async readFromOSC52(){return this.readFromOSC52WithQuery(f08)}handleOSC52Response(A){if(this.readResolve&&this.readTimeout){clearTimeout(this.readTimeout),this.readTimeout=null;try{let Q=Buffer.from(A,"base64").toString("utf8");this.readResolve(Q)}catch{this.readResolve(null)}this.readResolve=null,this.pendingReadPromise=null}}async readFromPbpaste(){try{let{stdout:A}=await ee("pbpaste");return A}catch{return null}}async readFromWlPaste(A){try{let Q=["--no-newline"];if(A==="primary")Q.push("--primary");let{stdout:B}=await ee("wl-paste",Q);return B}catch{return null}}async readFromXclip(A){try{let{stdout:Q}=await ee("xclip",["-selection",A,"-o"]);return Q}catch{return null}}async readFromPowerShell(){try{let{stdout:A}=await ee("powershell.exe",["-NoProfile","-Command","Get-Clipboard"]);return A}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(b08)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}let A=GE0();if(A==="darwin"){let Q=await this.readFromPbpaste();if(Q!==null)return Q}else if(A==="win32"){let Q=await this.readFromPowerShell();if(Q!==null)return Q}else{if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("clipboard");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("clipboard");if(Q!==null)return Q}if(j1A()){let Q=await this.readFromPowerShell();if(Q!==null)return Q}}return null}async readPrimarySelection(){let A=GE0();if(A==="darwin"||A==="win32")return this.readText();if(this.isOsc52Supported()){let Q=await this.readFromOSC52Primary();if(Q!==null)return Q}if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("primary");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("primary");if(Q!==null)return Q}return null}async writeText(A){let Q=pG(),B=!1;if(this.isOsc52Supported()&&(!Q||this.isTmuxOsc52Allowed())){let J=Buffer.from(A).toString("base64"),Y=x08(J);if(process.stdout.write(Y),B=!0,!Q)return!0}let $=GE0();if($==="darwin"){if(await this.writeToPbcopy(A))return!0}else if($==="win32"){if(await this.writeToPowerShell(A))return!0;if(await this.writeToClipExe(A))return!0}else{if(await this.commandExists("wl-copy")&&await this.writeToWlCopy(A))return!0;if(await this.commandExists("xclip")&&await this.writeToXclip(A))return!0;if(j1A()){if(await this.writeToPowerShell(A))return!0}}if(B)return!0;return!1}}var SF=new R1A;function u08(A){return A.replace(/\r\n|\r/g,`
|
|
5042
|
+
`+J.toStringDeep($,!0)}return B}addKeyHandler(A){this._keyHandlers.push(A)}removeKeyHandler(A){let Q=this._keyHandlers.indexOf(A);if(Q!==-1)this._keyHandlers.splice(Q,1)}handleKeyEvent(A){for(let Q of this._keyHandlers)if(Q(A)==="handled")return"handled";return"ignored"}dispose(){this._parent?._removeChild(this,!0),this._children.length=0,this._keyHandlers=[]}}function c31(A){return A._isFocusScopeNode===!0}class hu extends H6{_isFocusScopeNode=!0;_focusedChildren=[];constructor(A={}){super({canRequestFocus:A.canRequestFocus??!0,skipTraversal:A.skipTraversal??!0,...A})}get focusedChild(){return this._focusedChildren.length===0?null:this._focusedChildren[this._focusedChildren.length-1]}autofocus(A){if(A.parent===null)this._reparent(A);let Q=this._manager;if(Q===null){A._requestFocusWhenReparented=!0;return}Q._enqueueAutofocus(this,A)}_doRequestFocus({findFirstFocus:A}){while(this._focusedChildren.length>0&&(!this._focusedChildren[this._focusedChildren.length-1].canRequestFocus||this._focusedChildren[this._focusedChildren.length-1].enclosingScope===null))this._focusedChildren.pop();let Q=this.focusedChild;if(!A||Q===null){if(this.canRequestFocus)this._setAsFocusedChildForScope(),this._manager?._markNextFocus(this);return}Q._doRequestFocus({findFirstFocus:!0})}_pushFocusedChild(A){let Q=this._focusedChildren.indexOf(A);if(Q!==-1)this._focusedChildren.splice(Q,1);this._focusedChildren.push(A)}_removeFromHistory(A){let Q=this._focusedChildren.indexOf(A);if(Q!==-1)this._focusedChildren.splice(Q,1)}_clearFocusedChildren(){this._focusedChildren.length=0}get focusedChildren(){return this._focusedChildren}}class o3{static _instance=null;static _keystrokes=[];static _MAX_KEYSTROKES=100;_rootScope;_primaryFocus=null;_markedForFocus=null;_pendingAutofocuses=[];_haveScheduledUpdate=!1;constructor(){this._rootScope=new hu({debugLabel:"Root Focus Scope",canRequestFocus:!1}),this._rootScope._updateManager(this)}static getRecentKeystrokes(){return[...o3._keystrokes]}static _recordKeystroke(A,Q,B){if(o3._keystrokes.push({timestamp:Date.now(),key:A,focusPath:Q,handled:B}),o3._keystrokes.length>o3._MAX_KEYSTROKES)o3._keystrokes.shift()}static get instance(){if(!o3._instance)o3._instance=new o3;return o3._instance}get primaryFocus(){return this._primaryFocus}get rootScope(){return this._rootScope}requestFocus(A){if(!A.canRequestFocus)return!1;return A._doRequestFocus({findFirstFocus:!0}),!0}_markNextFocus(A){if(this._primaryFocus===A){this._markedForFocus=null;return}this._commitFocus(A)}_commitFocus(A){if(this._primaryFocus===A)return;let Q=this._primaryFocus;this._primaryFocus=A,Q?._setFocus(!1),A?._setFocus(!0)}_enqueueAutofocus(A,Q){this._pendingAutofocuses.push({scope:A,node:Q}),this._scheduleUpdate()}_scheduleUpdate(){if(this._haveScheduledUpdate)return;this._haveScheduledUpdate=!0,queueMicrotask(()=>{this._haveScheduledUpdate=!1,this._applyFocusChangesIfNeeded()})}_applyFocusChangesIfNeeded(){let A=this._pendingAutofocuses;this._pendingAutofocuses=[];for(let Q of A)this._applyAutofocusIfValid(Q)}_applyAutofocusIfValid(A){let{scope:Q,node:B}=A;if((Q.parent!==null||Q===this._rootScope)&&Q._manager===this&&Q.focusedChild===null&&B.ancestors.includes(Q))B._doRequestFocus({findFirstFocus:!0})}flushAutofocus(){this._haveScheduledUpdate=!1,this._applyFocusChangesIfNeeded()}handleKeyEvent(A){if(!this._primaryFocus)return!1;let Q=void 0,B=this._primaryFocus;while(B){let J=B._handleKeyEvent(A)==="handled";if(Q)Q.push({id:B.debugId,debugLabel:B.debugLabel,handled:J});if(J){if(Q)o3._recordKeystroke(this.formatKeyEvent(A),Q,!0);return!0}B=B.parent}if(Q)o3._recordKeystroke(this.formatKeyEvent(A),Q,!1);return!1}formatKeyEvent(A){let Q=[];if(A.ctrlKey)Q.push("Ctrl");if(A.altKey)Q.push("Alt");if(A.shiftKey)Q.push("Shift");if(A.metaKey)Q.push("Meta");if(A.key)Q.push(A.key);return Q.join("+")}handlePasteEvent(A){if(!this._primaryFocus)return!1;let Q=this._primaryFocus;while(Q){if(Q._handlePasteEvent(A)==="handled")return!0;Q=Q.parent}return!1}registerNode(A,Q=null){O4(A!==Q,"Focus node cannot be its own parent"),(Q??this._rootScope)._reparent(A)}unregisterNode(A){if(A.hasPrimaryFocus||this._markedForFocus===A)A.unfocus("previouslyFocusedChild");if(this._pendingAutofocuses=this._pendingAutofocuses.filter((B)=>B.node!==A&&B.scope!==A),A.parent?._removeChild(A,!0),this._primaryFocus===A)this._commitFocus(null);A._updateManager(null)}_focusNodeToDebugInfo(A){let Q=A instanceof hu,B=Q?A:null;return{id:A.debugId,debugLabel:A.debugLabel,hasPrimaryFocus:A.hasPrimaryFocus,hasFocus:A.hasFocus,canRequestFocus:A.canRequestFocus,skipTraversal:A.skipTraversal,isPrimaryFocus:this._primaryFocus===A,isScope:Q,focusedChildIds:B?B.focusedChildren.map(($)=>$.debugId):[],children:A.children.map(($)=>this._focusNodeToDebugInfo($))}}debugDumpFocusTree(){return{timestamp:Date.now(),rootScope:this._focusNodeToDebugInfo(this._rootScope),primaryFocusId:this._primaryFocus?.debugId??null,focusStack:this._rootScope.focusedChildren.map((A)=>({id:A.debugId,debugLabel:A.debugLabel}))}}dispose(){this._primaryFocus=null,this._markedForFocus=null,this._pendingAutofocuses=[],this._haveScheduledUpdate=!1,this._rootScope.dispose(),o3._instance=null}}class s4 extends x0{focusNode;child;autofocus;canRequestFocus;skipTraversal;onKey;onPaste;onFocusChange;debugLabel;constructor({key:A,focusNode:Q,child:B,autofocus:$=!1,canRequestFocus:J=!0,skipTraversal:Y=!1,onKey:Z,onPaste:X,onFocusChange:F,debugLabel:D}){super({key:A});this.focusNode=Q,this.child=B,this.autofocus=$,this.canRequestFocus=J,this.skipTraversal=Y,this.onKey=Z||null,this.onPaste=X||null,this.onFocusChange=F||null,this.debugLabel=D||null}createState(){return new gu}}class gu extends y0{_internalFocusNode=null;_isDisposed=!1;_focusChangeHandler=null;_didAutofocus=!1;get effectiveFocusNode(){return this.widget.focusNode??this._internalFocusNode}createFocusNode(A){return new H6(A)}initState(){if(super.initState(),!this.widget.focusNode){let B={canRequestFocus:this.widget.canRequestFocus,skipTraversal:this.widget.skipTraversal};if(this.widget.onKey)B.onKey=this.widget.onKey;if(this.widget.onPaste)B.onPaste=this.widget.onPaste;if(this.widget.debugLabel)B.debugLabel=this.widget.debugLabel;this._internalFocusNode=this.createFocusNode(B)}if(this.widget.onKey&&this.widget.focusNode)this.effectiveFocusNode.addKeyHandler(this.widget.onKey);if(this.widget.onPaste)this.effectiveFocusNode.onPaste=this.widget.onPaste;if(this.widget.onFocusChange)this._focusChangeHandler=(B)=>{if(!this._isDisposed&&this.widget.onFocusChange)this.widget.onFocusChange(B.hasFocus)},this.effectiveFocusNode.addListener(this._focusChangeHandler);let Q=this.context.findAncestorStateOfType(gu)?.effectiveFocusNode||null;if(o3.instance.registerNode(this.effectiveFocusNode,Q),this.widget.autofocus&&!this._didAutofocus)this._didAutofocus=!0,this.findEnclosingScope().autofocus(this.effectiveFocusNode)}findEnclosingScope(){return this.effectiveFocusNode.enclosingScope??o3.instance.rootScope}dispose(){if(this._didAutofocus=!1,this.widget.onKey)this.effectiveFocusNode.removeKeyHandler(this.widget.onKey);if(o3.instance.unregisterNode(this.effectiveFocusNode),this._isDisposed=!0,this._focusChangeHandler)this.effectiveFocusNode.removeListener(this._focusChangeHandler),this._focusChangeHandler=null;if(this._internalFocusNode)this._internalFocusNode.dispose(),this._internalFocusNode=null;super.dispose()}build(A){return this.widget.child}}function C1A(A){let Q=A.key;if(Q.length===1&&Q>="a"&&Q<="z")return Q;if(A.code!==void 0)return A.code;return Q}class g1{key;shift;ctrl;alt;meta;constructor(A,Q={}){this.key=A;this.shift=Q.shift??!1,this.ctrl=Q.ctrl??!1,this.alt=Q.alt??!1,this.meta=Q.meta??!1}accepts(A){return C1A(A)===this.key&&A.shiftKey===this.shift&&A.ctrlKey===this.ctrl&&A.altKey===this.alt&&A.metaKey===this.meta}static key(A){return new g1(A)}static ctrl(A){return new g1(A,{ctrl:!0})}static shift(A){return new g1(A,{shift:!0})}static alt(A){return new g1(A,{alt:!0})}static meta(A){return new g1(A,{meta:!0})}modifiers(){let A=[];if(this.meta)A.push("Meta");if(this.ctrl)A.push("Ctrl");if(this.alt)A.push("Alt");if(this.shift)A.push("Shift");return A}toString(){let A=this.modifiers();return A.length>0?`${A.join("+")}+${this.key}`:this.key}}class l31{shortcuts=new Map;constructor(A=new Map){this.shortcuts=new Map(A)}handleKeyEvent(A){for(let[Q,B]of this.shortcuts)if(Q.accepts(A))return B;return null}addShortcut(A,Q){this.shortcuts.set(A,Q)}removeShortcut(A){return this.shortcuts.delete(A)}getAllShortcuts(){return new Map(this.shortcuts)}copyWith(A){let Q=new Map([...this.shortcuts,...A]);return new l31(Q)}}class V8 extends x0{shortcuts;child;manager;debugLabel;focusNode;constructor({shortcuts:A,child:Q,manager:B,debugLabel:$,focusNode:J,key:Y}){super({key:Y});this.shortcuts=A,this.child=Q,this.manager=B,this.debugLabel=$,this.focusNode=J}createState(){return new M1A}}class M1A extends y0{manager=null;initState(){if(super.initState(),this.createManager(),this.widget.focusNode)this.widget.focusNode.addKeyHandler(this.handleKeyEvent)}didUpdateWidget(A){if(super.didUpdateWidget(A),A.shortcuts!==this.widget.shortcuts||A.manager!==this.widget.manager)this.createManager()}createManager(){if(this.widget.manager)this.manager=this.widget.manager;else this.manager=new l31(this.widget.shortcuts)}dispose(){if(this.widget.focusNode)this.widget.focusNode.removeKeyHandler(this.handleKeyEvent);super.dispose()}handleKeyEvent=(A)=>{if(!this.manager)return"ignored";let Q=this.manager.handleKeyEvent(A);if(Q){if(this.invokeIntent(Q)==="handled")return"handled"}return"ignored"};invokeIntent(A){let B=new XE0().findAction(A,this.context);if(B&&B.enabled){if(B.action.invoke(A)==="ignored")return null;return"handled"}return null}build(A){if(this.widget.focusNode)return this.widget.child;else return new s4({onKey:this.handleKeyEvent,autofocus:!1,canRequestFocus:!0,skipTraversal:!1,debugLabel:this.widget.debugLabel,child:this.widget.child})}}i0();i0();import{execSync as L1A}from"node:child_process";function i31(){let A=S08();if(A)return A;let Q=k08();if(Q)return{...Q,pixelWidth:0,pixelHeight:0};return null}function S08(){try{let A=(()=>{throw new Error("Cannot require module "+"ffi-napi");})(),Q=(()=>{throw new Error("Cannot require module "+"ref-napi");})(),$=(()=>{throw new Error("Cannot require module "+"ref-struct-di");})()(Q)({ws_row:Q.types.ushort,ws_col:Q.types.ushort,ws_xpixel:Q.types.ushort,ws_ypixel:Q.types.ushort}),J=A.Library("libc",{ioctl:["int",["int","ulong","pointer"]]}),Y=process.platform==="darwin"?1074295912:21523,Z=new $;if(J.ioctl(process.stdout.fd,Y,Z.ref())===0)return{rows:Z.ws_row,columns:Z.ws_col,pixelWidth:Z.ws_xpixel,pixelHeight:Z.ws_ypixel};return null}catch(A){return null}}function k08(){try{if(process.stdout.isTTY&&process.stdout.columns&&process.stdout.rows)return{columns:process.stdout.columns,rows:process.stdout.rows};let A=process.stdin;if(process.stdin.isTTY&&A.columns&&A.rows)return{columns:A.columns,rows:A.rows};let Q=process.stdout;if(typeof Q.getWindowSize==="function"){let B=Q.getWindowSize();if(B[0]>0&&B[1]>0)return{columns:B[0],rows:B[1]}}return null}catch(A){return null}}function te(A){return{syncOutput:!1,emojiWidth:!1,pixelMouse:!1,pixelDimensions:!1,xtversion:null,canRgb:!0,supportsCursorShape:!0,animationSupport:"fast",kittyKeyboard:!1,osc52:!1,kittyGraphics:!1,background:"unknown",colorPaletteNotifications:!1,kittyExplicitWidth:!1,underlineSupport:P9()?"none":"standard",scrollStep:()=>3,...A}}var O1A=[{sequence:"\x1B[?1049h\x1B[H\x1B]66;w=1; \x1B\\\x1B[6n\x1B[?1049l",description:"Query Kitty explicit width support"},{sequence:"\x1B]10;?\x07",description:"Query terminal foreground color (OSC 10)"},{sequence:"\x1B]11;?\x07",description:"Query terminal background color (OSC 11)"},{sequence:"\x1B]12;?\x07",description:"Query terminal cursor color (OSC 12)"},{sequence:"\x1B]4;0;?\x07",description:"Query terminal color 0 (OSC 4)"},{sequence:"\x1B]4;1;?\x07",description:"Query terminal color 1 (OSC 4)"},{sequence:"\x1B]4;2;?\x07",description:"Query terminal color 2 (OSC 4)"},{sequence:"\x1B]4;3;?\x07",description:"Query terminal color 3 (OSC 4)"},{sequence:"\x1B]4;4;?\x07",description:"Query terminal color 4 (OSC 4)"},{sequence:"\x1B]4;5;?\x07",description:"Query terminal color 5 (OSC 4)"},{sequence:"\x1B]4;6;?\x07",description:"Query terminal color 6 (OSC 4)"},{sequence:"\x1B]4;7;?\x07",description:"Query terminal color 7 (OSC 4)"},{sequence:"\x1B[?2026$p",description:"Query synchronized output support"},{sequence:"\x1B[?2027$p",description:"Query emoji width mode support"},{sequence:"\x1B[?1016$p",description:"Query pixel mouse mode support"},{sequence:"\x1B[?2031$p",description:"Query color palette change notifications support (mode 2031)"},{sequence:"\x1B[?u",description:"Query Kitty keyboard protocol support"},{sequence:"\x1B[>0q",description:"Query terminal version (XTVERSION)"},{sequence:"\x1BP+q4d73\x1B\\",description:"Query OSC 52 clipboard support (XTGETTCAP Ms)"},{sequence:dG("\x1B_Gi=1,a=q\x1B\\"),description:"Query Kitty graphics protocol support",shouldSend:()=>{return!P9()&&process.env.TERM_PROGRAM!=="Apple_Terminal"&&!Lu()}},{sequence:"\x1B[c",description:"Device Attributes (DA1)",isFinal:!0}];class DE0{options;capabilities;constructor(A={}){this.options=A;this.capabilities={syncOutput:!1,emojiWidth:!1,pixelMouse:!1,pixelDimensions:!1,xtversion:null,canRgb:this.detectRgbSupport(),supportsCursorShape:this.detectCursorShapeSupport(),animationSupport:this.detectAnimationSupport(),kittyKeyboard:!1,osc52:!1,kittyGraphics:this.detectKittyGraphicsFromEnv(),background:"unknown",colorPaletteNotifications:!1,kittyExplicitWidth:!1,underlineSupport:P9()?"none":"standard",scrollStep:()=>this.getScrollStep()}}complete=!1;colorUpdateTimer=null;onColorPaletteChange;inbandPixelData=null;kittyWidthQuerySent=!1;rgbColors={foreground:null,background:null,cursor:null,indices:[null,null,null,null,null,null,null,null]};processDecrqss(A,Q){if(A==="?2026")this.capabilities.syncOutput=Q==="1"||Q==="2";if(A==="?2027")this.capabilities.emojiWidth=Q==="1"||Q==="2";if(A==="?1016")this.capabilities.pixelMouse=Q==="1"||Q==="2";if(A==="?2031")this.capabilities.colorPaletteNotifications=Q==="1"||Q==="2";if(A==="u")this.capabilities.kittyKeyboard=!0;return!1}processDeviceAttributes(A,Q){if(this.checkPixelDimensions(),this.detectJetBrains()||this.detectTmux())this.capabilities.emojiWidth=!0;return this.complete=!0,!0}processXtversion(A){this.capabilities.xtversion=A;let Q=["ghostty","kitty","wezterm","foot","alacritty","iterm2","tmux"],B=A.toLowerCase();if(Q.some(($)=>B.includes($)))this.capabilities.osc52=!0;return!1}processXtgettcap(A,Q){if(A.toLowerCase()==="4d73")this.capabilities.osc52=Q.length>0;return!1}processKittyGraphics(){if(this.isITerm2())return this.capabilities.kittyGraphics=!1,!1;return this.capabilities.kittyGraphics=!0,!1}processCursorPositionReport(A,Q){if(this.kittyWidthQuerySent){if(A===1&&Q===2)this.capabilities.kittyExplicitWidth=!0,j.info("Kitty explicit width support detected");this.kittyWidthQuerySent=!1}return!1}markKittyWidthQuerySent(){this.kittyWidthQuerySent=!0}processOsc10(A){let Q=A.match(/^10;rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!Q||!Q[1]||!Q[2]||!Q[3])return!1;let B=Q[1],$=Q[2],J=Q[3],Y=(D)=>{let G=Number.parseInt(D,16),V=D.length*4;return G/(2**V-1)*255},Z=Math.round(Y(B)),X=Math.round(Y($)),F=Math.round(Y(J));return this.rgbColors.foreground={r:Z,g:X,b:F},!1}processOsc11(A){let Q=A.match(/^11;rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!Q||!Q[1]||!Q[2]||!Q[3])return!1;let B=Q[1],$=Q[2],J=Q[3],Y=(G)=>{let V=Number.parseInt(G,16),U=G.length*4;return V/(2**U-1)*255},Z=Math.round(Y(B)),X=Math.round(Y($)),F=Math.round(Y(J));this.rgbColors.background={r:Z,g:X,b:F};let D=0.299*Z+0.587*X+0.114*F;return this.capabilities.background=D<128?"dark":"light",!1}processOsc12(A){let Q=A.match(/^12;rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!Q||!Q[1]||!Q[2]||!Q[3])return!1;let B=Q[1],$=Q[2],J=Q[3],Y=(D)=>{let G=Number.parseInt(D,16),V=D.length*4;return G/(2**V-1)*255},Z=Math.round(Y(B)),X=Math.round(Y($)),F=Math.round(Y(J));return this.rgbColors.cursor={r:Z,g:X,b:F},!1}processOsc4(A){let Q=A.match(/^4;(\d+);rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!Q||!Q[1]||!Q[2]||!Q[3]||!Q[4])return!1;let B=Number.parseInt(Q[1],10),$=Q[2],J=Q[3],Y=Q[4],Z=(G)=>{let V=Number.parseInt(G,16),U=G.length*4;return V/(2**U-1)*255},X=Math.round(Z($)),F=Math.round(Z(J)),D=Math.round(Z(Y));if(B>=0&&B<=7)this.rgbColors.indices[B]={r:X,g:F,b:D};return!1}setColorPaletteChangeCallback(A){this.onColorPaletteChange=A}handleColorPaletteChangeNotification(){if(j.info("Color palette changed, re-querying colors..."),this.rgbColors={foreground:null,background:null,cursor:null,indices:[null,null,null,null,null,null,null,null]},this.colorUpdateTimer)clearTimeout(this.colorUpdateTimer);this.colorUpdateTimer=setTimeout(()=>{let A=this.getRgbColors();if(this.onColorPaletteChange&&A)j.info("Color re-query complete, notifying callback"),this.onColorPaletteChange();this.colorUpdateTimer=null},200)}getColorQuerySequences(){return["\x1B]10;?\x07","\x1B]11;?\x07","\x1B]12;?\x07","\x1B]4;0;?\x07","\x1B]4;1;?\x07","\x1B]4;2;?\x07","\x1B]4;3;?\x07","\x1B]4;4;?\x07","\x1B]4;5;?\x07","\x1B]4;6;?\x07","\x1B]4;7;?\x07"]}updateInbandPixelData(A,Q,B,$){if(B&&$&&B>0&&$>0)this.inbandPixelData={pixelWidth:B,pixelHeight:$,columns:A,rows:Q},this.capabilities.pixelDimensions=!0}checkPixelDimensions(){if(this.inbandPixelData){this.capabilities.pixelDimensions=!0;return}let A=i31();this.capabilities.pixelDimensions=!!(A&&A.pixelWidth>0&&A.pixelHeight>0)}isComplete(){return this.complete}getCapabilities(){return{...this.capabilities}}getRgbColors(){if(!this.rgbColors.foreground||!this.rgbColors.background||!this.rgbColors.cursor)return j.info("Missing fg, bg, or cursor color",{fg:!!this.rgbColors.foreground,bg:!!this.rgbColors.background,cursor:!!this.rgbColors.cursor}),null;for(let A=0;A<8;A++)if(!this.rgbColors.indices[A])return j.info(`Missing palette color ${A}`),null;return j.info("All RGB colors available",{fg:this.rgbColors.foreground,bg:this.rgbColors.background,cursor:this.rgbColors.cursor,indicesCount:this.rgbColors.indices.filter((A)=>A!==null).length}),{fg:this.rgbColors.foreground,bg:this.rgbColors.background,cursor:this.rgbColors.cursor,indices:this.rgbColors.indices}}shouldUsePixelMouse(){return this.capabilities.pixelMouse&&this.capabilities.pixelDimensions}getPixelDimensions(){if(this.inbandPixelData)return this.inbandPixelData;let A=i31();if(A&&A.pixelWidth>0&&A.pixelHeight>0)return{pixelWidth:A.pixelWidth,pixelHeight:A.pixelHeight,columns:A.columns,rows:A.rows};return null}getPendingQueries(){return this.complete?[]:["\x1B[c"]}detectKittyGraphicsFromEnv(){let A=["kitty","ghostty","wezterm"];if(pG())try{let Q="",B="";try{Q=L1A("tmux show-environment -g TERM 2>/dev/null",{encoding:"utf8",timeout:1000}).trim().replace(/^TERM=/,"").toLowerCase()}catch{}try{B=L1A("tmux show-environment -g TERM_PROGRAM 2>/dev/null",{encoding:"utf8",timeout:1000}).trim().replace(/^TERM_PROGRAM=/,"").toLowerCase()}catch{}for(let $ of A)if(Q.includes($)||B.includes($))return j.debug("Detected Kitty graphics support from tmux environment",{term:Q,termProgram:B}),!0}catch{}return!1}detectRgbSupport(){if(process.env.TERM_PROGRAM==="Apple_Terminal")return!1;return!0}detectCursorShapeSupport(){return!this.detectEmacs()&&!this.detectJetBrains()}detectAnimationSupport(){if(this.options.animationDisabled)return"disabled";if(process.env.NO_ANIMATION==="1"||process.env.NO_ANIMATIONS==="1")return"disabled";if(this.detectEmacs()||this.detectSSH())return"disabled";if(this.detectAppleTerminalUnderTmux())return"disabled";if(this.detectJetBrains())return"slow";return"fast"}detectEmacs(){return!!process.env.INSIDE_EMACS}detectJetBrains(){return process.env.TERMINAL_EMULATOR?.includes("JetBrains")??!1}detectSSH(){return!!(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)}detectTmux(){return!!process.env.TMUX}detectAppleTerminalUnderTmux(){return!!process.env.TMUX&&process.env.__CFBundleIdentifier==="com.apple.Terminal"}isITerm2(){if(this.capabilities.xtversion?.toLowerCase().includes("iterm2"))return!0;return process.env.TERM_PROGRAM==="iTerm.app"}getScrollStep(){if(this.capabilities.xtversion?.startsWith("ghostty"))return 1;if(P9())return 1;return 3}}i0();import{execFile as lP}from"node:child_process";import{existsSync as v08}from"node:fs";import{platform as GE0}from"node:os";import{promisify as y08}from"node:util";var ee=y08(lP);function j1A(){if(GE0()!=="linux")return!1;return Boolean(process.env.WSL_DISTRO_NAME)||v08("/proc/sys/fs/binfmt_misc/WSLInterop")}var x08=(A)=>`\x1B]52;c;${A}\x1B\\`,f08="\x1B]52;c;?\x1B\\",b08="\x1B]52;p;?\x1B\\";class R1A{capabilities=null;pendingReadPromise=null;readResolve=null;readTimeout=null;tmuxSetClipboard="unknown";setCapabilities(A){if(this.capabilities=A,pG())this.detectTmuxSetClipboard()}detectTmuxSetClipboard(){lP("tmux",["show-options","-s","-v","set-clipboard"],{timeout:1000},(A,Q)=>{if(!A){let B=Q.trim();if(B==="on"||B==="external"||B==="off")this.tmuxSetClipboard=B}})}isTmuxOsc52Allowed(){return this.tmuxSetClipboard==="on"||this.tmuxSetClipboard==="unknown"}isOsc52Supported(){return this.capabilities?.osc52??!1}async commandExists(A){try{return await ee("which",[A]),!0}catch{return!1}}async writeToPbcopy(A){try{let Q=lP("pbcopy");return Q.stdin?.write(A),Q.stdin?.end(),await new Promise((B,$)=>{Q.on("close",(J)=>{if(J===0)B();else $(Error(`pbcopy exited with code ${J}`))})}),!0}catch{return!1}}async writeToWlCopy(A){try{let Q=lP("wl-copy");return Q.stdin?.write(A),Q.stdin?.end(),await new Promise((B,$)=>{Q.on("close",(J)=>{if(J===0)B();else $(Error(`wl-copy exited with code ${J}`))})}),!0}catch{return!1}}async writeToXclip(A){try{let Q=lP("xclip",["-selection","clipboard"]);return Q.stdin?.write(A),Q.stdin?.end(),await new Promise((B,$)=>{Q.on("close",(J)=>{if(J===0)B();else $(Error(`xclip exited with code ${J}`))})}),!0}catch{return!1}}async writeToClipExe(A){try{let Q=lP("clip.exe");return Q.stdin?.write(A),Q.stdin?.end(),await new Promise((B,$)=>{Q.on("close",(J)=>{if(J===0)B();else $(Error(`clip.exe exited with code ${J}`))})}),!0}catch{return!1}}async writeToPowerShell(A){try{let Q=lP("powershell.exe",["-NoProfile","-Command","$Input | Set-Clipboard"]);return Q.stdin?.write(A),Q.stdin?.end(),await new Promise((B,$)=>{Q.on("close",(J)=>{if(J===0)B();else $(Error(`powershell.exe exited with code ${J}`))})}),!0}catch{return!1}}async readFromOSC52WithQuery(A){if(!this.isOsc52Supported())return null;if(this.pendingReadPromise!==void 0)return this.pendingReadPromise;this.pendingReadPromise=new Promise((B)=>{this.readResolve=B,this.readTimeout=setTimeout(()=>{this.readResolve=null,this.pendingReadPromise=null,B(null)},2000),process.stdout.write(A)});let Q=await this.pendingReadPromise;return this.pendingReadPromise=null,Q}async readFromOSC52(){return this.readFromOSC52WithQuery(f08)}handleOSC52Response(A){if(this.readResolve&&this.readTimeout){clearTimeout(this.readTimeout),this.readTimeout=null;try{let Q=Buffer.from(A,"base64").toString("utf8");this.readResolve(Q)}catch{this.readResolve(null)}this.readResolve=null,this.pendingReadPromise=null}}async readFromPbpaste(){try{let{stdout:A}=await ee("pbpaste");return A}catch{return null}}async readFromWlPaste(A){try{let Q=["--no-newline"];if(A==="primary")Q.push("--primary");let{stdout:B}=await ee("wl-paste",Q);return B}catch{return null}}async readFromXclip(A){try{let{stdout:Q}=await ee("xclip",["-selection",A,"-o"]);return Q}catch{return null}}async readFromPowerShell(){try{let{stdout:A}=await ee("powershell.exe",["-NoProfile","-Command","Get-Clipboard"]);return A}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(b08)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}let A=GE0();if(A==="darwin"){let Q=await this.readFromPbpaste();if(Q!==null)return Q}else if(A==="win32"){let Q=await this.readFromPowerShell();if(Q!==null)return Q}else{if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("clipboard");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("clipboard");if(Q!==null)return Q}if(j1A()){let Q=await this.readFromPowerShell();if(Q!==null)return Q}}return null}async readPrimarySelection(){let A=GE0();if(A==="darwin"||A==="win32")return this.readText();if(this.isOsc52Supported()){let Q=await this.readFromOSC52Primary();if(Q!==null)return Q}if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("primary");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("primary");if(Q!==null)return Q}return null}async writeText(A){let Q=pG(),B=!1;if(this.isOsc52Supported()&&(!Q||this.isTmuxOsc52Allowed())){let J=Buffer.from(A).toString("base64"),Y=x08(J);if(process.stdout.write(Y),B=!0,!Q)return!0}let $=GE0();if($==="darwin"){if(await this.writeToPbcopy(A))return!0}else if($==="win32"){if(await this.writeToPowerShell(A))return!0;if(await this.writeToClipExe(A))return!0}else{if(await this.commandExists("wl-copy")&&await this.writeToWlCopy(A))return!0;if(await this.commandExists("xclip")&&await this.writeToXclip(A))return!0;if(j1A()){if(await this.writeToPowerShell(A))return!0}}if(B)return!0;return!1}}var SF=new R1A;function u08(A){return A.replace(/\r\n|\r/g,`
|
|
5043
5043
|
`)}function h08(A){return A.replace(/[\u0000-\u0008\u000B-\u000C\u000E-\u001F\u007F-\u009F]/g,"")}function P1A(A){let Q=A;return Q=u08(Q),Q=h08(Q),Q}var g08=50,m08=200,p08=200,d08=50;class T1A{eventBuffer=[];bufferTimer=null;filterDirection=null;lastEventTime=0;onEmitEvent=()=>{};constructor(A){this.onEmitEvent=A}handleWheelEvent(A){if(A.button!=="wheel_up"&&A.button!=="wheel_down")return!0;let Q=Date.now();if(this.filterDirection!==null)if(Q-this.lastEventTime>m08)this.filterDirection=null;else return this.lastEventTime=Q,A.button===this.filterDirection;if(this.lastEventTime=Q,this.eventBuffer.push(A),!this.bufferTimer)this.bufferTimer=setTimeout(()=>{this.processBuffer()},g08);return!1}processBuffer(){if(this.bufferTimer=null,this.eventBuffer.length===0)return;if(this.eventBuffer.some((Q)=>Q.button==="wheel_down")){this.filterDirection="wheel_down";for(let Q of this.eventBuffer)if(Q.button==="wheel_down")this.onEmitEvent(Q)}else{this.filterDirection="wheel_up";for(let Q of this.eventBuffer)this.onEmitEvent(Q)}this.eventBuffer=[]}}class n31{parser=null;initialized=!1;inAltScreen=!1;suspended=!1;tty;screen;renderer;queryParser=null;capabilities=null;capabilityPromise=null;capabilityResolve=null;capabilityTimeout=null;windowsKittyProbeTimeout=null;windowsKittyProbePending=!1;terminalSize={width:80,height:24};jetBrainsWheelFilter;keyHandlers=[];mouseHandlers=[];resizeHandlers=[];focusHandlers=[];pasteHandlers=[];capabilityHandlers=[];boundHandleResize=this.handleResize.bind(this);boundCleanup=this.cleanup.bind(this);boundExitCleanup=this.exitCleanup.bind(this);boundHandleResume=this.handleResume.bind(this);resizeDebounceTimer=null;pendingResize=!1;lastRenderDiffStats={repaintedCellCount:0,totalCellCount:1920,repaintedPercent:0,bytesWritten:0};options={};constructor(){this.screen=new PZ(80,24),this.renderer=new fe,this.tty=vK0(),this.jetBrainsWheelFilter=new T1A((A)=>{for(let Q of this.mouseHandlers)Q(A)})}setOptions(A){this.options={...this.options,...A}}init(){if(this.initialized)throw Error("TUI is already initialized");try{if(this.parser=new uP,this.parser.onKey(this.handleKeyEvent.bind(this)),this.parser.onPaste(this.handlePasteEvent.bind(this)),this.parser.onOsc(this.handleOscEvent.bind(this)),this.queryParser=new DE0(this.options.queryOptions),this.parser.onDeviceAttributes((A)=>{if(this.queryParser&&this.initialized){if(this.queryParser.processDeviceAttributes(A.primary,A.secondary))this.finishInitialization()}}),this.parser.onDecrqss((A)=>{if(this.queryParser&&this.initialized)this.queryParser.processDecrqss(A.request,A.response),this.handleWindowsKittyProbeResponse(A.request,A.response)}),this.parser.onDcs((A)=>{if(this.queryParser&&this.initialized){if(A.final==="|"&&A.private===">")this.queryParser.processXtversion(A.data);if(A.final==="r"&&A.intermediates==="+"&&A.params.length>0&&A.params[0]?.value===1)this.parseXtgettcapResponse(A.data)}}),this.parser.onApc((A)=>{if(this.queryParser&&this.initialized){if(A.data.startsWith("G"))this.queryParser.processKittyGraphics()}}),this.parser.onCursorPositionReport((A)=>{if(this.queryParser&&this.initialized)this.queryParser.processCursorPositionReport(A.row,A.col)}),this.parser.onColorPaletteChange((A)=>{if(this.queryParser&&this.initialized){j.info("Color palette change detected, re-querying colors");let Q=this.queryParser.getColorQuerySequences();for(let B of Q)process.stdout.write(B);this.queryParser.handleColorPaletteChangeNotification()}}),this.parser.onMouse((A)=>{if(P9()&&!this.jetBrainsWheelFilter.handleWheelEvent(A))return;for(let Q of this.mouseHandlers)Q(A)}),this.parser.onFocus((A)=>{for(let Q of this.focusHandlers)Q(A)}),this.parser.onResize((A)=>{this.handleInbandResize(A)}),this.tty.on("data",(A)=>{this.parser?.parse(A)}),this.tty.resume(),process.on("SIGWINCH",this.boundHandleResize),process.stdout.isTTY)process.stdout.on("resize",this.boundHandleResize);this.updateTerminalSize(),this.screen.resize(this.terminalSize.width,this.terminalSize.height),this.setupCleanupHandlers(),this.initialized=!0,this.enableMouse(),this.enableBracketedPaste(),this.createCapabilityPromise(),this.startCapabilityDetection()}catch(A){throw this.deinit().catch(()=>{}),A}}async deinit(){if(this.initialized){let A="",Q="",B=(this.capabilities?.kittyKeyboard?this.renderer.disableKittyKeyboard():"")+this.renderer.disableModifyOtherKeys(),$=async(J)=>{if(!J)return;await new Promise((Y)=>{process.stdout.write(J,()=>{Y()})})};if(A+=this.renderer.endSync(),this.inAltScreen)A+=this.renderer.clearScreen()+B+this.renderer.exitAltScreen(),B="",this.inAltScreen=!1;if(Q+=this.renderer.reset()+this.renderer.disableMouse()+this.renderer.disableEmojiWidth()+this.renderer.disableInBandResize()+this.renderer.disableBracketedPaste()+B+this.renderer.setCursorShape(0)+this.renderer.showCursor(),this.capabilities?.colorPaletteNotifications)Q+="\x1B[?2031l";if(this.capabilities?.xtversion?.startsWith("ghostty"))Q+=this.renderer.setProgressBarOff();if(await $(A),process.platform==="win32"&&A)await new Promise((J)=>{setTimeout(J,d08)});await $(Q)}if(this.resizeDebounceTimer)clearTimeout(this.resizeDebounceTimer),this.resizeDebounceTimer=null;if(this.capabilityTimeout)clearTimeout(this.capabilityTimeout),this.capabilityTimeout=null;if(this.windowsKittyProbeTimeout)clearTimeout(this.windowsKittyProbeTimeout),this.windowsKittyProbeTimeout=null;this.windowsKittyProbePending=!1,this.keyHandlers.length=0,this.mouseHandlers.length=0,this.resizeHandlers.length=0,this.focusHandlers.length=0,this.pasteHandlers.length=0,this.capabilityHandlers.length=0,process.removeListener("SIGWINCH",this.boundHandleResize),process.stdout.removeListener("resize",this.boundHandleResize),process.removeListener("SIGINT",this.boundCleanup),process.removeListener("SIGTERM",this.boundCleanup),process.removeListener("exit",this.boundExitCleanup),process.removeListener("SIGCONT",this.boundHandleResume),this.tty.dispose(),this.parser=null,this.queryParser=null,this.capabilities=null,this.capabilityPromise=null,this.capabilityResolve=null,this.initialized=!1}getEarlyInputText(){return this.tty.getEarlyInputText()}onKey(A){this.keyHandlers.push(A)}offKey(A){let Q=this.keyHandlers.indexOf(A);if(Q!==-1)this.keyHandlers.splice(Q,1)}onMouse(A){this.mouseHandlers.push(A)}offMouse(A){let Q=this.mouseHandlers.indexOf(A);if(Q!==-1)this.mouseHandlers.splice(Q,1)}onResize(A){this.resizeHandlers.push(A)}offResize(A){let Q=this.resizeHandlers.indexOf(A);if(Q!==-1)this.resizeHandlers.splice(Q,1)}onFocus(A){this.focusHandlers.push(A)}offFocus(A){let Q=this.focusHandlers.indexOf(A);if(Q!==-1)this.focusHandlers.splice(Q,1)}onPaste(A){this.pasteHandlers.push(A)}offPaste(A){let Q=this.pasteHandlers.indexOf(A);if(Q!==-1)this.pasteHandlers.splice(Q,1)}onCapabilities(A){this.capabilityHandlers.push(A)}offCapabilities(A){let Q=this.capabilityHandlers.indexOf(A);if(Q!==-1)this.capabilityHandlers.splice(Q,1)}isInitialized(){return this.initialized}getCapabilities(){return this.capabilities}getQueryParser(){return this.queryParser}async waitForCapabilities(A=1000){if(!this.initialized)throw Error("TUI is not initialized");if(this.capabilities)return this.capabilities;if(!this.capabilityPromise)throw Error("Capability detection not started");return this.capabilityPromise}getSize(){return{...this.terminalSize}}getScreen(){return this.screen}getLastRenderDiffStats(){return this.lastRenderDiffStats}render(){if(!this.initialized)throw Error("TUI not initialized");if(this.suspended)return;let A=this.screen.getDiff(),Q=this.screen.getSize(),B=Q.width*Q.height,$=A.length,J=B>0?$/B*100:0;this.lastRenderDiffStats={repaintedCellCount:$,totalCellCount:B,repaintedPercent:J,bytesWritten:0};let Y=this.screen.getCursor();if(A.length>0||Y!==null){let X=new xe;X.append(this.renderer.startSync()),X.append(this.renderer.hideCursor()),X.append(this.renderer.reset()),X.append(this.renderer.moveTo(0,0));let F=this.renderer.render(A);if(X.append(F),Y)if(X.append(this.renderer.moveTo(Y.x,Y.y)),this.screen.isCursorVisible())X.append(this.renderer.setCursorShape(this.screen.getCursorShape())),X.append(this.renderer.showCursor());else X.append(this.renderer.hideCursor());else X.append(this.renderer.hideCursor());X.append(this.renderer.endSync());let D=X.toString();this.lastRenderDiffStats={...this.lastRenderDiffStats,bytesWritten:Buffer.byteLength(D,"utf8")},process.stdout.write(D),this.screen.present()}}clearScreen(){let A=this.renderer.clearScreen()+this.renderer.hideCursor();process.stdout.write(A),this.renderer.resetState()}showCursor(){process.stdout.write(this.renderer.showCursor())}hideCursor(){process.stdout.write(this.renderer.hideCursor())}setCursor(A,Q){this.screen.setCursor(A,Q)}clearCursor(){this.screen.clearCursor()}setCursorShape(A){this.screen.setCursorShape(A)}setMouseCursor(A){let Q=`\x1B]22;${A}\x07`;process.stdout.write(Q)}resetMouseCursor(){this.setMouseCursor(_5.DEFAULT)}enableBracketedPaste(){process.stdout.write(this.renderer.enableBracketedPaste())}disableBracketedPaste(){process.stdout.write(this.renderer.disableBracketedPaste())}enableKittyKeyboard(){process.stdout.write(this.renderer.enableKittyKeyboard())}disableKittyKeyboard(){process.stdout.write(this.renderer.disableKittyKeyboard())}enableModifyOtherKeys(){process.stdout.write(this.renderer.enableModifyOtherKeys())}disableModifyOtherKeys(){process.stdout.write(this.renderer.disableModifyOtherKeys())}async writeClipboard(A){return SF.writeText(A)}get clipboard(){return SF}enterAltScreen(){if(!this.initialized)throw Error("TUI not initialized");if(!this.inAltScreen)process.stdout.write(this.renderer.enterAltScreen()),this.inAltScreen=!0}exitAltScreen(){if(this.inAltScreen)process.stdout.write(this.renderer.exitAltScreen()),this.inAltScreen=!1}isInAltScreen(){return this.inAltScreen}enableMouse(){if(this.initialized){let A=process.platform!=="win32"&&(this.queryParser?.shouldUsePixelMouse()??!1),Q=this.renderer.enableMouse(A);process.stdout.write(Q)}}disableMouse(){if(this.initialized)process.stdout.write(this.renderer.disableMouse())}enableEmojiWidth(){if(this.initialized){let A=this.renderer.enableEmojiWidth();process.stdout.write(A)}}disableEmojiWidth(){if(this.initialized)process.stdout.write(this.renderer.disableEmojiWidth())}enableInBandResize(){if(this.initialized){let A=this.renderer.enableInBandResize();process.stdout.write(A)}}disableInBandResize(){if(this.initialized)process.stdout.write(this.renderer.disableInBandResize())}enableColorPaletteNotifications(){if(this.initialized)j.info("Enabling mode 2031 (color palette change notifications)"),process.stdout.write("\x1B[?2031h")}disableColorPaletteNotifications(){if(this.initialized)process.stdout.write("\x1B[?2031l")}setMouseShape(A){if(this.initialized)process.stdout.write(this.renderer.setMouseShape(A))}suspend(){if(!this.initialized||this.suspended)return;let A="";if(A+=this.renderer.reset()+this.renderer.disableMouse()+this.renderer.disableEmojiWidth()+this.renderer.disableInBandResize()+this.renderer.disableBracketedPaste()+(this.capabilities?.kittyKeyboard?this.renderer.disableKittyKeyboard():"")+this.renderer.disableModifyOtherKeys()+this.renderer.setCursorShape(0)+this.renderer.showCursor(),this.capabilities?.colorPaletteNotifications)A+="\x1B[?2031l";if(this.capabilities?.xtversion?.startsWith("ghostty"))A+=this.renderer.setProgressBarOff();if(this.inAltScreen)A+=this.renderer.exitAltScreen(),this.inAltScreen=!1;if(process.stdout.write(A),this.tty.pause(),this.suspended=!0,process.stdout.isTTY)process.stdout.uncork()}resume(){if(!this.initialized||!this.suspended)return;if(this.tty.resume(),this.parser)this.parser.reset();if(this.enterAltScreen(),this.hideCursor(),this.enableMouse(),this.enableBracketedPaste(),this.capabilities?.emojiWidth)this.enableEmojiWidth();if(this.capabilities?.kittyKeyboard)this.enableKittyKeyboard();this.enableModifyOtherKeys(),this.enableInBandResize(),this.screen.markForRefresh(),this.suspended=!1}isSuspended(){return this.suspended}handleSuspend(){if(!this.initialized||this.suspended)return;if(process.platform==="win32")return;this.suspend();try{process.kill(0,"SIGTSTP"),j.debug(`Successfully suspended process ${process.pid}`)}catch(A){j.debug(`Failed to suspend process ${process.pid}: ${A}`)}}handleResume(){if(!this.initialized||!this.suspended)return;this.resume(),setImmediate(()=>{if(this.initialized&&!this.suspended)this.render()})}updateTerminalSize(){if(!this.tty.stdin||!_1A(this.tty.stdin)){this.terminalSize={width:80,height:24};return}let A=c08(process.stdout);if(A)this.terminalSize=A}handleKeyEvent(A){for(let Q of this.keyHandlers)Q(A)}handlePasteEvent(A){this.dispatchSyntheticPaste(A.text)}dispatchSyntheticPaste(A){let Q={type:"paste",text:P1A(A)};for(let B of this.pasteHandlers)B(Q)}handleOscEvent(A){if(A.data.startsWith("10;")&&this.queryParser){this.queryParser.processOsc10(A.data);return}if(A.data.startsWith("11;")&&this.queryParser){this.queryParser.processOsc11(A.data);return}if(A.data.startsWith("12;")&&this.queryParser){this.queryParser.processOsc12(A.data);return}if(A.data.startsWith("4;")&&this.queryParser){this.queryParser.processOsc4(A.data);return}if(A.data.startsWith("52;c;")){let Q=A.data.slice(5);if(Q&&Q!=="?")SF.handleOSC52Response(Q)}}createCapabilityPromise(){this.capabilityPromise=new Promise((A)=>{this.capabilityResolve=A})}startCapabilityDetection(){if(!this.tty.stdin||!_1A(this.tty.stdin)){if(this.capabilityResolve)this.capabilityResolve(null);return}if(this.queryParser=new DE0(this.options.queryOptions),process.env.TERM_PROGRAM==="Apple_Terminal"){let A=te({canRgb:!1});this.capabilities=A;let Q={type:"capability",capabilities:this.capabilities};this.renderer.updateCapabilities(this.capabilities);for(let B of this.capabilityHandlers)B(Q);if(this.capabilityResolve)this.capabilityResolve(A),this.capabilityResolve=null;return}if(process.platform==="win32"){this.startWindowsKittyProbe();return}this.sendCapabilityQueries(),this.startCapabilityTimeout()}finishInitialization(){if(!this.initialized||!this.queryParser||this.capabilities)return;if(this.capabilities=this.queryParser.getCapabilities(),this.capabilityTimeout)clearTimeout(this.capabilityTimeout),this.capabilityTimeout=null;let A={type:"capability",capabilities:this.capabilities};this.renderer.updateCapabilities(this.capabilities),jK0(this.capabilities.background);for(let Q of this.capabilityHandlers)Q(A);if(this.capabilityResolve)j.info("Terminal capabilities detected:",this.capabilities),this.capabilityResolve(this.capabilities),this.capabilityResolve=null;if(this.queryParser.shouldUsePixelMouse()){let Q=this.queryParser.getPixelDimensions();if(Q){let B=Q.pixelWidth/Q.columns,$=Q.pixelHeight/Q.rows;this.parser?.setSgrToMouseConverter((J)=>Pe(J,!0,B,$))}}if(this.capabilities.emojiWidth)this.enableEmojiWidth();if(this.capabilities.kittyKeyboard)this.enableKittyKeyboard();if(this.enableModifyOtherKeys(),this.enableInBandResize(),this.capabilities.colorPaletteNotifications)this.enableColorPaletteNotifications();SF.setCapabilities(this.capabilities)}sendCapabilityQueries(){if(!this.queryParser)return;for(let A of O1A){if(A.shouldSend&&!A.shouldSend())continue;if(process.stdout.write(A.sequence),A.description==="Query Kitty explicit width support")this.queryParser.markKittyWidthQuerySent()}}startCapabilityTimeout(){if(this.capabilityTimeout)clearTimeout(this.capabilityTimeout);this.capabilityTimeout=setTimeout(()=>{if(!this.capabilities&&this.capabilityResolve&&this.queryParser)this.finishInitialization()},2000)}startWindowsKittyProbe(){this.windowsKittyProbePending=!0,process.stdout.write(this.renderer.queryKittyKeyboard()),this.windowsKittyProbeTimeout=setTimeout(()=>{this.finishWindowsKittyProbe(!1)},p08)}handleWindowsKittyProbeResponse(A,Q){if(process.platform!=="win32"||!this.windowsKittyProbePending||A!=="u")return;this.finishWindowsKittyProbe(!0)}finishWindowsKittyProbe(A){if(!this.windowsKittyProbePending)return;if(this.windowsKittyProbePending=!1,this.windowsKittyProbeTimeout)clearTimeout(this.windowsKittyProbeTimeout),this.windowsKittyProbeTimeout=null;if(!A)this.tty.enableWindowsVirtualTerminalInput();this.sendCapabilityQueries(),this.startCapabilityTimeout()}parseXtgettcapResponse(A){if(!this.queryParser)return;let Q=A.indexOf("=");if(Q!==-1){let B=A.slice(0,Q),$=A.slice(Q+1);if(this.queryParser.processXtgettcap(B,$))this.finishInitialization()}}handleResize(){if(this.pendingResize=!0,this.resizeDebounceTimer)clearTimeout(this.resizeDebounceTimer);this.resizeDebounceTimer=setTimeout(()=>{this.processResize()},10)}handleInbandResize(A){if(this.terminalSize={width:A.width,height:A.height},this.queryParser&&A.pixelWidth&&A.pixelHeight){let Q=this.queryParser.shouldUsePixelMouse();this.queryParser.updateInbandPixelData(A.width,A.height,A.pixelWidth,A.pixelHeight);let B=this.queryParser.shouldUsePixelMouse();if(process.platform!=="win32"&&!Q&&B)this.disableMouse(),this.enableMouse();if(B){let $=A.pixelWidth/A.width,J=A.pixelHeight/A.height;this.parser?.setSgrToMouseConverter((Y)=>Pe(Y,!0,$,J))}}this.screen.resize(A.width,A.height),setImmediate(()=>{for(let Q of this.resizeHandlers)try{Q(A)}catch(B){j.error("Error in resize handler:",B)}})}processResize(){if(!this.pendingResize||!this.initialized)return;let A={...this.terminalSize};if(this.updateTerminalSize(),A.width===this.terminalSize.width&&A.height===this.terminalSize.height){this.pendingResize=!1;return}this.finishResize(),this.pendingResize=!1}finishResize(){this.screen.resize(this.terminalSize.width,this.terminalSize.height);let A={type:"resize",width:this.terminalSize.width,height:this.terminalSize.height};setImmediate(()=>{for(let Q of this.resizeHandlers)try{Q(A)}catch(B){j.error("Error in resize handler:",B)}})}setupCleanupHandlers(){process.setMaxListeners(0),process.on("SIGINT",this.boundCleanup),process.on("SIGTERM",this.boundCleanup),process.on("exit",this.boundExitCleanup),process.on("SIGCONT",this.boundHandleResume)}exitCleanup(){if(!this.initialized)return;let A=this.renderer.endSync(),Q=(this.capabilities?.kittyKeyboard?this.renderer.disableKittyKeyboard():"")+this.renderer.disableModifyOtherKeys();if(this.inAltScreen)A+=this.renderer.clearScreen()+Q+this.renderer.exitAltScreen(),Q="",this.inAltScreen=!1;if(A+=this.renderer.reset()+this.renderer.disableMouse()+this.renderer.disableEmojiWidth()+this.renderer.disableInBandResize()+this.renderer.disableBracketedPaste()+Q+this.renderer.setCursorShape(0)+this.renderer.showCursor(),this.capabilities?.colorPaletteNotifications)A+="\x1B[?2031l";if(this.capabilities?.xtversion?.startsWith("ghostty"))A+=this.renderer.setProgressBarOff();try{process.stdout.write(A)}catch{}this.tty.dispose(),this.initialized=!1}cleanup(){this.deinit().catch(()=>{})}}function _1A(A){return"isTTY"in A&&A.isTTY===!0&&typeof A.setRawMode==="function"}function c08(A){try{if(A._refreshSize?.(),A.isTTY&&A.columns&&A.rows)return{width:A.columns,height:A.rows};let Q=A.getWindowSize?.();if(Q&&Q[0]>0&&Q[1]>0)return{width:Q[0],height:Q[1]}}catch{}return null}i0();i0();var A00;((J)=>{J.BUILD="build";J.LAYOUT="layout";J.PAINT="paint";J.RENDER="render"})(A00||={});var l08=60,aK=1000/l08;function i08(){if(typeof process>"u")return!1;return process.env.BUN_TEST==="1"||process.env.VITEST==="true"||process.env.NODE_TEST_CONTEXT==="1"}class W6{static _instance;_frameCallbacks=new Map;_postFrameCallbacks=[];_frameScheduled=!1;_frameInProgress=!1;_executingPostFrameCallbacks=!1;_pendingFrameImmediate=null;_pendingFrameTimer=null;_lastFrameTimestamp=0;_useFramePacing=!i08();_stats={lastFrameTime:0,phaseStats:{["build"]:{lastTime:0},["layout"]:{lastTime:0},["paint"]:{lastTime:0},["render"]:{lastTime:0}}};_lastCompletedStats=this.deepCopyStats(this._stats);static get instance(){return W6._instance??=new W6}requestFrame(){if(this._frameScheduled)return;if(this._frameInProgress){this._frameScheduled=!0;return}if(!this._useFramePacing){this._frameScheduled=!0,this.scheduleFrameExecution(0);return}let A=performance.now(),Q=this._lastFrameTimestamp,B=A-Q;if(Q===0||B>=aK){this._frameScheduled=!0,this.scheduleFrameExecution(0);return}let $=Math.max(0,aK-B);this._frameScheduled=!0,this.scheduleFrameExecution($)}scheduleFrameExecution(A){if(A<=0){this._pendingFrameImmediate=setImmediate(()=>this.runScheduledFrame());return}this._pendingFrameTimer=setTimeout(()=>this.runScheduledFrame(),A)}runScheduledFrame(){if(this._pendingFrameImmediate)clearImmediate(this._pendingFrameImmediate),this._pendingFrameImmediate=null;if(this._pendingFrameTimer)clearTimeout(this._pendingFrameTimer),this._pendingFrameTimer=null;if(this._frameInProgress)return;this.executeFrame()}addFrameCallback(A,Q,B,$=0,J){this._frameCallbacks.set(A,{callback:Q,phase:B,priority:$,name:J||A})}removeFrameCallback(A){this._frameCallbacks.delete(A)}addPostFrameCallback(A,Q){if(this._postFrameCallbacks.push({callback:A,name:Q}),!this._frameScheduled&&(!this._frameInProgress||this._executingPostFrameCallbacks))this.requestFrame()}executeFrame(){if(this._frameInProgress)return;let A=performance.now();this._frameScheduled=!1,this._frameInProgress=!0;try{for(let Q of["build","layout","paint","render"])this.executePhase(Q);this.executePostFrameCallbacks()}catch(Q){j.error("Frame execution error:",Q instanceof Error?Q.message:String(Q))}finally{if(this.recordFrameStats(performance.now()-A),this._lastFrameTimestamp=A,this._lastCompletedStats=this.deepCopyStats(this._stats),this._frameInProgress=!1,this._frameScheduled){let B=performance.now()-this._lastFrameTimestamp,$=B>=aK?0:Math.max(0,aK-B);this.scheduleFrameExecution($)}}}executePhase(A){let Q=performance.now();try{let B=Array.from(this._frameCallbacks.values()).filter(($)=>$.phase===A).sort(($,J)=>$.priority-J.priority);for(let $ of B)try{$.callback()}catch(J){j.error(`Frame callback error in ${A} phase (${$.name})`,{errorMessage:J instanceof Error?J.message:String(J),errorType:J?.constructor?.name,stackTrace:J instanceof Error?J.stack:void 0}),O4(!1,`FATAL: ${A} error in ${$.name}: ${J}`)}}finally{let B=performance.now()-Q;this.recordPhaseStats(A,B)}}executePostFrameCallbacks(){if(this._postFrameCallbacks.length===0)return;let A=this._postFrameCallbacks.splice(0);this._executingPostFrameCallbacks=!0;try{for(let{callback:Q,name:B}of A)try{Q()}catch($){j.error(`Post-frame callback error (${B||"anonymous"}):`,$ instanceof Error?$.message:String($))}}finally{this._executingPostFrameCallbacks=!1}}recordFrameStats(A){this._stats.lastFrameTime=A}recordPhaseStats(A,Q){this._stats.phaseStats[A].lastTime=Q}get isFrameScheduled(){return this._frameScheduled||this._frameInProgress}get isFrameInProgress(){return this._frameInProgress}get frameStats(){return this.deepCopyStats(this._lastCompletedStats)}deepCopyStats(A){return{...A,phaseStats:{["build"]:{...A.phaseStats.build},["layout"]:{...A.phaseStats.layout},["paint"]:{...A.phaseStats.paint},["render"]:{...A.phaseStats.render}}}}resetStats(){this._stats={lastFrameTime:0,phaseStats:{["build"]:{lastTime:0},["layout"]:{lastTime:0},["paint"]:{lastTime:0},["render"]:{lastTime:0}}}}get pendingPostFrameCallbacks(){return this._postFrameCallbacks.length}cancelPendingWork(){let A=this._pendingFrameImmediate!==null;if(this._pendingFrameImmediate)clearImmediate(this._pendingFrameImmediate),this._pendingFrameImmediate=null;let Q=this._pendingFrameTimer!==null;if(this._pendingFrameTimer)clearTimeout(this._pendingFrameTimer),this._pendingFrameTimer=null;let B=this._postFrameCallbacks.length;this._postFrameCallbacks.length=0;let $=this._frameScheduled,J=this._frameInProgress;return this._frameScheduled=!1,{hadPendingImmediate:A,hadPendingTimer:Q,clearedPostFrameCallbacks:B,frameWasScheduled:$,frameInProgress:J}}dispose(){if(this._pendingFrameImmediate)clearImmediate(this._pendingFrameImmediate),this._pendingFrameImmediate=null;if(this._pendingFrameTimer)clearTimeout(this._pendingFrameTimer),this._pendingFrameTimer=null;this._frameCallbacks.clear(),this._postFrameCallbacks.length=0,this._frameScheduled=!1,this._frameInProgress=!1,this._lastFrameTimestamp=0,this.resetStats()}}class a31{_dirtyElements=new Set;_stats={totalRebuilds:0,elementsRebuiltThisFrame:0,maxElementsPerFrame:0,averageElementsPerFrame:0,lastBuildTime:0,averageBuildTime:0,maxBuildTime:0};_buildTimes=[];_elementsPerFrame=[];constructor(){}scheduleBuildFor(A){if(this._dirtyElements.has(A))return;this._dirtyElements.add(A),W6.instance.requestFrame()}buildScopes(){if(this._dirtyElements.size===0)return;let A=performance.now(),Q=0;try{while(this._dirtyElements.size>0){let B=Array.from(this._dirtyElements);this._dirtyElements.clear(),B.sort(($,J)=>$.depth-J.depth);for(let $ of B)if($.dirty)try{$.performRebuild(),$._dirty=!1,Q++}catch(J){j.error("Element rebuild error:",{error:J instanceof Error?J.message:String(J),stack:J instanceof Error?J.stack:void 0,elementType:$.widget.constructor.name,elementDebugLabel:$.widget.debugLabel}),$._dirty=!1}}}finally{this.recordBuildStats(performance.now()-A,Q)}}recordBuildStats(A,Q){if(this._stats.totalRebuilds+=Q,this._stats.elementsRebuiltThisFrame=Q,this._stats.lastBuildTime=A,this._stats.maxElementsPerFrame=Math.max(this._stats.maxElementsPerFrame,Q),this._stats.maxBuildTime=Math.max(this._stats.maxBuildTime,A),this._buildTimes.push(A),this._elementsPerFrame.push(Q),this._buildTimes.length>60)this._buildTimes.shift(),this._elementsPerFrame.shift();this._stats.averageBuildTime=this._buildTimes.reduce((B,$)=>B+$,0)/this._buildTimes.length,this._stats.averageElementsPerFrame=this._elementsPerFrame.reduce((B,$)=>B+$,0)/this._elementsPerFrame.length}get dirtyElements(){return Array.from(this._dirtyElements)}get hasDirtyElements(){return this._dirtyElements.size>0}get buildStats(){return{...this._stats}}resetBuildStats(){this._stats={totalRebuilds:0,elementsRebuiltThisFrame:0,maxElementsPerFrame:0,averageElementsPerFrame:0,lastBuildTime:0,averageBuildTime:0,maxBuildTime:0},this._buildTimes.length=0,this._elementsPerFrame.length=0}dispose(){this._dirtyElements.clear()}}function kF(A,Q){if(A.length===0)return 0;let B=[...A].sort((Y,Z)=>Y-Z),$=Math.max(0,Math.min(Q,1)),J=Math.ceil(B.length*$)-1;return B[Math.max(0,J)]||0}class S1A{frameTimes=[];phaseTimes={build:[],layout:[],paint:[],render:[]};keyEventTimes=[];mouseEventTimes=[];repaintPercents=[];bytesWritten=[];lastKeyEventTime=0;lastMouseEventTime=0;lastRepaintPercent=0;lastBytesWritten=0;MAX_SAMPLES=1024;recordFrame(A){if(this.frameTimes.push(A),this.frameTimes.length>this.MAX_SAMPLES)this.frameTimes.shift()}recordPhase(A,Q){let B=this.phaseTimes[A];if(B.push(Q),B.length>this.MAX_SAMPLES)B.shift()}recordKeyEvent(A){if(this.lastKeyEventTime=A,this.keyEventTimes.push(A),this.keyEventTimes.length>this.MAX_SAMPLES)this.keyEventTimes.shift()}recordMouseEvent(A){if(this.lastMouseEventTime=A,this.mouseEventTimes.push(A),this.mouseEventTimes.length>this.MAX_SAMPLES)this.mouseEventTimes.shift()}recordRepaintPercent(A){if(this.lastRepaintPercent=A,this.repaintPercents.push(A),this.repaintPercents.length>this.MAX_SAMPLES)this.repaintPercents.shift()}recordBytesWritten(A){if(this.lastBytesWritten=A,this.bytesWritten.push(A),this.bytesWritten.length>this.MAX_SAMPLES)this.bytesWritten.shift()}getFrameP99(){return kF(this.frameTimes,0.99)}getFrameP95(){return kF(this.frameTimes,0.95)}getPhaseP99(A){return kF(this.phaseTimes[A],0.99)}getPhaseP95(A){return kF(this.phaseTimes[A],0.95)}getLastKeyEventTime(){return this.lastKeyEventTime}getKeyEventP99(){return kF(this.keyEventTimes,0.99)}getKeyEventP95(){return kF(this.keyEventTimes,0.95)}getLastMouseEventTime(){return this.lastMouseEventTime}getMouseEventP99(){return kF(this.mouseEventTimes,0.99)}getMouseEventP95(){return kF(this.mouseEventTimes,0.95)}getLastRepaintPercent(){return this.lastRepaintPercent}getRepaintPercentP99(){return kF(this.repaintPercents,0.99)}getRepaintPercentP95(){return kF(this.repaintPercents,0.95)}getLastBytesWritten(){return this.lastBytesWritten}getBytesWrittenP99(){return kF(this.bytesWritten,0.99)}getBytesWrittenP95(){return kF(this.bytesWritten,0.95)}reset(){this.frameTimes=[];for(let A of Object.values(A00))this.phaseTimes[A]=[];this.keyEventTimes=[],this.mouseEventTimes=[],this.repaintPercents=[],this.bytesWritten=[],this.lastKeyEventTime=0,this.lastMouseEventTime=0,this.lastRepaintPercent=0,this.lastBytesWritten=0}}class o31{enabled=!1;tracker=new S1A;setEnabled(A){this.enabled=A}isEnabled(){return this.enabled}recordKeyEvent(A){this.tracker.recordKeyEvent(A)}recordMouseEvent(A){this.tracker.recordMouseEvent(A)}recordStats(A,Q){this.tracker.recordFrame(A.lastFrameTime);for(let B of Object.values(A00))this.tracker.recordPhase(B,A.phaseStats[B].lastTime);if(Q)this.tracker.recordRepaintPercent(Q.repaintedPercent),this.tracker.recordBytesWritten(Q.bytesWritten)}draw(A,Q){if(!this.enabled)return;let{width:B,height:$}=A.getSize(),J=34,Y=14,Z=B-J-2,X=1;if(Z<0||X+Y>=$)return;let F=C2.default().colorScheme,D=F.border,G=F.foreground,V=F.warning,U=" Gotta Go Fast ",K=Math.floor((J-U.length)/2);A.setCell(Z,X,EA("╭",{fg:G}));for(let j0=1;j0<J-1;j0++)if(j0>=K&&j0<K+U.length)A.setCell(Z+j0,X,EA(U[j0-K]||"─",{fg:V}));else A.setCell(Z+j0,X,EA("─",{fg:G}));A.setCell(Z+J-1,X,EA("╮",{fg:G}));for(let j0=1;j0<Y-1;j0++){A.setCell(Z,X+j0,EA("│",{fg:G})),A.setCell(Z+J-1,X+j0,EA("│",{fg:G}));for(let u0=1;u0<J-1;u0++)A.setCell(Z+u0,X+j0,EA(" ",{fg:G}))}A.setCell(Z,X+Y-1,EA("╰",{fg:G}));for(let j0=1;j0<J-1;j0++)A.setCell(Z+j0,X+Y-1,EA("─",{fg:G}));A.setCell(Z+J-1,X+Y-1,EA("╯",{fg:G}));let E=Z+1,H=X+1;this.drawText(A,E,H++," Last P95 P99",D);let W=this.tracker.getLastKeyEventTime(),z=this.tracker.getKeyEventP95(),q=this.tracker.getKeyEventP99(),N=W.toFixed(2).padStart(5," "),I=z.toFixed(2).padStart(5," "),w=q.toFixed(2).padStart(5," "),C=this.getTimingColor(W),O=this.getTimingColor(z),P=this.getTimingColor(q);this.drawLastP95P99Row(A,E,H++,{label:"Key",labelColor:D,last:{text:N,color:C},p95:{text:I,color:O},p99:{text:w,color:P}});let k=this.tracker.getLastMouseEventTime(),_=this.tracker.getMouseEventP95(),f=this.tracker.getMouseEventP99(),h=k.toFixed(2).padStart(5," "),b=_.toFixed(2).padStart(5," "),y=f.toFixed(2).padStart(5," "),u=this.getTimingColor(k),p=this.getTimingColor(_),d=this.getTimingColor(f);this.drawLastP95P99Row(A,E,H++,{label:"Mouse",labelColor:D,last:{text:h,color:u},p95:{text:b,color:p},p99:{text:y,color:d}}),H++;for(let j0 of["build","layout","paint","render"]){let u0=Q.phaseStats[j0].lastTime,E1=this.tracker.getPhaseP95(j0),W0=this.tracker.getPhaseP99(j0),T0=u0.toFixed(2).padStart(5," "),t0=E1.toFixed(2).padStart(5," "),s0=W0.toFixed(2).padStart(5," "),_0=this.getTimingColor(u0),d0=this.getTimingColor(E1),n0=this.getTimingColor(W0),U1=j0.charAt(0).toUpperCase()+j0.slice(1);this.drawLastP95P99Row(A,E,H++,{label:U1,labelColor:D,last:{text:T0,color:_0},p95:{text:t0,color:d0},p99:{text:s0,color:n0}})}H++;let g=Q.lastFrameTime,n=this.tracker.getFrameP95(),c=this.tracker.getFrameP99(),B0=g.toFixed(2).padStart(5," "),O0=n.toFixed(2).padStart(5," "),i=c.toFixed(2).padStart(5," "),Q0=this.getTimingColor(g),U0=this.getTimingColor(n),z0=this.getTimingColor(c);this.drawLastP95P99Row(A,E,H++,{label:"Frame",labelColor:G,last:{text:B0,color:Q0},p95:{text:O0,color:U0},p99:{text:i,color:z0}});let A0=this.tracker.getLastRepaintPercent(),J0=this.tracker.getRepaintPercentP95(),a=this.tracker.getRepaintPercentP99(),r=`${A0.toFixed(1)}%`.padStart(5," "),s=`${J0.toFixed(1)}%`.padStart(5," "),t=`${a.toFixed(1)}%`.padStart(5," "),Y0=this.getPercentColor(A0),D0=this.getPercentColor(J0),K0=this.getPercentColor(a);this.drawLastP95P99Row(A,E,H++,{label:"Repaint",labelColor:G,last:{text:r,color:Y0},p95:{text:s,color:D0},p99:{text:t,color:K0}});let H0=this.formatBytes(this.tracker.getLastBytesWritten()).padStart(5," "),R0=this.formatBytes(this.tracker.getBytesWrittenP95()).padStart(5," "),X0=this.formatBytes(this.tracker.getBytesWrittenP99()).padStart(5," ");this.drawLastP95P99Row(A,E,H,{label:"Bytes",labelColor:G,last:{text:H0,color:G},p95:{text:R0,color:G},p99:{text:X0,color:G}})}drawLastP95P99Row(A,Q,B,$){let J=` ${$.label.padStart(7," ")} `,Y=Q;this.drawText(A,Y,B,J,$.labelColor),Y+=J.length,this.drawText(A,Y,B,$.last.text,$.last.color),Y+=$.last.text.length,this.drawText(A,Y,B," ",$.labelColor),Y+=3,this.drawText(A,Y,B,$.p95.text,$.p95.color),Y+=$.p95.text.length,this.drawText(A,Y,B," ",$.labelColor),Y+=3,this.drawText(A,Y,B,$.p99.text,$.p99.color)}getTimingColor(A){let Q=C2.default().colorScheme,B=aK,$=aK*0.7;if(A>=B)return Q.destructive;if(A>=$)return Q.warning;return Q.foreground}getPercentColor(A){let Q=C2.default().colorScheme;if(A>=50)return Q.destructive;if(A>=20)return Q.warning;return Q.foreground}drawText(A,Q,B,$,J){for(let Y=0;Y<$.length;Y++)A.setCell(Q+Y,B,EA($[Y]||" ",{fg:J}))}formatBytes(A){if(A>=1e4)return`${Math.round(A/1000)}k`;if(A>=1000)return`${(A/1000).toFixed(1)}k`;return`${Math.round(A)}`}}class mu{size;capabilities;constructor(A,Q){this.size=A;this.capabilities=Q}get supportsEmojiWidth(){return this.capabilities.emojiWidth}get supportsSyncOutput(){return this.capabilities.syncOutput}}class J4 extends M6{data;constructor({key:A,data:Q,child:B}){super(A!==void 0?{key:A,child:B}:{child:B});this.data=Q}updateShouldNotify(A){return this.data!==A.data||this.data.size.width!==A.data.size.width||this.data.size.height!==A.data.size.height||this.data.capabilities!==A.data.capabilities}static of(A){let Q=A.dependOnInheritedWidgetOfExactType(J4);if(!Q)throw Error("MediaQuery not found in context. Wrap your app with MediaQuery widget.");return Q.data}static sizeOf(A){return J4.of(A).size}static capabilitiesOf(A){return J4.of(A).capabilities}}class r31{_nodesNeedingPaint=new Set;_rootRenderObject=null;_rootConstraints=null;constructor(){}requestLayout(A){if(!W6.instance.isFrameInProgress)W6.instance.requestFrame()}requestPaint(A){if(this._nodesNeedingPaint.has(A))return;if(this._nodesNeedingPaint.add(A),!W6.instance.isFrameInProgress)W6.instance.requestFrame()}setRootRenderObject(A){this._rootRenderObject=A}updateRootConstraints(A){let Q=new L1(0,A.width,0,A.height),B=!this._rootConstraints||this._rootConstraints.maxWidth!==Q.maxWidth||this._rootConstraints.maxHeight!==Q.maxHeight;if(this._rootConstraints=Q,B&&this._rootRenderObject&&"markNeedsLayout"in this._rootRenderObject)this._rootRenderObject.markNeedsLayout()}flushLayout(){let A=!1;if(this._rootRenderObject&&this._rootConstraints&&"needsLayout"in this._rootRenderObject&&this._rootRenderObject.needsLayout){if("layout"in this._rootRenderObject&&typeof this._rootRenderObject.layout==="function")this._rootRenderObject.layout(this._rootConstraints),A=!0}return A}flushPaint(){if(this._nodesNeedingPaint.size===0)return;try{for(let A of this._nodesNeedingPaint)if(A.needsPaint)A._needsPaint=!1}finally{this._nodesNeedingPaint.clear()}}get nodesNeedingLayout(){return[]}get nodesNeedingPaint(){return Array.from(this._nodesNeedingPaint)}get hasNodesNeedingLayout(){return Boolean(this._rootRenderObject&&this._rootRenderObject.needsLayout)}get hasNodesNeedingPaint(){return this._nodesNeedingPaint.size>0}dispose(){this._nodesNeedingPaint.clear()}removeFromQueues(A){this._nodesNeedingPaint.delete(A)}}class d4{static _instance;frameScheduler=W6.instance;buildOwner;pipelineOwner;focusManager=o3.instance;mouseManager=b8.instance;frameStatsOverlay=new o31;tui=new n31;rootElement;isRunning=!1;rootElementMountedCallback;forcePaintOnNextFrame=!1;shouldPaintCurrentFrame=!1;didPaintCurrentFrame=!1;eventCallbacks={key:[],mouse:[],paste:[]};keyInterceptors=[];rgbColorChangeCallbacks=[];cachedRgbColors=null;static get instance(){return d4._instance??=new d4}pendingResizeEvent=null;constructor(){this.buildOwner=new a31,this.pipelineOwner=new r31,this.frameScheduler.addFrameCallback("frame-start",()=>this.beginFrame(),"build",-2000,"WidgetsBinding.beginFrame"),this.frameScheduler.addFrameCallback("resize",()=>this.processResizeIfPending(),"build",-1000,"WidgetsBinding.processResizeIfPending"),this.frameScheduler.addFrameCallback("build",()=>{this.buildOwner.buildScopes(),this.updateRootRenderObject()},"build",0,"BuildOwner.buildScopes"),this.frameScheduler.addFrameCallback("layout",()=>{if(this.updateRootConstraints(),this.pipelineOwner.flushLayout())this.shouldPaintCurrentFrame=!0},"layout",0,"PipelineOwner.flushLayout"),this.frameScheduler.addFrameCallback("paint",()=>this.paint(),"paint",0,"WidgetsBinding.paint"),this.frameScheduler.addFrameCallback("render",()=>this.render(),"render",0,"WidgetsBinding.render"),Y0A({scheduleBuildFor:(A)=>this.buildOwner.scheduleBuildFor(A)},{requestLayout:(A)=>this.pipelineOwner.requestLayout(A),requestPaint:(A)=>this.pipelineOwner.requestPaint(A),removeFromQueues:(A)=>this.pipelineOwner.removeFromQueues(A)}),this.setupErrorHandler()}setupErrorHandler(){process.on("uncaughtException",(A)=>{j.error("Framework uncaught exception",A)})}getRgbColors(){return this.cachedRgbColors}onRgbColorsChanged(A){return this.rgbColorChangeCallbacks.push(A),()=>{let Q=this.rgbColorChangeCallbacks.indexOf(A);if(Q!==-1)this.rgbColorChangeCallbacks.splice(Q,1)}}notifyRgbColorsChanged(){for(let A of this.rgbColorChangeCallbacks)A()}updateRgbColors(A){this.cachedRgbColors=A;let Q=this.tui.getScreen();Q.setDefaultColors({type:"rgb",value:A.bg},{type:"rgb",value:A.fg}),Q.setIndexRgbMapping(A.indices),jK0(nw(),A.bg),this.notifyRgbColorsChanged(),this.requestForcedPaintFrame()}async runApp(A){if(this.isRunning)throw Error("App is already running");try{this.isRunning=!0,this.tui.init(),this.tui.enterAltScreen();let{initFocusTracking:Q}=await Promise.resolve().then(() => v1A);Q(this.tui);let{initIdleTracking:B}=await Promise.resolve().then(() => (UE0(),x1A));B(this.tui),await this.tui.waitForCapabilities(1000);let $=this.tui.getQueryParser(),J=$?.getRgbColors();if(j.info("Initial RGB colors from terminal",{available:!!J}),J)this.updateRgbColors(J);if($)$.setColorPaletteChangeCallback(()=>{let X=$.getRgbColors();if(X)this.updateRgbColors(X)});let Y=this.createMediaQueryWrapper(A);if(this.rootElement=Y.createElement(),this.rootElement.mount(),this.rootElementMountedCallback)this.rootElementMountedCallback(this.rootElement);let Z=this.rootElement.renderObject;if(!Z&&this.rootElement.children.length>0)Z=this.rootElement.children[0]?.renderObject;if(Z)this.pipelineOwner.setRootRenderObject(Z),this.updateRootConstraints();if(this.rootElement.renderObject)this.mouseManager.setRootRenderObject(this.rootElement.renderObject);this.mouseManager.setTui(this.tui),j.debug("Setting up event handlers..."),this.setupEventHandlers(),j.debug("Requesting initial frame..."),this.frameScheduler.requestFrame(),j.debug("Waiting for exit...",{isRunning:this.isRunning}),await this.waitForExit(),j.debug("waitForExit completed")}finally{j.debug("Cleaning up..."),await this.cleanup()}}stop(){if(this.isRunning=!1,this.exitResolve)this.exitResolve(),this.exitResolve=null}updateRootConstraints(){let A=this.tui.getSize();this.pipelineOwner.updateRootConstraints(A)}updateRootRenderObject(){if(!this.rootElement)return;let A=this.rootElement.renderObject;if(!A&&this.rootElement.children.length>0)A=this.rootElement.children[0]?.renderObject;if(A)this.pipelineOwner.setRootRenderObject(A),this.mouseManager.setRootRenderObject(A)}processResizeIfPending(){if(!this.pendingResizeEvent)return;let A=this.pendingResizeEvent;if(this.pendingResizeEvent=null,this.rootElement){let Q={width:A.width,height:A.height},B=this.tui.getCapabilities()||te(),$=new mu(Q,B),J=this.rootElement;if(J.widget instanceof J4){let Z=new J4({data:$,child:J.widget.child});J.update(Z)}this.tui.getScreen().markForRefresh(),this.pipelineOwner.updateRootConstraints(Q),this.rootElement.markNeedsRebuild(),this.frameScheduler.requestFrame(),this.frameScheduler.addPostFrameCallback(()=>{this.mouseManager.reestablishHoverState()},"MouseManager.reestablishHoverState")}}beginFrame(){this.didPaintCurrentFrame=!1,this.shouldPaintCurrentFrame=this.forcePaintOnNextFrame||this.buildOwner.hasDirtyElements||this.pipelineOwner.hasNodesNeedingLayout||this.pipelineOwner.hasNodesNeedingPaint||this.tui.getScreen().requiresFullRefresh,this.forcePaintOnNextFrame=!1}requestForcedPaintFrame(){this.forcePaintOnNextFrame=!0,this.frameScheduler.requestFrame()}paint(){if(!this.shouldPaintCurrentFrame)return;if(this.pipelineOwner.flushPaint(),!this.rootElement)return;let A=this.rootElement.renderObject;if(!A&&this.rootElement.children.length>0)A=this.rootElement.children[0]?.renderObject;if(!A)return;try{let Q=this.tui.getScreen();Q.clear(),Q.clearCursor(),this.renderRenderObject(A,Q,0,0);let B=this.frameScheduler.frameStats;this.frameStatsOverlay.recordStats(B,this.tui.getLastRenderDiffStats()),this.frameStatsOverlay.draw(Q,B),this.didPaintCurrentFrame=!0}catch(Q){j.error("Paint error:",Q)}}render(){if(!this.didPaintCurrentFrame)return;try{this.tui.render()}catch(A){j.error("Render error:",A)}}renderRenderObject(A,Q,B,$){if("paint"in A&&typeof A.paint==="function")A.paint(Q,B,$)}createMediaQueryWrapper(A){let Q=this.tui.getCapabilities()||te(),B=this.tui.getSize(),$=new mu(B,Q);return new J4({data:$,child:A})}setupEventHandlers(){this.tui.onResize((A)=>{this.mouseManager.clearHoverState(),this.pendingResizeEvent=A,this.frameScheduler.requestFrame()}),this.tui.onKey((A)=>{let Q=performance.now();for(let J of this.eventCallbacks.key)J(A);for(let J of this.keyInterceptors)if(J(A)){let Y=performance.now()-Q;this.frameStatsOverlay.recordKeyEvent(Y);return}if(this.focusManager.handleKeyEvent(A)){let J=performance.now()-Q;this.frameStatsOverlay.recordKeyEvent(J);return}this.handleGlobalKeyEvent(A);let $=performance.now()-Q;this.frameStatsOverlay.recordKeyEvent($)}),this.tui.onMouse((A)=>{let Q=performance.now();for(let $ of this.eventCallbacks.mouse)$(A);this.mouseManager.handleMouseEvent(A);let B=performance.now()-Q;this.frameStatsOverlay.recordMouseEvent(B)}),this.tui.onPaste((A)=>{for(let Q of this.eventCallbacks.paste)Q(A);this.focusManager.handlePasteEvent(A)}),this.tui.onCapabilities((A)=>{if(this.rootElement){let Q=this.tui.getSize(),B=new mu(Q,A.capabilities),$=this.rootElement;if($.widget instanceof J4){let J=new J4({data:B,child:$.widget.child});$.update(J)}this.rootElement.markNeedsRebuild(),this.frameScheduler.requestFrame()}})}handleGlobalKeyEvent(A){if(A.ctrlKey&&A.key==="z"&&!A.shiftKey&&!A.altKey&&!A.metaKey){this.tui.handleSuspend();return}}toggleFrameStatsOverlay(){let A=!this.frameStatsOverlay.isEnabled();this.frameStatsOverlay.setEnabled(A),this.requestForcedPaintFrame()}exitPromise=null;exitResolve=null;async waitForExit(){if(this.exitPromise!==null)return this.exitPromise;return this.exitPromise=new Promise((A)=>{if(this.exitResolve=A,!this.isRunning)A()}),this.exitPromise}async cleanup(){if(this.isRunning=!1,this.rootElement)this.rootElement.unmount(),this.rootElement=void 0;this.buildOwner.dispose(),this.pipelineOwner.dispose(),this.focusManager.dispose(),this.mouseManager.dispose(),this.frameScheduler.cancelPendingWork(),this.frameScheduler.removeFrameCallback("frame-start"),this.frameScheduler.removeFrameCallback("resize"),this.frameScheduler.removeFrameCallback("build"),this.frameScheduler.removeFrameCallback("layout"),this.frameScheduler.removeFrameCallback("paint"),this.frameScheduler.removeFrameCallback("render"),await this.tui.deinit()}get tuiInstance(){return this.tui}get rootElementInstance(){return this.rootElement}setRootElementMountedCallback(A){this.rootElementMountedCallback=A}on(A,Q){let B=this.eventCallbacks[A];return B.push(Q),()=>{let $=B.indexOf(Q);if($!==-1)B.splice($,1)}}dispatchSyntheticPaste(A){this.tui.dispatchSyntheticPaste(A)}addKeyInterceptor(A){return this.keyInterceptors.push(A),()=>{let Q=this.keyInterceptors.indexOf(A);if(Q!==-1)this.keyInterceptors.splice(Q,1)}}}async function B00(A,Q){let B=d4.instance;if(Q?.onRootElementMounted)B.setRootElementMountedCallback(Q.onRootElementMounted);await B.runApp(A)}class M1 extends wB{createElement(){return new s31(this)}}class s31 extends _Z{_child;_context;constructor(A){super(A)}get child(){return this._child}get renderObject(){return this._child?.renderObject}mount(){this._context=new cG(this,this.widget),this.rebuild(),this.markMounted()}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;this._context=void 0,super.unmount()}update(A){if(this.widget===A)return;if(super.update(A),this._context)this._context.widget=A;this.rebuild()}performRebuild(){this.rebuild()}rebuild(){if(!this._context)throw Error("Cannot rebuild unmounted element");let A=this.widget.build(this._context);if(this._child){if(this._child.widget===A)return;if(this._child.widget.canUpdate(A))this._child.update(A);else{let Q=this._child,B=this.findNearestRenderObjectAncestor();if(B&&Q.renderObject)B.dropChild(Q.renderObject);else if(!B&&Q.renderObject)Q.renderObject.detach();if(this._child.unmount(),this.removeChild(this._child),this._child=A.createElement(),this.addChild(this._child),this._child.mount(),B&&this._child.renderObject)B.adoptChild(this._child.renderObject),this._child.renderObject.markNeedsLayout();else if(!B&&this._child.renderObject)this._child.renderObject.attach(),this._child.renderObject.markNeedsLayout();if(this._child.renderObject)this._child.renderObject.markNeedsLayout()}}else this._child=A.createElement(),this.addChild(this._child),this._child.mount()}findNearestRenderObjectAncestor(){let A=this.parent;while(A){if(A.renderObject){if(this._child?.renderObject&&A.renderObject===this._child.renderObject){A=A.parent;continue}return A.renderObject}A=A.parent}return}}class kZ extends M6{forceDim;constructor({key:A,forceDim:Q,child:B}){super({key:A,child:B});this.forceDim=Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(kZ)}static shouldForceDim(A){return kZ.maybeOf(A)?.forceDim??!1}updateShouldNotify(A){return this.forceDim!==A.forceDim}}class oK extends M6{controller;constructor({key:A,controller:Q,child:B}){super({key:A,child:B});this.controller=Q}static of(A){return A.dependOnInheritedWidgetOfExactType(oK)?.controller??null}static require(A){let Q=oK.of(A);if(!Q)throw Error(`InheritedSelectionArea.require() called with a context that does not contain an InheritedSelectionArea.
|
|
5044
5044
|
No InheritedSelectionArea ancestor could be found starting from the given context. This can happen if the context comes from a widget above the SelectionArea.
|
|
5045
5045
|
The context used was: `+A.widget.constructor.name);return Q}updateShouldNotify(A){return this.controller!==A.controller}}var f1A={left:1,top:1,right:0,bottom:0};function b1A(A,Q,B){if(A.selectableId===Q.selectableId)return A.offset-Q.offset;return B(A.selectableId,Q.selectableId)}class x{color;backgroundColor;bold;italic;underline;strikethrough;dim;constructor({color:A,backgroundColor:Q,bold:B,italic:$,underline:J,strikethrough:Y,dim:Z}={}){if(A!==void 0)this.color=A;if(Q!==void 0)this.backgroundColor=Q;if(B!==void 0)this.bold=B;if($!==void 0)this.italic=$;if(J!==void 0)this.underline=J;if(Y!==void 0)this.strikethrough=Y;if(Z!==void 0)this.dim=Z}copyWith({color:A,backgroundColor:Q,bold:B,italic:$,underline:J,strikethrough:Y,dim:Z}){let X={};if(A!==void 0||this.color!==void 0)X.color=A??this.color;if(Q!==void 0||this.backgroundColor!==void 0)X.backgroundColor=Q??this.backgroundColor;if(B!==void 0||this.bold!==void 0)X.bold=B??this.bold;if($!==void 0||this.italic!==void 0)X.italic=$??this.italic;if(J!==void 0||this.underline!==void 0)X.underline=J??this.underline;if(Y!==void 0||this.strikethrough!==void 0)X.strikethrough=Y??this.strikethrough;if(Z!==void 0||this.dim!==void 0)X.dim=Z??this.dim;return new x(X)}merge(A){if(!A)return this;let Q={};if(A.color!==void 0||this.color!==void 0)Q.color=A.color??this.color;if(A.backgroundColor!==void 0||this.backgroundColor!==void 0)Q.backgroundColor=A.backgroundColor??this.backgroundColor;if(A.bold!==void 0||this.bold!==void 0)Q.bold=A.bold??this.bold;if(A.italic!==void 0||this.italic!==void 0)Q.italic=A.italic??this.italic;if(A.underline!==void 0||this.underline!==void 0)Q.underline=A.underline??this.underline;if(A.strikethrough!==void 0||this.strikethrough!==void 0)Q.strikethrough=A.strikethrough??this.strikethrough;if(A.dim!==void 0||this.dim!==void 0)Q.dim=A.dim??this.dim;return new x(Q)}static normal(A){return A?new x({color:A}):new x}static bold(A){return A?new x({color:A,bold:!0}):new x({bold:!0})}static italic(A){return A?new x({color:A,italic:!0}):new x({italic:!0})}static underline(A){return A?new x({color:A,underline:!0}):new x({underline:!0})}static colored(A){return new x({color:A})}static background(A){return new x({backgroundColor:A})}}class M{text;style;children;hyperlink;onClick;constructor(A,Q,B,$,J){this.text=A;this.style=Q;this.children=B;this.hyperlink=$;this.onClick=J}toPlainText(){let A=this.text??"";if(this.children)for(let Q of this.children)A+=Q.toPlainText();return String(A)}equals(A){if(!A)return!1;if(this.text!==A.text)return!1;if(this.hyperlink?.uri!==A.hyperlink?.uri)return!1;if(this.style!==A.style){if(!this.style||!A.style)return!1;if(this.style.color!==A.style.color)return!1;if(this.style.backgroundColor!==A.style.backgroundColor)return!1;if(this.style.bold!==A.style.bold)return!1;if(this.style.italic!==A.style.italic)return!1;if(this.style.underline!==A.style.underline)return!1}if(this.children?.length!==A.children?.length)return!1;if(this.children&&A.children)for(let Q=0;Q<this.children.length;Q++){let B=this.children[Q],$=A.children[Q];if(!B||!$||!B.equals($))return!1}return!0}visitTextSpan(A){if(!A(this))return;if(this.children)for(let Q of this.children)Q.visitTextSpan(A)}}function u1A(A){let Q=A.text?.replace(/\r/g,""),B=A.children?.map(($)=>u1A($));return new M(Q,A.style,B,A.hyperlink,A.onClick)}class l extends a3{text;textAlign;maxLines;overflow;selectable;constructor({key:A,text:Q,textAlign:B="left",maxLines:$,overflow:J="clip",selectable:Y=!1}){super(A?{key:A}:{});this.text=u1A(Q),this.textAlign=B,this.maxLines=$,this.overflow=J,this.selectable=Y,this.sendDebugData({text:Q})}static spans(A){return new l({text:new M("",void 0,A)})}createElement(){return new h1A(this)}createRenderObject(){return new g1A(this.text,this.textAlign,this.maxLines,this.overflow,!1,q0.index(8),q0.yellow,this.selectable)}updateRenderObject(A){}}class h1A extends CB{constructor(A){super(A)}get richTextWidget(){return this.widget}mount(){super.mount(),this._updateRenderObjectWithMediaQuery()}performRebuild(){super.performRebuild(),setTimeout(()=>this._ensureRenderObjectContext(),0)}_ensureRenderObjectContext(){if(!this.renderObject)return;let A=this.renderObject,Q=new cG(this,this.widget);A.setContext(Q)}update(A){super.update(A),this._updateRenderObjectWithMediaQuery()}_updateRenderObjectWithMediaQuery(){if(!this.renderObject)return;try{let A=new cG(this,this.widget),Q=J4.of(A),B=S1.maybeOf(A),$=B?.colorScheme.selection??q0.index(8),J=B?.colorScheme.copyHighlight??q0.yellow,Y=this.renderObject;Y.setContext(A),Y.updateText(this.richTextWidget.text,this.richTextWidget.textAlign,this.richTextWidget.maxLines,this.richTextWidget.overflow,Q.supportsEmojiWidth,$,J,this.richTextWidget.selectable)}catch(A){let Q=new cG(this,this.widget),B=this.renderObject;B.setContext(Q),B.updateText(this.richTextWidget.text,this.richTextWidget.textAlign,this.richTextWidget.maxLines,this.richTextWidget.overflow,!1,q0.index(8),q0.yellow,this.richTextWidget.selectable)}}}class g1A extends V4{_text;_textAlign;_maxLines;_overflow;_emojiWidthSupported;_selectable;selectableId=0;_selectionArea;_selectedRanges=[];set selectionArea(A){this._selectionArea=A}get selectionArea(){return this._selectionArea}_cachedStyledCells;_selectionStart=null;_selectionEnd=null;_characterPositions=[];_visualLines=[];_selectionColor=q0.index(8);_copyHighlightColor=q0.yellow;_highlightMode="selection";_hasTappableSpans=!1;_context;constructor(A,Q,B,$="clip",J=!1,Y=q0.index(8),Z=q0.yellow,X=!1){super();this._text=A;this._textAlign=Q;this._maxLines=B;this._overflow=$;this._emojiWidthSupported=J;this._selectable=X;this._selectionColor=Y,this._copyHighlightColor=Z,this._hasTappableSpans=this.hasAnyTappableSpans()}get text(){return this._text}get textAlign(){return this._textAlign}get maxLines(){return this._maxLines}get overflow(){return this._overflow}get hasMouseListeners(){return this._hasTappableSpans}handleMouseEvent(A){if(!this._hasTappableSpans)return;switch(A.type){case"hover":{if(this.getOnClickAtPosition(A.localPosition.x,A.localPosition.y))b8.instance.requestCursorChange(_5.POINTER);else b8.instance.requestCursorChange(_5.DEFAULT);break}case"exit":b8.instance.requestCursorChange(_5.DEFAULT);break;case"click":{let Q=this.getOnClickAtPosition(A.localPosition.x,A.localPosition.y);if(Q)Q();break}}}updateSelection(A,Q,B="selection"){if(this._selectionStart!==A||this._selectionEnd!==Q||this._highlightMode!==B)this._selectionStart=A,this._selectionEnd=Q,this._highlightMode=B,this.markNeedsPaint()}setHighlightMode(A){if(this._highlightMode!==A)this._highlightMode=A,this.markNeedsPaint()}get plainText(){return this._text.toPlainText()}getCharacterRect(A){if(A<0||A>=this._characterPositions.length)return null;let Q=this._characterPositions[A];if(!Q)return null;return{x:Q.x,y:Q.y,width:Q.width,height:1}}getOffsetForPosition(A,Q){if(this._characterPositions.length===0)return null;let B=Math.round(A),$=Math.floor(Q),J=1/0,Y=1/0,Z=-1/0,X=-1/0;for(let G of this._characterPositions)J=Math.min(J,G.x),Y=Math.min(Y,G.y),Z=Math.max(Z,G.x+G.width),X=Math.max(X,G.y+1);if(B<J||B>=Z||$<Y||$>=X)return null;for(let G=0;G<this._characterPositions.length;G++){let V=this._characterPositions[G];if(!V)continue;if(B>=V.x&&B<V.x+V.width&&$>=V.y&&$<V.y+1)return G}for(let G=0;G<this._characterPositions.length;G++){let V=this._characterPositions[G];if(!V)continue;if($>=V.y&&$<V.y+1){if(B<V.x)return G;if(G===this._characterPositions.length-1||this._characterPositions[G+1]&&this._characterPositions[G+1].y>V.y){if(B>=V.x+V.width)return G+1}}}let F=0,D=1/0;for(let G=0;G<this._characterPositions.length;G++){let V=this._characterPositions[G];if(!V)continue;let U=Math.abs($-V.y)+Math.abs(B-V.x);if(U<D)D=U,F=G}return F}getVisualLines(){return this._visualLines}getRenderableCharacterCount(){return this._characterPositions.length}getHyperlinkAtPosition(A,Q){let B=this.getOffsetForPosition(A,Q);if(B===null)return null;return this.getCachedStyledCells()[B]?.hyperlink?.uri??null}getOnClickAtPosition(A,Q){let B=this.getOffsetForPosition(A,Q);if(B===null)return null;let $=0,J=(Z)=>{if(Z.text){let X=_F(Z.text);if(B>=$&&B<$+X)return{found:!0,onClick:Z.onClick??null};$+=X}if(Z.children)for(let X of Z.children){let F=J(X);if(F.found)return F}return{found:!1}},Y=J(this._text);return Y.found?Y.onClick:null}hasAnyTappableSpans(){let A=(Q)=>{if(Q.onClick)return!0;if(Q.children){for(let B of Q.children)if(A(B))return!0}return!1};return A(this._text)}updateText(A,Q,B,$="clip",J=!1,Y=q0.index(8),Z=q0.yellow,X=!1){this._text=A,this._textAlign=Q,this._maxLines=B,this._overflow=$,this._emojiWidthSupported=J,this._selectionColor=Y,this._copyHighlightColor=Z,this._selectable=X,this._hasTappableSpans=this.hasAnyTappableSpans(),this._cachedStyledCells=void 0,this._characterPositions=[],this._visualLines=[],this._cachedStyledCells=this.getStyledCells(),this.markNeedsLayout(),this.markNeedsPaint()}getStyledCells(){let A=[],Q=this._context?S1.of(this._context).colorScheme.foreground:q0.default(),B=this.getStyledSegments(this._text,new x({color:Q})),$=this._context?kZ.shouldForceDim(this._context):!1;for(let J of B){let Y=a4(J.text);for(let Z of Y){let X=s6(Z,this._emojiWidthSupported),F={};if(J.style.color)F.fg=J.style.color;if(J.style.backgroundColor)F.bg=J.style.backgroundColor;if(J.style.bold)F.bold=J.style.bold;if(J.style.italic)F.italic=J.style.italic;if(J.style.underline)F.underline=J.style.underline;if(J.style.strikethrough)F.strikethrough=J.style.strikethrough;if(J.style.dim||$)F.dim=!0;A.push(EA(Z,F,X,J.hyperlink))}}return A}getCachedStyledCells(){return this._cachedStyledCells??this.getStyledCells()}getTotalCellsWidth(A){let Q=0;for(let B of A)Q+=B.width;return Q}wrapCells(A,Q){if(Q===1/0)return this.handleExplicitLineBreaksInCells(A);let B=[],$=[],J=0,Y=0;while(Y<A.length){let Z=A[Y];if(!Z){Y++;continue}if(Z.char===`
|
|
@@ -5286,7 +5286,7 @@ Ctrl-X, Y, Z to unlock`;if(E){let B0=G.text.replace(/`([^`]+)`/g,"$1")+`
|
|
|
5286
5286
|
* MIT Licence
|
|
5287
5287
|
*/var Sh=9000000000000000,fC=1e9,J$1="0123456789abcdef",zW0="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",qW0="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Y$1={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Sh,maxE:Sh,crypto:!1},YBA,Iz,Q6=!0,IW0="[DecimalError] ",xC=IW0+"Invalid argument: ",ZBA=IW0+"Precision limit exceeded",XBA=IW0+"crypto unavailable",FBA="[object Decimal]",_B=Math.floor,X7=Math.pow,hY8=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,gY8=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,mY8=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,DBA=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,QV=1e7,gA=7,pY8=9007199254740991,dY8=zW0.length-1,Z$1=qW0.length-1,c1={toStringTag:FBA};c1.absoluteValue=c1.abs=function(){var A=new this.constructor(this);if(A.s<0)A.s=1;return qA(A)};c1.ceil=function(){return qA(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())+gA,$.rounding=1,B=cY8($,EBA($,B)),$.precision=A,$.rounding=Q,qA(Iz==2||Iz==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(qA(X,A+1,0),X.times(X).times(X).eq(G)){$=X;break}}Z+=4,J=1}else{if(!+B||!+B.slice(1)&&B.charAt(0)=="5")qA($,A+1,1),Q=!$.times($).times($).eq(G);break}return Q6=!0,qA($,A,V.rounding,Q)};c1.decimalPlaces=c1.dp=function(){var A,Q=this.d,B=NaN;if(Q){if(A=Q.length-1,B=(A-_B(this.e/gA))*gA,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 qA(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 qA(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 qA(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,qA(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()?FE(Q,$,J):new Q(0):new Q(NaN);if(A.isZero())return FE(Q,$+4,J).times(0.5);return Q.precision=$+6,Q.rounding=1,A=new Q(1).minus(A).div(A.plus(1)).sqrt().atan(),Q.precision=$,Q.rounding=J,A.times(2)};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 qA(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=FE(Y,B+4,$).times(0.5),A.s=J.s,A;return new Y(NaN)}return Y.precision=B+6,Y.rounding=1,J=J.div(new Y(1).minus(J.times(J)).sqrt().plus(1)).atan(),Y.precision=B,Y.rounding=$,J.times(2)};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<=Z$1)return Z=FE(G,V+4,U).times(0.5),Z.s=D.s,Z}else if(D.isZero())return new G(D);else if(D.abs().eq(1)&&V+4<=Z$1)return Z=FE(G,V+4,U).times(0.25),Z.s=D.s,Z;G.precision=X=V+10,G.rounding=1,B=Math.min(28,X/gA+2|0);for(A=B;A;--A)D=D.div(D.times(D).plus(1).sqrt().plus(1));Q6=!1,Q=Math.ceil(X/gA),$=1,F=D.times(D),Z=new G(D),J=D;for(;A!==-1;)if(J=J.times(F),Y=Z.minus(J.div($+=2)),J=J.times(F),Z=Y.plus(J.div($+=2)),Z.d[Q]!==void 0)for(A=Q;Z.d[A]===Y.d[A]&&A--;);if(B)Z=Z.times(2<<B-1);return Q6=!0,qA(Z,G.precision=V,G.rounding=U,!0)};c1.isFinite=function(){return!!this.d};c1.isInteger=c1.isInt=function(){return!!this.d&&_B(this.e/gA)>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),j10(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=qA(F,V+1,0);break}while(j10(F.d,J+=10,U));return Q6=!0,qA(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?qA(A,X,F):A}if(B=_B(A.e/gA),G=_B(K.e/gA),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/gA),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?qA(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 qA(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 X$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,qA(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?qA(A,X,F):A}if(Y=_B(V.e/gA),$=_B(A.e/gA),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/gA),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?qA(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=GBA(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 qA(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())+gA,$.rounding=1,B=iY8($,EBA($,B)),$.precision=A,$.rounding=Q,qA(Iz>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(qA(Y,F+1,0),Y.times(Y).eq(Z)){$=Y;break}}B+=4,J=1}else{if(!+Q||!+Q.slice(1)&&Q.charAt(0)=="5")qA($,F+1,1),A=!$.times($).eq(Z);break}return Q6=!0,qA($,F,G.rounding,A)};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,qA(Iz==2||Iz==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/gA)+_B(A.e/gA),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?qA(A,V.precision,V.rounding):A};c1.toBinary=function(A,Q){return F$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(BY(A,0,fC),Q===void 0)Q=$.rounding;else BY(Q,0,8);return qA(B,A+B.e+1,Q)};c1.toExponential=function(A,Q){var B,$=this,J=$.constructor;if(A===void 0)B=DE($,!0);else{if(BY(A,0,fC),Q===void 0)Q=J.rounding;else BY(Q,0,8);$=qA(new J($),A+1,Q),B=DE($,!0,A+1)}return $.isNeg()&&!$.isZero()?"-"+B:B};c1.toFixed=function(A,Q){var B,$,J=this,Y=J.constructor;if(A===void 0)B=DE(J);else{if(BY(A,0,fC),Q===void 0)Q=Y.rounding;else BY(Q,0,8);$=qA(new Y(J),A+J.e+1,Q),B=DE($,!1,A+$.e+1)}return J.isNeg()&&!J.isZero()?"-"+B:B};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=GBA(E)-K.e-1,Z=Y%gA,Q.d[0]=X7(10,Z<0?gA+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*gA*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 F$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 BY(Q,0,8);if(!B.d)return A.s?B:A;if(!A.d){if(A.s)A.s=B.s;return A}}if(A.d[0])Q6=!1,B=u8(B,A,0,Q,1).times(A),Q6=!0,qA(B);else A.s=B.s,B=A;return B};c1.toNumber=function(){return+this};c1.toOctal=function(A,Q){return F$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 qA(X,$,Y);if(Q=_B(A.e/gA),Q>=A.d.length-1&&(B=D<0?-D:D)<=pY8)return J=VBA(F,X,B,$),A.s<0?new F(1).div(J):qA(J,$,Y);if(Z=X.s,Z<0){if(Q<A.d.length-1)return new F(NaN);if((A.d[Q]&1)==0)Z=1;if(X.e==0&&X.d[0]==1&&X.d.length==1)return X.s=Z,X}if(B=X7(+X,D),Q=B==0||!isFinite(B)?_B(D*(Math.log("0."+yQ(X.d))/Math.LN10+X.e+1)):new F(B+"").e,Q>F.maxE+1||Q<F.minE-1)return new F(Q>0?Z/0:0);if(Q6=!1,F.rounding=X.s=1,B=Math.min(12,(Q+"").length),J=X$1(A.times(yC(X,$+B)),$),J.d){if(J=qA(J,$+5,1),j10(J.d,$,Y)){if(Q=$+10,J=qA(X$1(A.times(yC(X,Q+B)),Q),Q+5,1),+yQ(J.d).slice($+1,$+15)+1==100000000000000)J=qA(J,$+1,0)}}return J.s=Z,Q6=!0,F.rounding=Y,qA(J,$,Y)};c1.toPrecision=function(A,Q){var B,$=this,J=$.constructor;if(A===void 0)B=DE($,$.e<=J.toExpNeg||$.e>=J.toExpPos);else{if(BY(A,1,fC),Q===void 0)Q=J.rounding;else BY(Q,0,8);$=qA(new J($),A,Q),B=DE($,A<=$.e||$.e<=J.toExpNeg,A)}return $.isNeg()&&!$.isZero()?"-"+B:B};c1.toSignificantDigits=c1.toSD=function(A,Q){var B=this,$=B.constructor;if(A===void 0)A=$.precision,Q=$.rounding;else if(BY(A,1,fC),Q===void 0)Q=$.rounding;else BY(Q,0,8);return qA(new $(B),A,Q)};c1.toString=function(){var A=this,Q=A.constructor,B=DE(A,A.e<=Q.toExpNeg||A.e>=Q.toExpPos);return A.isNeg()&&!A.isZero()?"-"+B:B};c1.truncated=c1.trunc=function(){return qA(new this.constructor(this),this.e+1,1)};c1.valueOf=c1.toJSON=function(){var A=this,Q=A.constructor,B=DE(A,A.e<=Q.toExpNeg||A.e>=Q.toExpPos);return A.isNeg()?"-"+B:B};function yQ(A){var Q,B,$,J=A.length-1,Y="",Z=A[0];if(J>0){Y+=Z;for(Q=1;Q<J;Q++){if($=A[Q]+"",B=gA-$.length,B)Y+=vC(B);Y+=$}if(Z=A[Q],$=Z+"",B=gA-$.length,B)Y+=vC(B)}else if(Z===0)return"0";for(;Z%10===0;)Z/=10;return Y+Z}function BY(A,Q,B){if(A!==~~A||A<Q||A>B)throw Error(xC+A)}function j10(A,Q,B,$){var J,Y,Z,X;for(Y=A[0];Y>=10;Y/=10)--Q;if(--Q<0)Q+=gA,J=0;else J=Math.ceil((Q+1)/gA),Q%=gA;if(Y=X7(10,gA-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]+=J$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 cY8(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,_,f,h,b=$.constructor,y=$.s==J.s?1:-1,u=$.d,p=J.d;if(!u||!u[0]||!p||!p[0])return new b(!$.s||!J.s||(u?p&&u[0]==p[0]:!p)?NaN:u&&u[0]==0||!p?y*0:y/0);if(F)K=1,G=$.e-J.e;else F=QV,K=gA,G=_B($.e/K)-_B(J.e/K);f=p.length,k=u.length,z=new b(y),q=z.d=[];for(V=0;p[V]==(u[V]||0);V++);if(p[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,p=p[0],C++;for(;(V<k||U)&&C--;V++)O=U*F+(u[V]||0),q[V]=O/p|0,U=O%p|0;E=U||V<k}else{if(U=F/(p[0]+1)|0,U>1)p=A(p,U,F),u=A(u,U,F),f=p.length,k=u.length;P=f,N=u.slice(0,f),I=N.length;for(;I<f;)N[I++]=0;if(h=p.slice(),h.unshift(0),_=p[0],p[1]>=F/2)++_;do{if(U=0,D=Q(p,N,f,I),D<0){if(w=N[0],f!=I)w=w*F+(N[1]||0);if(U=w/_|0,U>1){if(U>=F)U=F-1;if(H=A(p,U,F),W=H.length,I=N.length,D=Q(H,N,W,I),D==1)U--,B(H,f<W?h:p,W,F)}else{if(U==0)D=U=1;H=p.slice()}if(W=H.length,W<I)H.unshift(0);if(B(N,H,I,F),D==-1){if(I=N.length,D=Q(p,N,f,I),D<1)U++,B(N,f<I?h:p,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,YBA=E;else{for(V=1,U=q[0];U>=10;U/=10)V++;z.e=V+G*K-1,qA(z,X?Y+z.e+1:Y,Z,E)}return z}}();function qA(A,Q,B,$){var J,Y,Z,X,F,D,G,V,U,K=A.constructor;A:if(Q!=null){if(V=A.d,!V)return A;for(J=1,X=V[0];X>=10;X/=10)J++;if(Y=Q-J,Y<0)Y+=gA,Z=Q,G=V[U=0],F=G/X7(10,J-Z-1)%10|0;else if(U=Math.ceil((Y+1)/gA),X=V.length,U>=X)if($){for(;X++<=U;)V.push(0);G=F=0,J=1,Y%=gA,Z=Y-gA+1}else break A;else{G=X=V[U];for(J=1;X>=10;X/=10)J++;Y%=gA,Z=Y-gA+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,(gA-Q%gA)%gA),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,gA-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 DE(A,Q,B){if(!A.isFinite())return KBA(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*=gA;B>=10;B/=10)Q++;return Q}function NW0(A,Q,B){if(Q>dY8){if(Q6=!0,B)A.precision=B;throw Error(ZBA)}return qA(new A(zW0),Q,1,!0)}function FE(A,Q,B){if(Q>Z$1)throw Error(ZBA);return qA(new A(qW0),Q,B,!0)}function GBA(A){var Q=A.length-1,B=Q*gA+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 VBA(A,Q,B,$){var J,Y=new A(1),Z=Math.ceil($/gA+4);Q6=!1;for(;;){if(B%2){if(Y=Y.times(Q),$BA(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),$BA(Q.d,Z)}return Q6=!0,Y}function BBA(A){return A.d[A.d.length-1]&1}function UBA(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 X$1(A,Q){var B,$,J,Y,Z,X,F,D=0,G=0,V=0,U=A.constructor,K=U.rounding,E=U.precision;if(!A.d||!A.d[0]||A.e>17)return new U(A.d?!A.d[0]?1:A.s<0?0:1/0:A.s?A.s<0?0:A:NaN);if(Q==null)Q6=!1,F=E;else F=Q;X=new U(0.03125);while(A.e>-2)A=A.times(X),V+=5;$=Math.log(X7(2,V))/Math.LN10*2+5|0,F+=$,B=Y=Z=new U(1),U.precision=F;for(;;){if(Y=qA(Y.times(A),F,1),B=B.times(++G),X=Z.plus(u8(Y,B,F,1)),yQ(X.d).slice(0,F)===yQ(Z.d).slice(0,F)){J=V;while(J--)Z=qA(Z.times(Z),F,1);if(Q==null)if(D<3&&j10(Z.d,F-$,K,D))U.precision=F+=10,B=Y=X=new U(1),G=0,D++;else return qA(Z,U.precision=E,K,Q6=!0);else return U.precision=E,Z}Z=X}}function 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?qA(H,N,q,Q6=!0):H;V=H,F=Z=H=u8(H.minus(1),H.plus(1),G,1),U=qA(H.times(H),G,1),J=3;for(;;){if(Z=qA(Z.times(U),G,1),D=F.plus(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(j10(F.d,G-E,q,X))z.precision=G+=E,D=Z=H=u8(V.minus(1),V.plus(1),G,1),U=qA(H.times(H),G,1),J=X=1;else return qA(F,z.precision=N,q,Q6=!0);else return z.precision=N,F}F=D,J+=2}}function KBA(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)%gA,B<0)$+=gA;if($<J){if($)A.d.push(+Q.slice(0,$));for(J-=gA;$<J;)A.d.push(+Q.slice($,$+=gA));Q=Q.slice($),$=gA-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 lY8(A,Q){var B,$,J,Y,Z,X,F,D,G;if(Q.indexOf("_")>-1){if(Q=Q.replace(/(\d)_(?=\d)/g,"$1"),DBA.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(gY8.test(Q))B=16,Q=Q.toLowerCase();else if(hY8.test(Q))B=2;else if(mY8.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=VBA($,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):R10.pow(2,F));return Q6=!0,A}function iY8(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/gA);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 EBA(A,Q){var B,$=Q.s<0,J=FE(A,A.precision,1),Y=J.times(0.5);if(Q=Q.abs(),Q.lte(Y))return Iz=$?4:1,Q;if(B=Q.divToInt(J),B.isZero())Iz=$?3:2;else{if(Q=Q.minus(B.times(J)),Q.lte(Y))return Iz=BBA(B)?$?2:3:$?4:1,Q;Iz=BBA(B)?$?1:4:$?3:2}return Q.minus(J).abs()}function F$1(A,Q,B,$){var J,Y,Z,X,F,D,G,V,U,K=A.constructor,E=B!==void 0;if(E)if(BY(B,1,fC),$===void 0)$=K.rounding;else BY($,0,8);else B=K.precision,$=K.rounding;if(!A.isFinite())G=KBA(A);else{if(G=DE(A),Z=G.indexOf("."),E){if(J=2,Q==16)B=B*4-3;else if(Q==8)B=B*3-2}else J=Q;if(Z>=0)G=G.replace(".",""),U=new K(1),U.e=G.length-Z,U.d=HW0(DE(U),10,J),U.e=U.d.length;V=HW0(G,10,J),Y=F=V.length;for(;V[--F]==0;)V.pop();if(!V[0])G=E?"0p+0":"0";else{if(Z<0)Y--;else A=new K(A),A.d=V,A.e=Y,A=u8(A,U,B,$,0,J),V=A.d,Y=A.e,D=YBA;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+=J$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+=J$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 $BA(A,Q){if(A.length>Q)return A.length=Q,!0}function nY8(A){return new this(A).abs()}function aY8(A){return new this(A).acos()}function oY8(A){return new this(A).acosh()}function rY8(A,Q){return new this(A).plus(Q)}function sY8(A){return new this(A).asin()}function tY8(A){return new this(A).asinh()}function eY8(A){return new this(A).atan()}function AZ8(A){return new this(A).atanh()}function QZ8(A,Q){A=new this(A),Q=new this(Q);var B,$=this.precision,J=this.rounding,Y=$+4;if(!A.s||!Q.s)B=new this(NaN);else if(!A.d&&!Q.d)B=FE(this,Y,1).times(Q.s>0?0.25:0.75),B.s=A.s;else if(!Q.d||A.isZero())B=Q.s<0?FE(this,$,J):new this(0),B.s=A.s;else if(!A.d||Q.isZero())B=FE(this,Y,1).times(0.5),B.s=A.s;else if(Q.s<0)this.precision=Y,this.rounding=1,B=this.atan(u8(A,Q,Y,1)),Q=FE(this,Y,1),this.precision=$,this.rounding=J,B=A.s<0?B.minus(Q):B.plus(Q);else B=this.atan(u8(A,Q,Y,1));return B}function BZ8(A){return new this(A).cbrt()}function $Z8(A){return qA(A=new this(A),A.e+1,2)}function JZ8(A,Q,B){return new this(A).clamp(Q,B)}function YZ8(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]=Y$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]=Y$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(XBA);else this[B]=!1;else throw Error(xC+B+": "+$);return this}function ZZ8(A){return new this(A).cos()}function XZ8(A){return new this(A).cosh()}function HBA(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,JBA(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 DBA.test(Y)?WW0(D,Y):lY8(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=YZ8,J.clone=HBA,J.isDecimal=JBA,J.abs=nY8,J.acos=aY8,J.acosh=oY8,J.add=rY8,J.asin=sY8,J.asinh=tY8,J.atan=eY8,J.atanh=AZ8,J.atan2=QZ8,J.cbrt=BZ8,J.ceil=$Z8,J.clamp=JZ8,J.cos=ZZ8,J.cosh=XZ8,J.div=FZ8,J.exp=DZ8,J.floor=GZ8,J.hypot=VZ8,J.ln=UZ8,J.log=KZ8,J.log10=HZ8,J.log2=EZ8,J.max=WZ8,J.min=zZ8,J.mod=qZ8,J.mul=NZ8,J.pow=IZ8,J.random=wZ8,J.round=CZ8,J.sign=MZ8,J.sin=LZ8,J.sinh=OZ8,J.sqrt=jZ8,J.sub=RZ8,J.sum=PZ8,J.tan=_Z8,J.tanh=TZ8,J.trunc=SZ8,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 FZ8(A,Q){return new this(A).div(Q)}function DZ8(A){return new this(A).exp()}function GZ8(A){return qA(A=new this(A),A.e+1,3)}function VZ8(){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 JBA(A){return A instanceof R10||A&&A.toStringTag===FBA||!1}function UZ8(A){return new this(A).ln()}function KZ8(A,Q){return new this(A).log(Q)}function EZ8(A){return new this(A).log(2)}function HZ8(A){return new this(A).log(10)}function WZ8(){return UBA(this,arguments,-1)}function zZ8(){return UBA(this,arguments,1)}function qZ8(A,Q){return new this(A).mod(Q)}function NZ8(A,Q){return new this(A).mul(Q)}function IZ8(A,Q){return new this(A).pow(Q)}function wZ8(A){var Q,B,$,J,Y=0,Z=new this(1),X=[];if(A===void 0)A=this.precision;else BY(A,1,fC);if($=Math.ceil(A/gA),!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(XBA);if($=X[--Y],A%=gA,$&&A)J=X7(10,gA-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-=gA)X.shift();for($=1,J=X[0];J>=10;J/=10)$++;if($<gA)B-=gA-$}return Z.e=B,Z.d=X,Z}function CZ8(A){return qA(A=new this(A),A.e+1,this.rounding)}function MZ8(A){return A=new this(A),A.d?A.d[0]?A.s:0*A.s:A.s||NaN}function LZ8(A){return new this(A).sin()}function OZ8(A){return new this(A).sinh()}function jZ8(A){return new this(A).sqrt()}function RZ8(A,Q){return new this(A).sub(Q)}function PZ8(){var A=0,Q=arguments,B=new this(Q[A]);Q6=!1;for(;B.s&&++A<Q.length;)B=B.plus(Q[A]);return Q6=!0,qA(B,this.precision,this.rounding)}function _Z8(A){return new this(A).tan()}function TZ8(A){return new this(A).tanh()}function SZ8(A){return qA(A=new this(A),A.e+1,1)}c1[Symbol.for("nodejs.util.inspect.custom")]=c1.toString;c1[Symbol.toStringTag]="Decimal";var R10=c1.constructor=HBA(Y$1);zW0=new R10(zW0);qW0=new R10(qW0);var D$1=2;function kZ8(A,Q){let B=Q.decimalPlaces==="more-if-tiny"?Math.abs(A)<0.01?D$1+1:D$1:Q.decimalPlaces??D$1,$=Q.intent==="balance"?A<0?"expand":"trunc":"halfExpand";return{decimalPlaces:B,roundingMode:$}}function bC(A,Q){let{decimalPlaces:B,roundingMode:$}=kZ8(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 P10(A){if(A>=1e6)return`${Math.round(A/1e6)}M`;if(A>=1000)return`${Math.round(A/1000)}k`;return A.toString()}function vZ8(A){if(!A)return"";let Q=A.split("-");if(Q.length>=2)return Q.slice(0,2).join("-");return A}function WBA(A){let Q=[],B=(A.inputTokens??0)+(A.cacheCreationInputTokens??0),$=A.cacheReadInputTokens??0;if(B>0)Q.push(`${P10(B)} in`);if($>0)Q.push(`${P10($)} cache read`);if(A.outputTokens)Q.push(`${P10(A.outputTokens)} out`);if(A.model)Q.push(vZ8(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 G$1 extends GA{}class V$1 extends GA{}function yZ8(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 xZ8(A,Q){let B=S0.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(`
|
|
5288
5288
|
|
|
5289
|
-
`)),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 fZ8(A,Q,B){let $=xZ8(A,Q);if(!A.costBreakdownURL)return new cA({header:"Thread Cost",minWidth:80,maxWidth:100,onDismiss:B,child:$});let J=A.costBreakdownURL,Y=new I4(()=>{return MA.maybeInvoke(Q,new P$(J,"Cost breakdown URL copied to clipboard","Failed to copy cost breakdown URL")),"handled"}),Z=new I4(()=>{return L6(Q,J),"handled"});return new cA({header:"Thread Cost",minWidth:80,maxWidth:100,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["o"],label:"open in browser"},{keys:["y"],label:"copy url"}],onDismiss:B,child:new MA({actions:new Map([[G$1,Y],[V$1,Z]]),child:new V8({debugLabel:"ThreadCostShortcuts",shortcuts:new Map([[g1.key("o"),new V$1],[g1.key("y"),new G$1]]),child:new s4({autofocus:!0,debugLabel:"ThreadCostBody",child:$})})})})}function zBA(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(yZ8(J,Y.error),"error",5000),$();return}Q.push(fZ8(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 bZ8=250,uZ8=2000;class U$1 extends x0{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 NBA}}class NBA extends y0{editorController=new k3;commandPalette=new D00(this);commandRegistry=new kQ1;toastController=new H21;exitHintTimer=new du(this,1000);ideStatus=new s3(this,{});threadNavigationHistory=new jQ1;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;debugOverlayVisible=!1;focusDebugVisible=!1;agentModeCostInfo=null;unregisterCommands=null;pluginIntegration=null;configReloadSubscription=null;configReloadToastTimer=null;pendingConfigReloadToastType=null;lastConfigReloadToast=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.connectToExistingThread(A,{recordNavigation:!0})};shareThreadWithSupport=async(A,Q)=>{let B;if(this.activeThreadContext&&this.activeThreadContext.client.getThreadId()===A){let $=this.activeThreadContext.observer.activeError().getValue();if($)B={message:$.message,type:$.code,stack:$.stack,retryAfterSeconds:$.retryAt!==void 0?Math.max(0,Math.ceil(($.retryAt-Date.now())/1000)):void 0}}await Z9A({configService:this.widget.configService},A,Q,B)};setThreadVisibility=(A,Q)=>{return X9A({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await U5A({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await K5A({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 E5A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(C$.getInstance().interceptConsole(),this.widget.showNeoWelcome)this.neoWelcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:Q,error:B})=>{if(j.error("Neo failed to connect to thread",{threadID:Q,error:B}),!Q)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configReloadSubscription=this.widget.configService.configReloadEvents.subscribe((Q)=>this.scheduleConfigReloadToast(Q)),this.configSubscription=this.widget.configService.config.subscribe((Q)=>{this.applyDraftThreadSettingsSeed(c90(Q.settings))}),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID){let Q={};if(A)Q.initialUserInput=A;this.connectToExistingThread(this.widget.initialThreadID,Q)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.pluginIntegration=new OQ1({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()},bZ8),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<uZ8)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?$9A({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)=>TB1({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()}},zBA({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 pQ1({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 tB1({toolboxes:this.widget.neoContext.toolboxes,onDismiss:Y}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async(J,Y,Z)=>{try{await L6(Y,"https://ampcode.com/chronicle")}finally{Z()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{oJ(this.widget.neoContext.settingsFilePath).catch((J)=>{j.error("Failed to open settings file in editor",{error:J})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(J,Y,Z)=>{J.pushWithDismiss((X)=>new gQ1({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 bQ1({commands:_$.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show neo welcome",description:"Show the Neo welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(J,Y,Z)=>{Z(),A.showNeoWelcome()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new cA({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new l({text:new M(F21({version:"0.0.1777706852-g76c1b8",buildTimestamp:"2026-05-02T07:31:06.538Z",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)=>{MA.maybeInvoke(Y,new wh)}},...Q,...i2A(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 sB1({initialAgentMode:this.widget.neoContext.sessionAgentMode,analyzeContextForThread:this.widget.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,shareThreadWithSupport:this.shareThreadWithSupport,setThreadVisibility:this.setThreadVisibility,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:B}),J=J4.of(A),Z=[new p0({constraints:L1.tight(J.size.width,J.size.height),child:$})];if(this.commandPalette.isEnabled())Z.push(new AA({debugLabel:"CommandPaletteOverlay",child:new vQ1({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)Z.push(TB1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)Z.push(new AA({debugLabel:"NeoWelcomeDialogOverlay",child:new B$1({onDismiss:this.dismissNeoWelcome})}));if(Z.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.agentModeCostInfo)Z.push(new AA({debugLabel:"AgentModeCostModalOverlay",child:this.buildAgentModeCostModal(this.agentModeCostInfo)}));if(this.widget.neoContext.isInternalUser)Z.push(new uQ1({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:_10.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)Z.push(new hQ1);return new S9({neoContext:this.widget.neoContext,child:new _$({commandRegistry:this.commandRegistry,child:new jC({completionBuilder:this.widget.completionBuilder,child:new S3({controller:this.toastController,child:new MA({actions:this.buildActions(),child:new V8({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[g1.ctrl("c"),new iH0],[g1.ctrl("o"),new nH0],[g1.alt("i"),new oH0],[g1.alt("p"),new YC],[g1.ctrl("t"),new rH0]]),child:new s4({debugLabel:"AppShellFocus",child:new W21({controller:this.toastController,child:new HA({children:Z})})})})})})})})})}buildActions(){let A=new I4(()=>{if(aJ.hasAnyCopyableSelection())return aJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new I4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new I4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new I4(()=>{let V=this.activeThreadContext?.client.getThreadId();return this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(V),this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.writeTerminalTitle(void 0),this.activeThreadContext=null,this.connectingToThreadID=null}),"handled"}),J=new I4(()=>{return d4.instance.stop(),"handled"}),Y=new I4((V)=>{if(!V.text)return"ignored";return d4.instance.tuiInstance.clipboard.writeText(V.text).then(()=>{this.toastController.show(V.successMessage,"success",2000)}).catch((U)=>{j.error("Failed to copy Neo text to clipboard",{error:U}),this.toastController.show(V.failureMessage,"error",2000)}),"handled"}),Z=new I4(()=>{return d4.instance.toggleFrameStatsOverlay(),"handled"}),X=new I4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),F=new I4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";let V=this.activeThreadContext?.client.getThreadId();if(!V)return this.toastController.show("No active thread","error",2000),"handled";return L51(V).then((U)=>{this.toastController.show(ha4(U),"success",2000)}).catch((U)=>{let K=U instanceof Error?U.message:String(U);j.error("Failed to copy thread log",{error:U}),this.toastController.show(`Failed to copy thread log: ${K}`,"error",2000)}),"handled"}),D=new I4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"}),G=new I4((V)=>{return this.setState(()=>{this.agentModeCostInfo={agentMode:V.agentMode,speedCostMultiplier:V.speedCostMultiplier}}),"handled"});return new Map([[iH0,A],[Y10,$],[wh,J],[P$,Y],[F10,B],[nH0,Q],[oH0,X],[C_,F],[D10,G],[YC,Z],[rH0,D]])}dismissAgentModeCostModal=()=>{if(!this.agentModeCostInfo)return;this.setState(()=>{this.agentModeCostInfo=null})};buildAgentModeCostModal(A){let Q=(l8(A.agentMode)?.displayName??A.agentMode).toLowerCase();return new cA({header:"Fast Mode Enabled",minWidth:54,maxWidth:72,footer:[{keys:["Esc"],label:"close"}],onDismiss:this.dismissAgentModeCostModal,child:new l({text:new M(`This agent mode now runs in fast mode.
|
|
5289
|
+
`)),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 fZ8(A,Q,B){let $=xZ8(A,Q);if(!A.costBreakdownURL)return new cA({header:"Thread Cost",minWidth:80,maxWidth:100,onDismiss:B,child:$});let J=A.costBreakdownURL,Y=new I4(()=>{return MA.maybeInvoke(Q,new P$(J,"Cost breakdown URL copied to clipboard","Failed to copy cost breakdown URL")),"handled"}),Z=new I4(()=>{return L6(Q,J),"handled"});return new cA({header:"Thread Cost",minWidth:80,maxWidth:100,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["o"],label:"open in browser"},{keys:["y"],label:"copy url"}],onDismiss:B,child:new MA({actions:new Map([[G$1,Y],[V$1,Z]]),child:new V8({debugLabel:"ThreadCostShortcuts",shortcuts:new Map([[g1.key("o"),new V$1],[g1.key("y"),new G$1]]),child:new s4({autofocus:!0,debugLabel:"ThreadCostBody",child:$})})})})}function zBA(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(yZ8(J,Y.error),"error",5000),$();return}Q.push(fZ8(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 bZ8=250,uZ8=2000;class U$1 extends x0{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 NBA}}class NBA extends y0{editorController=new k3;commandPalette=new D00(this);commandRegistry=new kQ1;toastController=new H21;exitHintTimer=new du(this,1000);ideStatus=new s3(this,{});threadNavigationHistory=new jQ1;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;debugOverlayVisible=!1;focusDebugVisible=!1;agentModeCostInfo=null;unregisterCommands=null;pluginIntegration=null;configReloadSubscription=null;configReloadToastTimer=null;pendingConfigReloadToastType=null;lastConfigReloadToast=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.connectToExistingThread(A,{recordNavigation:!0})};shareThreadWithSupport=async(A,Q)=>{let B;if(this.activeThreadContext&&this.activeThreadContext.client.getThreadId()===A){let $=this.activeThreadContext.observer.activeError().getValue();if($)B={message:$.message,type:$.code,stack:$.stack,retryAfterSeconds:$.retryAt!==void 0?Math.max(0,Math.ceil(($.retryAt-Date.now())/1000)):void 0}}await Z9A({configService:this.widget.configService},A,Q,B)};setThreadVisibility=(A,Q)=>{return X9A({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await U5A({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await K5A({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 E5A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(C$.getInstance().interceptConsole(),this.widget.showNeoWelcome)this.neoWelcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:Q,error:B})=>{if(j.error("Neo failed to connect to thread",{threadID:Q,error:B}),!Q)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configReloadSubscription=this.widget.configService.configReloadEvents.subscribe((Q)=>this.scheduleConfigReloadToast(Q)),this.configSubscription=this.widget.configService.config.subscribe((Q)=>{this.applyDraftThreadSettingsSeed(c90(Q.settings))}),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID){let Q={};if(A)Q.initialUserInput=A;this.connectToExistingThread(this.widget.initialThreadID,Q)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.pluginIntegration=new OQ1({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()},bZ8),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<uZ8)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?$9A({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)=>TB1({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()}},zBA({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 pQ1({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 tB1({toolboxes:this.widget.neoContext.toolboxes,onDismiss:Y}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async(J,Y,Z)=>{try{await L6(Y,"https://ampcode.com/chronicle")}finally{Z()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{oJ(this.widget.neoContext.settingsFilePath).catch((J)=>{j.error("Failed to open settings file in editor",{error:J})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(J,Y,Z)=>{J.pushWithDismiss((X)=>new gQ1({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 bQ1({commands:_$.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show neo welcome",description:"Show the Neo welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(J,Y,Z)=>{Z(),A.showNeoWelcome()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new cA({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new l({text:new M(F21({version:"0.0.1777710388-ge5e9da",buildTimestamp:"2026-05-02T08:30:18.646Z",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)=>{MA.maybeInvoke(Y,new wh)}},...Q,...i2A(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 sB1({initialAgentMode:this.widget.neoContext.sessionAgentMode,analyzeContextForThread:this.widget.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,shareThreadWithSupport:this.shareThreadWithSupport,setThreadVisibility:this.setThreadVisibility,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:B}),J=J4.of(A),Z=[new p0({constraints:L1.tight(J.size.width,J.size.height),child:$})];if(this.commandPalette.isEnabled())Z.push(new AA({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new vQ1({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)Z.push(TB1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)Z.push(new AA({debugLabel:"NeoWelcomeDialogOverlay",child:new B$1({onDismiss:this.dismissNeoWelcome})}));if(Z.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.agentModeCostInfo)Z.push(new AA({debugLabel:"AgentModeCostModalOverlay",child:this.buildAgentModeCostModal(this.agentModeCostInfo)}));if(this.widget.neoContext.isInternalUser)Z.push(new uQ1({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:_10.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)Z.push(new hQ1);return new S9({neoContext:this.widget.neoContext,child:new _$({commandRegistry:this.commandRegistry,child:new jC({completionBuilder:this.widget.completionBuilder,child:new S3({controller:this.toastController,child:new MA({actions:this.buildActions(),child:new V8({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[g1.ctrl("c"),new iH0],[g1.ctrl("o"),new nH0],[g1.alt("i"),new oH0],[g1.alt("p"),new YC],[g1.ctrl("t"),new rH0]]),child:new s4({debugLabel:"AppShellFocus",child:new W21({controller:this.toastController,child:new HA({children:Z})})})})})})})})})}buildActions(){let A=new I4(()=>{if(aJ.hasAnyCopyableSelection())return aJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new I4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new I4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new I4(()=>{let V=this.activeThreadContext?.client.getThreadId();return this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(V),this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.writeTerminalTitle(void 0),this.activeThreadContext=null,this.connectingToThreadID=null}),"handled"}),J=new I4(()=>{return d4.instance.stop(),"handled"}),Y=new I4((V)=>{if(!V.text)return"ignored";return d4.instance.tuiInstance.clipboard.writeText(V.text).then(()=>{this.toastController.show(V.successMessage,"success",2000)}).catch((U)=>{j.error("Failed to copy Neo text to clipboard",{error:U}),this.toastController.show(V.failureMessage,"error",2000)}),"handled"}),Z=new I4(()=>{return d4.instance.toggleFrameStatsOverlay(),"handled"}),X=new I4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),F=new I4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";let V=this.activeThreadContext?.client.getThreadId();if(!V)return this.toastController.show("No active thread","error",2000),"handled";return L51(V).then((U)=>{this.toastController.show(ha4(U),"success",2000)}).catch((U)=>{let K=U instanceof Error?U.message:String(U);j.error("Failed to copy thread log",{error:U}),this.toastController.show(`Failed to copy thread log: ${K}`,"error",2000)}),"handled"}),D=new I4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"}),G=new I4((V)=>{return this.setState(()=>{this.agentModeCostInfo={agentMode:V.agentMode,speedCostMultiplier:V.speedCostMultiplier}}),"handled"});return new Map([[iH0,A],[Y10,$],[wh,J],[P$,Y],[F10,B],[nH0,Q],[oH0,X],[C_,F],[D10,G],[YC,Z],[rH0,D]])}closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};dismissAgentModeCostModal=()=>{if(!this.agentModeCostInfo)return;this.setState(()=>{this.agentModeCostInfo=null})};buildAgentModeCostModal(A){let Q=(l8(A.agentMode)?.displayName??A.agentMode).toLowerCase();return new cA({header:"Fast Mode Enabled",minWidth:54,maxWidth:72,footer:[{keys:["Esc"],label:"close"}],onDismiss:this.dismissAgentModeCostModal,child:new l({text:new M(`This agent mode now runs in fast mode.
|
|
5290
5290
|
|
|
5291
5291
|
`+`↯${Q} costs ${A.speedCostMultiplier} the standard rate for this mode.
|
|
5292
5292
|
|
|
@@ -6058,7 +6058,7 @@ ${J}`,Q);this.line=B,this.column=$,this.codeblock=J}}/*!
|
|
|
6058
6058
|
`),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(`
|
|
6059
6059
|
`))}return new p0({decoration:{color:B.colorScheme.background,border:e1.all(new A4($.app.keybind,1,"rounded"))},child:new b0({padding:w0.symmetric(0,1),child:new l({text:new M(void 0,void 0,Y)})})})}}class qJ1 extends a3{chartData;highlightIndex;showAxes;colors;constructor({key:A,chartData:Q,highlightIndex:B=null,showAxes:$=!0,colors:J=fz0}){super(A?{key:A}:{});this.chartData=Q,this.highlightIndex=B,this.showAxes=$,this.colors=J}createRenderObject(){return new WJ1({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 bYA(A,Q,B,$,J,Y,Z){if(Y<=0)return null;switch(A){case"horizontal-bar":{let X=B;return X>=0&&X<Y?X:null}case"bar":case"stacked-bar":{let X=Z?A2:0,F=$-X;if(F<=0)return null;let D=Q-X;if(D<0||D>=F)return null;let G=Math.max(1,Math.floor(F/Y)),V=Math.floor(D/G);return V>=0&&V<Y?V:null}case"line":case"sparkline":case"stacked-area":{let X=Z?A2:0,F=$-X;if(F<=0)return null;let D=Math.max(0,Math.min(F-1,Q-X));if(Y===1)return 0;let G=F/(Y-1),V=Math.round(D/G);return Math.max(0,Math.min(Y-1,V))}default:return null}}function tU8(A,Q,B,$,J,Y,Z,X){if(J<=0||Q<0||Q>=J)return null;let F=2;switch(A){case"horizontal-bar":return{x:Math.floor(B/2),y:Q};case"bar":case"stacked-bar":{let D=Y?A2:0,G=B-D,V=$-(Y?F:0);if(G<=0||V<=0)return null;let U=Math.max(1,Math.floor(G/J)),K=D+Q*U+Math.floor(U/2),E=X>0?Z/X:0,H=Math.round((1-E)*(V-1));return{x:K,y:H}}case"line":case"sparkline":case"stacked-area":{let D=Y?A2:0,G=B-D,V=$-(Y?F:0);if(G<=0||V<=0)return null;let U=J>1?D+Math.round(Q/(J-1)*(G-1)):D+Math.floor(G/2),K=X>0?Z/X:0,E=Math.round((1-K)*(V-1));return{x:U,y:E}}default:return null}}function eU8(A){let Q=0;for(let B of A)for(let $ of B.points)if($.value>Q)Q=$.value;return Q||1}function AK8(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 QK8(A,Q,B,$,J,Y,Z){let X;try{let E=S1.of(A),H=S0.of(A);X={foreground:E.colorScheme.foreground,background:E.colorScheme.background,border:H.app.keybind}}catch{X={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let F=new x({color:X.foreground,bold:!0}),D=new x({color:X.foreground}),G=new x({color:X.foreground,dim:!0}),V=[],U=new x({color:X.foreground,underline:!0}),K=(E,H)=>new M(H,U,void 0,_K0(E),()=>{L6(A,E)});if($.length<=1){if(V.push(new M(`${Q.label}: `,F)),Q.link)V.push(K(Q.link,Y(Q.value)));else V.push(new M(Y(Q.value),D));if(Q.meta)V.push(new M(` (${Q.meta})`,G))}else{let E=Z==="stacked-bar"||Z==="stacked-area";V.push(new M(`${Q.label}
|
|
6060
6060
|
`,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(`
|
|
6061
|
-
`))}if(E)V.push(new M(" ",G)),V.push(new M("Total: ",G)),V.push(new M(Y(H),D))}return new p0({decoration:{color:X.background,border:e1.all(new A4(X.border,1,"rounded"))},child:new l({text:new M(void 0,void 0,V)})})}i0();S8();EO();X2();F8();oQ();$r();LX();KQ();V9();Q$();TU();QA();Xx();fk();j1();i0();KQ();class NJ1{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.1777706852-g76c1b8"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await a70(Q,this.configService)}catch(Q){j.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class rC extends x0{props;constructor(A){super();this.props=A}createState(){return new uYA}}class uYA extends y0{_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 hYA extends y0{controller=new k3;focusNode=new H6({debugLabel:"CommandArgumentPrompt",onKey:(A)=>{if(A.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(A){let Q=S0.of(A),{colors:B,app:$}=Q,J=this.widget.props.isRequiredArg??!0,Y=this.controller.text.trim().length>0,Z=!J||Y,X=e1.all(new A4(B.foreground,1,"solid")),F=new M$({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(K)=>{let E=K.trim();if(J&&E.length===0)return;this.widget.props.onSubmit(E)},autofocus:!0,style:{textColor:B.foreground,border:null},maxLines:1}),D=new B1({children:[new p0({decoration:{color:B.background},child:new l({text:new M(">",new x({color:B.foreground}))})}),new T1({child:F})]}),G=new p0({padding:w0.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 p0({padding:w0.symmetric(1,0),child:new l({text:new M("",void 0,V)})});return new p0({decoration:{border:X,color:B.background},padding:w0.all(1),child:new f0({children:[G,new C0({height:1}),D,new H5,U]})})}}class l10 extends x0{props;constructor(A){super();this.props=A}createState(){return new hYA}}Q$();class gYA extends y0{controller=new k3;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new H6({debugLabel:"CommandMultilinePrompt",onKey:(A)=>{if(A.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(A)=>{if(this.imageAttachments.length>=C7)return!1;let Q=await bF(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(A){let Q=S0.of(A),{colors:B,app:$}=Q,Y=J4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),X=new AV({controller:this.controller,triggers:[new QY],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(K)=>{this.widget.props.onSubmit(K.trim(),this.imageAttachments)},theme:B,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:d4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),F=new s4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:X}),D=new p0({constraints:new L1({maxHeight:Z}),padding:w0.symmetric(1,0),child:F}),G=new p0({padding:w0.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 p0({padding:w0.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 C0({height:1}),new T1({child:D}),new C0({height:1}),V];return new p0({decoration:{border:e1.all(new A4(B.foreground,1,"solid")),color:B.background},padding:w0.all(1),child:new f0({children:U})})}}class IJ1 extends x0{props;constructor(A){super();this.props=A}createState(){return new gYA}}function mYA(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 wJ1 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)=>mYA(J.pubDate).length));return new t6({items:Q,getLabel:(J)=>J.title,onAccept:(J)=>this.props.onSelect?.(J),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(J,Y,Z,X)=>{let F=S0.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 C0({width:W,child:B1.end([new l({text:new M(H,new x({color:K}))})])});return new p0({decoration:V?{color:V}:void 0,padding:w0.symmetric(2,0),child:new B1({children:[new T1({child:new l({text:new M(J.title,new x({color:U})),overflow:"ellipsis",maxLines:1})}),new C0({width:2}),E(mYA(J.pubDate),B)]})})}})}}class yB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!yB._instance)yB._instance=new yB;return yB._instance}get allExpanded(){return this._allExpanded}setAllExpanded(A){if(this._allExpanded===A)return;this._allExpanded=A,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(A){return this._listeners.add(A),()=>this.removeListener(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A()}}i0();class pYA extends y0{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=S0.of(A),{app:B,colors:$}=Q,J=this.currentQuery.trim().toLowerCase(),Y=J.length>0?this.getValidationError(J):null,Z=this.getAvailableLabels(),F=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...Z];return new t6({title:"Add Label",items:F,getLabel:(D)=>{if("__isCreateMarker"in D)return this.currentQuery.trim().toLowerCase();return D.name},onAccept:(D)=>{if("__isCreateMarker"in D)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(D.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:Y||"Type to create a new label",renderItem:(D,G,V,U)=>{let K=G?B.selectionBackground:void 0,E=G?B.selectionForeground:$.foreground;if("__isCreateMarker"in D&&D.__isCreateMarker){let W=this.currentQuery.trim().toLowerCase();return new p0({decoration:K?{color:K}:void 0,padding:w0.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 p0({decoration:K?{color:K}:void 0,padding:w0.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 CJ1 extends x0{props;constructor(A){super();this.props=A}createState(){return new pYA}}class $V extends x0{props;constructor(A){super();this.props=A}createState(){return new dYA}}class dYA extends y0{_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=S0.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 T1({child:new f0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)F.push(new C0({height:2,child:new p0({padding:w0.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 p0({decoration:new t4(B.background,J),child:new C0({width:60,height:7,child:new f0({mainAxisAlignment:"start",children:F})})});if(this.widget.props.onAbort)return new AA({debugLabel:"LoadingDialog",child:new s4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class UE extends x0{props;constructor(A){super();this.props=A}createState(){return new cYA}}class cYA extends y0{scrollController=new Z6;scrollAreaKey=new w2("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 s2}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=S0.of(A),B=this.widget.props.message,$=(()=>{if(this.isWidgetMessage(B))return{title:B.title,type:B.type};if(B instanceof Error&&B.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:B.message};if(B instanceof Error&&B.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:B.message};let G=iE0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=e1.all(new A4(Q.colors.border,1,"solid")),Z=new p0({padding:w0.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 T1({child:new o2({child:new p0({padding:w0.symmetric(1,0),child:new B1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new hA({controller:this.scrollController,autofocus:!0,child:X})}),new L2({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 p0({padding:w0.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 AA({debugLabel:"MessageDialog",child:new HA({fit:"expand",children:[new i1({onClick:()=>{},child:new C0}),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 p0({decoration:{border:Y,color:Q.colors.background},padding:w0.all(1),child:new f0({mainAxisAlignment:"center",children:[Z,new C0({height:1}),F,D]})})})]})})}}S8();class lYA extends x0{props;constructor(A){super();this.props=A}createState(){return new iYA}}class iYA extends y0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=A.startsWith("file://")?A.slice(7):A,B=this.widget.props.cwd;if(Q.startsWith(B))return Q.slice(B.length+1);return Q}statusIcon(A){let Q=t3.default(),{colors:B,app:$}=Q;switch(A){case"loading":return{icon:"◌",color:B.warning};case"active":return{icon:"✓",color:$.toolSuccess};case"error":return{icon:"✗",color:$.toolError}}}build(A){let Q=S0.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} ${H4(J,"plugin")} active`,new x({bold:!0}))),Z>0||X>0)$.push(new M(` (${Z} ${H4(Z,"command")}, ${X} ${H4(X,"tool")})`,new x({dim:!0})));$.push(new M(`
|
|
6061
|
+
`))}if(E)V.push(new M(" ",G)),V.push(new M("Total: ",G)),V.push(new M(Y(H),D))}return new p0({decoration:{color:X.background,border:e1.all(new A4(X.border,1,"rounded"))},child:new l({text:new M(void 0,void 0,V)})})}i0();S8();EO();X2();F8();oQ();$r();LX();KQ();V9();Q$();TU();QA();Xx();fk();j1();i0();KQ();class NJ1{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.1777710388-ge5e9da"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await a70(Q,this.configService)}catch(Q){j.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class rC extends x0{props;constructor(A){super();this.props=A}createState(){return new uYA}}class uYA extends y0{_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 hYA extends y0{controller=new k3;focusNode=new H6({debugLabel:"CommandArgumentPrompt",onKey:(A)=>{if(A.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(A){let Q=S0.of(A),{colors:B,app:$}=Q,J=this.widget.props.isRequiredArg??!0,Y=this.controller.text.trim().length>0,Z=!J||Y,X=e1.all(new A4(B.foreground,1,"solid")),F=new M$({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(K)=>{let E=K.trim();if(J&&E.length===0)return;this.widget.props.onSubmit(E)},autofocus:!0,style:{textColor:B.foreground,border:null},maxLines:1}),D=new B1({children:[new p0({decoration:{color:B.background},child:new l({text:new M(">",new x({color:B.foreground}))})}),new T1({child:F})]}),G=new p0({padding:w0.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 p0({padding:w0.symmetric(1,0),child:new l({text:new M("",void 0,V)})});return new p0({decoration:{border:X,color:B.background},padding:w0.all(1),child:new f0({children:[G,new C0({height:1}),D,new H5,U]})})}}class l10 extends x0{props;constructor(A){super();this.props=A}createState(){return new hYA}}Q$();class gYA extends y0{controller=new k3;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new H6({debugLabel:"CommandMultilinePrompt",onKey:(A)=>{if(A.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(A)=>{if(this.imageAttachments.length>=C7)return!1;let Q=await bF(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(A){let Q=S0.of(A),{colors:B,app:$}=Q,Y=J4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),X=new AV({controller:this.controller,triggers:[new QY],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(K)=>{this.widget.props.onSubmit(K.trim(),this.imageAttachments)},theme:B,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:d4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),F=new s4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:X}),D=new p0({constraints:new L1({maxHeight:Z}),padding:w0.symmetric(1,0),child:F}),G=new p0({padding:w0.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 p0({padding:w0.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 C0({height:1}),new T1({child:D}),new C0({height:1}),V];return new p0({decoration:{border:e1.all(new A4(B.foreground,1,"solid")),color:B.background},padding:w0.all(1),child:new f0({children:U})})}}class IJ1 extends x0{props;constructor(A){super();this.props=A}createState(){return new gYA}}function mYA(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 wJ1 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)=>mYA(J.pubDate).length));return new t6({items:Q,getLabel:(J)=>J.title,onAccept:(J)=>this.props.onSelect?.(J),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(J,Y,Z,X)=>{let F=S0.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 C0({width:W,child:B1.end([new l({text:new M(H,new x({color:K}))})])});return new p0({decoration:V?{color:V}:void 0,padding:w0.symmetric(2,0),child:new B1({children:[new T1({child:new l({text:new M(J.title,new x({color:U})),overflow:"ellipsis",maxLines:1})}),new C0({width:2}),E(mYA(J.pubDate),B)]})})}})}}class yB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!yB._instance)yB._instance=new yB;return yB._instance}get allExpanded(){return this._allExpanded}setAllExpanded(A){if(this._allExpanded===A)return;this._allExpanded=A,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(A){return this._listeners.add(A),()=>this.removeListener(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A()}}i0();class pYA extends y0{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=S0.of(A),{app:B,colors:$}=Q,J=this.currentQuery.trim().toLowerCase(),Y=J.length>0?this.getValidationError(J):null,Z=this.getAvailableLabels(),F=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...Z];return new t6({title:"Add Label",items:F,getLabel:(D)=>{if("__isCreateMarker"in D)return this.currentQuery.trim().toLowerCase();return D.name},onAccept:(D)=>{if("__isCreateMarker"in D)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(D.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:Y||"Type to create a new label",renderItem:(D,G,V,U)=>{let K=G?B.selectionBackground:void 0,E=G?B.selectionForeground:$.foreground;if("__isCreateMarker"in D&&D.__isCreateMarker){let W=this.currentQuery.trim().toLowerCase();return new p0({decoration:K?{color:K}:void 0,padding:w0.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 p0({decoration:K?{color:K}:void 0,padding:w0.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 CJ1 extends x0{props;constructor(A){super();this.props=A}createState(){return new pYA}}class $V extends x0{props;constructor(A){super();this.props=A}createState(){return new dYA}}class dYA extends y0{_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=S0.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 T1({child:new f0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)F.push(new C0({height:2,child:new p0({padding:w0.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 p0({decoration:new t4(B.background,J),child:new C0({width:60,height:7,child:new f0({mainAxisAlignment:"start",children:F})})});if(this.widget.props.onAbort)return new AA({debugLabel:"LoadingDialog",child:new s4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class UE extends x0{props;constructor(A){super();this.props=A}createState(){return new cYA}}class cYA extends y0{scrollController=new Z6;scrollAreaKey=new w2("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 s2}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=S0.of(A),B=this.widget.props.message,$=(()=>{if(this.isWidgetMessage(B))return{title:B.title,type:B.type};if(B instanceof Error&&B.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:B.message};if(B instanceof Error&&B.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:B.message};let G=iE0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=e1.all(new A4(Q.colors.border,1,"solid")),Z=new p0({padding:w0.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 T1({child:new o2({child:new p0({padding:w0.symmetric(1,0),child:new B1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new hA({controller:this.scrollController,autofocus:!0,child:X})}),new L2({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 p0({padding:w0.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 AA({debugLabel:"MessageDialog",child:new HA({fit:"expand",children:[new i1({onClick:()=>{},child:new C0}),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 p0({decoration:{border:Y,color:Q.colors.background},padding:w0.all(1),child:new f0({mainAxisAlignment:"center",children:[Z,new C0({height:1}),F,D]})})})]})})}}S8();class lYA extends x0{props;constructor(A){super();this.props=A}createState(){return new iYA}}class iYA extends y0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=A.startsWith("file://")?A.slice(7):A,B=this.widget.props.cwd;if(Q.startsWith(B))return Q.slice(B.length+1);return Q}statusIcon(A){let Q=t3.default(),{colors:B,app:$}=Q;switch(A){case"loading":return{icon:"◌",color:B.warning};case"active":return{icon:"✓",color:$.toolSuccess};case"error":return{icon:"✗",color:$.toolError}}}build(A){let Q=S0.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} ${H4(J,"plugin")} active`,new x({bold:!0}))),Z>0||X>0)$.push(new M(` (${Z} ${H4(Z,"command")}, ${X} ${H4(X,"tool")})`,new x({dim:!0})));$.push(new M(`
|
|
6062
6062
|
|
|
6063
6063
|
`));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(`
|
|
6064
6064
|
`)),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(`
|
|
@@ -6236,7 +6236,7 @@ ${s.content||""}`:s.content||"",u0=[],E1=s.baseDir.startsWith("file://")?Vq0(s.b
|
|
|
6236
6236
|
`)}function PFA(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=Y84({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(o0.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(o0.red("Error: ")+F.error.message+`
|
|
6237
6237
|
`),process.exit(1)}process.stdout.write(await zW8(F.result.displayText)+`
|
|
6238
6238
|
`),process.exit(0)})}var uI8=P40.join(MX,"logs","headless.log"),jX1=P40.join(wu,"device-id.json"),hI8=`cli-tui-${QUA(16).toString("hex")}`;async function gI8(){for(let A of zO)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(() => C4(Cg(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){DY.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
|
|
6239
|
-
`)}function mI8(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 B9(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",cI8(Q.model))}function oVA(A){let Q=A.indexOf(":");if(Q===-1)throw new F4(`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 F4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function pI8(A){if(A===void 0)return;let Q=A.trim();if(i54(Q))return Q;throw new F4(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function dI8(A,Q){if(jD(A,Q))return;let B=XJ(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new F4(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function cI8(A){if(!A.includes("="))return oVA(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new F4(`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 F4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new F4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);oVA(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new F4("No valid model overrides found in --model flag value.",1);return Q}function lI8(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 iI8(A){try{return await BUA(A,"utf-8")}catch{return A}}async function RX1(A,Q,B){let $=lI8(A,Q);if(!$)return;let J=bA(B)?B.features:[],Y=bA(B)?B.user.email:void 0;if(!Mg(J,F2.HARNESS_SYSTEM_PROMPT)&&!(Y&&ZQ(Y)))throw new F4("You are not allowed to do this.",1);sB("systemPrompt",await iI8($))}function Mg(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function nI8(A){return A!=="pending"}function t_(A){if(!bA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function aI8(A){let Q=t_(A);if(Q)return Q.id;if(kD(A))throw Error(A.error.message);throw Error("unreachable")}function oI8(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 rI8(A){let $=oI8(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 F4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function _40(A,Q){let B=j51(Error(A.error.message));if(B.message===g7.networkOffline||B.message===g7.networkTimeout)return rI8(Q);if(B.message!==g7.internalBug)return new F4(B.message,1,B.suggestion);return new F4(A.error.message.replace(/^Error: /,""),1)}var rVA=[{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??PF,description:`Custom settings file path (overrides the default location ${PF})`},{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 ${at})`},{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:P9(),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:KO.SMART.key,description:`Set the agent mode (${YJ({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(YJ().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neoOrb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"showNeoWelcome",long:"show-neo-welcome",type:"switch",description:"Show the Neo welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],sVA=(A)=>("deprecated"in A)&&A.deprecated===!0,sI8=(A)=>("hidden"in A)&&A.hidden===!0,tI8=(A)=>("default"in A),eI8=(A)=>("default"in A)?A.default:void 0;function AN0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=pI8(Q.effort);if(B!==void 0)dI8(Q.mode,B);return B}function Aw8(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 F4(g7.unknownCommand(B),1,Z)}}async function $N0(A){return{...A,getThreadEnvironment:fW,getEnvironmentData:(Q,B)=>aD({filesystem:A.fileSystem},Q,B),osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new Fj(A.fileSystem),generateThreadTitle:QH4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>tQ(A.configService),pluginService:A.pluginService}}function $UA(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:fW,getEnvironmentData:(Q,B)=>aD({filesystem:A.fileSystem},Q,B),filesystem:A.fileSystem,threadService:A.threadService}}var QN0=Z1.file(bI8.homedir()),PX1=process.env.XDG_CONFIG_HOME?Z1.file(process.env.XDG_CONFIG_HOME):K1.joinPath(QN0,".config");function Qw8(A){return Tx4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(DK0())GK0();else if(process.platform==="darwin"&&Q==="idle"&&A.isTUIVoiceNotifEnabled())_x4();else Ds(Q);let B=iP(),$=Q00();if((!B||$||Lu())&&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(iP()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function Q2(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;m84("0.0.
|
|
6239
|
+
`)}function mI8(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 B9(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",cI8(Q.model))}function oVA(A){let Q=A.indexOf(":");if(Q===-1)throw new F4(`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 F4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function pI8(A){if(A===void 0)return;let Q=A.trim();if(i54(Q))return Q;throw new F4(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function dI8(A,Q){if(jD(A,Q))return;let B=XJ(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new F4(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function cI8(A){if(!A.includes("="))return oVA(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new F4(`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 F4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new F4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);oVA(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new F4("No valid model overrides found in --model flag value.",1);return Q}function lI8(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 iI8(A){try{return await BUA(A,"utf-8")}catch{return A}}async function RX1(A,Q,B){let $=lI8(A,Q);if(!$)return;let J=bA(B)?B.features:[],Y=bA(B)?B.user.email:void 0;if(!Mg(J,F2.HARNESS_SYSTEM_PROMPT)&&!(Y&&ZQ(Y)))throw new F4("You are not allowed to do this.",1);sB("systemPrompt",await iI8($))}function Mg(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function nI8(A){return A!=="pending"}function t_(A){if(!bA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function aI8(A){let Q=t_(A);if(Q)return Q.id;if(kD(A))throw Error(A.error.message);throw Error("unreachable")}function oI8(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 rI8(A){let $=oI8(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 F4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function _40(A,Q){let B=j51(Error(A.error.message));if(B.message===g7.networkOffline||B.message===g7.networkTimeout)return rI8(Q);if(B.message!==g7.internalBug)return new F4(B.message,1,B.suggestion);return new F4(A.error.message.replace(/^Error: /,""),1)}var rVA=[{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??PF,description:`Custom settings file path (overrides the default location ${PF})`},{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 ${at})`},{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:P9(),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:KO.SMART.key,description:`Set the agent mode (${YJ({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(YJ().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neoOrb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"showNeoWelcome",long:"show-neo-welcome",type:"switch",description:"Show the Neo welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],sVA=(A)=>("deprecated"in A)&&A.deprecated===!0,sI8=(A)=>("hidden"in A)&&A.hidden===!0,tI8=(A)=>("default"in A),eI8=(A)=>("default"in A)?A.default:void 0;function AN0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=pI8(Q.effort);if(B!==void 0)dI8(Q.mode,B);return B}function Aw8(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 F4(g7.unknownCommand(B),1,Z)}}async function $N0(A){return{...A,getThreadEnvironment:fW,getEnvironmentData:(Q,B)=>aD({filesystem:A.fileSystem},Q,B),osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new Fj(A.fileSystem),generateThreadTitle:QH4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>tQ(A.configService),pluginService:A.pluginService}}function $UA(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:fW,getEnvironmentData:(Q,B)=>aD({filesystem:A.fileSystem},Q,B),filesystem:A.fileSystem,threadService:A.threadService}}var QN0=Z1.file(bI8.homedir()),PX1=process.env.XDG_CONFIG_HOME?Z1.file(process.env.XDG_CONFIG_HOME):K1.joinPath(QN0,".config");function Qw8(A){return Tx4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(DK0())GK0();else if(process.platform==="darwin"&&Q==="idle"&&A.isTUIVoiceNotifEnabled())_x4();else Ds(Q);let B=iP(),$=Q00();if((!B||$||Lu())&&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(iP()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function Q2(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;m84("0.0.1777710388-ge5e9da");let Y=Jv({storage:A.settings,secretStorage:A.secrets,workspaceRoot:g0.of(Z1.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:QN0,userConfigDir:PX1});cBA(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...
|
|
6240
6240
|
`);let g=await Bw8(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 tW(),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=y1(tQ(Y).pipe(L5(nI8))),D=$?"pending":await F;if(!$)j.info("Server status resolved",{status:"ready",isAuthenticated:bA(D),isError:kD(D),errorMessage:kD(D)?D.error.message:void 0});let G=F.then((d)=>aI8(d));G.catch(()=>{return});let U=!A.executeMode&&!Q.takeMeBack&&bA(D)&&Mg(D.features,F2.THREAD_ACTORS_TUI)?"all":process.env.PLUGINS??"permissions",{toolService:K,dispose:E}=hD0({configService:Y}),H=new Map,W=()=>H.clear(),z=new hm0(Y,A.settings.getWorkspaceRootPath()),q=IJ0({configService:Y,filesystem:e5}),N=PF4({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 MO(A.secrets),Q0=await i.getClientInfo(d,g),U0=n?.scopes??Q0?.scopes,z0=At4();j.info("OAuth headless mode check",{useHeadless:z0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:N5.isTTY});let A0;if(z0)A0=A.executeMode?es4():ts4(d);let J0=new Nb0({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:U0,headlessAuthHandler:A0});return j.debug("OAuth provider created",{serverName:d,serverUrl:g,hasManualClientId:!!(n?.clientId??Q0?.clientId),willUseDCR:!(n?.clientId??Q0?.clientId),scopes:U0,headlessMode:z0,executeMode:A.executeMode}),J0})();return H.set(c,O0),O0}}),I=er({configService:Y,filesystem:e5,spawn:af}),w;if(J)w=new Map;else if(A.executeMode){let d=await Qv4({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=As({toolService:K,providers:[N,I]});if(Q.jetbrains)HO("JetBrains");else if(Q.ide&&bt4())HO("VS Code");else if(Q.ide&&ut4())HO("Neovim");else if(Q.ide){let d=await gI8();if(d){let g=G70(d.ideName);if(g)HO(g)}}if(A.executeMode)p84(!0);let C,O=a8.status.pipe(O1((d)=>Boolean(d.connected&&d.authenticated&&d.ideName&&z34(d.ideName))),m4()).subscribe((d)=>{if(d){if(!C)C=K.registerTool(Av4)}else C?.dispose(),C=void 0}),P;if(!A.executeMode){let d=await A.settings.get("fuzzy.alwaysIncludePaths")??[];P=new Nu(process.cwd(),{alwaysIncludePaths:d},!0)}else P=new class extends Nu{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let k=new Ql0(Oj(Y,{usesThreadActors:!1}),{maxThreads:200});j.info("Starting Amp background services");let _=new N$1,f=Q.headless?V1A():void 0,h=f??new ku({configService:Y}),b=h instanceof ku?h:void 0;if(b)b.pluginExecutorKind="local";let y=hi({configService:Y,fileSystem:e5,platform:h,internalPlugins:Re,loadServerPlugins:le(Y),pluginFilter:U}),u=w$0({pluginService:y,toolService:K}),p={configService:Y,toolService:K,mcpService:N,skillService:q,toolboxService:I,trustStore:z,threadService:k,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:P,fileSystem:e5,terminal:_,pluginService:y,pluginPlatform:b,headlessPluginPlatform:f,serverStatus:D,serverStatusPromise:F,viewerUserIDPromise:G,hasAPIKeyAtStartup:X};return{...p,async asyncDispose(){if(p.mcpService.hasAuthenticatingClients())j.info("Waiting for OAuth authentication to complete before exit..."),await p.mcpService.waitForAuthentication();for(let d of w.values())d.dispose();await p.mcpService.dispose(),W(),await p.threadService.asyncDispose(),p.configService.unsubscribe(),E(),p.fuzzyServer.dispose(),p.settingsStorage[Symbol.dispose](),O.unsubscribe(),C?.dispose(),u.dispose(),await p.pluginService.dispose()}}}async function Bw8(A){if(!A.executeMode){if(!await AE0("Would you like to log in to Amp? [(y)es, (n)o]: "))return N5.write(`Login cancelled. Run the command again to retry.
|
|
6241
6241
|
`),!1}return await JUA(A)}async function JUA(A){let Q=QUA(32).toString("hex"),B=await Su(A.ampURL,Q),$=new AbortController;try{await ND(B,$.signal)}catch(Y){j.error("Error opening browser",{error:Y})}let J=await Su(A.ampURL,Q,!1);N5.write(`If your browser does not open automatically, visit:
|
|
6242
6242
|
|
|
@@ -6244,7 +6244,7 @@ ${o0.blue.bold(J)}
|
|
|
6244
6244
|
|
|
6245
6245
|
`);try{return await t0A(A.ampURL,Q,A.secrets,$),N5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(Y){return j.error("Login failed",{error:Y}),DY.write(`
|
|
6246
6246
|
Login failed: ${Y instanceof Error?Y.message:String(Y)}
|
|
6247
|
-
`),!1}}function $w8(A){let Q=new Zw().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((E)=>{if(E.code==="commander.help"||E.code==="commander.version"||E.exitCode===0)OP(),process.exit(0);let H=E.originalError??E;na4(H)}),F4A(Q,{version:"0.0.
|
|
6247
|
+
`),!1}}function $w8(A){let Q=new Zw().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((E)=>{if(E.code==="commander.help"||E.code==="commander.version"||E.exitCode===0)OP(),process.exit(0);let H=E.originalError??E;na4(H)}),F4A(Q,{version:"0.0.1777710388-ge5e9da",buildTimestamp:"2026-05-02T08:30:18.646Z",buildType:"'release'"}),Q.addHelpText("after",yt4()),Q.configureHelp({formatHelp:xt4}),Q.command("logout").description("Log out by removing stored API key").action(async(E,H)=>{let W=H.optsWithGlobals(),z=await E8(W);await Uw8(z)}),Q.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(E,H)=>{let W=H.optsWithGlobals(),z=await E8(W);await Vw8(z,await He(W,z.settings))}),Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(E,H,W)=>{let z=W.optsWithGlobals(),q=await E8(z);await cs4(E??"get",q.ampURL,q.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(E,H)=>{let W=H.optsWithGlobals(),z=await E8(W);await ls4(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 ee4({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 ua4(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(`
|
|
6248
6248
|
`)).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 F4("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.
|
|
6249
6249
|
|
|
6250
6250
|
`),W.outputHelp(),process.exit(0);let q=i8(z)??WB(z),N=W.optsWithGlobals(),I=await E8(N);B9(W,N);let w=await Q2(I,N),C=!1;try{if(H.checkout&&H.skipCheckout)throw new F4("Choose either --checkout or --skip-checkout, not both.",1);if(kD(w.serverStatus))throw _40(w.serverStatus,I.ampURL);let O=bA(w.serverStatus)?w.serverStatus.features:void 0;if(!Mg(O,F2.V2))throw new F4("live-sync is not enabled for your user",1);await m0A({ampURL:I.ampURL,threadId:q,configService:w.configService,threadService:w.threadService,apiKey:process.env.AMP_API_KEY,applyOnce:typeof H.apply==="string",checkoutMode:H.checkout?"always":H.skipCheckout?"never":"prompt",promptForYesNo:AE0}),C=!0}finally{if(await w.asyncDispose(),C)process.exit(0)}});let B=async(E,H,W)=>{Jv({storage:H.settings,secretStorage:H.secrets,workspaceRoot:g0.of(Z1.file(process.cwd())),defaultAmpURL:H.ampURL,homeDir:QN0,userConfigDir:PX1});let z={...H,executeMode:!1};await BN0(z,{...E,openThreadSwitcher:!0},W,A)},$=Q.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").option("--include-archived","Include archived threads in the list").action(async(E,H)=>{let W=H.optsWithGlobals(),z=await E8(W);await AUA(W,z,H)});$.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(E,H)=>{let W=H.optsWithGlobals(),z=await E8(W);await Mw8(W,z,H)}),$.command("continue [threadIDOrURL]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, interactive mode shows a picker. Use --last to continue the last thread for the current mode directly.").option("--last","Continue the last thread for the current mode directly").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(E,H,W)=>{let z=W.optsWithGlobals(),q=await E8(z);if(H.pick)DY.write(`${o0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
|
|
@@ -6277,8 +6277,8 @@ ${I}
|
|
|
6277
6277
|
`))}),H.args.length>0)Aw8(z,H);await BN0(z,W,H,A)}),He4(Q),Q}async function Lg(A,Q){await SZ((B)=>YE0(B,A,Q))}async function tVA(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 F4(`Cannot resume thread created by another user.
|
|
6278
6278
|
|
|
6279
6279
|
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 YUA(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 ZUA(A,Q,B){if(A.streamJson&&!Q)throw new F4("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new F4("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new F4("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new F4("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 F4("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archive&&!Q)throw new F4("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 F4("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 F4("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"
|
|
6280
|
-
Or pipe via stdin: echo "your message" | amp --execute`)}function Jw8(A,Q){if(UQ4([j90.parse({tool:"*",action:"allow"})]),SBA(A.settings))j.debug("Enabling permissions plugin"),Q.registerInternalPlugin({name:"permissions",entryPoint:E$1})}async function BN0(A,Q,B,$){if(Q.headless)return Yw8(A,Q,B);let J=await Q2(A,Q),Y=await J.serverStatusPromise,Z=await J.configService.getLatest(),X=bA(Y)&&Mg(Y.features,F2.THREAD_ACTORS_TUI),F=X&&!Q.takeMeBack;if(Q.showNeoWelcome&&!X)throw await J.asyncDispose(),new F4("--show-neo-welcome is only available with the Neo TUI feature flag",1);if(F)return Jw8(Z,J.pluginService),Zw8(A,Q,B,J);else{if(Q.threadId&&W7(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 F4(`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 Xw8(A,Q,B,$,{dependencies:J})}}async function Yw8(A,Q,B){let $=(z,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=uA1();j.info("Startup phase",{phase:z,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};B9(B,Q);let J=process.hrtime.bigint(),Y=await Q2(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(kD(Z))throw _40(Z,A.ampURL);let X=bA(Z)?Z:null,F=X?.user.email;await RX1(B,Q,Z);let D=t_(Z),G=F00(Q,D);if(G instanceof Error)l5(G.message);if(X&&!Bv(Q.mode,F))throw new F4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!F||!ZQ(F)))throw new F4("Headless executor mode is only available for Amp employees",1);RU0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new F4("API key required for headless mode. Please run `amp login` first.",1);let K=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(K&&!W7(K))throw new F4(`Invalid thread ID: ${K}`,1);let E=K?void 0:await ww8({dependencies:Y,apiKey:U,visibility:G??void 0}),H=K??E?.threadId;if(!H)throw new F4("Failed to resolve headless thread ID",1);let W=await Jt4(H);if(W.status==="already-running")await Y.asyncDispose(),await tW(),process.exit(0);try{await os4({ampURL:A.ampURL,apiKey:U,workspaceRoot:process.cwd(),threadId:H,ownerUserId:E?.ownerUserId,threadVersion:E?.threadVersion,agentMode:E?.agentMode,initialToolDiscovery:Promise.all([Y.mcpService.initialized,Y.toolboxService.initialized]).then(()=>{return}),configService:Y.configService,mcpService:Y.mcpService,toolService:Y.toolService,skillService:Y.skillService,fileSystem:Y.fileSystem,pluginService:Y.pluginService,pluginPlatform:Y.headlessPluginPlatform})}finally{await W.release(),await Y.asyncDispose()}await tW(),process.exit(0)}async function Zw8(A,Q,B,$){let{userInput:J,stdinInput:Y}=await YUA(Q),Z=!!Q.streamJson||!!Q.streamJsonThinking;ZUA({...Q,streamJson:Z},A.executeMode,J),B9(B,Q);let X=Q.threadId&&W7(Q.threadId)?Q.threadId:void 0,F=Q.observe?i8(Q.observe)??WB(Q.observe):void 0,D=await $.serverStatusPromise;if(kD(D))throw _40(D,A.ampURL);let G=await $.secretStorage.get("apiKey",A.ampURL);if(!G)throw new F4("API key required. Please run `amp login` first.",1);let V=bA(D)&&ZQ(D.user.email);if(V)RU0();if(A.executeMode){b31($.mcpService,A.settings);try{let U=AN0(B,Q),K=await $C(),E=X?U:QE0({agentMode:Q.mode,explicitEffort:U,sessionState:K}),H=X?void 0:BE0(await vu($.configService),{agentMode:Q.mode,explicitEffort:U,sessionState:K}),W=await Ks4({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 tW(),process.exit(0)}else{let U=AN0(B,Q),K=Oj($.configService,{usesThreadActors:!0}),E=new k_($.fuzzyServer),H=process.cwd();await K$1({ampURL:A.ampURL,apiKey:G,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??pJ(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:W})=>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.showNeoWelcome,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:U}),process.exit(0)}}async function Xw8(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(z0,A0)=>{let J0=Number(process.hrtime.bigint()-A0)/1e6,a=uA1();j.info("Startup phase",{phase:z0,phaseMs:Math.round(J0),sinceMainMs:a===null?void 0:Math.round(a)})},{userInput:X,stdinInput:F}=await YUA(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;ZUA({...Q,streamJson:D},A.executeMode,X),B9(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await Q2(A,Q),U=V.hasAPIKeyAtStartup,K=V.serverStatus==="pending";if(j.info("Interactive auth startup mode",{deferInteractiveAuth:K,hasAPIKeyAtStartup:U,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!J)Z("runMainThread:createThreadDependencies",G);let{serverStatus:E}=V;if(!K&&kD(E))throw _40(E,A.ampURL);let H=bA(E)?E:null,W=H?.user.email,z=!!(W&&ZQ(W));if(z)RU0();if(!K)await RX1(B,Q,E);let q=t_(E),N=q?.features??[],I=q?.team??null,w=F00(Q,q);if(w instanceof Error)l5(w.message);if(H&&!Bv(Q.mode,W))throw new F4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let C=Q.threadId&&W7(Q.threadId)?Q.threadId:void 0;G=process.hrtime.bigint();let O=await $N0(V);Z("runMainThread:createWorkerDeps",G);let P=A.executeMode?void 0:async(z0)=>Lg(z0,"interactive"),k={threadService:V.threadService,workerDeps:O,createThread:async(z0)=>{let A0=K?await V.serverStatusPromise:E,J0=await PU0(A.settings,process.cwd(),t_(A0),w);if(J0 instanceof Error)l5(J0.message);return eY1(O,{threadMeta:J0?yZ(J0):void 0,agentMode:z0??Q.mode,onFirstAssistantMessage:P})},validateThreadOwnership:async(z0,A0)=>{if(A0?.nonBlockingOwnershipCheck){tVA(z0,V.configService,V.viewerUserIDPromise).catch((J0)=>{if(J0 instanceof F4){if(A0.onOwnershipError){A0.onOwnershipError(J0,z0);return}eW(J0,z0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:J0})});return}try{await tVA(z0,V.configService,V.viewerUserIDPromise)}catch(J0){if(J0 instanceof F4)throw J0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:J0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:P,handleError:eW},_=async()=>{try{return LFA(k,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(z0){if(z0 instanceof F4)throw z0;throw await eW(z0,Q.threadId),Error("handleError should have called process.exit()")}},f=(async()=>{if(K){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await V.configService.getLatest(),A0=Pc(z0),J0=await OA.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(A0)});if(J0.ok)return j.info("User free tier status:",J0),J0.result;return}catch(z0){j.error("Failed to fetch free tier status:",z0);return}})(),b=!A.executeMode?new M$1:null,y,u=null;if(b)y=b,u=(async()=>{let z0=K?await V.serverStatusPromise:V.serverStatus;if(kD(z0))throw _40(z0,A.ampURL);await RX1(B,Q,z0);let A0=process.hrtime.bigint(),J0=await _();if(Z("runMainThread:createThreadPool",A0),b.attach(J0),X){let a=await y1(J0.threadHandles$);if(!a)throw new F4("No active thread is available yet.",1);await a.sendMessage({content:[{type:"text",text:X}]})}})(),u.catch(async(z0)=>{let A0=z0 instanceof Error?z0:Error(String(z0));b.setInitError(A0),await eW(z0,Q.threadId)});else G=process.hrtime.bigint(),y=await _(),Z("runMainThread:createThreadPool",G);let p=Q.notifications!==void 0?Q.notifications:!A.executeMode,d=H!==null&&Mg(H.features,F2.TUI_VOICE_NOTIF);if(K)V.serverStatusPromise.then((z0)=>{d=bA(z0)&&Mg(z0.features,F2.TUI_VOICE_NOTIF)}).catch((z0)=>{j.debug("Failed to resolve TUI voice notification feature flag",{error:z0})});G=process.hrtime.bigint();let g=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),Qw8({configService:V.configService,threadService:V.threadService,config:g,useNotificationsForService:p,isTUIVoiceNotifEnabled:()=>d,threadViewStates$:()=>y.threadHandles$.pipe(i4((z0)=>{if(!z0)return g0.of({});return u6(z0.thread$,z0.threadViewState$).pipe(O1(([A0,J0])=>({[A0.id]:J0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){b31(V.mcpService,A.settings);let z0=AN0(B,Q),A0=await $C(),J0=C?z0:QE0({agentMode:Q.mode,explicitEffort:z0,sessionState:A0}),a={userInput:X,stdinInput:F,dependencies:V,streamJson:D,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:z,agentMode:Q.mode,reasoningEffort:J0,labels:Q.label},r=await Eo4({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 V70();let z0=await _D({jetbrainsOnly:Q.jetbrains});if(z0.length===0){if(Q.jetbrains)n=!await V.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let A0=z0[0];if(A0)a8.selectConfig(A0)}else c=!0}G=process.hrtime.bigint();let B0=B31("0.0.1777706852-g76c1b8",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let O0=new u31(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),X&&A.executeMode){let z0=await y1(y.threadHandles$);if(!z0)throw new F4("No active thread is available yet.",1);await z0.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),U0={...i,launchCount:i.launchCount+1,lastReasoningEffortByMode:Q0?{...i.lastReasoningEffortByMode,[Q.mode]:Q0}:i.lastReasoningEffortByMode};SZ((z0)=>({...z0,launchCount:z0.launchCount+1}));try{if(G=process.hrtime.bigint(),await b$A({history:new Ze,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:OA,threadPool:y,createSystemPromptDeps:async()=>$UA(V),ideClient:a8,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:hI8,logFile:{path:$},sessionState:U0,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-02T07:31:06.538Z"},(z0)=>new T$1({...z0,threadPool:z0.threadPool},(A0)=>new sY1({...A0,threadState:A0.threadState}))),Z("runMainThread:mountApp-returned",G),u)await u}finally{await y.dispose().catch((z0)=>{j.error("Failed to dispose thread pool during shutdown",z0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function E8(A){if(j.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)DY.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
6281
|
-
`);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 vF4({get:async(X)=>{if(X!==Pi)return;try{let F=await BUA(jX1,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(X,F)=>{if(X!==Pi)return;await xI8(P40.dirname(jX1),{recursive:!0}),await fI8(jX1,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:sB0()});d84($);let J=await HK0({...A,workspaceTrust:{current:!0,changes:ax0},getHook:process.env.AMP_URL?(X,F)=>{if(X==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(A.mcpConfig){let X=await F1A(A.mcpConfig);J=D1A(J,X)}let Y=P40.dirname(J.getSettingsFilePath());Px4(wu,Y),J=L54(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()}),!QN(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:JE0(await He(A,J))}}function Fw8(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 Dw8(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=P40.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?uI8:at));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function Gw8(){Lc4();let A=Fw8(process.argv),Q=Dw8(process.argv,A),B=ka4(Q),$=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)o0.level=0;if(mI8(j),j.info("Starting Amp CLI.",{version:"0.0.
|
|
6280
|
+
Or pipe via stdin: echo "your message" | amp --execute`)}function Jw8(A,Q){if(UQ4([j90.parse({tool:"*",action:"allow"})]),SBA(A.settings))j.debug("Enabling permissions plugin"),Q.registerInternalPlugin({name:"permissions",entryPoint:E$1})}async function BN0(A,Q,B,$){if(Q.headless)return Yw8(A,Q,B);let J=await Q2(A,Q),Y=await J.serverStatusPromise,Z=await J.configService.getLatest(),X=bA(Y)&&Mg(Y.features,F2.THREAD_ACTORS_TUI),F=X&&!Q.takeMeBack;if(Q.showNeoWelcome&&!X)throw await J.asyncDispose(),new F4("--show-neo-welcome is only available with the Neo TUI feature flag",1);if(F)return Jw8(Z,J.pluginService),Zw8(A,Q,B,J);else{if(Q.threadId&&W7(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 F4(`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 Xw8(A,Q,B,$,{dependencies:J})}}async function Yw8(A,Q,B){let $=(z,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=uA1();j.info("Startup phase",{phase:z,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};B9(B,Q);let J=process.hrtime.bigint(),Y=await Q2(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(kD(Z))throw _40(Z,A.ampURL);let X=bA(Z)?Z:null,F=X?.user.email;await RX1(B,Q,Z);let D=t_(Z),G=F00(Q,D);if(G instanceof Error)l5(G.message);if(X&&!Bv(Q.mode,F))throw new F4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!F||!ZQ(F)))throw new F4("Headless executor mode is only available for Amp employees",1);RU0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new F4("API key required for headless mode. Please run `amp login` first.",1);let K=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(K&&!W7(K))throw new F4(`Invalid thread ID: ${K}`,1);let E=K?void 0:await ww8({dependencies:Y,apiKey:U,visibility:G??void 0}),H=K??E?.threadId;if(!H)throw new F4("Failed to resolve headless thread ID",1);let W=await Jt4(H);if(W.status==="already-running")await Y.asyncDispose(),await tW(),process.exit(0);try{await os4({ampURL:A.ampURL,apiKey:U,workspaceRoot:process.cwd(),threadId:H,ownerUserId:E?.ownerUserId,threadVersion:E?.threadVersion,agentMode:E?.agentMode,initialToolDiscovery:Promise.all([Y.mcpService.initialized,Y.toolboxService.initialized]).then(()=>{return}),configService:Y.configService,mcpService:Y.mcpService,toolService:Y.toolService,skillService:Y.skillService,fileSystem:Y.fileSystem,pluginService:Y.pluginService,pluginPlatform:Y.headlessPluginPlatform})}finally{await W.release(),await Y.asyncDispose()}await tW(),process.exit(0)}async function Zw8(A,Q,B,$){let{userInput:J,stdinInput:Y}=await YUA(Q),Z=!!Q.streamJson||!!Q.streamJsonThinking;ZUA({...Q,streamJson:Z},A.executeMode,J),B9(B,Q);let X=Q.threadId&&W7(Q.threadId)?Q.threadId:void 0,F=Q.observe?i8(Q.observe)??WB(Q.observe):void 0,D=await $.serverStatusPromise;if(kD(D))throw _40(D,A.ampURL);let G=await $.secretStorage.get("apiKey",A.ampURL);if(!G)throw new F4("API key required. Please run `amp login` first.",1);let V=bA(D)&&ZQ(D.user.email);if(V)RU0();if(A.executeMode){b31($.mcpService,A.settings);try{let U=AN0(B,Q),K=await $C(),E=X?U:QE0({agentMode:Q.mode,explicitEffort:U,sessionState:K}),H=X?void 0:BE0(await vu($.configService),{agentMode:Q.mode,explicitEffort:U,sessionState:K}),W=await Ks4({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 tW(),process.exit(0)}else{let U=AN0(B,Q),K=Oj($.configService,{usesThreadActors:!0}),E=new k_($.fuzzyServer),H=process.cwd();await K$1({ampURL:A.ampURL,apiKey:G,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??pJ(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:W})=>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.showNeoWelcome,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:U}),process.exit(0)}}async function Xw8(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(z0,A0)=>{let J0=Number(process.hrtime.bigint()-A0)/1e6,a=uA1();j.info("Startup phase",{phase:z0,phaseMs:Math.round(J0),sinceMainMs:a===null?void 0:Math.round(a)})},{userInput:X,stdinInput:F}=await YUA(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;ZUA({...Q,streamJson:D},A.executeMode,X),B9(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await Q2(A,Q),U=V.hasAPIKeyAtStartup,K=V.serverStatus==="pending";if(j.info("Interactive auth startup mode",{deferInteractiveAuth:K,hasAPIKeyAtStartup:U,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!J)Z("runMainThread:createThreadDependencies",G);let{serverStatus:E}=V;if(!K&&kD(E))throw _40(E,A.ampURL);let H=bA(E)?E:null,W=H?.user.email,z=!!(W&&ZQ(W));if(z)RU0();if(!K)await RX1(B,Q,E);let q=t_(E),N=q?.features??[],I=q?.team??null,w=F00(Q,q);if(w instanceof Error)l5(w.message);if(H&&!Bv(Q.mode,W))throw new F4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let C=Q.threadId&&W7(Q.threadId)?Q.threadId:void 0;G=process.hrtime.bigint();let O=await $N0(V);Z("runMainThread:createWorkerDeps",G);let P=A.executeMode?void 0:async(z0)=>Lg(z0,"interactive"),k={threadService:V.threadService,workerDeps:O,createThread:async(z0)=>{let A0=K?await V.serverStatusPromise:E,J0=await PU0(A.settings,process.cwd(),t_(A0),w);if(J0 instanceof Error)l5(J0.message);return eY1(O,{threadMeta:J0?yZ(J0):void 0,agentMode:z0??Q.mode,onFirstAssistantMessage:P})},validateThreadOwnership:async(z0,A0)=>{if(A0?.nonBlockingOwnershipCheck){tVA(z0,V.configService,V.viewerUserIDPromise).catch((J0)=>{if(J0 instanceof F4){if(A0.onOwnershipError){A0.onOwnershipError(J0,z0);return}eW(J0,z0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:J0})});return}try{await tVA(z0,V.configService,V.viewerUserIDPromise)}catch(J0){if(J0 instanceof F4)throw J0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:J0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:P,handleError:eW},_=async()=>{try{return LFA(k,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(z0){if(z0 instanceof F4)throw z0;throw await eW(z0,Q.threadId),Error("handleError should have called process.exit()")}},f=(async()=>{if(K){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await V.configService.getLatest(),A0=Pc(z0),J0=await OA.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(A0)});if(J0.ok)return j.info("User free tier status:",J0),J0.result;return}catch(z0){j.error("Failed to fetch free tier status:",z0);return}})(),b=!A.executeMode?new M$1:null,y,u=null;if(b)y=b,u=(async()=>{let z0=K?await V.serverStatusPromise:V.serverStatus;if(kD(z0))throw _40(z0,A.ampURL);await RX1(B,Q,z0);let A0=process.hrtime.bigint(),J0=await _();if(Z("runMainThread:createThreadPool",A0),b.attach(J0),X){let a=await y1(J0.threadHandles$);if(!a)throw new F4("No active thread is available yet.",1);await a.sendMessage({content:[{type:"text",text:X}]})}})(),u.catch(async(z0)=>{let A0=z0 instanceof Error?z0:Error(String(z0));b.setInitError(A0),await eW(z0,Q.threadId)});else G=process.hrtime.bigint(),y=await _(),Z("runMainThread:createThreadPool",G);let p=Q.notifications!==void 0?Q.notifications:!A.executeMode,d=H!==null&&Mg(H.features,F2.TUI_VOICE_NOTIF);if(K)V.serverStatusPromise.then((z0)=>{d=bA(z0)&&Mg(z0.features,F2.TUI_VOICE_NOTIF)}).catch((z0)=>{j.debug("Failed to resolve TUI voice notification feature flag",{error:z0})});G=process.hrtime.bigint();let g=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),Qw8({configService:V.configService,threadService:V.threadService,config:g,useNotificationsForService:p,isTUIVoiceNotifEnabled:()=>d,threadViewStates$:()=>y.threadHandles$.pipe(i4((z0)=>{if(!z0)return g0.of({});return u6(z0.thread$,z0.threadViewState$).pipe(O1(([A0,J0])=>({[A0.id]:J0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){b31(V.mcpService,A.settings);let z0=AN0(B,Q),A0=await $C(),J0=C?z0:QE0({agentMode:Q.mode,explicitEffort:z0,sessionState:A0}),a={userInput:X,stdinInput:F,dependencies:V,streamJson:D,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:z,agentMode:Q.mode,reasoningEffort:J0,labels:Q.label},r=await Eo4({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 V70();let z0=await _D({jetbrainsOnly:Q.jetbrains});if(z0.length===0){if(Q.jetbrains)n=!await V.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let A0=z0[0];if(A0)a8.selectConfig(A0)}else c=!0}G=process.hrtime.bigint();let B0=B31("0.0.1777710388-ge5e9da",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let O0=new u31(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),X&&A.executeMode){let z0=await y1(y.threadHandles$);if(!z0)throw new F4("No active thread is available yet.",1);await z0.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),U0={...i,launchCount:i.launchCount+1,lastReasoningEffortByMode:Q0?{...i.lastReasoningEffortByMode,[Q.mode]:Q0}:i.lastReasoningEffortByMode};SZ((z0)=>({...z0,launchCount:z0.launchCount+1}));try{if(G=process.hrtime.bigint(),await b$A({history:new Ze,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:OA,threadPool:y,createSystemPromptDeps:async()=>$UA(V),ideClient:a8,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:hI8,logFile:{path:$},sessionState:U0,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-02T08:30:18.646Z"},(z0)=>new T$1({...z0,threadPool:z0.threadPool},(A0)=>new sY1({...A0,threadState:A0.threadState}))),Z("runMainThread:mountApp-returned",G),u)await u}finally{await y.dispose().catch((z0)=>{j.error("Failed to dispose thread pool during shutdown",z0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function E8(A){if(j.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)DY.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
6281
|
+
`);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 vF4({get:async(X)=>{if(X!==Pi)return;try{let F=await BUA(jX1,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(X,F)=>{if(X!==Pi)return;await xI8(P40.dirname(jX1),{recursive:!0}),await fI8(jX1,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:sB0()});d84($);let J=await HK0({...A,workspaceTrust:{current:!0,changes:ax0},getHook:process.env.AMP_URL?(X,F)=>{if(X==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(A.mcpConfig){let X=await F1A(A.mcpConfig);J=D1A(J,X)}let Y=P40.dirname(J.getSettingsFilePath());Px4(wu,Y),J=L54(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()}),!QN(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:JE0(await He(A,J))}}function Fw8(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 Dw8(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=P40.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?uI8:at));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function Gw8(){Lc4();let A=Fw8(process.argv),Q=Dw8(process.argv,A),B=ka4(Q),$=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)o0.level=0;if(mI8(j),j.info("Starting Amp CLI.",{version:"0.0.1777710388-ge5e9da",buildTimestamp:"2026-05-02T08:30:18.646Z"}),process.platform==="win32"&&yP())Be4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new F4(g7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await $w8(B).parseAsync(process.argv)}jx4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await Gw8().catch(eW)});async function Vw8(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}
|
|
6282
6282
|
`);else if(!QN(A.ampURL))N5.write(`Logging in to ${new URL(A.ampURL).hostname}
|
|
6283
6283
|
`);let $=process.env.AMP_API_KEY;if($)N5.write(`API key found in environment variable, storing...
|
|
6284
6284
|
`),await Q.set("apiKey",$,A.ampURL),N5.write(`API key successfully stored.
|