@sourcegraph/amp 0.0.1777564642-g9dea90 → 0.0.1777566445-g595ffb
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +9 -9
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -4794,12 +4794,12 @@ ${E}`))}},error:(K)=>{if(!U)U=!0,F(Error(`Failed to spawn brew: ${K.message}`))}
|
|
|
4794
4794
|
${E}`;if(Y==="pnpm"&&E.includes("Unable to find the global bin directory"))W+=`
|
|
4795
4795
|
|
|
4796
4796
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
4797
|
-
npm install -g @sourcegraph/amp`;F(Error(W))}},error:(K)=>{if(!V)V=!0,F(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,X()}})})}l0();l0();MI();async function UK0(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=ze(A,D),V=G<0,U,K;if(F.time){let E=F.time[A],W=F.time[D],H=Date.now();if(E)U=Math.floor((H-new Date(E).getTime())/3600000);if(W)K=Math.floor((H-new Date(W).getTime())/3600000)}return R.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 R.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var zo5="https://static.ampcode.com/cli/cli-version.txt";async function KK0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${zo5}?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=ze(A,J),Z=Y<0;return R.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return R.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var qo5=604800000;function et4(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>qo5)return{ageMs:B};return null}function ze(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 t81(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Q)return null;let B=parseInt(Q[1],10)*1000,$=Q[2],J=B!==0?mU(B):void 0;return{sha:$,age:J}}catch{return null}}j1();l0();import{readFile as No5,realpath as Io5}from"node:fs/promises";import{homedir as wo5}from"node:os";import{dirname as Ae4,join as e81}from"node:path";async function Qe4(A){switch(A){case"binary":case"brew":return Co5(Ke());case"npm":case"pnpm":case"yarn":case"bun":return Mo5();case"bootstrap":return Lo5()}}async function Co5(A){let Q=await vG(A,["--version"],5000);if(Q.reason!=="success")return R.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function Mo5(){try{let A=process.argv[1];if(!A)return null;let Q=await Io5(A),B=Ae4(Ae4(Q));return await Be4(e81(B,"package.json"))}catch(A){return R.debug("failed to read installed version from package.json",{error:A}),null}}async function Lo5(){try{let A=process.env.AMP_HOME??e81(wo5(),".amp");return await Be4(e81(A,"package","package.json"))}catch(A){return R.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function Be4(A){let Q=await No5(A,"utf8"),B=JSON.parse(Q);if(B.name!=="@sourcegraph/amp")return R.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var Oo5=3600000,jo5=5000;function A31(A,Q,B={}){let $=new t4,J=$.pipe($6({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??Oo5,X=!1,F=()=>{X=!0};return setImmediate(async()=>{let D=new SY().scoped("update");if(Y>0){if(await gU(Y),X)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!X){let U=await Ro5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await gU(jo5),X)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!X){let W=Math.min(K,E);await gU(W),E-=W}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:F}}async function Ro5(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 GK0(),X=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:X});let F;if(X)F=await KK0(A);else{let V=await _P();F=await UK0(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 Qe4(Z);if(V&&ze(V,F.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:F.latestVersion}),J.updatedTo=V,ze(A,V)<0){let U=await iH(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!==Ke()){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 He(F.latestVersion,Z),J.updatedTo=F.latestVersion;let V=await iH(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}}MI();import{stderr as yG}from"node:process";function $e4(A){let Q=new nI().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 g81($.force||!1,$.verbose||!1,"0.0.
|
|
4797
|
+
npm install -g @sourcegraph/amp`;F(Error(W))}},error:(K)=>{if(!V)V=!0,F(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,X()}})})}l0();l0();MI();async function UK0(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=ze(A,D),V=G<0,U,K;if(F.time){let E=F.time[A],W=F.time[D],H=Date.now();if(E)U=Math.floor((H-new Date(E).getTime())/3600000);if(W)K=Math.floor((H-new Date(W).getTime())/3600000)}return R.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 R.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var zo5="https://static.ampcode.com/cli/cli-version.txt";async function KK0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${zo5}?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=ze(A,J),Z=Y<0;return R.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return R.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var qo5=604800000;function et4(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>qo5)return{ageMs:B};return null}function ze(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 t81(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Q)return null;let B=parseInt(Q[1],10)*1000,$=Q[2],J=B!==0?mU(B):void 0;return{sha:$,age:J}}catch{return null}}j1();l0();import{readFile as No5,realpath as Io5}from"node:fs/promises";import{homedir as wo5}from"node:os";import{dirname as Ae4,join as e81}from"node:path";async function Qe4(A){switch(A){case"binary":case"brew":return Co5(Ke());case"npm":case"pnpm":case"yarn":case"bun":return Mo5();case"bootstrap":return Lo5()}}async function Co5(A){let Q=await vG(A,["--version"],5000);if(Q.reason!=="success")return R.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function Mo5(){try{let A=process.argv[1];if(!A)return null;let Q=await Io5(A),B=Ae4(Ae4(Q));return await Be4(e81(B,"package.json"))}catch(A){return R.debug("failed to read installed version from package.json",{error:A}),null}}async function Lo5(){try{let A=process.env.AMP_HOME??e81(wo5(),".amp");return await Be4(e81(A,"package","package.json"))}catch(A){return R.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function Be4(A){let Q=await No5(A,"utf8"),B=JSON.parse(Q);if(B.name!=="@sourcegraph/amp")return R.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var Oo5=3600000,jo5=5000;function A31(A,Q,B={}){let $=new t4,J=$.pipe($6({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??Oo5,X=!1,F=()=>{X=!0};return setImmediate(async()=>{let D=new SY().scoped("update");if(Y>0){if(await gU(Y),X)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!X){let U=await Ro5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await gU(jo5),X)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!X){let W=Math.min(K,E);await gU(W),E-=W}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:F}}async function Ro5(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 GK0(),X=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:X});let F;if(X)F=await KK0(A);else{let V=await _P();F=await UK0(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 Qe4(Z);if(V&&ze(V,F.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:F.latestVersion}),J.updatedTo=V,ze(A,V)<0){let U=await iH(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!==Ke()){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 He(F.latestVersion,Z),J.updatedTo=F.latestVersion;let V=await iH(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}}MI();import{stderr as yG}from"node:process";function $e4(A){let Q=new nI().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 g81($.force||!1,$.verbose||!1,"0.0.1777566445-g595ffb"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new nI("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 _o5($.targetVersion)});A.addCommand(B)}function Po5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
|
|
4798
4798
|
`),$=!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 _o5(A){let B=process.platform==="win32"&&PP()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:$,renderProgress:J}=Po5(yG);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")yG.write(a0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
4799
4799
|
|
|
4800
4800
|
`));try{if(!A){yG.write(a0.blue(`Checking for updates...
|
|
4801
|
-
`));let X=!1,F;if(PP()){let D=await KK0("0.0.
|
|
4802
|
-
`));let V=await iH("0.0.
|
|
4801
|
+
`));let X=!1,F;if(PP()){let D=await KK0("0.0.1777566445-g595ffb");X=D.hasUpdate,F=D.latestVersion}else{let D=await _P(),G=await UK0("0.0.1777566445-g595ffb",D);X=G.hasUpdate,F=G.latestVersion}if(!X){let D=t81("0.0.1777566445-g595ffb"),G=D?.age?`released ${D.age} ago`:`built ${mU(new Date("2026-04-30T16:31:16.215Z"))} ago`;yG.write(a0.green(`✓ Amp is already up to date on version ${"0.0.1777566445-g595ffb"} (${G})
|
|
4802
|
+
`));let V=await iH("0.0.1777566445-g595ffb",B);if(V.warning)yG.write(`
|
|
4803
4803
|
`+a0.yellow(V.warning)+`
|
|
4804
4804
|
`);process.exit(0)}if(!F)yG.write(a0.yellow("[WARN] could not find latest version")),process.exit(0);A=F}yG.write(a0.blue(`Updating to version ${A}...
|
|
4805
4805
|
`)),await He(A,void 0,(X)=>{$(),yG.write(a0.dim(`Running: ${X}
|
|
@@ -5336,7 +5336,7 @@ Ctrl-X, Y, Z to unlock`;if(E){let n=G.text.replace(/`([^`]+)`/g,"$1")+`
|
|
|
5336
5336
|
`));if(X.tools.length===0)Z.push(new L(` └─ No tools available
|
|
5337
5337
|
`,J));else for(let G of X.tools)RJ8(Z,G,B);Z.push(new L(`
|
|
5338
5338
|
`))}return Z}function RJ8(A,Q,B){let{colors:$,app:J}=B,Y=PJ8(Q.status,B);if(A.push(new L(` ${Y.icon} `,new x({color:Y.color}))),A.push(new L(Q.name,new x({color:Q.status==="pending"?$.warning:J.command}))),Q.status==="pending")A.push(new L(" discovering...",new x({color:$.foreground,dim:!0})));else if(Q.description)A.push(new L(` ${zQA(Q.description,50)}`,new x({color:$.foreground,dim:!0})));if(Q.error)A.push(new L(` ${zQA(Q.error,40)}`,new x({color:J.toolError})));A.push(new L(`
|
|
5339
|
-
`))}function PJ8(A,Q){let{colors:B,app:$}=Q;switch(A){case"pending":return{icon:"◌",color:B.warning};case"registered":return{icon:"•",color:B.mutedForeground};case"failed":return{icon:"✗",color:$.toolError};case"duplicate":return{icon:"◇",color:B.warning};default:return{icon:"?",color:B.foreground}}}function zQA(A,Q){let B=A.replace(/\s+/g," ").trim();if(pA(B)<=Q)return B;let $="...",J=pA($);if(Q<=J)return jF($,Q);return`${jF(B,Q-J,!0,"")}${$}`}class iB1 extends v0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;isFirstOpen;notificationService;onThreadArchived;initialUserInput;openThreadPickerOnStart;neoContext;constructor(A){super();this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.initialThreadID=A.initialThreadID,this.isFirstOpen=A.isFirstOpen??!1,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.initialUserInput=A.initialUserInput,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new wQA}}class wQA extends k0{editorController=new S3;commandPalette=new se(this);commandRegistry=new LQ1;toastController=new G21;exitHintTimer=new yu(this,1000);ideStatus=new r3(this,{});threadNavigationHistory=new qQ1;draftThreadSettings={};draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;connectionErrorsSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;firstOpenDialogVisible=!1;debugOverlayVisible=!1;focusDebugVisible=!1;agentModeCostInfo=null;unregisterCommands=null;pluginIntegration=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 k2A({configService:this.widget.configService},A,Q,B)};setThreadVisibility=(A,Q)=>{return v2A({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await B5A({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await $5A({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 J5A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(M$.getInstance().interceptConsole(),this.widget.isFirstOpen)this.firstOpenDialogVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:Q,error:B})=>{if(R.error("Neo failed to connect to thread",{threadID:Q,error:B}),!Q)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),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 zQ1({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=c4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this,Q=this.widget.neoContext.pluginService?_2A({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)=>MB1({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()}},{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 hQ1({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 lB1({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 s6(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:()=>{aJ(this.widget.neoContext.settingsFilePath).catch((J)=>{R.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 bQ1({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 _Q1({commands:_$.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new A6({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new l({text:new L($21({version:"0.0.1777564642-g9dea90",buildTimestamp:"2026-04-30T16:00:58.215Z",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:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:g1.ctrl("c"),status:{type:"enabled"},run:(J,Y)=>{vA.maybeInvoke(Y,new Dh)}},...Q,...q2A(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 cB1({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=Z4.of(A),Z=[new p0({constraints:M1.tight(J.size.width,J.size.height),child:$})];if(this.commandPalette.isEnabled())Z.push(new QA({debugLabel:"CommandPaletteOverlay",child:new OQ1({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible)Z.push(MB1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.firstOpenDialogVisible)Z.push(new QA({debugLabel:"NeoFirstOpenDialogOverlay",child:new xQ1({onDismiss:this.dismissFirstOpenDialog})}));if(Z.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.agentModeCostInfo)Z.push(new QA({debugLabel:"AgentModeCostModalOverlay",child:this.buildAgentModeCostModal(this.agentModeCostInfo)}));if(this.widget.neoContext.isInternalUser)Z.push(new TQ1({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:z10.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)Z.push(new fQ1);return new $7({neoContext:this.widget.neoContext,child:new _$({commandRegistry:this.commandRegistry,child:new EC({completionBuilder:this.widget.completionBuilder,child:new T3({controller:this.toastController,child:new vA({actions:this.buildActions(),child:new u8({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[g1.ctrl("c"),new fW0],[g1.ctrl("o"),new bW0],[g1.alt("i"),new hW0],[g1.alt("p"),new nw],[g1.ctrl("t"),new gW0]]),child:new AA({debugLabel:"AppShellFocus",child:new V21({controller:this.toastController,child:new zA({children:Z})})})})})})})})})}buildActions(){let A=new M4(()=>{if(nJ.hasAnyCopyableSelection())return nJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new M4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new M4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new M4(()=>{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 M4(()=>{return c4.instance.stop(),"handled"}),Y=new M4((V)=>{if(!V.text)return"ignored";return c4.instance.tuiInstance.clipboard.writeText(V.text).then(()=>{this.toastController.show(V.successMessage,"success",2000)}).catch((U)=>{R.error("Failed to copy Neo text to clipboard",{error:U}),this.toastController.show(V.failureMessage,"error",2000)}),"handled"}),Z=new M4(()=>{return c4.instance.toggleFrameStatsOverlay(),"handled"}),X=new M4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),F=new M4(()=>{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 O51(V).then((U)=>{this.toastController.show(ba4(U),"success",2000)}).catch((U)=>{let K=U instanceof Error?U.message:String(U);R.error("Failed to copy thread log",{error:U}),this.toastController.show(`Failed to copy thread log: ${K}`,"error",2000)}),"handled"}),D=new M4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"}),G=new M4((V)=>{return this.setState(()=>{this.agentModeCostInfo={agentMode:V.agentMode,speedCostMultiplier:V.speedCostMultiplier}}),"handled"});return new Map([[fW0,A],[r00,$],[Dh,J],[vZ,Y],[e00,B],[bW0,Q],[hW0,X],[q_,F],[A10,G],[nw,Z],[gW0,D]])}dismissAgentModeCostModal=()=>{if(!this.agentModeCostInfo)return;this.setState(()=>{this.agentModeCostInfo=null})};buildAgentModeCostModal(A){let Q=(X8(A.agentMode)?.displayName??A.agentMode).toLowerCase();return new A6({header:"Fast Mode Enabled",minWidth:54,maxWidth:72,footer:[{keys:["Esc"],label:"close"}],onDismiss:this.dismissAgentModeCostModal,child:new l({text:new L(`This agent mode now runs in fast mode.
|
|
5339
|
+
`))}function PJ8(A,Q){let{colors:B,app:$}=Q;switch(A){case"pending":return{icon:"◌",color:B.warning};case"registered":return{icon:"•",color:B.mutedForeground};case"failed":return{icon:"✗",color:$.toolError};case"duplicate":return{icon:"◇",color:B.warning};default:return{icon:"?",color:B.foreground}}}function zQA(A,Q){let B=A.replace(/\s+/g," ").trim();if(pA(B)<=Q)return B;let $="...",J=pA($);if(Q<=J)return jF($,Q);return`${jF(B,Q-J,!0,"")}${$}`}class iB1 extends v0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;isFirstOpen;notificationService;onThreadArchived;initialUserInput;openThreadPickerOnStart;neoContext;constructor(A){super();this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.initialThreadID=A.initialThreadID,this.isFirstOpen=A.isFirstOpen??!1,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.initialUserInput=A.initialUserInput,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new wQA}}class wQA extends k0{editorController=new S3;commandPalette=new se(this);commandRegistry=new LQ1;toastController=new G21;exitHintTimer=new yu(this,1000);ideStatus=new r3(this,{});threadNavigationHistory=new qQ1;draftThreadSettings={};draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;connectionErrorsSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;firstOpenDialogVisible=!1;debugOverlayVisible=!1;focusDebugVisible=!1;agentModeCostInfo=null;unregisterCommands=null;pluginIntegration=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 k2A({configService:this.widget.configService},A,Q,B)};setThreadVisibility=(A,Q)=>{return v2A({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await B5A({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await $5A({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 J5A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(M$.getInstance().interceptConsole(),this.widget.isFirstOpen)this.firstOpenDialogVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:Q,error:B})=>{if(R.error("Neo failed to connect to thread",{threadID:Q,error:B}),!Q)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),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 zQ1({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=c4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this,Q=this.widget.neoContext.pluginService?_2A({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)=>MB1({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()}},{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 hQ1({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 lB1({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 s6(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:()=>{aJ(this.widget.neoContext.settingsFilePath).catch((J)=>{R.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 bQ1({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 _Q1({commands:_$.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new A6({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new l({text:new L($21({version:"0.0.1777566445-g595ffb",buildTimestamp:"2026-04-30T16:31:16.215Z",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:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:g1.ctrl("c"),status:{type:"enabled"},run:(J,Y)=>{vA.maybeInvoke(Y,new Dh)}},...Q,...q2A(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 cB1({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=Z4.of(A),Z=[new p0({constraints:M1.tight(J.size.width,J.size.height),child:$})];if(this.commandPalette.isEnabled())Z.push(new QA({debugLabel:"CommandPaletteOverlay",child:new OQ1({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible)Z.push(MB1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.firstOpenDialogVisible)Z.push(new QA({debugLabel:"NeoFirstOpenDialogOverlay",child:new xQ1({onDismiss:this.dismissFirstOpenDialog})}));if(Z.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.agentModeCostInfo)Z.push(new QA({debugLabel:"AgentModeCostModalOverlay",child:this.buildAgentModeCostModal(this.agentModeCostInfo)}));if(this.widget.neoContext.isInternalUser)Z.push(new TQ1({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:z10.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)Z.push(new fQ1);return new $7({neoContext:this.widget.neoContext,child:new _$({commandRegistry:this.commandRegistry,child:new EC({completionBuilder:this.widget.completionBuilder,child:new T3({controller:this.toastController,child:new vA({actions:this.buildActions(),child:new u8({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[g1.ctrl("c"),new fW0],[g1.ctrl("o"),new bW0],[g1.alt("i"),new hW0],[g1.alt("p"),new nw],[g1.ctrl("t"),new gW0]]),child:new AA({debugLabel:"AppShellFocus",child:new V21({controller:this.toastController,child:new zA({children:Z})})})})})})})})})}buildActions(){let A=new M4(()=>{if(nJ.hasAnyCopyableSelection())return nJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new M4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new M4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new M4(()=>{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 M4(()=>{return c4.instance.stop(),"handled"}),Y=new M4((V)=>{if(!V.text)return"ignored";return c4.instance.tuiInstance.clipboard.writeText(V.text).then(()=>{this.toastController.show(V.successMessage,"success",2000)}).catch((U)=>{R.error("Failed to copy Neo text to clipboard",{error:U}),this.toastController.show(V.failureMessage,"error",2000)}),"handled"}),Z=new M4(()=>{return c4.instance.toggleFrameStatsOverlay(),"handled"}),X=new M4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),F=new M4(()=>{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 O51(V).then((U)=>{this.toastController.show(ba4(U),"success",2000)}).catch((U)=>{let K=U instanceof Error?U.message:String(U);R.error("Failed to copy thread log",{error:U}),this.toastController.show(`Failed to copy thread log: ${K}`,"error",2000)}),"handled"}),D=new M4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"}),G=new M4((V)=>{return this.setState(()=>{this.agentModeCostInfo={agentMode:V.agentMode,speedCostMultiplier:V.speedCostMultiplier}}),"handled"});return new Map([[fW0,A],[r00,$],[Dh,J],[vZ,Y],[e00,B],[bW0,Q],[hW0,X],[q_,F],[A10,G],[nw,Z],[gW0,D]])}dismissAgentModeCostModal=()=>{if(!this.agentModeCostInfo)return;this.setState(()=>{this.agentModeCostInfo=null})};buildAgentModeCostModal(A){let Q=(X8(A.agentMode)?.displayName??A.agentMode).toLowerCase();return new A6({header:"Fast Mode Enabled",minWidth:54,maxWidth:72,footer:[{keys:["Esc"],label:"close"}],onDismiss:this.dismissAgentModeCostModal,child:new l({text:new L(`This agent mode now runs in fast mode.
|
|
5340
5340
|
|
|
5341
5341
|
`+`↯${Q} costs ${A.speedCostMultiplier} the standard rate for this mode.
|
|
5342
5342
|
|
|
@@ -6111,7 +6111,7 @@ ${J}`,Q);this.line=B,this.column=$,this.codeblock=J}}/*!
|
|
|
6111
6111
|
`),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 L(G.slice(1,-1),new x({color:$.app.keybind,bold:!0})));else Y.push(new L(G,new x({color:B.colorScheme.foreground})));if(Z<J.length-1)Y.push(new L(`
|
|
6112
6112
|
`))}return new p0({decoration:{color:B.colorScheme.background,border:A4.all(new Q4($.app.keybind,1,"rounded"))},child:new f0({padding:w0.symmetric(0,1),child:new l({text:new L(void 0,void 0,Y)})})})}}class JJ1 extends a2{chartData;highlightIndex;showAxes;colors;constructor({key:A,chartData:Q,highlightIndex:B=null,showAxes:$=!0,colors:J=_z0}){super(A?{key:A}:{});this.chartData=Q,this.highlightIndex=B,this.showAxes=$,this.colors=J}createRenderObject(){return new BJ1({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 eJA(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?e3: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?e3: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 fV8(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?e3: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,W=Math.round((1-E)*(V-1));return{x:K,y:W}}case"line":case"sparkline":case"stacked-area":{let D=Y?e3: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 bV8(A){let Q=0;for(let B of A)for(let $ of B.points)if($.value>Q)Q=$.value;return Q||1}function uV8(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 hV8(A,Q,B,$,J,Y,Z){let X;try{let E=S1.of(A),W=_0.of(A);X={foreground:E.colorScheme.foreground,background:E.colorScheme.background,border:W.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,W)=>new L(W,U,void 0,IK0(E),()=>{s6(A,E)});if($.length<=1){if(V.push(new L(`${Q.label}: `,F)),Q.link)V.push(K(Q.link,Y(Q.value)));else V.push(new L(Y(Q.value),D));if(Q.meta)V.push(new L(` (${Q.meta})`,G))}else{let E=Z==="stacked-bar"||Z==="stacked-area";V.push(new L(`${Q.label}
|
|
6113
6113
|
`,F));let W=0;for(let H=0;H<$.length;H++){let z=$[H],q=z.points[B];if(!q)continue;W+=q.value;let N=z.color??J[H%J.length]??X.foreground;if(V.push(new L("● ",new x({color:N}))),V.push(new L(`${z.name}: `,G)),q.link)V.push(K(q.link,Y(q.value)));else V.push(new L(Y(q.value),D));if(H<$.length-1||E)V.push(new L(`
|
|
6114
|
-
`))}if(E)V.push(new L(" ",G)),V.push(new L("Total: ",G)),V.push(new L(Y(W),D))}return new p0({decoration:{color:X.background,border:A4.all(new Q4(X.border,1,"rounded"))},child:new l({text:new L(void 0,void 0,V)})})}l0();T8();JO();F9();F8();VQ();co();IX();HQ();N7();Q$();MR();r4();xy();Sk();j1();l0();HQ();class YJ1{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.1777564642-g9dea90"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await m70(Q,this.configService)}catch(Q){R.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 hC extends v0{props;constructor(A){super();this.props=A}createState(){return new AYA}}class AYA extends k0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(A){let Q=(B)=>{this.setState(()=>{this._state=B(this._state)})};return this.widget.props.builder(A,Q,this._state)}}class QYA extends k0{controller=new S3;focusNode=new H6({debugLabel:"CommandArgumentPrompt",onKey:(A)=>{if(A.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(A){let Q=_0.of(A),{colors:B,app:$}=Q,J=this.widget.props.isRequiredArg??!0,Y=this.controller.text.trim().length>0,Z=!J||Y,X=A4.all(new Q4(B.foreground,1,"solid")),F=new L$({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(K)=>{let E=K.trim();if(J&&E.length===0)return;this.widget.props.onSubmit(E)},autofocus:!0,style:{textColor:B.foreground,border:null},maxLines:1}),D=new A1({children:[new p0({decoration:{color:B.background},child:new l({text:new L(">",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 L(this.widget.props.title,new x({color:$.command,bold:!0})):new L("",void 0,[new L("Command: ",new x({color:B.foreground})),new L(this.widget.props.commandName,new x({color:$.command,bold:!0}))])})}),V=[];if(Z)V.push(new L("Enter",new x({color:$.keybind}))),V.push(new L(" to submit, ",new x({color:B.foreground,dim:!0})));V.push(new L("Esc",new x({color:$.keybind}))),V.push(new L(" to cancel",new x({color:B.foreground,dim:!0})));let U=new p0({padding:w0.symmetric(1,0),child:new l({text:new L("",void 0,V)})});return new p0({decoration:{border:X,color:B.background},padding:w0.all(1),child:new x0({children:[G,new L0({height:1}),D,new r6,U]})})}}class b10 extends v0{props;constructor(A){super();this.props=A}createState(){return new QYA}}Q$();class BYA extends k0{controller=new S3;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>=w7)return!1;let Q=await vF(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(A){let Q=_0.of(A),{colors:B,app:$}=Q,Y=Z4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),X=new nG({controller:this.controller,triggers:[new eJ],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:c4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),F=new AA({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:X}),D=new p0({constraints:new M1({maxHeight:Z}),padding:w0.symmetric(1,0),child:F}),G=new p0({padding:w0.symmetric(1,0),child:new l({text:new L("",void 0,[new L("Command: ",new x({color:B.foreground})),new L(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 L("",void 0,[new L("Esc",new x({color:$.keybind})),new L(" again to clear input",new x({color:B.foreground,dim:!0}))]):new L("",void 0,[new L("Press ",new x({color:B.foreground,dim:!0})),new L("Enter",new x({color:$.keybind})),new L(" to submit, ",new x({color:B.foreground,dim:!0})),new L("Esc",new x({color:$.keybind})),new L(" to clear",new x({color:B.foreground,dim:!0}))])})}),U=[G,new L0({height:1}),new T1({child:D}),new L0({height:1}),V];return new p0({decoration:{border:A4.all(new Q4(B.foreground,1,"solid")),color:B.background},padding:w0.all(1),child:new x0({children:U})})}}class ZJ1 extends v0{props;constructor(A){super();this.props=A}createState(){return new BYA}}function $YA(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 XJ1 extends L1{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)=>$YA(J.pubDate).length));return new t6({items:Q,getLabel:(J)=>J.title,onAccept:(J)=>this.props.onSelect?.(J),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(J,Y,Z,X)=>{let F=_0.of(X),{colors:D}=F,G=F.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(W,H)=>new L0({width:H,child:A1.end([new l({text:new L(W,new x({color:K}))})])});return new p0({decoration:V?{color:V}:void 0,padding:w0.symmetric(2,0),child:new A1({children:[new T1({child:new l({text:new L(J.title,new x({color:U})),overflow:"ellipsis",maxLines:1})}),new L0({width:2}),E($YA(J.pubDate),B)]})})}})}}class xB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!xB._instance)xB._instance=new xB;return xB._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()}}l0();class JYA extends k0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){R.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){R.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let B=this.widget.props.currentLabels||[],$=this.labels.some((Y)=>Y.name===Q),J=B.includes(Q);return!$&&!J}build(A){let Q=_0.of(A),{app:B,colors:$}=Q,J=this.currentQuery.trim().toLowerCase(),Y=J.length>0?this.getValidationError(J):null,Z=this.getAvailableLabels(),F=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...Z];return new t6({title:"Add Label",items:F,getLabel:(D)=>{if("__isCreateMarker"in D)return this.currentQuery.trim().toLowerCase();return D.name},onAccept:(D)=>{if("__isCreateMarker"in D)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(D.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:Y||"Type to create a new label",renderItem:(D,G,V,U)=>{let K=G?B.selectionBackground:void 0,E=G?B.selectionForeground:$.foreground;if("__isCreateMarker"in D&&D.__isCreateMarker){let H=this.currentQuery.trim().toLowerCase();return new p0({decoration:K?{color:K}:void 0,padding:w0.symmetric(2,0),child:new l({text:new L("",void 0,[new L("Create new label: ",new x({color:E})),new L(H,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 L(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 FJ1 extends v0{props;constructor(A){super();this.props=A}createState(){return new JYA}}class rG extends v0{props;constructor(A){super();this.props=A}createState(){return new YYA}}class YYA extends k0{_spinner=new M6;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(A){let Q=_0.of(A),{colors:B,app:$}=Q,J=A4.all(new Q4(B.foreground,1,"solid")),Y=this._spinner.toBraille(),Z=new l({textAlign:"center",text:new L("",void 0,[new L(Y,new x({color:$.processing})),new L(" ",void 0),new L(this.widget.props.message,new x({color:B.foreground}))])}),F=[new T1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)F.push(new L0({height:2,child:new p0({padding:w0.symmetric(2,0),child:new l({text:new L("",new x({dim:!0}),[new L("Press ",new x({color:B.foreground})),new L("Esc",new x({color:B.info})),new L(" to cancel",new x({color:B.foreground}))])})})}));let D=new p0({decoration:new a4(B.background,J),child:new L0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:F})})});if(this.widget.props.onAbort)return new QA({debugLabel:"LoadingDialog",child:new AA({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class JE extends v0{props;constructor(A){super();this.props=A}createState(){return new ZYA}}class ZYA extends k0{scrollController=new Z6;scrollAreaKey=new I2("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 t2}resolveFooterStyle(A){if(this.isWidgetMessage(A))return A.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let B=Q.size;if(typeof B.height==="number"&&B.height>0)return this.viewportHeight=B.height,B.height}return this.viewportHeight}build(A){let Q=_0.of(A),B=this.widget.props.message,$=(()=>{if(this.isWidgetMessage(B))return{title:B.title,type:B.type};if(B instanceof Error&&B.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:B.message};if(B instanceof Error&&B.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:B.message};let G=uE0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=A4.all(new Q4(Q.colors.border,1,"solid")),Z=new p0({padding:w0.symmetric(1,0),child:new l({text:new L($.title,new x({color:J,bold:!0}))})}),X=this.isWidgetMessage(B)?B.widget:new l({text:new L($.description,new x({color:Q.colors.foreground})),selectable:!0}),F=new T1({child:new r2({child:new p0({padding:w0.symmetric(1,0),child:new A1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new xA({controller:this.scrollController,autofocus:!0,child:X})}),new M2({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 L("",void 0,[new L("Press ",new x({color:Q.colors.foreground,dim:!0})),new L("R",new x({color:Q.app.keybind})),new L(" to retry, ",new x({color:Q.colors.foreground,dim:!0})),new L("Esc",new x({color:Q.app.keybind})),new L(" to cancel",new x({color:Q.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new L("",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 L("",U,[new L("Press ",U),new L("Escape",V),new L(" to close • Use ",U),new L("↑↓",V),new L(" or ",U),new L("j/k",V),new L(" to scroll",U)])}return new L("Press any key to close",new x({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new QA({debugLabel:"MessageDialog",child:new zA({fit:"expand",children:[new i1({onClick:()=>{},child:new L0}),new AA({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 x0({mainAxisAlignment:"center",children:[Z,new L0({height:1}),F,D]})})})]})})}}T8();class XYA extends v0{props;constructor(A){super();this.props=A}createState(){return new FYA}}class FYA extends k0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=A.startsWith("file://")?A.slice(7):A,B=this.widget.props.cwd;if(Q.startsWith(B))return Q.slice(B.length+1);return Q}statusIcon(A){let Q=s3.default(),{colors:B,app:$}=Q;switch(A){case"loading":return{icon:"◌",color:B.warning};case"active":return{icon:"✓",color:$.toolSuccess};case"error":return{icon:"✗",color:$.toolError}}}build(A){let Q=_0.of(A),{app:B}=Q;if(this.plugins.length===0)return new l({text:new L("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 L(`${Y}/${J} ${E4(J,"plugin")} active`,new x({bold:!0}))),Z>0||X>0)$.push(new L(` (${Z} ${E4(Z,"command")}, ${X} ${E4(X,"tool")})`,new x({dim:!0})));$.push(new L(`
|
|
6114
|
+
`))}if(E)V.push(new L(" ",G)),V.push(new L("Total: ",G)),V.push(new L(Y(W),D))}return new p0({decoration:{color:X.background,border:A4.all(new Q4(X.border,1,"rounded"))},child:new l({text:new L(void 0,void 0,V)})})}l0();T8();JO();F9();F8();VQ();co();IX();HQ();N7();Q$();MR();r4();xy();Sk();j1();l0();HQ();class YJ1{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.1777566445-g595ffb"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await m70(Q,this.configService)}catch(Q){R.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 hC extends v0{props;constructor(A){super();this.props=A}createState(){return new AYA}}class AYA extends k0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(A){let Q=(B)=>{this.setState(()=>{this._state=B(this._state)})};return this.widget.props.builder(A,Q,this._state)}}class QYA extends k0{controller=new S3;focusNode=new H6({debugLabel:"CommandArgumentPrompt",onKey:(A)=>{if(A.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(A){let Q=_0.of(A),{colors:B,app:$}=Q,J=this.widget.props.isRequiredArg??!0,Y=this.controller.text.trim().length>0,Z=!J||Y,X=A4.all(new Q4(B.foreground,1,"solid")),F=new L$({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(K)=>{let E=K.trim();if(J&&E.length===0)return;this.widget.props.onSubmit(E)},autofocus:!0,style:{textColor:B.foreground,border:null},maxLines:1}),D=new A1({children:[new p0({decoration:{color:B.background},child:new l({text:new L(">",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 L(this.widget.props.title,new x({color:$.command,bold:!0})):new L("",void 0,[new L("Command: ",new x({color:B.foreground})),new L(this.widget.props.commandName,new x({color:$.command,bold:!0}))])})}),V=[];if(Z)V.push(new L("Enter",new x({color:$.keybind}))),V.push(new L(" to submit, ",new x({color:B.foreground,dim:!0})));V.push(new L("Esc",new x({color:$.keybind}))),V.push(new L(" to cancel",new x({color:B.foreground,dim:!0})));let U=new p0({padding:w0.symmetric(1,0),child:new l({text:new L("",void 0,V)})});return new p0({decoration:{border:X,color:B.background},padding:w0.all(1),child:new x0({children:[G,new L0({height:1}),D,new r6,U]})})}}class b10 extends v0{props;constructor(A){super();this.props=A}createState(){return new QYA}}Q$();class BYA extends k0{controller=new S3;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>=w7)return!1;let Q=await vF(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(A){let Q=_0.of(A),{colors:B,app:$}=Q,Y=Z4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),X=new nG({controller:this.controller,triggers:[new eJ],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:c4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),F=new AA({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:X}),D=new p0({constraints:new M1({maxHeight:Z}),padding:w0.symmetric(1,0),child:F}),G=new p0({padding:w0.symmetric(1,0),child:new l({text:new L("",void 0,[new L("Command: ",new x({color:B.foreground})),new L(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 L("",void 0,[new L("Esc",new x({color:$.keybind})),new L(" again to clear input",new x({color:B.foreground,dim:!0}))]):new L("",void 0,[new L("Press ",new x({color:B.foreground,dim:!0})),new L("Enter",new x({color:$.keybind})),new L(" to submit, ",new x({color:B.foreground,dim:!0})),new L("Esc",new x({color:$.keybind})),new L(" to clear",new x({color:B.foreground,dim:!0}))])})}),U=[G,new L0({height:1}),new T1({child:D}),new L0({height:1}),V];return new p0({decoration:{border:A4.all(new Q4(B.foreground,1,"solid")),color:B.background},padding:w0.all(1),child:new x0({children:U})})}}class ZJ1 extends v0{props;constructor(A){super();this.props=A}createState(){return new BYA}}function $YA(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 XJ1 extends L1{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)=>$YA(J.pubDate).length));return new t6({items:Q,getLabel:(J)=>J.title,onAccept:(J)=>this.props.onSelect?.(J),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(J,Y,Z,X)=>{let F=_0.of(X),{colors:D}=F,G=F.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(W,H)=>new L0({width:H,child:A1.end([new l({text:new L(W,new x({color:K}))})])});return new p0({decoration:V?{color:V}:void 0,padding:w0.symmetric(2,0),child:new A1({children:[new T1({child:new l({text:new L(J.title,new x({color:U})),overflow:"ellipsis",maxLines:1})}),new L0({width:2}),E($YA(J.pubDate),B)]})})}})}}class xB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!xB._instance)xB._instance=new xB;return xB._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()}}l0();class JYA extends k0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){R.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){R.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let B=this.widget.props.currentLabels||[],$=this.labels.some((Y)=>Y.name===Q),J=B.includes(Q);return!$&&!J}build(A){let Q=_0.of(A),{app:B,colors:$}=Q,J=this.currentQuery.trim().toLowerCase(),Y=J.length>0?this.getValidationError(J):null,Z=this.getAvailableLabels(),F=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...Z];return new t6({title:"Add Label",items:F,getLabel:(D)=>{if("__isCreateMarker"in D)return this.currentQuery.trim().toLowerCase();return D.name},onAccept:(D)=>{if("__isCreateMarker"in D)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(D.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:Y||"Type to create a new label",renderItem:(D,G,V,U)=>{let K=G?B.selectionBackground:void 0,E=G?B.selectionForeground:$.foreground;if("__isCreateMarker"in D&&D.__isCreateMarker){let H=this.currentQuery.trim().toLowerCase();return new p0({decoration:K?{color:K}:void 0,padding:w0.symmetric(2,0),child:new l({text:new L("",void 0,[new L("Create new label: ",new x({color:E})),new L(H,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 L(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 FJ1 extends v0{props;constructor(A){super();this.props=A}createState(){return new JYA}}class rG extends v0{props;constructor(A){super();this.props=A}createState(){return new YYA}}class YYA extends k0{_spinner=new M6;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(A){let Q=_0.of(A),{colors:B,app:$}=Q,J=A4.all(new Q4(B.foreground,1,"solid")),Y=this._spinner.toBraille(),Z=new l({textAlign:"center",text:new L("",void 0,[new L(Y,new x({color:$.processing})),new L(" ",void 0),new L(this.widget.props.message,new x({color:B.foreground}))])}),F=[new T1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)F.push(new L0({height:2,child:new p0({padding:w0.symmetric(2,0),child:new l({text:new L("",new x({dim:!0}),[new L("Press ",new x({color:B.foreground})),new L("Esc",new x({color:B.info})),new L(" to cancel",new x({color:B.foreground}))])})})}));let D=new p0({decoration:new a4(B.background,J),child:new L0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:F})})});if(this.widget.props.onAbort)return new QA({debugLabel:"LoadingDialog",child:new AA({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class JE extends v0{props;constructor(A){super();this.props=A}createState(){return new ZYA}}class ZYA extends k0{scrollController=new Z6;scrollAreaKey=new I2("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 t2}resolveFooterStyle(A){if(this.isWidgetMessage(A))return A.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let B=Q.size;if(typeof B.height==="number"&&B.height>0)return this.viewportHeight=B.height,B.height}return this.viewportHeight}build(A){let Q=_0.of(A),B=this.widget.props.message,$=(()=>{if(this.isWidgetMessage(B))return{title:B.title,type:B.type};if(B instanceof Error&&B.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:B.message};if(B instanceof Error&&B.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:B.message};let G=uE0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=A4.all(new Q4(Q.colors.border,1,"solid")),Z=new p0({padding:w0.symmetric(1,0),child:new l({text:new L($.title,new x({color:J,bold:!0}))})}),X=this.isWidgetMessage(B)?B.widget:new l({text:new L($.description,new x({color:Q.colors.foreground})),selectable:!0}),F=new T1({child:new r2({child:new p0({padding:w0.symmetric(1,0),child:new A1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new xA({controller:this.scrollController,autofocus:!0,child:X})}),new M2({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 L("",void 0,[new L("Press ",new x({color:Q.colors.foreground,dim:!0})),new L("R",new x({color:Q.app.keybind})),new L(" to retry, ",new x({color:Q.colors.foreground,dim:!0})),new L("Esc",new x({color:Q.app.keybind})),new L(" to cancel",new x({color:Q.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new L("",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 L("",U,[new L("Press ",U),new L("Escape",V),new L(" to close • Use ",U),new L("↑↓",V),new L(" or ",U),new L("j/k",V),new L(" to scroll",U)])}return new L("Press any key to close",new x({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new QA({debugLabel:"MessageDialog",child:new zA({fit:"expand",children:[new i1({onClick:()=>{},child:new L0}),new AA({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 x0({mainAxisAlignment:"center",children:[Z,new L0({height:1}),F,D]})})})]})})}}T8();class XYA extends v0{props;constructor(A){super();this.props=A}createState(){return new FYA}}class FYA extends k0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=A.startsWith("file://")?A.slice(7):A,B=this.widget.props.cwd;if(Q.startsWith(B))return Q.slice(B.length+1);return Q}statusIcon(A){let Q=s3.default(),{colors:B,app:$}=Q;switch(A){case"loading":return{icon:"◌",color:B.warning};case"active":return{icon:"✓",color:$.toolSuccess};case"error":return{icon:"✗",color:$.toolError}}}build(A){let Q=_0.of(A),{app:B}=Q;if(this.plugins.length===0)return new l({text:new L("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 L(`${Y}/${J} ${E4(J,"plugin")} active`,new x({bold:!0}))),Z>0||X>0)$.push(new L(` (${Z} ${E4(Z,"command")}, ${X} ${E4(X,"tool")})`,new x({dim:!0})));$.push(new L(`
|
|
6115
6115
|
|
|
6116
6116
|
`));for(let F of this.plugins){let{icon:D,color:G}=this.statusIcon(F.status),V=this.getRelativePath(F.uri.toString());if($.push(new L(`${D} `,new x({color:G}))),$.push(new L(V,new x({bold:!0}))),$.push(new L(` ${F.status}`,new x({dim:!0}))),$.push(new L(`
|
|
6117
6117
|
`)),F.status==="active"&&F.registeredEvents.length>0)$.push(new L(" Events: ",new x({dim:!0}))),$.push(new L(F.registeredEvents.join(", "),new x({color:B.link}))),$.push(new L(`
|
|
@@ -6289,7 +6289,7 @@ ${t.content||""}`:t.content||"",P0=[],h0=t.baseDir.startsWith("file://")?Jq0(t.b
|
|
|
6289
6289
|
`)}function cXA(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=a54({settings:{url:Y.ampURL,proxy:Z},secrets:{getToken:(D,G)=>Y.secrets.get(D,G)}}),F=await mA.userDisplayBalanceInfo({},{config:X});if(!F.ok){if(F.error.code==="auth-required")process.stderr.write(a0.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(a0.red("Error: ")+F.error.message+`
|
|
6290
6290
|
`),process.exit(1)}process.stdout.write(await QW8(F.result.displayText)+`
|
|
6291
6291
|
`),process.exit(0)})}var CN8=I40.join(NX,"logs","headless.log"),UX1=I40.join(Ku,"device-id.json"),MN8=`cli-tui-${zVA(16).toString("hex")}`;async function LN8(){for(let A of XO)try{if((await A.listConfigs()).length>0)return A}catch(Q){R.debug("Failed to detect query-based IDE integration",{ideName:A.ideName,error:Q})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => I4(Dg(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){XY.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
|
|
6292
|
-
`)}function ON8(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")y9("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")y9("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)y9("internal.model",jN8(Q.model))}function VVA(A){let Q=A.indexOf(":");if(Q===-1)throw new K4(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let B=A.slice(0,Q).trim(),$=A.slice(Q+1).trim();if(!B||!$)throw new K4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function jN8(A){if(!A.includes("="))return VVA(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new K4(`Invalid mode-specific model entry "${$}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let Y=$.slice(0,J).trim(),Z=$.slice(J+1).trim();if(!Y)throw new K4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new K4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);VVA(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new K4("No valid model overrides found in --model flag value.",1);return Q}function RN8(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 PN8(A){try{return await qVA(A,"utf-8")}catch{return A}}async function EX1(A,Q,B){let $=RN8(A,Q);if(!$)return;let J=bA(B)?B.features:[],Y=bA(B)?B.user.email:void 0;if(!w40(J,D9.HARNESS_SYSTEM_PROMPT)&&!(Y&&XQ(Y)))throw new K4("You are not allowed to do this.",1);y9("systemPrompt",await PN8($))}function w40(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function _N8(A){return A!=="pending"}function n_(A){if(!bA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function TN8(A){let Q=n_(A);if(Q)return Q.id;if(RD(A))throw Error(A.error.message);throw Error("unreachable")}function SN8(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 kN8(A){let $=SN8(A)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new K4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function C40(A,Q){let B=R51(Error(A.error.message));if(B.message===g7.networkOffline||B.message===g7.networkTimeout)return kN8(Q);if(B.message!==g7.internalBug)return new K4(B.message,1,B.suggestion);return new K4(A.error.message.replace(/^Error: /,""),1)}var UVA=[{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??LF,description:`Custom settings file path (overrides the default location ${LF})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(R).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${ht})`},{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:BO.SMART.key,description:`Set the agent mode (${ZJ({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(ZJ().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"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}],KVA=(A)=>("deprecated"in A)&&A.deprecated===!0,vN8=(A)=>("hidden"in A)&&A.hidden===!0,yN8=(A)=>("default"in A),xN8=(A)=>("default"in A)?A.default:void 0,NVA=[{name:"toggle-skills-count",entryPoint:ye},{name:"permissions",entryPoint:aB1}];function fN8(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 K4(g7.unknownCommand(B),1,Z)}}async function oq0(A){return{...A,getThreadEnvironment:RH,osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new Aj(A.fileSystem),generateThreadTitle:XE4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>AB(A.configService),pluginService:A.pluginService}}function IVA(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:RH,filesystem:A.fileSystem,threadService:A.threadService}}var wVA="code-tour";function KX1(A){return A.filter((Q)=>Q.name!==wVA)}function bN8(A){return{...A,skills:A.skills.pipe(I1(KX1)),getSkills:async()=>KX1(await A.getSkills()),getSkill:async(Q)=>Q===wVA?void 0:A.getSkill(Q),getSkillsList:async()=>{let Q=KX1(await A.getSkills());return Sy(Q)}}}var nq0=X1.file(wN8.homedir()),WX1=process.env.XDG_CONFIG_HOME?X1.file(process.env.XDG_CONFIG_HOME):U1.joinPath(nq0,".config");function uN8(A){return Px4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(AK0())QK0();else if(process.platform==="darwin"&&Q==="idle"&&A.isTUIVoiceNotifEnabled())Rx4();else As(Q);let B=mP(),$=ce();if((!B||$||MK0())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(fG("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(fG("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(mP()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function A2(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;T84("0.0.
|
|
6292
|
+
`)}function ON8(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")y9("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")y9("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)y9("internal.model",jN8(Q.model))}function VVA(A){let Q=A.indexOf(":");if(Q===-1)throw new K4(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let B=A.slice(0,Q).trim(),$=A.slice(Q+1).trim();if(!B||!$)throw new K4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function jN8(A){if(!A.includes("="))return VVA(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new K4(`Invalid mode-specific model entry "${$}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let Y=$.slice(0,J).trim(),Z=$.slice(J+1).trim();if(!Y)throw new K4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new K4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);VVA(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new K4("No valid model overrides found in --model flag value.",1);return Q}function RN8(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 PN8(A){try{return await qVA(A,"utf-8")}catch{return A}}async function EX1(A,Q,B){let $=RN8(A,Q);if(!$)return;let J=bA(B)?B.features:[],Y=bA(B)?B.user.email:void 0;if(!w40(J,D9.HARNESS_SYSTEM_PROMPT)&&!(Y&&XQ(Y)))throw new K4("You are not allowed to do this.",1);y9("systemPrompt",await PN8($))}function w40(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function _N8(A){return A!=="pending"}function n_(A){if(!bA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function TN8(A){let Q=n_(A);if(Q)return Q.id;if(RD(A))throw Error(A.error.message);throw Error("unreachable")}function SN8(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 kN8(A){let $=SN8(A)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new K4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function C40(A,Q){let B=R51(Error(A.error.message));if(B.message===g7.networkOffline||B.message===g7.networkTimeout)return kN8(Q);if(B.message!==g7.internalBug)return new K4(B.message,1,B.suggestion);return new K4(A.error.message.replace(/^Error: /,""),1)}var UVA=[{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??LF,description:`Custom settings file path (overrides the default location ${LF})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(R).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${ht})`},{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:BO.SMART.key,description:`Set the agent mode (${ZJ({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(ZJ().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"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}],KVA=(A)=>("deprecated"in A)&&A.deprecated===!0,vN8=(A)=>("hidden"in A)&&A.hidden===!0,yN8=(A)=>("default"in A),xN8=(A)=>("default"in A)?A.default:void 0,NVA=[{name:"toggle-skills-count",entryPoint:ye},{name:"permissions",entryPoint:aB1}];function fN8(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 K4(g7.unknownCommand(B),1,Z)}}async function oq0(A){return{...A,getThreadEnvironment:RH,osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new Aj(A.fileSystem),generateThreadTitle:XE4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>AB(A.configService),pluginService:A.pluginService}}function IVA(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:RH,filesystem:A.fileSystem,threadService:A.threadService}}var wVA="code-tour";function KX1(A){return A.filter((Q)=>Q.name!==wVA)}function bN8(A){return{...A,skills:A.skills.pipe(I1(KX1)),getSkills:async()=>KX1(await A.getSkills()),getSkill:async(Q)=>Q===wVA?void 0:A.getSkill(Q),getSkillsList:async()=>{let Q=KX1(await A.getSkills());return Sy(Q)}}}var nq0=X1.file(wN8.homedir()),WX1=process.env.XDG_CONFIG_HOME?X1.file(process.env.XDG_CONFIG_HOME):U1.joinPath(nq0,".config");function uN8(A){return Px4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(AK0())QK0();else if(process.platform==="darwin"&&Q==="idle"&&A.isTUIVoiceNotifEnabled())Rx4();else As(Q);let B=mP(),$=ce();if((!B||$||MK0())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(fG("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(fG("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(mP()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function A2(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;T84("0.0.1777566445-g595ffb");let Y=tk({storage:A.settings,secretStorage:A.secrets,workspaceRoot:u0.of(X1.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:nq0,userConfigDir:WX1});lQA(Y);let Z=await Y.getLatest();R.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let X=!1;{let p=await A.secrets.get("apiKey",A.ampURL);if(X=Boolean(p),R.info("API key lookup before login",{found:Boolean(p),ampURL:A.ampURL,deferAuth:$}),!p)if($)R.info("No API key found, continuing startup with deferred auth");else{q5.write(`No API key found. Starting login flow...
|
|
6293
6293
|
`);let d=await hN8(A),g=await A.secrets.get("apiKey",A.ampURL);if(R.info("Login flow completed",{success:d,storedKeyPresent:Boolean(g),ampURL:A.ampURL}),!d)await dH(),process.exit(1);X=!0}}{let p=await Y.getLatest(),d=p.settings.url,g=p.secrets.isSet?.[d];R.info("Config secrets state after login",{configURL:d,apiKeySet:g?.apiKey??!1})}let F=k1(AB(Y).pipe(M5(_N8))),D=$?"pending":await F;if(!$)R.info("Server status resolved",{status:"ready",isAuthenticated:bA(D),isError:RD(D),errorMessage:RD(D)?D.error.message:void 0});let G=F.then((p)=>TN8(p));G.catch(()=>{return});let{toolService:V,dispose:U}=SD0({configService:Y}),K=new Map,E=()=>K.clear(),W=new vm0(Y,A.settings.getWorkspaceRootPath()),H=GJ0({configService:Y,filesystem:D8}),z=zF4({configService:Y,trustStore:W,skillMCPServers:H.skillMCPServers,createOAuthProvider:async(p,d,g)=>{let n=`${p}:${d}`,c=K.get(n);if(c)return R.debug("Reusing existing OAuth provider for server",{serverName:p,serverUrl:d}),c;R.debug("Creating OAuth provider for server",{serverName:p,serverUrl:d});let $0=(async()=>{let j0=new KO(A.secrets),i=await j0.getClientInfo(p,d),e=g?.scopes??i?.scopes,G0=ps4();R.info("OAuth headless mode check",{useHeadless:G0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:q5.isTTY});let O0;if(G0)O0=A.executeMode?ms4():gs4(p);let A0=new Kb0({storage:j0,serverName:p,serverUrl:d,clientId:g?.clientId??i?.clientId,clientSecret:g?.clientSecret??i?.clientSecret,authUrl:g?.authUrl??i?.authUrl,tokenUrl:g?.tokenUrl??i?.tokenUrl,scopes:e,headlessAuthHandler:O0});return R.debug("OAuth provider created",{serverName:p,serverUrl:d,hasManualClientId:!!(g?.clientId??i?.clientId),willUseDCR:!(g?.clientId??i?.clientId),scopes:e,headlessMode:G0,executeMode:A.executeMode}),A0})();return K.set(n,$0),$0}}),q=pr({configService:Y,filesystem:D8,spawn:gf}),N;if(J)N=new Map;else if(A.executeMode){let p=await lk4({toolService:V,providers:[z,q],initialTimeout:15000});N=p.registrations;for(let[d,g]of p.initErrors)R.warn(`${d} provider initialization slow or failed:`,g)}else N=dr({toolService:V,providers:[z,q]});if(Q.jetbrains)YO("JetBrains");else if(Q.ide&&Ot4())YO("VS Code");else if(Q.ide&&jt4())YO("Neovim");else if(Q.ide){let p=await LN8();if(p){let d=$70(p.ideName);if(d)YO(d)}}if(A.executeMode)S84(!0);let I,w=a8.status.pipe(I1((p)=>Boolean(p.connected&&p.authenticated&&p.ideName&&Z34(p.ideName))),x4()).subscribe((p)=>{if(p){if(!I)I=V.registerTool(ck4)}else I?.dispose(),I=void 0}),C;if(!A.executeMode){let p=await A.settings.get("fuzzy.alwaysIncludePaths")??[];C=new Vu(process.cwd(),{alwaysIncludePaths:p},!0)}else C=new class extends Vu{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let O=new ud0(Jj(Y),{maxThreads:200});R.info("Starting Amp background services");let P=new eB1,k=process.env.PLUGINS??"off",_=Q.headless?A1A():void 0,f=_??new Mu({configService:Y}),h=f instanceof Mu?f:void 0;if(h)h.pluginExecutorKind="local";let b=Pi({configService:Y,fileSystem:D8,platform:f,internalPlugins:NVA,pluginFilter:k}),y=U$0({pluginService:b,toolService:V}),u={configService:Y,toolService:V,mcpService:z,skillService:H,toolboxService:q,trustStore:W,threadService:O,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:C,fileSystem:D8,terminal:P,pluginService:b,pluginPlatform:h,headlessPluginPlatform:_,serverStatus:D,serverStatusPromise:F,viewerUserIDPromise:G,hasAPIKeyAtStartup:X};return{...u,async asyncDispose(){if(u.mcpService.hasAuthenticatingClients())R.info("Waiting for OAuth authentication to complete before exit..."),await u.mcpService.waitForAuthentication();for(let p of N.values())p.dispose();await u.mcpService.dispose(),E(),await u.threadService.asyncDispose(),u.configService.unsubscribe(),U(),u.fuzzyServer.dispose(),u.settingsStorage[Symbol.dispose](),w.unsubscribe(),I?.dispose(),y.dispose(),await u.pluginService.dispose()}}}async function hN8(A){if(!A.executeMode){if(!await iK0("Would you like to log in to Amp? [(y)es, (n)o]: "))return q5.write(`Login cancelled. Run the command again to retry.
|
|
6294
6294
|
`),!1}return await CVA(A)}async function CVA(A){let Q=zVA(32).toString("hex"),B=await Cu(A.ampURL,Q),$=new AbortController;try{await HD(B,$.signal)}catch(Y){R.error("Error opening browser",{error:Y})}let J=await Cu(A.ampURL,Q,!1);q5.write(`If your browser does not open automatically, visit:
|
|
6295
6295
|
|
|
@@ -6297,7 +6297,7 @@ ${a0.blue.bold(J)}
|
|
|
6297
6297
|
|
|
6298
6298
|
`);try{return await g0A(A.ampURL,Q,A.secrets,$),q5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(Y){return R.error("Login failed",{error:Y}),XY.write(`
|
|
6299
6299
|
Login failed: ${Y instanceof Error?Y.message:String(Y)}
|
|
6300
|
-
`),!1}}function gN8(A){let Q=new nI().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)NP(),process.exit(0);let W=E.originalError??E;la4(W)}),t1A(Q,{version:"0.0.
|
|
6300
|
+
`),!1}}function gN8(A){let Q=new nI().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)NP(),process.exit(0);let W=E.originalError??E;la4(W)}),t1A(Q,{version:"0.0.1777566445-g595ffb",buildTimestamp:"2026-04-30T16:31:16.215Z",buildType:"'release'"}),Q.addHelpText("after",Ct4()),Q.configureHelp({formatHelp:Mt4}),Q.command("logout").description("Log out by removing stored API key").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await E8(H);await aN8(z)}),Q.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await E8(H);await nN8(z,await Ze(H,z.settings))}),Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(E,W,H)=>{let z=H.optsWithGlobals(),q=await E8(z);await ks4(E??"get",q.ampURL,q.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(E,W)=>{let H=W.optsWithGlobals(),z=await E8(H);await vs4(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 me4({raw:E.raw===!0}),process.exit(process.exitCode??0)}),Q.command("cplog <threadIDOrURL>",{hidden:!0}).summary("Copy a thread-scoped log file to the clipboard").description("Internal: snapshot <cwd>/.amp/in/<threadID>.log (written by the CLI for thread-scoped logs) to a timestamped JSONL file in the OS temp directory and copy that file to the clipboard for Slack paste.").action(async(E)=>{await fa4(E),process.exit(process.exitCode??0)}),Q.command("live-sync [threadIDOrURL]",{hidden:!0}).summary("Mirror live DTW thread changes into the current checkout").description("Experimental: watch a v2 thread URL or ID and mirror its live working-tree changes into your local checkout, or apply the current snapshot once and exit.").addHelpText("after",["","Examples:"," amp live-sync T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync --apply T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync https://ampcode.com/threads/T-5928a90d-d53b-488f-a829-4e36442142ee"].join(`
|
|
6301
6301
|
`)).option("--apply <threadIDOrURL>","Apply the current DTW thread snapshot once and exit").option("--checkout","Automatically check out the thread commit when it differs").option("--skip-checkout","Skip the startup checkout prompt when commits differ").action(async(E,W,H)=>{if(E&&W.apply)throw new K4("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let z=W.apply??E;if(!z||z.trim().length===0)q5.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.
|
|
6302
6302
|
|
|
6303
6303
|
`),H.outputHelp(),process.exit(0);let q=i8(z)??zB(z),N=H.optsWithGlobals(),I=await E8(N);B9(H,N);let w=await A2(I,N),C=!1;try{if(W.checkout&&W.skipCheckout)throw new K4("Choose either --checkout or --skip-checkout, not both.",1);if(RD(w.serverStatus))throw C40(w.serverStatus,I.ampURL);let O=bA(w.serverStatus)?w.serverStatus.features:void 0;if(!w40(O,D9.V2))throw new K4("live-sync is not enabled for your user",1);await _0A({ampURL:I.ampURL,threadId:q,configService:w.configService,threadService:w.threadService,apiKey:process.env.AMP_API_KEY,applyOnce:typeof W.apply==="string",checkoutMode:W.checkout?"always":W.skipCheckout?"never":"prompt",promptForYesNo:iK0}),C=!0}finally{if(await w.asyncDispose(),C)process.exit(0)}});let B=async(E,W,H)=>{tk({storage:W.settings,secretStorage:W.secrets,workspaceRoot:u0.of(X1.file(process.cwd())),defaultAmpURL:W.ampURL,homeDir:nq0,userConfigDir:WX1});let z={...W,executeMode:!1};await aq0(z,{...E,openThreadSwitcher:!0},H,A)},$=Q.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").option("--include-archived","Include archived threads in the list").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await E8(H);await HVA(H,z,W)});$.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await E8(H);await YI8(H,z,W)}),$.command("continue [threadIDOrURL]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, interactive mode shows a picker. Use --last to continue the last thread for the current mode directly.").option("--last","Continue the last thread for the current mode directly").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(E,W,H)=>{let z=H.optsWithGlobals(),q=await E8(z);if(W.pick)XY.write(`${a0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
|
|
@@ -6330,8 +6330,8 @@ ${I}
|
|
|
6330
6330
|
`))}),W.args.length>0)fN8(z,W);await aq0(z,H,W,A)}),$e4(Q),Q}async function Gg(A,Q){await PZ((B)=>sK0(B,A,Q))}async function EVA(A,Q,B){let $=Date.now(),[J,Y]=await Promise.all([mA.getThreadLinkInfo({thread:A},{config:Q}),B]);if(R.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 K4(`Cannot resume thread created by another user.
|
|
6331
6331
|
|
|
6332
6332
|
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 MVA(A){if(A.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof A.execute==="string"){let Q=(await GH0()).trimEnd();return{userInput:A.execute,stdinInput:Q||null}}return{userInput:(await GH0()).trimEnd(),stdinInput:null}}function LVA(A,Q,B){if(A.streamJson&&!Q)throw new K4("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new K4("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new K4("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new K4("The --stats and --stream-json flags are mutually exclusive output formats",1,'Use one or the other: amp --execute "your message" --stats OR amp --execute "your message" --stream-json');if(A.stats&&!Q)throw new K4("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archive&&!Q)throw new K4("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(A.streamJsonInput&&typeof A.execute==="string"&&A.execute.trim()!=="")throw new K4("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Q&&B===""&&!A.streamJsonInput&&!A.headless)throw new K4("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
|
|
6333
|
-
Or pipe via stdin: echo "your message" | amp --execute`)}async function aq0(A,Q,B,$){if(Q.headless)return mN8(A,Q,B);let J=await A2(A,Q),Y=await J.serverStatusPromise,Z=bA(Y)&&w40(Y.features,D9.THREAD_ACTORS_TUI),X=Z&&!Q.takeMeBack;if(Q.showNeoWelcome&&!Z)throw await J.asyncDispose(),new K4("--show-neo-welcome is only available with the Neo TUI feature flag",1);if(X)return pN8(A,Q,B,J);else return dN8(A,Q,B,$,{dependencies:J})}async function mN8(A,Q,B){let $=(z,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=gA1();R.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 A2(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(RD(Z))throw C40(Z,A.ampURL);let X=bA(Z)?Z:null,F=X?.user.email;await EX1(B,Q,Z);let D=n_(Z),G=B10(Q,D);if(G instanceof Error)l5(G.message);if(X&&!rk(Q.mode,F))throw new K4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!F||!XQ(F)))throw new K4("Headless executor mode is only available for Amp employees",1);let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new K4("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&&!KQ(K))throw new K4(`Invalid thread ID: ${K}`,1);let E=K?void 0:await $I8({dependencies:Y,apiKey:U,visibility:G??void 0}),W=K??E?.threadId;if(!W)throw new K4("Failed to resolve headless thread ID",1);let H=await is4(W);if(H.status==="already-running")await Y.asyncDispose(),await dH(),process.exit(0);try{await bs4({ampURL:A.ampURL,apiKey:U,workspaceRoot:process.cwd(),threadId:W,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 H.release(),await Y.asyncDispose()}await dH(),process.exit(0)}async function pN8(A,Q,B,$){let{userInput:J,stdinInput:Y}=await MVA(Q),Z=!!Q.streamJson||!!Q.streamJsonThinking;LVA({...Q,streamJson:Z},A.executeMode,J),B9(B,Q);let X=Q.threadId&&KQ(Q.threadId)?Q.threadId:void 0,F=Q.observe?i8(Q.observe)??zB(Q.observe):void 0,D=await $.serverStatusPromise;if(RD(D))throw C40(D,A.ampURL);let G=await $.secretStorage.get("apiKey",A.ampURL);if(!G)throw new K4("API key required. Please run `amp login` first.",1);if(A.executeMode){y31($.mcpService,A.settings);try{let V=await Qs4({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,labels:Q.label,initialThreadID:X});if(await Gg(V,"execute"),Q.archive)await $.threadService.archive(V,!0)}finally{await $.asyncDispose()}await dH(),process.exit(0)}else{let V=Jj($.configService),U=new R_($.fuzzyServer),K=process.cwd();await nB1({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:E})=>Rw({fileSystem:$.fileSystem,workspaceRoot:K},E),completionBuilder:U,workspaceRoot:K,listThreads:()=>V.listThreads(),getThreadFromServer:(E)=>V.getThread(E),toolboxes:$.toolboxService.toolboxes,isInternalUser:bA(D)&&XQ(D.user.email),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}),process.exit(0)}}async function dN8(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(G0,O0)=>{let A0=Number(process.hrtime.bigint()-O0)/1e6,V0=gA1();R.info("Startup phase",{phase:G0,phaseMs:Math.round(A0),sinceMainMs:V0===null?void 0:Math.round(V0)})},{userInput:X,stdinInput:F}=await MVA(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;LVA({...Q,streamJson:D},A.executeMode,X),B9(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await A2(A,Q),U=V.hasAPIKeyAtStartup,K=V.serverStatus==="pending";if(R.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&&RD(E))throw C40(E,A.ampURL);let W=bA(E)?E:null,H=W?.user.email,z=!!(H&&XQ(H));if(!K)await EX1(B,Q,E);let q=n_(E),N=q?.features??[],I=q?.team??null,w=B10(Q,q);if(w instanceof Error)l5(w.message);if(W&&!rk(Q.mode,H))throw new K4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let C=Q.threadId&&KQ(Q.threadId)?Q.threadId:void 0;if(!A.executeMode&&!Q.headless)V.skillService=bN8(V.skillService);G=process.hrtime.bigint();let O=await oq0(V);Z("runMainThread:createWorkerDeps",G);let P=A.executeMode?void 0:async(G0)=>Gg(G0,"interactive"),k={threadService:V.threadService,workerDeps:O,createThread:async(G0)=>{let O0=K?await V.serverStatusPromise:E,A0=await NU0(A.settings,process.cwd(),n_(O0),w);if(A0 instanceof Error)l5(A0.message);return hY1(O,{threadMeta:A0?iG(A0):void 0,agentMode:G0??Q.mode,onFirstAssistantMessage:P})},validateThreadOwnership:async(G0,O0)=>{if(O0?.nonBlockingOwnershipCheck){EVA(G0,V.configService,V.viewerUserIDPromise).catch((A0)=>{if(A0 instanceof K4){if(O0.onOwnershipError){O0.onOwnershipError(A0,G0);return}cH(A0,G0);return}R.warn("Failed to validate thread ownership in CLI, allowing to open",{error:A0})});return}try{await EVA(G0,V.configService,V.viewerUserIDPromise)}catch(A0){if(A0 instanceof K4)throw A0;R.warn("Failed to validate thread ownership in CLI, allowing to open",{error:A0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:P,handleError:cH},_=async()=>{try{return gXA(k,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(G0){if(G0 instanceof K4)throw G0;throw await cH(G0,Q.threadId),Error("handleError should have called process.exit()")}},f=(async()=>{if(K){R.info("Skipping initial free tier status fetch until auth is complete");return}try{let G0=await V.configService.getLatest(),O0=Ec(G0),A0=await mA.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(O0)});if(A0.ok)return R.info("User free tier status:",A0),A0.result;return}catch(G0){R.error("Failed to fetch free tier status:",G0);return}})(),b=!A.executeMode?new D$1:null,y,u=null;if(b)y=b,u=(async()=>{let G0=K?await V.serverStatusPromise:V.serverStatus;if(RD(G0))throw C40(G0,A.ampURL);await EX1(B,Q,G0);let O0=process.hrtime.bigint(),A0=await _();if(Z("runMainThread:createThreadPool",O0),b.attach(A0),X){let V0=await k1(A0.threadHandles$);if(!V0)throw new K4("No active thread is available yet.",1);await V0.sendMessage({content:[{type:"text",text:X}]})}})(),u.catch(async(G0)=>{let O0=G0 instanceof Error?G0:Error(String(G0));b.setInitError(O0),await cH(G0,Q.threadId)});else G=process.hrtime.bigint(),y=await _(),Z("runMainThread:createThreadPool",G);let p=Q.notifications!==void 0?Q.notifications:!A.executeMode,d=W!==null&&w40(W.features,D9.TUI_VOICE_NOTIF);if(K)V.serverStatusPromise.then((G0)=>{d=bA(G0)&&w40(G0.features,D9.TUI_VOICE_NOTIF)}).catch((G0)=>{R.debug("Failed to resolve TUI voice notification feature flag",{error:G0})});G=process.hrtime.bigint();let g=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),uN8({configService:V.configService,threadService:V.threadService,config:g,useNotificationsForService:p,isTUIVoiceNotifEnabled:()=>d,threadViewStates$:()=>y.threadHandles$.pipe(p4((G0)=>{if(!G0)return u0.of({});return b6(G0.thread$,G0.threadViewState$).pipe(I1(([O0,A0])=>({[O0.id]:A0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){y31(V.mcpService,A.settings);let G0={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,labels:Q.label},O0=await Uo4({threadPool:y,...G0});if(await Gg(O0,"execute"),Q.archive)await V.threadService.archive(O0,!0);await V.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Q.jetbrains||Q.ide){await J70();let G0=await LD({jetbrainsOnly:Q.jetbrains});if(G0.length===0){if(Q.jetbrains)n=!await V.configService.get("jetbrains.skipInstall")}else if(G0.length===1){let O0=G0[0];if(O0)a8.selectConfig(O0)}else c=!0}G=process.hrtime.bigint();let $0=A31("0.0.1777564642-g9dea90",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let j0=new x31(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),X&&A.executeMode){let G0=await k1(y.threadHandles$);if(!G0)throw new K4("No active thread is available yet.",1);await G0.sendMessage({content:[{type:"text",text:X}]})}G=process.hrtime.bigint();let i=await Lu();Z("runMainThread:loadSessionState",G),R.info("Loaded session state:",i);let e={...i,launchCount:i.launchCount+1};PZ((G0)=>({...G0,launchCount:G0.launchCount+1}));try{if(G=process.hrtime.bigint(),await eBA({history:new st,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:mA,threadPool:y,createSystemPromptDeps:async()=>IVA(V),ideClient:a8,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:j0,updateService:$0,pluginPlatform:V.pluginPlatform,pluginService:V.pluginService},{initialServerStatus:V.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:V.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:C,showJetBrainsInstaller:n,showIdePickerHint:c,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:MN8,logFile:{path:$},sessionState:e,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-04-30T16:00:58.215Z"},(G0)=>new H$1({...G0,threadPool:G0.threadPool},(O0)=>new bY1({...O0,threadState:O0.threadState}))),Z("runMainThread:mountApp-returned",G),u)await u}finally{await y.dispose().catch((G0)=>{R.error("Failed to dispose thread pool during shutdown",G0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function E8(A){if(R.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)XY.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
6334
|
-
`);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;R.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await CF4({get:async(X)=>{if(X!==zi)return;try{let F=await qVA(UX1,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(X,F)=>{if(X!==zi)return;await NN8(I40.dirname(UX1),{recursive:!0}),await IN8(UX1,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:cB0()});k84($);let J=await ZK0({...A,workspaceTrust:{current:!0,changes:gx0},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 r0A(A.mcpConfig);J=s0A(J,X)}let Y=I40.dirname(J.getSettingsFilePath());jx4(Ku,Y),J=V54(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=x9;if(R.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!dq(Z))R.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:rK0(await Ze(A,J))}}function cN8(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 lN8(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=I40.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?CN8:ht));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function iN8(){Cc4();let A=cN8(process.argv),Q=lN8(process.argv,A),B=Ta4(Q),$=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)a0.level=0;if(ON8(R),R.info("Starting Amp CLI.",{version:"0.0.
|
|
6333
|
+
Or pipe via stdin: echo "your message" | amp --execute`)}async function aq0(A,Q,B,$){if(Q.headless)return mN8(A,Q,B);let J=await A2(A,Q),Y=await J.serverStatusPromise,Z=bA(Y)&&w40(Y.features,D9.THREAD_ACTORS_TUI),X=Z&&!Q.takeMeBack;if(Q.showNeoWelcome&&!Z)throw await J.asyncDispose(),new K4("--show-neo-welcome is only available with the Neo TUI feature flag",1);if(X)return pN8(A,Q,B,J);else return dN8(A,Q,B,$,{dependencies:J})}async function mN8(A,Q,B){let $=(z,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=gA1();R.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 A2(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(RD(Z))throw C40(Z,A.ampURL);let X=bA(Z)?Z:null,F=X?.user.email;await EX1(B,Q,Z);let D=n_(Z),G=B10(Q,D);if(G instanceof Error)l5(G.message);if(X&&!rk(Q.mode,F))throw new K4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!F||!XQ(F)))throw new K4("Headless executor mode is only available for Amp employees",1);let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new K4("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&&!KQ(K))throw new K4(`Invalid thread ID: ${K}`,1);let E=K?void 0:await $I8({dependencies:Y,apiKey:U,visibility:G??void 0}),W=K??E?.threadId;if(!W)throw new K4("Failed to resolve headless thread ID",1);let H=await is4(W);if(H.status==="already-running")await Y.asyncDispose(),await dH(),process.exit(0);try{await bs4({ampURL:A.ampURL,apiKey:U,workspaceRoot:process.cwd(),threadId:W,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 H.release(),await Y.asyncDispose()}await dH(),process.exit(0)}async function pN8(A,Q,B,$){let{userInput:J,stdinInput:Y}=await MVA(Q),Z=!!Q.streamJson||!!Q.streamJsonThinking;LVA({...Q,streamJson:Z},A.executeMode,J),B9(B,Q);let X=Q.threadId&&KQ(Q.threadId)?Q.threadId:void 0,F=Q.observe?i8(Q.observe)??zB(Q.observe):void 0,D=await $.serverStatusPromise;if(RD(D))throw C40(D,A.ampURL);let G=await $.secretStorage.get("apiKey",A.ampURL);if(!G)throw new K4("API key required. Please run `amp login` first.",1);if(A.executeMode){y31($.mcpService,A.settings);try{let V=await Qs4({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,labels:Q.label,initialThreadID:X});if(await Gg(V,"execute"),Q.archive)await $.threadService.archive(V,!0)}finally{await $.asyncDispose()}await dH(),process.exit(0)}else{let V=Jj($.configService),U=new R_($.fuzzyServer),K=process.cwd();await nB1({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:E})=>Rw({fileSystem:$.fileSystem,workspaceRoot:K},E),completionBuilder:U,workspaceRoot:K,listThreads:()=>V.listThreads(),getThreadFromServer:(E)=>V.getThread(E),toolboxes:$.toolboxService.toolboxes,isInternalUser:bA(D)&&XQ(D.user.email),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}),process.exit(0)}}async function dN8(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(G0,O0)=>{let A0=Number(process.hrtime.bigint()-O0)/1e6,V0=gA1();R.info("Startup phase",{phase:G0,phaseMs:Math.round(A0),sinceMainMs:V0===null?void 0:Math.round(V0)})},{userInput:X,stdinInput:F}=await MVA(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;LVA({...Q,streamJson:D},A.executeMode,X),B9(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await A2(A,Q),U=V.hasAPIKeyAtStartup,K=V.serverStatus==="pending";if(R.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&&RD(E))throw C40(E,A.ampURL);let W=bA(E)?E:null,H=W?.user.email,z=!!(H&&XQ(H));if(!K)await EX1(B,Q,E);let q=n_(E),N=q?.features??[],I=q?.team??null,w=B10(Q,q);if(w instanceof Error)l5(w.message);if(W&&!rk(Q.mode,H))throw new K4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let C=Q.threadId&&KQ(Q.threadId)?Q.threadId:void 0;if(!A.executeMode&&!Q.headless)V.skillService=bN8(V.skillService);G=process.hrtime.bigint();let O=await oq0(V);Z("runMainThread:createWorkerDeps",G);let P=A.executeMode?void 0:async(G0)=>Gg(G0,"interactive"),k={threadService:V.threadService,workerDeps:O,createThread:async(G0)=>{let O0=K?await V.serverStatusPromise:E,A0=await NU0(A.settings,process.cwd(),n_(O0),w);if(A0 instanceof Error)l5(A0.message);return hY1(O,{threadMeta:A0?iG(A0):void 0,agentMode:G0??Q.mode,onFirstAssistantMessage:P})},validateThreadOwnership:async(G0,O0)=>{if(O0?.nonBlockingOwnershipCheck){EVA(G0,V.configService,V.viewerUserIDPromise).catch((A0)=>{if(A0 instanceof K4){if(O0.onOwnershipError){O0.onOwnershipError(A0,G0);return}cH(A0,G0);return}R.warn("Failed to validate thread ownership in CLI, allowing to open",{error:A0})});return}try{await EVA(G0,V.configService,V.viewerUserIDPromise)}catch(A0){if(A0 instanceof K4)throw A0;R.warn("Failed to validate thread ownership in CLI, allowing to open",{error:A0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:P,handleError:cH},_=async()=>{try{return gXA(k,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(G0){if(G0 instanceof K4)throw G0;throw await cH(G0,Q.threadId),Error("handleError should have called process.exit()")}},f=(async()=>{if(K){R.info("Skipping initial free tier status fetch until auth is complete");return}try{let G0=await V.configService.getLatest(),O0=Ec(G0),A0=await mA.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(O0)});if(A0.ok)return R.info("User free tier status:",A0),A0.result;return}catch(G0){R.error("Failed to fetch free tier status:",G0);return}})(),b=!A.executeMode?new D$1:null,y,u=null;if(b)y=b,u=(async()=>{let G0=K?await V.serverStatusPromise:V.serverStatus;if(RD(G0))throw C40(G0,A.ampURL);await EX1(B,Q,G0);let O0=process.hrtime.bigint(),A0=await _();if(Z("runMainThread:createThreadPool",O0),b.attach(A0),X){let V0=await k1(A0.threadHandles$);if(!V0)throw new K4("No active thread is available yet.",1);await V0.sendMessage({content:[{type:"text",text:X}]})}})(),u.catch(async(G0)=>{let O0=G0 instanceof Error?G0:Error(String(G0));b.setInitError(O0),await cH(G0,Q.threadId)});else G=process.hrtime.bigint(),y=await _(),Z("runMainThread:createThreadPool",G);let p=Q.notifications!==void 0?Q.notifications:!A.executeMode,d=W!==null&&w40(W.features,D9.TUI_VOICE_NOTIF);if(K)V.serverStatusPromise.then((G0)=>{d=bA(G0)&&w40(G0.features,D9.TUI_VOICE_NOTIF)}).catch((G0)=>{R.debug("Failed to resolve TUI voice notification feature flag",{error:G0})});G=process.hrtime.bigint();let g=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),uN8({configService:V.configService,threadService:V.threadService,config:g,useNotificationsForService:p,isTUIVoiceNotifEnabled:()=>d,threadViewStates$:()=>y.threadHandles$.pipe(p4((G0)=>{if(!G0)return u0.of({});return b6(G0.thread$,G0.threadViewState$).pipe(I1(([O0,A0])=>({[O0.id]:A0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){y31(V.mcpService,A.settings);let G0={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,labels:Q.label},O0=await Uo4({threadPool:y,...G0});if(await Gg(O0,"execute"),Q.archive)await V.threadService.archive(O0,!0);await V.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Q.jetbrains||Q.ide){await J70();let G0=await LD({jetbrainsOnly:Q.jetbrains});if(G0.length===0){if(Q.jetbrains)n=!await V.configService.get("jetbrains.skipInstall")}else if(G0.length===1){let O0=G0[0];if(O0)a8.selectConfig(O0)}else c=!0}G=process.hrtime.bigint();let $0=A31("0.0.1777566445-g595ffb",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let j0=new x31(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),X&&A.executeMode){let G0=await k1(y.threadHandles$);if(!G0)throw new K4("No active thread is available yet.",1);await G0.sendMessage({content:[{type:"text",text:X}]})}G=process.hrtime.bigint();let i=await Lu();Z("runMainThread:loadSessionState",G),R.info("Loaded session state:",i);let e={...i,launchCount:i.launchCount+1};PZ((G0)=>({...G0,launchCount:G0.launchCount+1}));try{if(G=process.hrtime.bigint(),await eBA({history:new st,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:mA,threadPool:y,createSystemPromptDeps:async()=>IVA(V),ideClient:a8,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:j0,updateService:$0,pluginPlatform:V.pluginPlatform,pluginService:V.pluginService},{initialServerStatus:V.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:V.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:C,showJetBrainsInstaller:n,showIdePickerHint:c,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:MN8,logFile:{path:$},sessionState:e,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-04-30T16:31:16.215Z"},(G0)=>new H$1({...G0,threadPool:G0.threadPool},(O0)=>new bY1({...O0,threadState:O0.threadState}))),Z("runMainThread:mountApp-returned",G),u)await u}finally{await y.dispose().catch((G0)=>{R.error("Failed to dispose thread pool during shutdown",G0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function E8(A){if(R.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)XY.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
6334
|
+
`);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;R.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await CF4({get:async(X)=>{if(X!==zi)return;try{let F=await qVA(UX1,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(X,F)=>{if(X!==zi)return;await NN8(I40.dirname(UX1),{recursive:!0}),await IN8(UX1,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:cB0()});k84($);let J=await ZK0({...A,workspaceTrust:{current:!0,changes:gx0},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 r0A(A.mcpConfig);J=s0A(J,X)}let Y=I40.dirname(J.getSettingsFilePath());jx4(Ku,Y),J=V54(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=x9;if(R.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!dq(Z))R.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:rK0(await Ze(A,J))}}function cN8(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 lN8(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=I40.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?CN8:ht));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function iN8(){Cc4();let A=cN8(process.argv),Q=lN8(process.argv,A),B=Ta4(Q),$=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)a0.level=0;if(ON8(R),R.info("Starting Amp CLI.",{version:"0.0.1777566445-g595ffb",buildTimestamp:"2026-04-30T16:31:16.215Z"}),process.platform==="win32"&&PP())ct4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new K4(g7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await gN8(B).parseAsync(process.argv)}Lx4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await iN8().catch(cH)});async function nN8(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"),q5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
6335
6335
|
`);else if(!dq(A.ampURL))q5.write(`Logging in to ${new URL(A.ampURL).hostname}
|
|
6336
6336
|
`);let $=process.env.AMP_API_KEY;if($)q5.write(`API key found in environment variable, storing...
|
|
6337
6337
|
`),await Q.set("apiKey",$,A.ampURL),q5.write(`API key successfully stored.
|