@sourcegraph/amp 0.0.1777967145-g633c91 → 0.0.1777970347-gc2d807

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +12 -12
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -4821,12 +4821,12 @@ ${E}`))}},error:(K)=>{if(!U)U=!0,F(Error(`Failed to spawn brew: ${K.message}`))}
4821
4821
  ${E}`;if(Y==="pnpm"&&E.includes("Unable to find the global bin directory"))W+=`
4822
4822
 
4823
4823
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
4824
- 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()}})})}o0();o0();MN();async function ED0(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=mr(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 j.info("NPM version comparison",{currentVersion:A,latestVersion:D,compareResult:G,hasUpdate:V,currentVersionAge:U,latestVersionAge:K}),{hasUpdate:V,latestVersion:D,currentVersion:A,currentVersionAge:U,latestVersionAge:K,source:"npm"}}catch(X){return j.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var KS5="https://static.ampcode.com/cli/cli-version.txt";async function WD0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${KS5}?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=mr(A,J),Z=Y<0;return j.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return j.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var ES5=604800000;function dd4(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>ES5)return{ageMs:B};return null}function mr(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 t01(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?QU(B):void 0;return{sha:$,age:J}}catch{return null}}O1();o0();import{readFile as WS5,realpath as HS5}from"node:fs/promises";import{homedir as zS5}from"node:os";import{dirname as cd4,join as e01}from"node:path";async function ld4(A){switch(A){case"binary":case"brew":return qS5(br());case"npm":case"pnpm":case"yarn":case"bun":return NS5();case"bootstrap":return IS5()}}async function qS5(A){let Q=await iD(A,["--version"],5000);if(Q.reason!=="success")return j.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function NS5(){try{let A=process.argv[1];if(!A)return null;let Q=await HS5(A),B=cd4(cd4(Q));return await id4(e01(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function IS5(){try{let A=process.env.AMP_HOME??e01(zS5(),".amp");return await id4(e01(A,"package","package.json"))}catch(A){return j.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function id4(A){let Q=await WS5(A,"utf8"),B=JSON.parse(Q);if(B.name!=="@sourcegraph/amp")return j.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var wS5=3600000,CS5=5000;function A11(A,Q,B={}){let $=new h4,J=$.pipe(iA({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??wS5,X=!1,F=()=>{X=!0};return setImmediate(async()=>{let D=new MB().scoped("update");if(Y>0){if(await AU(Y),X)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!X){let U=await MS5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await AU(CS5),X)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!X){let W=Math.min(K,E);await AU(W),E-=W}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:F}}async function MS5(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 Df(),X=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:X});let F;if(X)F=await WD0(A);else{let V=await nj();F=await ED0(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 ld4(Z);if(V&&mr(V,F.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:F.latestVersion}),J.updatedTo=V,mr(A,V)<0){let U=await pW(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!==br()){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 gr(F.latestVersion,Z),J.updatedTo=F.latestVersion;let V=await pW(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}}MN();import{stderr as nD}from"node:process";function nd4(A){let Q=new aN().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 g01($.force||!1,$.verbose||!1,"0.0.1777967145-g633c91"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new aN("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 OS5($.targetVersion)});A.addCommand(B)}function LS5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
4824
+ 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()}})})}o0();o0();MN();async function ED0(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=mr(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 j.info("NPM version comparison",{currentVersion:A,latestVersion:D,compareResult:G,hasUpdate:V,currentVersionAge:U,latestVersionAge:K}),{hasUpdate:V,latestVersion:D,currentVersion:A,currentVersionAge:U,latestVersionAge:K,source:"npm"}}catch(X){return j.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var KS5="https://static.ampcode.com/cli/cli-version.txt";async function WD0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${KS5}?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=mr(A,J),Z=Y<0;return j.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return j.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var ES5=604800000;function dd4(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>ES5)return{ageMs:B};return null}function mr(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 t01(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?QU(B):void 0;return{sha:$,age:J}}catch{return null}}O1();o0();import{readFile as WS5,realpath as HS5}from"node:fs/promises";import{homedir as zS5}from"node:os";import{dirname as cd4,join as e01}from"node:path";async function ld4(A){switch(A){case"binary":case"brew":return qS5(br());case"npm":case"pnpm":case"yarn":case"bun":return NS5();case"bootstrap":return IS5()}}async function qS5(A){let Q=await iD(A,["--version"],5000);if(Q.reason!=="success")return j.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function NS5(){try{let A=process.argv[1];if(!A)return null;let Q=await HS5(A),B=cd4(cd4(Q));return await id4(e01(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function IS5(){try{let A=process.env.AMP_HOME??e01(zS5(),".amp");return await id4(e01(A,"package","package.json"))}catch(A){return j.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function id4(A){let Q=await WS5(A,"utf8"),B=JSON.parse(Q);if(B.name!=="@sourcegraph/amp")return j.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var wS5=3600000,CS5=5000;function A11(A,Q,B={}){let $=new h4,J=$.pipe(iA({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??wS5,X=!1,F=()=>{X=!0};return setImmediate(async()=>{let D=new MB().scoped("update");if(Y>0){if(await AU(Y),X)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!X){let U=await MS5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await AU(CS5),X)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!X){let W=Math.min(K,E);await AU(W),E-=W}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:F}}async function MS5(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 Df(),X=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:X});let F;if(X)F=await WD0(A);else{let V=await nj();F=await ED0(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 ld4(Z);if(V&&mr(V,F.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:F.latestVersion}),J.updatedTo=V,mr(A,V)<0){let U=await pW(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!==br()){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 gr(F.latestVersion,Z),J.updatedTo=F.latestVersion;let V=await pW(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}}MN();import{stderr as nD}from"node:process";function nd4(A){let Q=new aN().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 g01($.force||!1,$.verbose||!1,"0.0.1777970347-gc2d807"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new aN("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 OS5($.targetVersion)});A.addCommand(B)}function LS5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
4825
4825
  `),$=!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 OS5(A){let B=process.platform==="win32"&&ij()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:$,renderProgress:J}=LS5(nD);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")nD.write(s0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4826
4826
 
4827
4827
  `));try{if(!A){nD.write(s0.blue(`Checking for updates...
4828
- `));let X=!1,F;if(ij()){let D=await WD0("0.0.1777967145-g633c91");X=D.hasUpdate,F=D.latestVersion}else{let D=await nj(),G=await ED0("0.0.1777967145-g633c91",D);X=G.hasUpdate,F=G.latestVersion}if(!X){let D=t01("0.0.1777967145-g633c91"),G=D?.age?`released ${D.age} ago`:`built ${QU(new Date("2026-05-05T07:49:26.158Z"))} ago`;nD.write(s0.green(`✓ Amp is already up to date on version ${"0.0.1777967145-g633c91"} (${G})
4829
- `));let V=await pW("0.0.1777967145-g633c91",B);if(V.warning)nD.write(`
4828
+ `));let X=!1,F;if(ij()){let D=await WD0("0.0.1777970347-gc2d807");X=D.hasUpdate,F=D.latestVersion}else{let D=await nj(),G=await ED0("0.0.1777970347-gc2d807",D);X=G.hasUpdate,F=G.latestVersion}if(!X){let D=t01("0.0.1777970347-gc2d807"),G=D?.age?`released ${D.age} ago`:`built ${QU(new Date("2026-05-05T08:42:39.004Z"))} ago`;nD.write(s0.green(`✓ Amp is already up to date on version ${"0.0.1777970347-gc2d807"} (${G})
4829
+ `));let V=await pW("0.0.1777970347-gc2d807",B);if(V.warning)nD.write(`
4830
4830
  `+s0.yellow(V.warning)+`
4831
4831
  `);process.exit(0)}if(!F)nD.write(s0.yellow("[WARN] could not find latest version")),process.exit(0);A=F}nD.write(s0.blue(`Updating to version ${A}...
4832
4832
  `)),await gr(A,void 0,(X)=>{$(),nD.write(s0.dim(`Running: ${X}
@@ -5281,7 +5281,7 @@ ${$}`).join(`
5281
5281
  `)}function gi5(A){return A.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}function K51(A){return A.replace(/\[(image(?:\s+\d+)?)\]/gi,"").trim()}function mi5(A){let Q=aI.extname(A.sourcePath).toLowerCase();if(Q.length>0)return Q;if(A.source.type==="base64")switch(A.source.mediaType){case"image/jpeg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp"}return".png"}async function pi5(A,Q){let B=[];for(let[$,J]of Q.entries()){if(J.source.type!=="base64"){j.warn("Skipping non-base64 debug package issue image",{index:$,sourceType:J.source.type});continue}let Y=`issue-image-${$+1}${mi5(J)}`,Z=aI.join(A,Y);try{await $b(Z,Buffer.from(J.source.data,"base64")),B.push(Y)}catch(X){j.warn("Failed to write debug package issue image",{index:$,fileName:Y,error:X})}}return B}function di5(A,Q,B=[]){let $=["# Bug Report","","## Issue Description","",A,""];if(B.length>0){for(let[J,Y]of B.entries())$.push(`![Issue image ${J+1}](./${Y})`);$.push("")}if($.push("## Included Files","","- `cli-logs.json` — CLI logs filtered for this session PID","- `thread.yaml` — Full thread data (messages, metadata, agent mode, etc.)"),B.length>0)$.push("- `issue-image-*.*` — Images attached to the issue description");if(Jb(Q.thread))$.push("- `thread.sqlite` — DTW Durable Object SQLite dump","- `cloudflare-logs.json` — Worker logs from Cloudflare (if CLOUDFLARE_API_TOKEN was set)");if($.push("","## Debug Instructions","","To investigate, start with the issue description above, then:","","1. Review `cli-logs.json` for errors, warnings, and the sequence of events"),Jb(Q.thread))$.push("2. Open `thread.sqlite` and inspect the `messages` and `thread_events` tables:"," ```sh"," sqlite3 -json thread.sqlite 'SELECT * FROM messages ORDER BY created_at, rowid'"," sqlite3 -json thread.sqlite 'SELECT * FROM thread_events ORDER BY seq'"," ```","3. Review `cloudflare-logs.json` (if present) for server-side worker errors","4. Check Cloudflare dashboards for more detail:",` - Logs: <${V51(Q.thread.id)}>`,` - Data Studio: <${G51(Q.thread.id)}>`);return $.push("",yV0(Q)),$.join(`
5282
5282
  `)}function E51(A){let Q=A.activeThreadHandle.getInitialTreeURI();return{thread:A.thread,ampURL:A.ampURL,effectiveAgentMode:A.getEffectiveAgentMode(),isProcessing:A.isProcessing,threadPoolIsDTW:A.threadPool.isDTWMode?.()===!0,transportState:A.threadPool.getTransportConnectionState?.(),transportRole:A.threadPool.getTransportConnectionRole?.(),threadViewState:A.threadViewStates[A.thread.id],initialTreePath:Q?W5(Y8(Q)):void 0,currentWorkspacePath:W5(Y8(A.currentWorkspace)),clientId:A.clientId,logFile:A.logFile,pid:process.pid}}async function at4(A){try{let Q=aI.join("/tmp",`amp-thread-${A.thread.id}-${Date.now()}.json`),B=JSON.stringify(A.thread,null,2);await $b(Q,B,"utf-8"),await LJ(Q),j.info("Thread JSON written and opened in editor",{file:Q});return}catch(Q){return j.error("Failed to write thread JSON or open editor",Q),Error("Failed to write thread JSON or open editor",{cause:Q})}}async function ot4(A){try{let Q=aI.join("/tmp",`amp-thread-${A.thread.id}-${Date.now()}.yaml`),B=D51.default.stringify(A.thread);await $b(Q,B,"utf-8"),await LJ(Q),j.info("Thread YAML written and opened in editor",{file:Q});return}catch(Q){return j.error("Failed to write thread YAML or open editor",Q),Error("Failed to write thread YAML or open editor",{cause:Q})}}async function rt4(A,Q){if(typeof Q!=="string")return Error("Select a log option from the picker");switch(Q){case"cli-open":{let B=A.logFile;if(!B)return Error("CLI log file is unavailable for this session");let $="less -R +G",J=vV0(process.pid,B,$);try{try{R4.instance.tuiInstance.suspend(),Gt(J,{stdio:"inherit"})}finally{process.stdout.write("\x1B[?25l"),R4.instance.tuiInstance.resume()}j.info("Opened filtered CLI logs",{command:J,pid:process.pid,logFile:Vt(B),outputCommand:$??null});return}catch(Y){return j.error("Failed to open filtered CLI logs",{error:Y,command:J}),Error("Failed to open filtered CLI logs",{cause:Y})}}case"cloudflare-logs":{await K6(A.context??A.contextFallback,V51(A.thread.id));return}case"cloudflare-data-studio":{await K6(A.context??A.contextFallback,G51(A.thread.id));return}default:return Error(`Unknown log option: ${Q}`)}}async function st4(A){let Q=E51(A),B=nt4(Q),$=!1;try{await R4.instance.tuiInstance.clipboard.writeText(B),$=!0}catch(J){j.error("Failed to copy debug prompt",{error:J})}return new y2(new _A({child:new S6({markdown:[$?"**Copied Markdown debug prompt to clipboard.**":"**Clipboard copy failed. Select and copy manually.**","",B].join(`
5283
5283
  `)})}),"Debug Prompt","info","help",{width:100,height:28})}function ci5(A){return typeof A==="object"&&A!==null&&"label"in A&&typeof A.label==="string"&&"command"in A&&typeof A.command==="string"}async function tt4(A,Q){if(!ci5(Q))return Error("Select a command from the picker");try{await R4.instance.tuiInstance.clipboard.writeText(Q.command),A.showToast(`Copied: ${Q.label}`,"success")}catch(B){j.error("Failed to copy DTW debug command",{error:B})}}async function et4(A){return new y2(new _A({child:new S6({markdown:yV0(E51(A))})}),"Thread Diagnostics","info","help",{width:100,height:26})}async function Ae4(A,Q){let B=A.logFile;if(!B)return Error("CLI log file is unavailable for this session");let $=K51(Q.description);if($.trim().length===0)return Error("Description is required");let J=Q.images,Y=Vt(B),Z=process.pid,X=gi5($)||"debug-package",F=xi5.tmpdir(),D=aI.join(F,`amp-${X}`),G=`${D}.zip`;A.showStatusMessage("Building debug package...");try{Gt(`mkdir -p ${D}`);let V=`select(.pid == ${Z})`,U=Gt(`cat ${Y} | jq -c '${V}'`,{encoding:"utf-8",maxBuffer:52428800});await $b(aI.join(D,"cli-logs.json"),U,"utf-8"),await $b(aI.join(D,"thread.yaml"),D51.default.stringify(A.thread),"utf-8");let K=await pi5(D,J),E=di5($,E51(A),K);await $b(aI.join(D,"agent-read-this.md"),E,"utf-8"),Gt(`zip -j ${G} ${D}/*`),Gt(`osascript -e 'set the clipboard to POSIX file "${G}"'`),A.showToast("Debug package copied to clipboard — paste into Slack","success"),j.info("Packaged debug bundle to clipboard",{zipPath:G,packageDir:D,pid:Z,threadId:A.thread.id});return}catch(V){return j.error("Failed to package debug bundle",{error:V}),Error("Failed to package debug bundle",{cause:V})}}a8();var li5=80,ii5=20,Qe4=4,ni5=42,Ze4=420,Xe4=640,ai5=Math.max(32,lU),Be4="░▒▓█▁▂▃▄▅▆▇∿∾∽≋≈∼",xV0=["▁","▂","▃","▄","▅","▆","▇","█"],oi5=["▏","▎","▍","▌","▋","▊","▉","█"],ri5=["▕","▐","▉","▊","▋","▌","▍","▎"],si5=q0.symmetric(1,0),ti5=q0.all(1),ei5=q0.all(1),An5={primary:{r:102,g:102,b:102},secondary:{r:255,g:255,b:255}},Qn5={primary:{r:77,g:0,b:10},secondary:{r:255,g:77,b:95}};function Bn5(A){return{borderShape:A?.borderShape??"notched",borderAnimation:A?.borderAnimation??"subtle",titleAnimation:A?.titleAnimation??"none",timeMs:A?.timeMs,animate:A?.animate,seed:A?.seed??ni5}}function Fe4(A){switch(A){case"notched":return ti5;case"classic":return si5}}class TA extends I1{props;constructor(A){super();this.props=A}build(A){let Q=_0.of(A),B=B4.of(A),$=this.props.tone??"default",J=Bn5(this.props.visualStyle),Y=this.props.bodyFit??{kind:"shrink"},Z=Gn5(this.props,Y,B,J.borderShape),X=En5($,Q),F=i1.all(new n1(X.border,1,"rounded")),D=H51(this.props.header,J.borderShape),G=z51(this.props.footer,J.borderShape),V=Wn5(D===void 0?this.props.header:void 0,X.header,J),U=Nn5(this.props.child,Y),K=G===void 0?In5(this.props.footer,Q):new N0({height:0}),E=Y.kind==="fill"?"max":"min",W=typeof this.props.header==="string"?`NeoModal:${this.props.header}`:"NeoModal",H=this.props.autofocus??!0,z=this.props.chromePadding??Fe4(J.borderShape),q=D===void 0&&typeof this.props.header==="string"?1:0,N=G===void 0?Oe4(this.props.footer):0,I=new c4({autofocus:H,canRequestFocus:!0,debugLabel:W,onKey:(_)=>{if(_.key==="Escape")return this.props.onDismiss(),"handled";return"ignored"},child:new f0({mainAxisSize:E,crossAxisAlignment:"stretch",children:[V,new N0({height:q}),U,new N0({height:N}),K]})}),C=!(J.borderShape==="notched"||J.borderAnimation!=="none")?new p0({constraints:Z,decoration:new x4(Q.colors.background,F),padding:z,child:I}):Yn5({borderShape:J.borderShape,borderAnimation:J.borderAnimation,child:I,constraints:Z,background:Q.colors.background,borderColor:X.border,tone:$,headerColor:X.header,footerKeyColor:Q.app.keybind,footerHintColor:Q.colors.foreground,padding:z,title:D,footer:G,titleAnimation:J.titleAnimation,seed:J.seed,timeMs:J.timeMs,animate:J.animate}),O=new p0({decoration:new x4(Q.colors.background),padding:ei5,child:C});return new t4({fit:"expand",children:[new De4,new u1({onClick:()=>{},opaque:this.props.barrierOpaque??!0,child:N0.expand()}),new A4({child:O})]})}}class De4 extends e3{createRenderObject(){return new Ge4}}class Ge4 extends Y4{performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=Number.isFinite(A.maxWidth)?A.maxWidth:A.minWidth,B=Number.isFinite(A.maxHeight)?A.maxHeight:A.minHeight;this.setSize(Q,B)}paint(A,Q=0,B=0){let $=Math.floor(Q+this.offset.x),J=Math.floor(B+this.offset.y),Y=A.getSize(),Z=Math.max(0,$),X=Math.max(0,J),F=Math.min(Y.width,$+this.size.width),D=Math.min(Y.height,J+this.size.height);for(let G=X;G<D;G++)for(let V=Z;V<F;V++){let U=A.getCell(V,G);if(!U||$n5(U))continue;let K={char:U.char,style:{...U.style,dim:!0},width:U.width};if(U.hyperlink!==void 0)K.hyperlink=U.hyperlink;A.setCell(V,G,K)}}}function $n5(A){return A.char===" "&&A.width===1&&A.hyperlink===void 0&&Jn5(A.style)}function Jn5(A){return A.fg===void 0&&A.bg===void 0&&A.bold===void 0&&A.italic===void 0&&A.underline===void 0&&A.strikethrough===void 0&&A.reverse===void 0&&A.dim===void 0}function H51(A,Q){return Q==="notched"&&typeof A==="string"?A:void 0}function z51(A,Q){if(Q!=="notched")return;if(A===void 0)return[{keys:["Esc"],label:"close"}];if(!fV0(A)||A.length===0)return;return A}function Yn5(A){if(A.timeMs!==void 0)return $e4(A,A.timeMs);if(!(A.animate??Zn5(A)))return $e4(A,0);return new Ve4({borderShape:A.borderShape,borderAnimation:A.borderAnimation,child:A.child,constraints:A.constraints,background:A.background,borderColor:A.borderColor,tone:A.tone,headerColor:A.headerColor,footerKeyColor:A.footerKeyColor,footerHintColor:A.footerHintColor,padding:A.padding,title:A.title,footer:A.footer,titleAnimation:A.titleAnimation,seed:A.seed,initialTimeMs:0})}function $e4(A,Q){return new q51({borderShape:A.borderShape,borderAnimation:A.borderAnimation,child:A.child,constraints:A.constraints,background:A.background,borderColor:A.borderColor,tone:A.tone,headerColor:A.headerColor,footerKeyColor:A.footerKeyColor,footerHintColor:A.footerHintColor,padding:A.padding,title:A.title,footer:A.footer,titleAnimation:A.titleAnimation,seed:A.seed,timeMs:Q})}function Zn5(A){return A.titleAnimation!=="none"||A.borderAnimation!=="none"}class Ve4 extends v0{props;constructor(A){super();this.props=A}createState(){return new Ue4}}class Ue4 extends k0{startedAt=Date.now();timer=null;initState(){this.startTimer()}didUpdateWidget(A){if(A.props.borderShape!==this.widget.props.borderShape||A.props.borderAnimation!==this.widget.props.borderAnimation||A.props.seed!==this.widget.props.seed||A.props.title!==this.widget.props.title||A.props.titleAnimation!==this.widget.props.titleAnimation)this.startedAt=Date.now();this.startTimer()}dispose(){this.stopTimer(),super.dispose()}startTimer(){if(this.timer||this.animationComplete())return;this.timer=setInterval(()=>{if(!this.mounted)return;if(this.setState(()=>{}),this.animationComplete())this.stopTimer()},lU),this.timer.unref()}stopTimer(){if(!this.timer)return;clearInterval(this.timer),this.timer=null}animationComplete(){if(this.widget.props.borderAnimation!=="none")return!1;if(this.widget.props.titleAnimation!=="none")return Date.now()-this.startedAt>=we4(this.widget.props.titleAnimation);return!0}build(A){return new q51({borderShape:this.widget.props.borderShape,borderAnimation:this.widget.props.borderAnimation,child:this.widget.props.child,constraints:this.widget.props.constraints,background:this.widget.props.background,borderColor:this.widget.props.borderColor,tone:this.widget.props.tone,headerColor:this.widget.props.headerColor,footerKeyColor:this.widget.props.footerKeyColor,footerHintColor:this.widget.props.footerHintColor,padding:this.widget.props.padding,title:this.widget.props.title,footer:this.widget.props.footer,titleAnimation:this.widget.props.titleAnimation,seed:this.widget.props.seed,timeMs:Date.now()-this.startedAt+this.widget.props.initialTimeMs})}}class q51 extends q5{props;constructor(A){super({child:A.child});this.props=A}createRenderObject(){return new W51(this.props)}updateRenderObject(A){N4(A instanceof W51,"unexpected modal surface"),A.update(this.props)}}class W51 extends Y4{props;glow;constructor(A){super();this.props=A;this.glow=new T9(A.seed)}update(A){let Q=!this.props.constraints.equals(A.constraints)||this.props.padding!==A.padding;if(A.seed!==this.props.seed)this.glow=new T9(A.seed);if(this.props=A,Q)this.markNeedsLayout();this.markNeedsPaint()}performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=A.enforce(this.props.constraints),B=2+this.props.padding.horizontal,$=2+this.props.padding.vertical,J=new M1(Math.max(0,Q.minWidth-B),Math.max(0,Q.maxWidth-B),Math.max(0,Q.minHeight-$),Math.max(0,Q.maxHeight-$)),Y=this.children[0];if(Y)Y.layout(J),Y.setOffset(1+this.props.padding.left,1+this.props.padding.top);let Z=(Y?.size.width??0)+B,X=(Y?.size.height??0)+$,F=Q.constrain(Z,X);this.setSize(F.width,F.height)}paint(A,Q=0,B=0){let $=Math.floor(Q+this.offset.x),J=Math.floor(B+this.offset.y),Y=Math.floor(this.size.width),Z=Math.floor(this.size.height);if(Y<=0||Z<=0)return;A.fill($,J,Y,Z," ",{bg:this.props.background}),this.paintBorder(A,$,J,Y,Z),super.paint(A,Q,B)}paintBorder(A,Q,B,$,J){if($<2||J<2)return;for(let Y=1;Y<$-1;Y++)this.paintBorderCell(A,Q+Y,B,Y,0,$,J,"top"),this.paintBorderCell(A,Q+Y,B+J-1,Y,J-1,$,J,"bottom");for(let Y=1;Y<J-1;Y++)this.paintBorderCell(A,Q,B+Y,0,Y,$,J,"left"),this.paintBorderCell(A,Q+$-1,B+Y,$-1,Y,$,J,"right");if(this.paintCorner(A,Q,B,0,0,$,J,"top-left"),this.paintCorner(A,Q+$-1,B,$-1,0,$,J,"top-right"),this.paintCorner(A,Q,B+J-1,0,J-1,$,J,"bottom-left"),this.paintCorner(A,Q+$-1,B+J-1,$-1,J-1,$,J,"bottom-right"),this.props.borderShape==="notched")this.paintNotchedLabels(A,Q,B,$,J)}paintBorderCell(A,Q,B,$,J,Y,Z,X){let F=this.sampleBorderIntensity($,J,Y,Z);A.setChar(Q,B,this.borderGlyph(X,F),this.borderStyle(F),1)}paintCorner(A,Q,B,$,J,Y,Z,X){let F=this.sampleBorderIntensity($,J,Y,Z);A.setChar(Q,B,this.cornerGlyph(X,F),this.borderStyle(F),1)}paintNotchedLabels(A,Q,B,$,J){let Y=this.props.title;if(Y){let G=zn5(Y,this.props.titleAnimation,this.props.timeMs);this.paintBorderText(A,Q+2,B,` ${G} `,$-4,{fg:this.props.headerColor,bg:this.props.background,bold:!0})}let Z=this.props.footer;if(!Z||J<2)return;let X=Ke4(Z,{fg:this.props.footerKeyColor,bg:this.props.background},{fg:this.props.footerHintColor,bg:this.props.background,dim:!0}),F=Ee4(X),D=Math.max(2,$-F-2);this.paintStyledBorderText(A,Q+D,B+J-1,X,Math.max(0,$-D-2))}paintBorderText(A,Q,B,$,J,Y){this.paintStyledBorderText(A,Q,B,[{text:$,style:Y}],J)}paintStyledBorderText(A,Q,B,$,J){let Y=Q,Z=Fn5($,J);for(let X of Z)A.setChar(Y,B,X.grapheme,X.style,X.width),Y+=X.width}borderGlyph(A,Q){switch(this.props.borderAnimation){case"mysterious-message":return this.mysteriousMessageBorderGlyph(A,Q);case"none":case"subtle":return A==="left"||A==="right"?"│":"─"}}mysteriousMessageBorderGlyph(A,Q){let B=this.mysteriousMessageBorderIndex(Q);if(A==="left")return oi5[B]??"▏";if(A==="right")return ri5[B]??"▕";return xV0[B]??"▁"}mysteriousMessageBorderIndex(A){return Math.max(0,Math.min(xV0.length-1,Math.floor(A*xV0.length)))}mysteriousMessageCornerGlyph(A,Q){let B=this.mysteriousMessageBorderIndex(Q);if(A==="top-left"||A==="top-right")return xV0[B]??"▁";return"█"}cornerGlyph(A,Q){if(this.props.borderAnimation==="mysterious-message")return this.mysteriousMessageCornerGlyph(A,Q);switch(A){case"top-left":return"╭";case"top-right":return"╮";case"bottom-left":return"╰";case"bottom-right":return"╯"}}borderStyle(A){let Q={fg:this.borderColor(A),bg:this.props.background};if(this.props.borderAnimation==="mysterious-message"&&A>0.72)Q.bold=!0;return Q}borderColor(A){switch(this.props.borderAnimation){case"none":return this.props.borderColor;case"subtle":case"mysterious-message":return this.animatedBorderColor(A)}}animatedBorderColor(A){let Q=0.18+Ut(A)*0.82;switch(this.props.tone){case"default":return oQ(Q,void 0,An5);case"warning":return oQ(Q,Qq);case"success":return oQ(Q,void 0);case"error":return oQ(Q,void 0,Qn5)}}sampleBorderIntensity(A,Q,B,$){let J=Math.max(1,B*2+$*2-4),Y=Xn5(A,Q,B,$),Z=Y/J,X=this.props.timeMs/1000,F=this.glow.sample(A*1.3+Y*0.07,Q*1.1-X*5,X,1.2),D=(Z-X*0.18%1+1)%1,G=Math.min(D,1-D),V=Math.max(0,1-G/0.085)**2;return Ut(F*0.58+V*0.54)}}function Xn5(A,Q,B,$){if(Q<=0)return Math.max(0,A);if(A>=B-1)return B-1+Math.max(0,Q);if(Q>=$-1)return B+$-2+Math.max(0,B-1-A);return B*2+$-3+Math.max(0,$-1-Q)}function Ke4(A,Q,B){let $=[{text:" ",style:B}];return A.forEach((J,Y)=>{if(Y>0)$.push({text:" · ",style:B});J.keys.forEach((Z,X)=>{if(X>0)$.push({text:"/",style:B});$.push({text:Z,style:Q})}),$.push({text:` ${J.label}`,style:B})}),$.push({text:" ",style:B}),$}function Ee4(A){return We4(A).reduce((Q,B)=>Q+B.width,0)}function Fn5(A,Q){if(Q<=0)return[];let B=[],$=0;for(let J of We4(A)){if($+J.width>Q)return Dn5(B,$,Q,J.style);B.push(J),$+=J.width}return B}function We4(A){let Q=[];for(let B of A)for(let $ of f4(B.text))Q.push({grapheme:$,style:B.style,width:m6($)});return Q}function Dn5(A,Q,B,$){let Y=m6("…");if(Y>B)return A;let Z=Q;while(A.length>0&&Z+Y>B){let X=A.pop();if(X)Z-=X.width}if(Z+Y<=B)A.push({grapheme:"…",style:$,width:Y});return A}function Ut(A){return Math.max(0,Math.min(1,A))}function Gn5(A,Q,B,$){let J=Math.max(0,B.size.width-Qe4),Y=Math.max(0,B.size.height-Qe4),Z=Math.max(A.minWidth??0,Vn5(A,$)),X=Math.max(0,Math.min(A.maxWidth??li5,J));if(Q.kind==="fill"){let G=Un5(A,$),V=Math.max(Q.modalRows,G),U=Math.max(0,Math.min(V,Y));return new M1(Math.min(Z,X),X,U,U)}let F=Math.max(0,Math.min(A.maxHeight??ii5,Y)),D=Math.min(A.minHeight??0,F);return new M1(Math.min(Z,X),X,D,F)}function Vn5(A,Q){if(Q!=="notched")return 0;let B=0,$=H51(A.header,Q);if($)B=Math.max(B,4+n4(` ${$} `));let J=z51(A.footer,Q);if(J)B=Math.max(B,4+Ee4(Ke4(J,{},{})));return B}function Un5(A,Q){let B=A.chromePadding??Fe4(Q),$=H51(A.header,Q),J=z51(A.footer,Q),Y=2,Z=A.header===void 0||$!==void 0?0:1,X=$===void 0&&typeof A.header==="string"?1:0,F=J===void 0?Kn5(A.footer):0,D=J===void 0?Oe4(A.footer):0,G=1;return 2+B.top+B.bottom+Z+X+1+D+F}function Kn5(A){if(A===void 0)return 1;if(A==="none")return 0;if(fV0(A))return A.length===0?0:1;return 1}function En5(A,Q){switch(A){case"default":return{border:Q.colors.border,header:Q.app.command};case"warning":return{border:Q.colors.warning,header:Q.colors.warning};case"success":return{border:Q.app.toolSuccess,header:Q.app.toolSuccess};case"error":return{border:Q.app.toolError,header:Q.app.toolError}}}function Wn5(A,Q,B){if(A===void 0)return new N0({height:0});if(typeof A==="string")return new p0({padding:q0.symmetric(1,0),child:new A4({child:Hn5(A,Q,B)})});return A}function Hn5(A,Q,B){if(B.titleAnimation==="none")return new l({text:new M(A,new y({color:Q,bold:!0}))});let $=B.timeMs??(B.animate===!1?0:void 0);if($!==void 0)return new l({text:qe4(A,Q,B.titleAnimation,$)});return new He4({title:A,color:Q,animation:B.titleAnimation})}class He4 extends v0{props;constructor(A){super();this.props=A}createState(){return new ze4}}class ze4 extends k0{startedAt=Date.now();timer=null;initState(){this.startTimer()}didUpdateWidget(A){if(A.props.title!==this.widget.props.title||A.props.animation!==this.widget.props.animation||A.props.color!==this.widget.props.color)this.startedAt=Date.now();this.startTimer()}dispose(){this.stopTimer(),super.dispose()}startTimer(){if(this.timer||this.widget.props.animation==="none"||this.animationComplete())return;this.timer=setInterval(()=>{if(!this.mounted)return;if(this.setState(()=>{}),this.animationComplete())this.stopTimer()},ai5),this.timer.unref()}stopTimer(){if(!this.timer)return;clearInterval(this.timer),this.timer=null}animationComplete(){return Date.now()-this.startedAt>=we4(this.widget.props.animation)}build(A){return new l({text:qe4(this.widget.props.title,this.widget.props.color,this.widget.props.animation,Date.now()-this.startedAt)})}}function qe4(A,Q,B,$){let J=f4(A),Y=new y({color:Q,bold:!0}),Z=new y({color:Q,bold:!0,dim:!0});switch(B){case"none":return new M(A,Y);case"wipe":return new M("",void 0,Je4(J,Ne4(J,$),Y,Z));case"scramble":return new M("",void 0,Je4(J,Ie4(J,$),Y,Z))}}function zn5(A,Q,B){let $=f4(A);switch(Q){case"none":return A;case"wipe":return Ne4($,B).join("");case"scramble":return Ie4($,B).join("")}}function Je4(A,Q,B,$){return Q.map((J,Y)=>{let Z=J===A[Y]?B:$;return new M(J,Z)})}function Ne4(A,Q){let B=Ce4(Ut(Q/Ze4)),$=Math.floor(B*(A.length+1));return A.map((J,Y)=>{if(Y<$)return J;if(Y===$)return"▒";return" "})}function Ie4(A,Q){let $=Ce4(Ut(Q/Xe4))*(A.length+5),J=Math.floor(Q/45);return A.map((Y,Z)=>{if(Ut(($-Z)/5)>=1)return Y;return qn5(Z,J)})}function qn5(A,Q){return Be4[(A*7+Q*11)%Be4.length]??"░"}function we4(A){if(A==="scramble")return Xe4;return Ze4}function Ce4(A){return 1-(1-A)**3}function Nn5(A,Q){let B=Q.kind==="fill"?"tight":"loose";return new Z9({fit:B,child:new Me4({child:A})})}class Me4 extends q5{constructor({child:A}){super({child:A})}createRenderObject(){return new Le4}}class Le4 extends Y4{performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=this.children[0];if(Q)Q.layout(A.loosen()),Q.setOffset(0,0);let B=Q?.size.width??0,$=Q?.size.height??0,J=A.constrain(A.hasTightWidth?A.maxWidth:B,A.hasTightHeight?A.maxHeight:$);this.setSize(J.width,J.height)}}function In5(A,Q){if(A===void 0)return Ye4([{keys:["Esc"],label:"close"}],Q);if(fV0(A))return A.length===0?new N0({height:0}):Ye4(A,Q);if(A==="none")return new N0({height:0});return A}function fV0(A){return Array.isArray(A)}function Oe4(A){return A===void 0||fV0(A)&&A.length>0?1:0}function Ye4(A,Q){let B=new y({color:Q.app.keybind}),$=new y({color:Q.colors.foreground,dim:!0}),J=[];return A.forEach((Y,Z)=>{if(Z>0)J.push(new M(" · ",$));Y.keys.forEach((X,F)=>{if(F>0)J.push(new M("/",$));J.push(new M(X,B))}),J.push(new M(` ${Y.label}`,$))}),new A4({child:l.spans(J)})}function Cn5(A){return[{label:"cli: copy tail logs",command:oI("tail",process.pid,{path:A})},{label:"cli: copy logs snapshot",command:oI("snapshot",process.pid,{path:A})},{label:"cli: htop",command:`htop -p ${process.pid}`}]}async function Mn5(A,Q){try{await R4.instance.tuiInstance.clipboard.writeText(A.command)}catch(B){j.error("Failed to copy debug command from Neo command palette",{error:B})}finally{Q()}}function Ln5(A,Q){let B=vV0(process.pid,{path:A},"less -R +G");Q();try{R4.instance.tuiInstance.suspend(),wn5(B,{stdio:"inherit"})}catch($){j.error("Failed to open filtered CLI logs in pager",{error:$,command:B})}finally{process.stdout.write("\x1B[?25l"),R4.instance.tuiInstance.resume()}}function je4(A){return[{noun:"debug",verb:"page logs",description:"View CLI logs in pager",status:{type:"enabled"},run:(Q,B,$)=>{Ln5(A,$)}},{noun:"debug",verb:"copy command",description:"Copy debug command to clipboard",status:{type:"enabled"},run:(Q,B,$)=>{Q.pushWithDismiss((J)=>new TA({header:"Debug: Copy Command",minWidth:80,maxWidth:80,autofocus:!1,footer:"none",onDismiss:J,child:new p6({items:Cn5(A),getLabel:(Y)=>Y.label,showBorder:!1,onAccept:(Y)=>{Mn5(Y,$)},onDismiss:J})}))}}]}var Yb="exit-app-key-pressed",Zb="cancel-key-pressed",rI="loading-thread",Xb="previous-thread-reference",Fb="double-enter-steer";class Et extends a4{}class bV0 extends a4{}class uV0 extends a4{}class Wt extends a4{}class hV0 extends a4{}class Ht extends a4{}class Db extends a4{}class Gb extends a4{}class zt extends a4{}class qt extends a4{}class Nt extends a4{}class Vb extends a4{}class Y$ extends a4{text;successMessage;failureMessage;constructor(A="",Q="Selection copied to clipboard",B="Failed to copy selection"){super();this.text=A;this.successMessage=Q;this.failureMessage=B}}class gV0 extends a4{}class It extends a4{}class mV0 extends a4{}class pV0 extends a4{}class yR extends a4{}class wt extends a4{}class dV0 extends a4{}class cV0 extends a4{}class lV0 extends a4{}class xR extends a4{}class Ct extends a4{}class N51 extends a4{mode;constructor(A){super();this.mode=A}}C3();var Re4=process.platform==="win32"?" ":"█",Pe4=process.platform==="win32"?"░":"█";class D2 extends v0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:A,controller:Q,getScrollInfo:B,thickness:$=1,trackChar:J=Re4,thumbChar:Y=Pe4,showTrack:Z=!0,thumbColor:X,trackColor:F}){super(A?{key:A}:{});this.controller=Q,this.getScrollInfo=B,this.thickness=$,this.trackChar=J,this.thumbChar=Y,this.showTrack=Z,this.thumbColor=X,this.trackColor=F}createState(){return new _e4}}class _e4 extends k0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(A){let{totalContentHeight:Q,viewportHeight:B}=this.widget.getScrollInfo(),J=this.context.findRenderObject()?.size.height??0;if(J===0||Q<=B)return!1;let Y=this.widget.getScrollInfo(),Z=Math.min(1,B/Q),X=Math.max(1,J*Z),F=Math.max(0,Math.min(1,Y.scrollOffset/(Q-B))),D=J-X,G=Math.max(0,D*F),V=G+X;return A>=G&&A<=V}_handleHover=(A)=>{let Q=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(A.localPosition.y),Q!==this._isOverThumb)this.setState()};_handleDrag=(A)=>{let{totalContentHeight:Q,viewportHeight:B,scrollOffset:$}=this.widget.getScrollInfo(),Y=this.context.findRenderObject()?.size.height??0;if(Y===0||Q<=B)return;if(this._dragStartY===null)this._dragStartY=A.localPosition.y,this._dragStartOffset=$;let Z=A.localPosition.y-this._dragStartY,X=Math.min(1,B/Q),F=Math.max(1,Y*X),D=Y-F;if(D<=0)return;let G=Q-B,V=D/G,U=Z/V,K=Math.max(0,Math.min(G,this._dragStartOffset+U));this.widget.controller.jumpTo(K)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(A)=>{if(A.button!=="left")return;let Q=A.localPosition.y,{totalContentHeight:B,viewportHeight:$,scrollOffset:J}=this.widget.getScrollInfo(),Z=this.context.findRenderObject()?.size.height??0;if(Z===0||B<=$)return;let X=Math.min(1,$/B),F=Math.max(1,Z*X),D=B-$,G=Z-F,V=Math.max(0,Math.min(1,J/(B-$))),U=Math.max(0,G*V),K=U+F;if(Q>=U&&Q<=K)return;if(Q<U)this.widget.controller.animateTo(Math.max(0,J-$));else this.widget.controller.animateTo(Math.min(D,J+$))};build(A){return new u1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?N5.POINTER:N5.DEFAULT,child:new Te4({controller:this.widget.controller,getScrollInfo:this.widget.getScrollInfo,thickness:this.widget.thickness,trackChar:this.widget.trackChar,thumbChar:this.widget.thumbChar,showTrack:this.widget.showTrack,thumbColor:this.widget.thumbColor,trackColor:this.widget.trackColor})})}}class Te4 extends wI{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:A,controller:Q,getScrollInfo:B,thickness:$=1,trackChar:J=Re4,thumbChar:Y=Pe4,showTrack:Z=!0,thumbColor:X,trackColor:F}){super(A?{key:A}:{});this.controller=Q,this.getScrollInfo=B,this.thickness=$,this.trackChar=J,this.thumbChar=Y,this.showTrack=Z,this.thumbColor=X,this.trackColor=F}createRenderObject(){return new Se4(this)}updateRenderObject(A){A.updateWidget(this)}}class Se4 extends Y4{_widget;constructor(A){super();this._widget=A}updateWidget(A){this._widget=A,this.markNeedsLayout()}performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=Math.min(A.maxWidth,this._widget.thickness),B=A.maxHeight;this.setSize(Q,B),super.performLayout()}getMinIntrinsicWidth(A){return this._widget.thickness}getMaxIntrinsicWidth(A){return this._widget.thickness}getMinIntrinsicHeight(A){return 0}getMaxIntrinsicHeight(A){return 0}paint(A,Q,B){let{thumbStartFloat:$,thumbSizeFloat:J,showScrollbar:Y}=this._calculateScrollbarMetrics();if(!Y)return;let Z=this._widget.trackColor,X=this._widget.thumbColor,F=process.platform==="win32",D=$,G=$+J;if(!F){let V=["▁","▂","▃","▄","▅","▆","▇","█"];for(let U=0;U<this.size.height;U++){let K="█",E=!0;if(U===Math.floor(D)){let W=1-(D-U),H=Math.floor(W*8);K=V[H]||"█",E=!1}else if(U===Math.floor(G)){let W=1-(G-U),H=Math.floor(W*8);K=V[H]||"█"}else if(U>D&&U<G)E=!1;A.setChar(Q,B+U,K,{fg:X,bg:Z,reverse:E},1)}return}for(let V=0;V<this.size.height;V++){let U=V+0.5,K=U>=D&&U<G,E=K?this._widget.thumbChar:this._widget.trackChar;A.setChar(Q,B+V,E,{fg:K?X:Z,bg:Z,reverse:!1},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:A,viewportHeight:Q,scrollOffset:B}=this._widget.getScrollInfo(),$=this.size.height;if(A<=Q||$<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let J=Math.max(0,Math.min(1,B/(A-Q))),Y=Math.min(1,Q/A),Z=Math.max(1,$*Y),X=$-Z;return{thumbStartFloat:Math.max(0,X*J),thumbSizeFloat:Z,showScrollbar:!0}}}var ke4=1;class JZ extends v0{props;constructor(A){super();this.props=A}createState(){return new ve4}}class ve4 extends k0{ownership;viewportHeight=0;initState(){let A=this.widget.props.controller;if(A)this.ownership={controller:A,owned:!1};else{let Q=new oA;Q.followMode=!1,Q.jumpTo(0),this.ownership={controller:Q,owned:!0}}}didUpdateWidget(A){N4(A.props.controller===this.widget.props.controller,"NeoModalScrollArea.controller identity must be stable across rebuilds")}dispose(){if(this.ownership.owned)this.ownership.controller.dispose()}getScrollInfo=()=>{let{controller:A}=this.ownership,Q=this.viewportHeight;return{totalContentHeight:Math.max(A.maxScrollExtent+Q,0),viewportHeight:Q,scrollOffset:Math.max(A.offset,0)}};setMeasuredHeight=(A)=>{this.viewportHeight=A};build(A){let Q=_0.of(A),{controller:B}=this.ownership;return new ye4({thickness:ke4,onMeasured:this.setMeasuredHeight,scrollable:new _A({controller:B,autofocus:this.widget.props.autofocus??!0,keyboardScrolling:!0,child:this.widget.props.child}),scrollbar:new D2({controller:B,thickness:ke4,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:this.getScrollInfo})})}__testing={isOwned:()=>this.ownership.owned,controller:()=>this.ownership.controller}}class ye4 extends _9{thickness;onMeasured;constructor({scrollable:A,scrollbar:Q,thickness:B,onMeasured:$}){super({children:[A,Q]});this.thickness=B,this.onMeasured=$}createRenderObject(){return new xe4(this.thickness,this.onMeasured)}}class xe4 extends Y4{thickness;onMeasured;constructor(A,Q){super();this.thickness=A;this.onMeasured=Q}performLayout(){let A=this._lastConstraints;N4(!!A,"ScrollAreaLayoutRenderObject.performLayout called without constraints");let Q=A.maxWidth,B=Math.max(0,Math.min(this.thickness,Q)),$=Q-B,[J,Y]=this.children;N4(J!==void 0&&Y!==void 0,"ScrollAreaLayout requires scrollable and scrollbar children"),J.layout(new M1($,$,0,A.maxHeight)),J.setOffset(0,0);let Z=J.size.height;this.onMeasured(Z),Y.layout(new M1(B,B,Z,Z)),Y.setOffset($,0),this.setSize(Q,Z)}}var fe4=10;class I51 extends v0{pluginService;workspaceRoot;logFilePath;onDismiss;constructor(A){super();this.pluginService=A.pluginService,this.workspaceRoot=A.workspaceRoot,this.logFilePath=A.logFilePath,this.onDismiss=A.onDismiss}createState(){return new be4}}class be4 extends k0{plugins=[];subscription=null;initState(){this.subscription=this.widget.pluginService.plugins.subscribe((A)=>{this.setState(()=>{this.plugins=A})})}didUpdateWidget(A){if(A.pluginService===this.widget.pluginService)return;this.subscription?.unsubscribe(),this.subscription=this.widget.pluginService.plugins.subscribe((Q)=>{this.setState(()=>{this.plugins=Q})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}relativePath(A){let Q=A.startsWith("file://")?A.slice(7):A,B=this.widget.workspaceRoot.replace(/\/$/,"");return Q.startsWith(`${B}/`)?Q.slice(B.length+1):Q}detailPrefix(A){if(A.length===0)return` ${" ".repeat(fe4)}`;return` ${`${A}:`.padEnd(fe4," ")}`}pluginRows(A){let Q=_0.of(A),{app:B,colors:$}=Q,J=new y({color:$.foreground,dim:!0}),Y=new y({color:B.link});if(this.plugins.length===0)return[new u0({padding:q0.symmetric(1,1),child:new l({text:new M("No plugins found.",J)})})];return this.plugins.map((Z)=>{let X=Z.status==="active"?new y({color:B.toolSuccess}):Z.status==="error"?new y({color:B.toolError}):new y({color:$.warning}),F=[new l({text:new M(Z.status,X,[new M(" ",J),new M(this.relativePath(Z.uri.toString()),new y({color:B.command}))]),maxLines:1,overflow:"ellipsis"})];if(Z.errorMessage)F.push(new l({text:new M(this.detailPrefix("Error"),J,[new M(`see logs: ${this.widget.logFilePath}`,new y({color:B.toolError}))]),maxLines:1,overflow:"ellipsis"}));if(Z.registeredEvents.length>0)F.push(new l({text:new M(this.detailPrefix("Events"),J,[new M(Z.registeredEvents.join(", "),Y)]),maxLines:1,overflow:"ellipsis"}));for(let[D,G]of Z.registeredCommands.entries())F.push(new l({text:new M(D===0?this.detailPrefix("Commands"):this.detailPrefix(""),J,[new M(`${G.category}: ${G.title}`,Y)]),maxLines:1,overflow:"ellipsis"}));for(let[D,G]of Z.registeredTools.entries())F.push(new l({text:new M(D===0?this.detailPrefix("Tools"):this.detailPrefix(""),J,[new M(G.name,Y)]),maxLines:1,overflow:"ellipsis"}));return new u0({padding:q0.only({left:1,right:1,bottom:1}),child:new f0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:F})})})}build(A){let Q=this.plugins.filter((Y)=>Y.status==="active").length,B=this.plugins.reduce((Y,Z)=>Y+Z.registeredCommands.length,0),$=this.plugins.reduce((Y,Z)=>Y+Z.registeredTools.length,0),J=`${Q}/${this.plugins.length} ${K4(this.plugins.length,"plugin")} active (${B} ${K4(B,"command")}, ${$} ${K4($,"tool")})`;return new TA({header:"Plugins",autofocus:!1,maxWidth:90,maxHeight:30,footer:[{keys:["Esc"],label:"close"},{keys:["↑↓","j/k"],label:"scroll"}],onDismiss:this.widget.onDismiss,child:new f0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new u0({padding:q0.only({left:1,right:1,bottom:1}),child:new l({text:new M(J,new y({bold:!0}))})}),new Z9({fit:"loose",child:new JZ({child:new f0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:this.pluginRows(A)})})})]})})}}function ue4(A){return[{noun:"plugins",verb:"list",description:"List all loaded plugins",keywords:["extensions","tools","commands"],status:{type:"enabled"},run:(Q,B,$)=>{Q.push(new I51({pluginService:A.pluginService,workspaceRoot:A.workspaceRoot,logFilePath:A.logFilePath,onDismiss:$}))}},{noun:"plugins",verb:"reload",description:"Reload all plugins",keywords:["refresh","restart","extensions"],status:{type:"enabled"},run:()=>{A.pluginService.reload(),A.toastController.show("Reloading plugins...")}}]}o0();class Mt extends a4{}class Ub extends a4{}class w51 extends v0{props;constructor(A){super();this.props=A}createState(){return new he4}}class he4 extends k0{build(A){let{options:Q,onConfirm:B,onCancel:$}=this.widget.props,{colors:J}=_0.of(A),Y=Q.message?new l({text:new M(Q.message,new y({color:J.foreground}))}):new N0({height:1});return new TA({header:Q.title,minWidth:64,maxWidth:80,footer:[{keys:["Y"],label:Q.confirmButtonText??"yes"},{keys:["N","Esc"],label:"cancel"},{keys:["↑↓","j/k"],label:"scroll"}],autofocus:!1,onDismiss:$,child:new FA({actions:new Map([[Mt,new G4(()=>B())],[Ub,new G4(()=>$())]]),child:new h5({debugLabel:"NeoConfirmDialogShortcuts",shortcuts:On5(),child:new JZ({child:Y})})})})}}function On5(){return new Map([[v1.key("y"),new Mt],[v1.shift("Y"),new Mt],[v1.shift("y"),new Mt],[v1.key("n"),new Ub],[v1.shift("N"),new Ub],[v1.shift("n"),new Ub],[v1.key("Escape"),new Ub]])}class Lt extends v0{props;constructor(A){super();this.props=A}createState(){return new ge4}}class ge4 extends k0{controller=new I8;onTextChanged=()=>{this.setState()};initState(){this.controller.text=this.widget.props.initialValue??"",this.controller.addListener(this.onTextChanged)}dispose(){this.controller.removeListener(this.onTextChanged),this.controller.dispose(),super.dispose()}handleSubmit(){let A=this.controller.text.trim();if((this.widget.props.isRequired??!0)&&A.length===0)return;this.widget.props.onSubmit(A)}build(A){let{colors:Q,app:B}=_0.of(A),Y=!(this.widget.props.isRequired??!0)||this.controller.text.trim().length>0?[{keys:["Enter"],label:"submit"},{keys:["Esc"],label:"cancel"}]:[{keys:["Esc"],label:"cancel"}],Z=[];if(this.widget.props.helpText)Z.push(new l({text:new M(this.widget.props.helpText,new y({color:Q.foreground}))})),Z.push(new N0({height:1}));return Z.push(new B1({children:[new l({text:new M("> ",new y({color:B.command}))}),new S1({child:new A$({controller:this.controller,placeholder:this.widget.props.placeholder??"",autofocus:!0,maxLines:1,style:{textColor:Q.foreground,border:null},onSubmitted:()=>this.handleSubmit()})})]})),new TA({header:this.widget.props.header,minWidth:80,maxWidth:80,footer:Y,autofocus:!1,bodyFit:this.widget.props.bodyFit,onDismiss:this.widget.props.onDismiss,child:new f0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:Z})})}}class C51 extends I1{props;constructor(A){super();this.props=A}build(A){return new TA({header:this.props.options.title,minWidth:64,maxWidth:80,footer:[{keys:["↑/↓","j/k"],label:"move"},{keys:["Enter"],label:"select"},{keys:["Esc"],label:"cancel"}],autofocus:!1,onDismiss:this.props.onCancel,child:jn5(this.props)})}}function jn5(A){let Q=A.options.options.map((B)=>({value:B,label:B}));return new X9({options:Q,body:A.options.message,onSelect:(B)=>{if(B===null){A.onCancel();return}A.onSelect(B)},padding:q0.all(0),showBorder:!1,showDismissalMessage:!1,enableMouseInteraction:!1})}class M51{options;unregisterPluginCommands=null;pluginCommandSubscriptions=[];pluginErrorToastKeys=new Set;pendingInputDialog=null;pendingConfirmDialog=null;pendingSelectDialog=null;constructor(A){this.options=A}init(){this.configurePluginPlatform(),this.subscribePluginCommands()}dispose(){this.unregisterPluginCommands?.(),this.unregisterPluginCommands=null;for(let A of this.pluginCommandSubscriptions)A.unsubscribe();this.pluginCommandSubscriptions=[]}hasBlockingDialog(){return this.pendingInputDialog!==null||this.pendingConfirmDialog!==null||this.pendingSelectDialog!==null}buildDialogLayers(){let A=[];if(this.pendingInputDialog)A.push(new Lt({header:this.pendingInputDialog.options.title??"Input",helpText:this.pendingInputDialog.options.helpText,initialValue:this.pendingInputDialog.options.initialValue,isRequired:!1,onSubmit:this.resolveInputDialog,onDismiss:this.cancelInputDialog}));if(this.pendingConfirmDialog)A.push(new w51({options:this.pendingConfirmDialog.options,onConfirm:this.resolveConfirmDialog,onCancel:this.cancelConfirmDialog}));if(this.pendingSelectDialog)A.push(new C51({options:this.pendingSelectDialog.options,onSelect:this.resolveSelectDialog,onCancel:this.cancelSelectDialog}));return A}configurePluginPlatform(){let A=this.options.neoContext.pluginPlatform;if(!A)return;A.showToast=(Q)=>this.options.toastController.show(Q,"success"),A.showOpenedURLToast=(Q)=>{this.options.toastController.show(`Opened URL: ${Q}`,"success",8000)},A.appendToThreadHandler=this.options.neoContext.observerOnly?async()=>{throw Error("thread.append is only available from an executor-owned plugin runtime")}:this.options.appendToThread,A.showInputDialog=this.showInputDialog,A.showConfirmDialog=this.showConfirmDialog,A.showSelectDialog=this.showSelectDialog}subscribePluginCommands(){let A=this.options.neoContext.pluginService;if(!A)return;this.refreshPluginCommands(A.commands.list()),this.pluginCommandSubscriptions=[A.plugins.subscribe((Q)=>{this.showNewPluginErrorToasts(Q),this.refreshPluginCommands(A.commands.list())}),A.commands.changed.subscribe(()=>{this.refreshPluginCommands(A.commands.list())})]}refreshPluginCommands(A){this.unregisterPluginCommands?.();let B=A.map(($)=>this.createPluginCommand($)).map(($)=>this.options.commandRegistry.register($));this.unregisterPluginCommands=()=>{for(let $ of B)$()}}showNewPluginErrorToasts(A){let Q=new Set;for(let B of A){if(B.status!=="error")continue;let $=`${B.uri.toString()}
5284
- ${B.errorMessage??""}`;if(Q.add($),this.pluginErrorToastKeys.has($))continue;this.options.toastController.show(this.formatPluginErrorToast(B),"error",8000)}this.pluginErrorToastKeys=Q}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.neoContext.logFilePath}`}createPluginCommand(A){return{noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,keywords:["plugin",A.pluginName,A.id],status:{type:"enabled"},run:async(Q,B,$)=>{$();try{await this.options.neoContext.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(J){j.error("Neo plugin command failed",{error:J,command:A}),this.options.toastController.show(J instanceof Error?J.message:String(J),"error",5000)}}}}showInputDialog=(A)=>{return new Promise((Q)=>{if(!this.options.state.mounted){Q(void 0);return}this.options.state.setState(()=>{this.options.commandPalette.disable(),this.pendingInputDialog={options:A,resolve:Q}})})};showConfirmDialog=(A)=>{return new Promise((Q)=>{if(!this.options.state.mounted){Q(!1);return}this.options.state.setState(()=>{this.options.commandPalette.disable(),this.pendingConfirmDialog={options:A,resolve:Q}})})};showSelectDialog=(A)=>{return new Promise((Q)=>{if(!this.options.state.mounted){Q(void 0);return}this.options.state.setState(()=>{this.options.commandPalette.disable(),this.pendingSelectDialog={options:A,resolve:Q}})})};resolveInputDialog=(A)=>{let Q=this.pendingInputDialog;if(!Q)return;this.clearDialogState(()=>{this.pendingInputDialog=null}),Q.resolve(A)};cancelInputDialog=()=>{let A=this.pendingInputDialog;if(!A)return;this.clearDialogState(()=>{this.pendingInputDialog=null}),A.resolve(void 0)};resolveConfirmDialog=()=>{let A=this.pendingConfirmDialog;if(!A)return;this.clearDialogState(()=>{this.pendingConfirmDialog=null}),A.resolve(!0)};cancelConfirmDialog=()=>{let A=this.pendingConfirmDialog;if(!A)return;this.clearDialogState(()=>{this.pendingConfirmDialog=null}),A.resolve(!1)};resolveSelectDialog=(A)=>{let Q=this.pendingSelectDialog;if(!Q)return;this.clearDialogState(()=>{this.pendingSelectDialog=null}),Q.resolve(A)};cancelSelectDialog=()=>{let A=this.pendingSelectDialog;if(!A)return;this.clearDialogState(()=>{this.pendingSelectDialog=null}),A.resolve(void 0)};clearDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}}Qi();n2();import{readFile as Rn5}from"node:fs/promises";import L51 from"node:os";async function me4(A,Q){try{return{path:Q,contents:xg0(await Rn5(A,"utf8"))}}catch{return null}}async function pe4(A,Q){let B=[],$=await VA.getThread({thread:Q},{config:A.configService}),J=$.ok?$.result.thread.data:null;B.push({path:"thread.json",contents:JSON.stringify(YJ(J),null,2)});let Y=await me4(Fr(Q).sourcePath,`logs/${Q}.log`);if(Y)B.push(Y);let Z=await me4(A.settingsFilePath,"settings/global.json");if(Z)B.push(Z);let X=await Df()??"unknown",F=await VA.sendReport({threadID:Q,files:B,metadata:{clientVersion:"0.0.1777967145-g633c91",clientOS:`${L51.platform()} ${L51.release()} ${L51.arch()}`,installMethod:X}},{config:A.configService});if(!F.ok)throw Error(`Failed to submit report: ${F.error.message}`);return F.result.reportID}class O51{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.backStack.pop();this.forwardStack.push(Q)}}}}o0();r9();n2();async function de4(A,Q,B){let $;switch(B){case"private":$="This thread's visibility has been updated to private";break;case"workspace":$="This thread's visibility has been updated to workspace";break;case"group":$="This thread's visibility has been updated to group";break;case"unlisted":$="This thread's visibility has been updated to unlisted. Anyone on the Internet with the link can view it.";break;case"public":$="This thread's visibility has been updated to public. Anyone on the Internet can see it on your public profile, and it is publicly searchable.";break}try{let J=await VA.setThreadMeta({thread:Q,meta:QZ(B)},{config:A.configService});if(!J.ok)throw Error(J.error.message);let Y=!1;if(B!=="private"){let X=_B(new URL(A.ampURL),Q).toString();try{await R4.instance.tuiInstance.clipboard.writeText(X),Y=!0}catch(F){j.error("Failed to copy thread URL after visibility update",{error:F})}}let Z=Y?`${$} Link copied to clipboard.`:$;return new rQ(Z)}catch(J){let Y=J instanceof Error?J.message:String(J);if(Y.includes("no-workspace"))return Error("You are not a member of any workspace.");if(Y.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(Y.includes("no-groups"))return Error("You are not a member of any groups.");return j.error("Unexpected failure to update thread visibility",{error:J}),Error(`Failed to update thread visibility for ${Q}`)}}class iV0 extends q5{offstage;constructor({key:A,offstage:Q=!0,child:B}){super({key:A,child:B});this.offstage=Q}createRenderObject(){return new j51(this.offstage)}updateRenderObject(A){if(A instanceof j51)A.offstage=this.offstage}}class j51 extends Y4{_offstage;constructor(A){super();this._offstage=A}get offstage(){return this._offstage}set offstage(A){if(A===this._offstage)return;this._offstage=A,this.markNeedsLayout()}getMinIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicWidth(A)??0}getMaxIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicWidth(A)??0}getMinIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicHeight(A)??0}getMaxIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicHeight(A)??0}performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let B=A.constrain(Q.size.width,Q.size.height);this.setSize(B.width,B.height),Q.setOffset(0,0)}else{let B=A.smallest;this.setSize(B.width,B.height)}super.performLayout()}paint(A,Q,B){if(this._offstage)return;super.paint(A,Q,B)}hitTest(A,Q,B,$){if(this._offstage)return!1;return super.hitTest(A,Q,B,$)}}class R51{_state=null;_attach(A){this._state=A}_detach(){this._state=null}push(A){this._state?.push(A)}pushWithDismiss(A){this._state?.pushWithDismiss(A)}pop(){return this._state?.pop()??!1}get canPop(){return this._state?.canPop??!1}}class P51 extends v0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new ce4}}class ce4 extends k0{entries=[];initState(){this.widget.controller._attach(this)}didUpdateWidget(A){if(A.controller!==this.widget.controller)A.controller._detach(),this.widget.controller._attach(this)}dispose(){this.widget.controller._detach(),super.dispose()}push(A){let Q=new ej,B=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:B})})}pushWithDismiss(A){let Q=new ej,B=this.makeScopedDismiss(Q),$=A(B);this.setState(()=>{this.entries.push({key:Q,widget:$,dismiss:B})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new iV0({offstage:this.entries.length>0,child:this.widget.root}));for(let B=0;B<this.entries.length;B++){let $=this.entries[B],J=B===this.entries.length-1,Y=J?new c4({autofocus:!0,debugLabel:`ModalStackEntry[${B}]`,onKey:(Z)=>{if(Z.key!=="Escape")return"ignored";return $.dismiss(),"handled"},child:$.widget}):$.widget;Q.push(new iV0({key:$.key,offstage:!J,child:Y}))}return new t4({fit:"expand",children:Q})}}class T51 extends I1{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter(($)=>$.status.type!=="hidden"),B=Pn5(Q);return new TA({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:q0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new p6({items:Q,showBorder:!1,getLabel:($)=>{let J=_51($);return $.keywords&&$.keywords.length>0?`${J} ${$.keywords.join(" ").toLowerCase()}`:J},sortItems:($,J,Y)=>{if(Y===""){let G=$.item.status.type==="disabled"?1:0,V=J.item.status.type==="disabled"?1:0;if(G!==V)return G-V;let U=$.item.sortBoost??0,K=J.item.sortBoost??0;if(U!==K)return K-U;let E=$.item.noun?.toLowerCase()??"",W=J.item.noun?.toLowerCase()??"";if(E!==W)return E<W?-1:1;return 0}let Z=qR($.item.verb.toLowerCase(),Y),X=qR(J.item.verb.toLowerCase(),Y);if(Z!==X)return X-Z;let F=qR(_51($.item),Y),D=qR(_51(J.item),Y);if(F!==D)return D-F;return J.score-$.score},isItemDisabled:($)=>$.status.type==="disabled",buildDisabledReasonWidget:($,J)=>{if($.status.type!=="disabled")return;let{colors:Y}=_0.of(J);return new l({text:new M($.status.reason,new y({color:Y.mutedForeground,dim:!0})),textAlign:"center"})},renderItem:($,J,Y,Z)=>new le4({command:$,isSelected:J,isDisabled:Y,categoryWidth:B,buildContext:Z}),onAccept:($)=>{this.props.onAccept($)},onDismiss:this.props.onDismiss})})}}class le4 extends I1{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:B,isDisabled:$,categoryWidth:J,buildContext:Y}=this.props,Z=_0.of(Y),{colors:X,app:F}=Z,D=B?F.selectionBackground:void 0,G=B?F.selectionForeground:X.foreground,V=B?G:X.mutedForeground,U=new l({text:new M(Q.noun?.toLowerCase()??"",new y({color:V,dim:$||!B})),textAlign:"right"}),K=[new M(Q.verb.toLowerCase(),new y({color:G,bold:!0,dim:$}))];if($)K.push(new M(" (unavailable)",new y({color:G,dim:!0})));let E=l.spans(K),W=[{child:U,fixedWidth:J},{child:E,expanded:!0}];if(Q.shortcut)W.push({child:_n5(Q.shortcut,Z,$)});return new ie4({columns:W,padding:q0.horizontal(1),backgroundColor:D})}}function _51(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function Pn5(A){return A.reduce((Q,B)=>{return B.noun?Math.max(Q,n4(B.noun)):Q},0)}function _n5(A,Q,B){let{colors:$,app:J}=Q,Y=new y({color:$.mutedForeground,dim:B}),Z=[];for(let X of A.modifiers()){if(Z.length>0)Z.push(new M(" ",Y));Z.push(new M(X,new y({color:J.keybind,bold:!0,dim:B})))}if(Z.length>0)Z.push(new M(" ",Y));return Z.push(new M(A.key,new y({color:J.keybind,bold:!0,dim:B}))),l.spans(Z)}class ie4 extends I1{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:B=2,padding:$,backgroundColor:J}=this.props,Y=[];for(let X=0;X<Q.length;X++){let F=Q[X];if(X>0&&B>0)Y.push(new N0({width:B}));if(F.fixedWidth!==void 0)Y.push(new N0({width:F.fixedWidth,child:F.child}));else if(F.expanded)Y.push(new S1({child:F.child}));else Y.push(F.child)}let Z=new B1({crossAxisAlignment:"start",children:Y});if(!$&&!J)return Z;return new p0({decoration:J?{color:J}:void 0,padding:$,child:Z})}}class S51{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#B(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#B()}}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#B(){for(let A of this.#Q)A()}}class Z$ extends z6{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=Z$.maybeOf(A);if(!Q)throw Error("No NeoCommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(Z$)?.commandRegistry??null}}class k51 extends v0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new ne4}}class ne4 extends k0{modalStack=new R51;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=Z$.of(this.context);this.commandRegistry=A,A.addListener(this.onCommandsChanged)})}dispose(){this.commandRegistry?.removeListener(this.onCommandsChanged),this.commandRegistry=null,super.dispose()}onCommandsChanged=()=>{this.setState()};build(A){let Q=Z$.of(A).commands,B=new T51({commands:Q,onAccept:($)=>{$.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new P51({root:B,controller:this.modalStack})}}var v51=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Move cursor left/right",methods:[{keys:["←"]},{keys:["→"]},{input:"B",keys:["Ctrl"]},{input:"F",keys:["Ctrl"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!0},{description:"Insert newline",methods:[{keys:["Enter"]},{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!1},{description:"Submit message",methods:[{keys:["Enter"]}],submitOnEnterOnly:!0},{description:"Submit message",methods:[{keys:["Ctrl/Cmd","Enter"]}],submitOnEnterOnly:!1},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]},{keys:["Ctrl","←"]},{input:"B",keys:["Alt"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]},{keys:["Ctrl","→"]},{input:"F",keys:["Alt"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]},{input:"H",keys:["Ctrl"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]},{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]},{input:"S",keys:["Alt"]}]},{description:"Toggle reasoning effort",methods:[{input:"D",keys:["Alt"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]},{description:"Mention threads",methods:[{keys:["@@"]}]},{description:"Show prompt history",methods:[{input:"R",keys:["Ctrl"]}]},{description:"Toggle inline shortcuts help",methods:[{keys:["?"]}]},{description:"Toggle thinking/dense view",methods:[{input:"T",keys:["Alt"]}]}],y51=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Half-page scroll",methods:[{input:"K",keys:["Alt"]},{input:"J",keys:["Alt"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class nV0 extends I1{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let B=B4.of(A).size.width,$=50,J=B<50,Y=[];for(let Z of this.items){let[X,F]=this.renderRow(Z),D;if(J)D=new f0({crossAxisAlignment:"start",mainAxisSize:"min",children:[X,new u0({padding:q0.only({left:4}),child:F})]});else D=new B1({crossAxisAlignment:"start",children:[new S1({flex:1,child:X}),new N0({width:1}),new S1({flex:1,child:F})]});Y.push(new u0({padding:q0.horizontal(6),child:D}))}return new f0({crossAxisAlignment:"start",mainAxisSize:"min",children:Y})}}class x51 extends v0{commands;submitOnEnter;constructor({key:A,commands:Q,submitOnEnter:B}){super(A?{key:A}:{});this.commands=Q,this.submitOnEnter=B??!0}createState(){return new ae4}}class ae4 extends k0{scrollController;initState(){this.scrollController=new oA,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0)}dispose(){}build(A){let B=k1.of(A).colorScheme,J=_0.of(A).app,Y=B4.of(A),Z=new y({color:B.primary,bold:!0}),X=new y({color:B.secondary,bold:!0}),F=new y({color:J.keybind}),D=new y({color:J.command}),G=new y({color:B.foreground}),V=new y({color:B.foreground}),U=Y.size.width,K=Y.size.height,E=U-4,W=K-4,H=Math.max(40,Math.min(80,E)),z=new Set(["permissions-disable"]),N=[...this.widget.commands.filter((O)=>{let _=O.noun?.toLowerCase();return _!=="dev"&&_!=="debug"&&!O.id.startsWith("debug-")&&!z.has(O.id)})].sort((O,_)=>{let S=(O.noun??"").toLowerCase(),T=(_.noun??"").toLowerCase(),b=S.localeCompare(T);if(b!==0)return b;let h=O.verb.toLowerCase(),x=_.verb.toLowerCase(),v=h.localeCompare(x);if(v!==0)return v;return O.id.localeCompare(_.id)}),I=new _A({autofocus:!0,controller:this.scrollController,child:new p0({constraints:new M1(H,H,0,Number.POSITIVE_INFINITY),child:new f0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new A4({child:new l({text:new M(`Amp CLI - Help & Keyboard Shortcuts
5284
+ ${B.errorMessage??""}`;if(Q.add($),this.pluginErrorToastKeys.has($))continue;this.options.toastController.show(this.formatPluginErrorToast(B),"error",8000)}this.pluginErrorToastKeys=Q}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.neoContext.logFilePath}`}createPluginCommand(A){return{noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,keywords:["plugin",A.pluginName,A.id],status:{type:"enabled"},run:async(Q,B,$)=>{$();try{await this.options.neoContext.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(J){j.error("Neo plugin command failed",{error:J,command:A}),this.options.toastController.show(J instanceof Error?J.message:String(J),"error",5000)}}}}showInputDialog=(A)=>{return new Promise((Q)=>{if(!this.options.state.mounted){Q(void 0);return}this.options.state.setState(()=>{this.options.commandPalette.disable(),this.pendingInputDialog={options:A,resolve:Q}})})};showConfirmDialog=(A)=>{return new Promise((Q)=>{if(!this.options.state.mounted){Q(!1);return}this.options.state.setState(()=>{this.options.commandPalette.disable(),this.pendingConfirmDialog={options:A,resolve:Q}})})};showSelectDialog=(A)=>{return new Promise((Q)=>{if(!this.options.state.mounted){Q(void 0);return}this.options.state.setState(()=>{this.options.commandPalette.disable(),this.pendingSelectDialog={options:A,resolve:Q}})})};resolveInputDialog=(A)=>{let Q=this.pendingInputDialog;if(!Q)return;this.clearDialogState(()=>{this.pendingInputDialog=null}),Q.resolve(A)};cancelInputDialog=()=>{let A=this.pendingInputDialog;if(!A)return;this.clearDialogState(()=>{this.pendingInputDialog=null}),A.resolve(void 0)};resolveConfirmDialog=()=>{let A=this.pendingConfirmDialog;if(!A)return;this.clearDialogState(()=>{this.pendingConfirmDialog=null}),A.resolve(!0)};cancelConfirmDialog=()=>{let A=this.pendingConfirmDialog;if(!A)return;this.clearDialogState(()=>{this.pendingConfirmDialog=null}),A.resolve(!1)};resolveSelectDialog=(A)=>{let Q=this.pendingSelectDialog;if(!Q)return;this.clearDialogState(()=>{this.pendingSelectDialog=null}),Q.resolve(A)};cancelSelectDialog=()=>{let A=this.pendingSelectDialog;if(!A)return;this.clearDialogState(()=>{this.pendingSelectDialog=null}),A.resolve(void 0)};clearDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}}Qi();n2();import{readFile as Rn5}from"node:fs/promises";import L51 from"node:os";async function me4(A,Q){try{return{path:Q,contents:xg0(await Rn5(A,"utf8"))}}catch{return null}}async function pe4(A,Q){let B=[],$=await VA.getThread({thread:Q},{config:A.configService}),J=$.ok?$.result.thread.data:null;B.push({path:"thread.json",contents:JSON.stringify(YJ(J),null,2)});let Y=await me4(Fr(Q).sourcePath,`logs/${Q}.log`);if(Y)B.push(Y);let Z=await me4(A.settingsFilePath,"settings/global.json");if(Z)B.push(Z);let X=await Df()??"unknown",F=await VA.sendReport({threadID:Q,files:B,metadata:{clientVersion:"0.0.1777970347-gc2d807",clientOS:`${L51.platform()} ${L51.release()} ${L51.arch()}`,installMethod:X}},{config:A.configService});if(!F.ok)throw Error(`Failed to submit report: ${F.error.message}`);return F.result.reportID}class O51{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.backStack.pop();this.forwardStack.push(Q)}}}}o0();r9();n2();async function de4(A,Q,B){let $;switch(B){case"private":$="This thread's visibility has been updated to private";break;case"workspace":$="This thread's visibility has been updated to workspace";break;case"group":$="This thread's visibility has been updated to group";break;case"unlisted":$="This thread's visibility has been updated to unlisted. Anyone on the Internet with the link can view it.";break;case"public":$="This thread's visibility has been updated to public. Anyone on the Internet can see it on your public profile, and it is publicly searchable.";break}try{let J=await VA.setThreadMeta({thread:Q,meta:QZ(B)},{config:A.configService});if(!J.ok)throw Error(J.error.message);let Y=!1;if(B!=="private"){let X=_B(new URL(A.ampURL),Q).toString();try{await R4.instance.tuiInstance.clipboard.writeText(X),Y=!0}catch(F){j.error("Failed to copy thread URL after visibility update",{error:F})}}let Z=Y?`${$} Link copied to clipboard.`:$;return new rQ(Z)}catch(J){let Y=J instanceof Error?J.message:String(J);if(Y.includes("no-workspace"))return Error("You are not a member of any workspace.");if(Y.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(Y.includes("no-groups"))return Error("You are not a member of any groups.");return j.error("Unexpected failure to update thread visibility",{error:J}),Error(`Failed to update thread visibility for ${Q}`)}}class iV0 extends q5{offstage;constructor({key:A,offstage:Q=!0,child:B}){super({key:A,child:B});this.offstage=Q}createRenderObject(){return new j51(this.offstage)}updateRenderObject(A){if(A instanceof j51)A.offstage=this.offstage}}class j51 extends Y4{_offstage;constructor(A){super();this._offstage=A}get offstage(){return this._offstage}set offstage(A){if(A===this._offstage)return;this._offstage=A,this.markNeedsLayout()}getMinIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicWidth(A)??0}getMaxIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicWidth(A)??0}getMinIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicHeight(A)??0}getMaxIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicHeight(A)??0}performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let B=A.constrain(Q.size.width,Q.size.height);this.setSize(B.width,B.height),Q.setOffset(0,0)}else{let B=A.smallest;this.setSize(B.width,B.height)}super.performLayout()}paint(A,Q,B){if(this._offstage)return;super.paint(A,Q,B)}hitTest(A,Q,B,$){if(this._offstage)return!1;return super.hitTest(A,Q,B,$)}}class R51{_state=null;_attach(A){this._state=A}_detach(){this._state=null}push(A){this._state?.push(A)}pushWithDismiss(A){this._state?.pushWithDismiss(A)}pop(){return this._state?.pop()??!1}get canPop(){return this._state?.canPop??!1}}class P51 extends v0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new ce4}}class ce4 extends k0{entries=[];initState(){this.widget.controller._attach(this)}didUpdateWidget(A){if(A.controller!==this.widget.controller)A.controller._detach(),this.widget.controller._attach(this)}dispose(){this.widget.controller._detach(),super.dispose()}push(A){let Q=new ej,B=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:B})})}pushWithDismiss(A){let Q=new ej,B=this.makeScopedDismiss(Q),$=A(B);this.setState(()=>{this.entries.push({key:Q,widget:$,dismiss:B})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new iV0({offstage:this.entries.length>0,child:this.widget.root}));for(let B=0;B<this.entries.length;B++){let $=this.entries[B],J=B===this.entries.length-1,Y=J?new c4({autofocus:!0,debugLabel:`ModalStackEntry[${B}]`,onKey:(Z)=>{if(Z.key!=="Escape")return"ignored";return $.dismiss(),"handled"},child:$.widget}):$.widget;Q.push(new iV0({key:$.key,offstage:!J,child:Y}))}return new t4({fit:"expand",children:Q})}}class T51 extends I1{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter(($)=>$.status.type!=="hidden"),B=Pn5(Q);return new TA({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:q0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new p6({items:Q,showBorder:!1,getLabel:($)=>{let J=_51($);return $.keywords&&$.keywords.length>0?`${J} ${$.keywords.join(" ").toLowerCase()}`:J},sortItems:($,J,Y)=>{if(Y===""){let G=$.item.status.type==="disabled"?1:0,V=J.item.status.type==="disabled"?1:0;if(G!==V)return G-V;let U=$.item.sortBoost??0,K=J.item.sortBoost??0;if(U!==K)return K-U;let E=$.item.noun?.toLowerCase()??"",W=J.item.noun?.toLowerCase()??"";if(E!==W)return E<W?-1:1;return 0}let Z=qR($.item.verb.toLowerCase(),Y),X=qR(J.item.verb.toLowerCase(),Y);if(Z!==X)return X-Z;let F=qR(_51($.item),Y),D=qR(_51(J.item),Y);if(F!==D)return D-F;return J.score-$.score},isItemDisabled:($)=>$.status.type==="disabled",buildDisabledReasonWidget:($,J)=>{if($.status.type!=="disabled")return;let{colors:Y}=_0.of(J);return new l({text:new M($.status.reason,new y({color:Y.mutedForeground,dim:!0})),textAlign:"center"})},renderItem:($,J,Y,Z)=>new le4({command:$,isSelected:J,isDisabled:Y,categoryWidth:B,buildContext:Z}),onAccept:($)=>{this.props.onAccept($)},onDismiss:this.props.onDismiss})})}}class le4 extends I1{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:B,isDisabled:$,categoryWidth:J,buildContext:Y}=this.props,Z=_0.of(Y),{colors:X,app:F}=Z,D=B?F.selectionBackground:void 0,G=B?F.selectionForeground:X.foreground,V=B?G:X.mutedForeground,U=new l({text:new M(Q.noun?.toLowerCase()??"",new y({color:V,dim:$||!B})),textAlign:"right"}),K=[new M(Q.verb.toLowerCase(),new y({color:G,bold:!0,dim:$}))];if($)K.push(new M(" (unavailable)",new y({color:G,dim:!0})));let E=l.spans(K),W=[{child:U,fixedWidth:J},{child:E,expanded:!0}];if(Q.shortcut)W.push({child:_n5(Q.shortcut,Z,$)});return new ie4({columns:W,padding:q0.horizontal(1),backgroundColor:D})}}function _51(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function Pn5(A){return A.reduce((Q,B)=>{return B.noun?Math.max(Q,n4(B.noun)):Q},0)}function _n5(A,Q,B){let{colors:$,app:J}=Q,Y=new y({color:$.mutedForeground,dim:B}),Z=[];for(let X of A.modifiers()){if(Z.length>0)Z.push(new M(" ",Y));Z.push(new M(X,new y({color:J.keybind,bold:!0,dim:B})))}if(Z.length>0)Z.push(new M(" ",Y));return Z.push(new M(A.key,new y({color:J.keybind,bold:!0,dim:B}))),l.spans(Z)}class ie4 extends I1{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:B=2,padding:$,backgroundColor:J}=this.props,Y=[];for(let X=0;X<Q.length;X++){let F=Q[X];if(X>0&&B>0)Y.push(new N0({width:B}));if(F.fixedWidth!==void 0)Y.push(new N0({width:F.fixedWidth,child:F.child}));else if(F.expanded)Y.push(new S1({child:F.child}));else Y.push(F.child)}let Z=new B1({crossAxisAlignment:"start",children:Y});if(!$&&!J)return Z;return new p0({decoration:J?{color:J}:void 0,padding:$,child:Z})}}class S51{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#B(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#B()}}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#B(){for(let A of this.#Q)A()}}class Z$ extends z6{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=Z$.maybeOf(A);if(!Q)throw Error("No NeoCommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(Z$)?.commandRegistry??null}}class k51 extends v0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new ne4}}class ne4 extends k0{modalStack=new R51;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=Z$.of(this.context);this.commandRegistry=A,A.addListener(this.onCommandsChanged)})}dispose(){this.commandRegistry?.removeListener(this.onCommandsChanged),this.commandRegistry=null,super.dispose()}onCommandsChanged=()=>{this.setState()};build(A){let Q=Z$.of(A).commands,B=new T51({commands:Q,onAccept:($)=>{$.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new P51({root:B,controller:this.modalStack})}}var v51=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Move cursor left/right",methods:[{keys:["←"]},{keys:["→"]},{input:"B",keys:["Ctrl"]},{input:"F",keys:["Ctrl"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!0},{description:"Insert newline",methods:[{keys:["Enter"]},{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!1},{description:"Submit message",methods:[{keys:["Enter"]}],submitOnEnterOnly:!0},{description:"Submit message",methods:[{keys:["Ctrl/Cmd","Enter"]}],submitOnEnterOnly:!1},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]},{keys:["Ctrl","←"]},{input:"B",keys:["Alt"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]},{keys:["Ctrl","→"]},{input:"F",keys:["Alt"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]},{input:"H",keys:["Ctrl"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]},{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]},{input:"S",keys:["Alt"]}]},{description:"Toggle reasoning effort",methods:[{input:"D",keys:["Alt"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]},{description:"Mention threads",methods:[{keys:["@@"]}]},{description:"Show prompt history",methods:[{input:"R",keys:["Ctrl"]}]},{description:"Toggle inline shortcuts help",methods:[{keys:["?"]}]},{description:"Toggle thinking/dense view",methods:[{input:"T",keys:["Alt"]}]}],y51=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Half-page scroll",methods:[{input:"K",keys:["Alt"]},{input:"J",keys:["Alt"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class nV0 extends I1{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let B=B4.of(A).size.width,$=50,J=B<50,Y=[];for(let Z of this.items){let[X,F]=this.renderRow(Z),D;if(J)D=new f0({crossAxisAlignment:"start",mainAxisSize:"min",children:[X,new u0({padding:q0.only({left:4}),child:F})]});else D=new B1({crossAxisAlignment:"start",children:[new S1({flex:1,child:X}),new N0({width:1}),new S1({flex:1,child:F})]});Y.push(new u0({padding:q0.horizontal(6),child:D}))}return new f0({crossAxisAlignment:"start",mainAxisSize:"min",children:Y})}}class x51 extends v0{commands;submitOnEnter;constructor({key:A,commands:Q,submitOnEnter:B}){super(A?{key:A}:{});this.commands=Q,this.submitOnEnter=B??!0}createState(){return new ae4}}class ae4 extends k0{scrollController;initState(){this.scrollController=new oA,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0)}dispose(){}build(A){let B=k1.of(A).colorScheme,J=_0.of(A).app,Y=B4.of(A),Z=new y({color:B.primary,bold:!0}),X=new y({color:B.secondary,bold:!0}),F=new y({color:J.keybind}),D=new y({color:J.command}),G=new y({color:B.foreground}),V=new y({color:B.foreground}),U=Y.size.width,K=Y.size.height,E=U-4,W=K-4,H=Math.max(40,Math.min(80,E)),z=new Set(["permissions-disable"]),N=[...this.widget.commands.filter((O)=>{let _=O.noun?.toLowerCase();return _!=="dev"&&_!=="debug"&&!O.id.startsWith("debug-")&&!z.has(O.id)})].sort((O,_)=>{let S=(O.noun??"").toLowerCase(),T=(_.noun??"").toLowerCase(),b=S.localeCompare(T);if(b!==0)return b;let h=O.verb.toLowerCase(),x=_.verb.toLowerCase(),v=h.localeCompare(x);if(v!==0)return v;return O.id.localeCompare(_.id)}),I=new _A({autofocus:!0,controller:this.scrollController,child:new p0({constraints:new M1(H,H,0,Number.POSITIVE_INFINITY),child:new f0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new A4({child:new l({text:new M(`Amp CLI - Help & Keyboard Shortcuts
5285
5285
  `,Z)})}),new N0({height:1}),new u0({padding:q0.horizontal(2),child:new l({text:new M(`Editor Shortcuts
5286
5286
  `,X)})}),new nV0({items:v51.filter((O)=>O.submitOnEnterOnly===void 0||O.submitOnEnterOnly===this.widget.submitOnEnter),renderRow:(O)=>{let _=[];for(let T of O.methods){let b=this.buildCleanKeyCombination(T);_.push(b)}let S=_.join(", ");return[new l({text:new M(S,F)}),new l({text:new M(O.description,G)})]}}),new N0({height:1}),new u0({padding:q0.horizontal(2),child:new l({text:new M(`Scrolling & Navigation
5287
5287
  `,X)})}),new nV0({items:y51,renderRow:(O)=>{let _=[];for(let T of O.methods){let b=this.buildCleanKeyCombination(T);_.push(b)}let S=_.join(", ");return[new l({text:new M(S,F)}),new l({text:new M(O.description,G)})]}}),new N0({height:1}),new u0({padding:q0.horizontal(2),child:new l({text:new M(`Command Palette Commands
@@ -5359,12 +5359,12 @@ Ctrl-X, Y, Z to unlock`;if(E){let Q0=G.text.replace(/`([^`]+)`/g,"$1")+`
5359
5359
 
5360
5360
 
5361
5361
  `,C)])}),h];if(!D&&!E&&G.url){let c=G.url.replace(/^https?:\/\//,"");v.push(new zA({uri:G.url,text:c,style:new y({color:B.secondary,underline:!0})}))}if(b&&!E)v.push(b);let u=new N0({width:z4A,child:new f0({crossAxisAlignment:"start",mainAxisSize:"min",children:v})});if(Z==="disabled")return A4.child(u);let m=Lr5(Y.size),d=this.widget.orbVisualStyle==="neo"?m.width:d31,g=this.widget.orbVisualStyle==="neo"?m.height:c31,n=new Kf({width:d,height:g,agentMode:this.widget.agentMode,colorMode:W.colorMode,visualStyle:this.widget.orbVisualStyle,neoGlyphSet:this.neoGlyphSet,primaryColor:H?.primary,secondaryColor:H?.secondary,glow:this._glow,backgroundColor:B.background,t:V,effectTime:this._effectTime,fps:0,shockwaves:this._shockwaves,onShockwave:this.handleShockwave,onClick:this.widget.interactive?this.handleOrbClick:void 0});return A4.child(new B1({mainAxisAlignment:"center",crossAxisAlignment:"center",mainAxisSize:"min",children:[n,new N0({width:q4A}),u]}))}}o0();n2();g$();O1();var jr5=["ctrl+x","y","z"];class a31{state;_message=null;_isOverlayShown=!1;_progress=null;subscription=null;sequenceManager=null;interceptorUnsubscribe=null;configService=null;constructor(A){this.state=A;let Q=A.dispose.bind(A);A.dispose=()=>{this.dispose(),Q()}}get message(){return this._message}get isOverlayShown(){return this._isOverlayShown}get progress(){return this._progress}start(A){this.subscription?.unsubscribe(),this.teardownSequence(),this._message=null,this._isOverlayShown=!1,this.configService=A,this.subscription=NQ(A).pipe(E5((Q)=>Q!=="pending"),L1((Q)=>OA(Q)?Q.mysteriousMessage??null:null),S4((Q,B)=>Q?.id===B?.id)).subscribe((Q)=>{if(!this.state.mounted)return;let B=Q?.id!==this._message?.id;this.state.setState(()=>{if(B){if(this.teardownSequence(),Q)this.setupSequence();this._isOverlayShown=!1}this._message=Q})})}destruct(){if(!this._message)return;let A=this._message.id;VA.markAsReadMysteriousMessage({messageId:A},{config:this.configService}).then((Q)=>{if(!this.state.mounted)return;if(!Q.ok){j.error("Failed to destruct mysterious message",Q.error);return}if(this._message?.id!==A)return;this.state.setState(()=>{this.teardownSequence(),this._message=null,this._isOverlayShown=!1})}).catch((Q)=>{j.error("Failed to destruct mysterious message",Q)})}dispose(){this.teardownSequence(),this.subscription?.unsubscribe(),this.subscription=null}setupSequence(){this.sequenceManager=new Rf(new Map([[new jf(jr5),new BR]])),this.interceptorUnsubscribe=R4.instance.addKeyInterceptor((A)=>{if(!this.sequenceManager)return!1;if(this._isOverlayShown)return!1;let Q=this.sequenceManager.handleKeyEvent(A);if(Q.consumed)return this.state.setState(()=>{if(this._progress=Q.progress,Q.intent)this._isOverlayShown=!0}),!0;if(this._progress)this.state.setState(()=>{this._progress=null});return!1})}teardownSequence(){this.interceptorUnsubscribe?.(),this.interceptorUnsubscribe=null,this.sequenceManager?.dispose(),this.sequenceManager=null,this._progress=null}}class o31 extends v0{props;constructor(A){super();this.props=A}createState(){return new I4A}}class I4A extends k0{splashOrbExplosion=null;splashOrbExplosionSeq=0;editorTextChangeListener=null;mystery=new a31(this);initState(){this.subscribeToEditorController(),this.mystery.start(this.widget.props.configService)}didUpdateWidget(A){if(A.props.editorController!==this.widget.props.editorController)this.unsubscribeFromEditorController(A.props.editorController),this.subscribeToEditorController()}dispose(){this.unsubscribeFromEditorController(this.widget.props.editorController),super.dispose()}subscribeToEditorController(){this.editorTextChangeListener=()=>this.setState(),this.widget.props.editorController.addListener(this.editorTextChangeListener)}unsubscribeFromEditorController(A){if(!this.editorTextChangeListener)return;A.removeListener(this.editorTextChangeListener),this.editorTextChangeListener=null}submitPrompt=async(A)=>{this.widget.props.editorController.clear(),this.widget.props.onNewThread(A,this.widget.props.agentMode,this.widget.props.visibility)};buildHints(){let A=new Set(this.widget.props.hints);if(this.widget.props.previousThreadIDForReference&&this.widget.props.editorController.text.trim()==="")A.add(Xb);return A}handleSplashOrbExplode=(A)=>{this.splashOrbExplosionSeq+=1,this.setState(()=>{this.splashOrbExplosion={seq:this.splashOrbExplosionSeq,originX:A.x,originY:A.y}})};handleSplashOrbExplosionComplete=()=>{if(!this.splashOrbExplosion)return;this.setState(()=>{this.splashOrbExplosion=null})};build(A){let{editorController:Q,agentMode:B,threadSettings:$,configSettings:J}=this.widget.props,Y=G2.of(A),Z=Q.text.trim()!=="",{reasoningEffort:X,speedCostMultiplier:F}=sV0(B,$,J),D=new G4(()=>{let K=m$(void 0,{isInternalUser:Y.isInternalUser});return this.widget.props.onAgentModeChange(Qd(B,K)),"handled"}),G=new Map([[xR,D]]),U=[new yt({child:new Ib({agentMode:B,orbVisualStyle:Y.splashOrbVisualStyle,settleAnimation:Z,onOrbExplode:this.handleSplashOrbExplode,mysteriousMessage:this.mystery.message,mysterySequenceProgress:this.mystery.progress,interactive:!this.mystery.isOverlayShown,useNeoColors:!0}),editorController:Q,activeThreadID:null,queuedMessages:[],selectedQueuedMessageIndex:null,onSteerNextQueuedMessage:()=>{},onDequeueAllMessages:()=>{},editorEnabled:!0,hints:this.buildHints(),agentState:"idle",compactionState:"idle",connectionState:"disconnected",pendingSend:!1,cancelling:!1,agentMode:B,reasoningEffort:X,speedCostMultiplier:F,statusMessage:this.widget.props.statusMessage,ideStatus:this.widget.props.ideStatus,environment:this.widget.props.environment,previousThreadIDForReference:this.widget.props.previousThreadIDForReference,onSubmit:this.submitPrompt})];if(this.splashOrbExplosion)U.push(new p31({key:new mA(`splash-orb-explosion-${this.splashOrbExplosion.seq}`),originX:this.splashOrbExplosion.originX,originY:this.splashOrbExplosion.originY,agentMode:B,visualStyle:Y.splashOrbVisualStyle,onComplete:this.handleSplashOrbExplosionComplete}));if(this.mystery.isOverlayShown&&this.mystery.message)U.push(new xt({key:new mA(`mysterious-message-modal-${this.mystery.message.id}`),message:this.mystery.message,onDestruct:()=>this.mystery.destruct()}));return new FA({actions:G,child:new h5({debugLabel:"EmptyThreadShortcuts",shortcuts:new Map([[v1.ctrl("s"),new xR],[v1.alt("s"),new xR],[v1.alt("d"),new Ct]]),child:new t4({children:U})})})}}o0();n2();var Rr5=/^[a-z0-9][a-z0-9-]*$/,Pr5={kind:"fill",modalRows:18};function w4A(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!Rr5.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}class C4A extends v0{props;constructor(A){super();this.props=A}createState(){return new M4A}}class M4A extends k0{allLabels=[];currentLabels=null;loadError=null;currentQuery="";initState(){this.loadAll()}async loadAll(){try{let[A,Q]=await Promise.all([VA.getUserLabels({query:""},{config:this.widget.props.configService}),cf({configService:this.widget.props.configService},this.widget.props.threadID)]);if(!this.mounted)return;this.setState(()=>{if(!A.ok){this.loadError=Error(A.error.message??"Failed to load labels");return}if(this.allLabels=A.result,Q instanceof Error)this.loadError=Q;else this.currentLabels=Q.map((B)=>B.name)})}catch(A){if(j.error("Failed to load labels",A),!this.mounted)return;this.setState(()=>{this.loadError=A instanceof Error?A:Error(String(A))})}}handleQueryChange=(A)=>{if(this.currentQuery===A)return;this.setState(()=>{this.currentQuery=A})};build(A){if(this.loadError)return new l({text:new M(`Failed to load labels: ${this.loadError.message}`),textAlign:"center"});if(this.currentLabels===null)return new l({text:new M("Loading labels…"),textAlign:"center"});let{colors:Q,app:B}=_0.of(A),$=this.currentLabels,J=[{kind:"create"},...this.allLabels.filter((Z)=>!$.includes(Z.name)).map((Z)=>({kind:"label",label:Z}))],Y=this.currentQuery.length>0?w4A(this.currentQuery):null;return new p6({items:J,showBorder:!1,getLabel:(Z)=>Z.kind==="create"?this.currentQuery.trim().toLowerCase():Z.label.name,onAccept:(Z)=>{let X=Z.kind==="create"?this.currentQuery.trim().toLowerCase():Z.label.name;this.widget.props.onSelect(X)},onDismiss:this.widget.props.onDismiss,onQueryChange:this.handleQueryChange,emptyStateText:Y||"Type to create a new label",renderItem:(Z,X)=>{let F=X?B.selectionBackground:void 0,D=X?B.selectionForeground:Q.foreground;if(Z.kind==="create"){let G=this.currentQuery.trim().toLowerCase();return new p0({decoration:F?{color:F}:void 0,padding:q0.symmetric(2,0),child:new l({text:new M("",void 0,[new M("Create new label: ",new y({color:D})),new M(G,new y({color:D,bold:!0}))]),maxLines:1,overflow:"ellipsis"})})}return new p0({decoration:F?{color:F}:void 0,padding:q0.symmetric(2,0),child:new l({text:new M(Z.label.name,new y({color:D})),maxLines:1,overflow:"ellipsis"})})},filterItem:(Z,X)=>{if(Z.kind==="create")return this.shouldShowCreateMarker(X);let F=X.trim().toLowerCase();return F.length===0||Z.label.name.includes(F)},sortItems:(Z,X)=>{if(Z.item.kind==="create"&&X.item.kind!=="create")return-1;if(Z.item.kind!=="create"&&X.item.kind==="create")return 1;return X.score-Z.score}})}shouldShowCreateMarker(A){if(A.length===0)return!1;let Q=A.trim().toLowerCase();if(w4A(Q)!==null)return!1;let B=this.currentLabels??[],$=this.allLabels.some((Y)=>Y.name===Q),J=B.includes(Q);return!$&&!J}}async function _r5(A,Q,B,$){let J=await A.addLabel(Q,B);if(J instanceof Error)$?.show(`Failed to add label: ${J.message}`,"error")}function L4A(A,Q){return{noun:"label",verb:"add",description:"Add label to thread",get status(){return Q()?{type:"enabled"}:{type:"disabled",reason:"Cannot add labels to an empty thread"}},run:(B,$,J)=>{let Y=Q()?.client.getThreadId();if(!Y)return;let Z=H3.maybeOf($);B.push(new TA({header:"Add Label",autofocus:!1,minWidth:80,maxWidth:80,bodyFit:Pr5,onDismiss:J,child:new C4A({threadID:Y,configService:A.configService,onDismiss:J,onSelect:(X)=>{J(),_r5(A,Y,X,Z)}})}))}}}class O4A extends v0{props;constructor(A){super();this.props=A}createState(){return new j4A}}class j4A extends k0{labels=null;loadError=null;initState(){this.loadCurrentLabels()}async loadCurrentLabels(){let A=await cf({configService:this.widget.props.configService},this.widget.props.threadID);if(!this.mounted)return;this.setState(()=>{if(A instanceof Error)this.loadError=A;else this.labels=A})}build(A){if(this.loadError)return new l({text:new M(`Failed to load labels: ${this.loadError.message}`),textAlign:"center"});if(this.labels===null)return new l({text:new M("Loading labels…"),textAlign:"center"});if(this.labels.length===0)return new l({text:new M("This thread has no labels to remove."),textAlign:"center"});return new p6({items:this.labels,getLabel:(Q)=>Q.name,showBorder:!1,onAccept:this.widget.props.onSelect,onDismiss:this.widget.props.onDismiss})}}async function Tr5(A,Q,B,$){let J=await A.removeLabel(Q,B);if(J instanceof Error)$?.show(`Failed to remove label: ${J.message}`,"error")}function R4A(A,Q){return{noun:"label",verb:"remove",description:"Remove label from thread",get status(){return Q()?{type:"enabled"}:{type:"disabled",reason:"Cannot remove labels from an empty thread"}},run:(B,$,J)=>{let Y=Q()?.client.getThreadId();if(!Y)return;let Z=H3.maybeOf($);B.push(new TA({header:"Remove Label",autofocus:!1,minWidth:80,maxWidth:80,onDismiss:J,child:new O4A({threadID:Y,configService:A.configService,onDismiss:J,onSelect:(X)=>{J(),Tr5(A,Y,X.name,Z)}})}))}}}var P4A=60,Sr5=200,kr5=100,vr5=110,yr5=26;function _4A(A){return A.replace(/\r?\n/g," ")}function xr5(A){let Q=_4A(A),B=f4(Q);if(B.length<=P4A)return Q;return B.slice(0,P4A).join("")}function fr5(A,Q,B=process.platform){if(B==="win32"){let $=A.replace(/\\/g,"/").toLowerCase(),J=Q.replace(/\\/g,"/").toLowerCase();return $===J}return A===Q}class GU0 extends v0{props;constructor(A){super();this.props=A}createState(){return new T4A}}class T4A extends k0{filterByWorkspace=!0;cachedEntries=[];scoringLabelCache=new Map;initState(){this.refreshCachedEntries()}didUpdateWidget(A){if(super.didUpdateWidget(A),A.props.entries!==this.widget.props.entries||A.props.currentCwd!==this.widget.props.currentCwd)this.refreshCachedEntries()}handleKeyEvent=(A)=>{if(A.ctrlKey&&A.key.toLowerCase()==="t"||A.altKey&&A.key.toLowerCase()==="w")return this.setState(()=>{this.filterByWorkspace=!this.filterByWorkspace,this.refreshCachedEntries()}),"handled";return"ignored"};computeFilteredEntries(){let{entries:A,currentCwd:Q}=this.widget.props,B;if(this.filterByWorkspace)B=A.filter((Y)=>Y.cwd===void 0||fr5(Y.cwd,Q));else B=[...A];B=B.reverse();let $=new Set,J=[];for(let Y of B){if(!$.has(Y.text))$.add(Y.text),J.push(Y);if(J.length>=Sr5)break}return J}refreshCachedEntries(){this.cachedEntries=this.computeFilteredEntries()}handleAccept=(A)=>{this.widget.props.onAccept(A.text)};handleDismiss=()=>{this.widget.props.onDismiss()};getScoringLabel(A){let Q=this.scoringLabelCache.get(A);if(Q!==void 0)return Q;let B=xr5(A);return this.scoringLabelCache.set(A,B),B}build(A){let Q=_0.of(A),{colors:B,app:$}=Q,J=this.filterByWorkspace?"Showing: current workspace":"Showing: all workspaces";return new TA({header:"Prompt History",maxWidth:vr5,maxHeight:yr5,autofocus:!1,footer:[{keys:["Alt+W","Ctrl+T"],label:`toggle filter · ${J}`}],onDismiss:this.handleDismiss,child:new m4({canRequestFocus:!1,skipTraversal:!0,debugLabel:"NeoPromptHistoryPicker",onKey:this.handleKeyEvent,child:new p6({items:this.cachedEntries,showBorder:!1,getLabel:(Y)=>this.getScoringLabel(Y.text),filterItem:(Y,Z)=>{if(!Z)return!0;return Y.text.toLowerCase().includes(Z.toLowerCase())},sortItems:()=>0,onAccept:this.handleAccept,onDismiss:this.handleDismiss,emptyStateText:this.filterByWorkspace?"No history for this workspace":"No prompt history",maxRenderItems:kr5,renderItem:(Y,Z)=>{let X=Z?$.selectionBackground:void 0,F=Z?$.selectionForeground:B.foreground,D=_4A(Y.text);return new B1({children:[new S1({child:new p0({decoration:X?{color:X}:void 0,padding:q0.symmetric(2,0),child:new l({text:new M(D,new y({color:F})),maxLines:1,overflow:"ellipsis"})})})]})}})})})}}C3();import{homedir as br5}from"node:os";import{relative as ur5,sep as hr5}from"node:path";import{fileURLToPath as gr5}from"node:url";var mr5="https://ampcode.com/manual#agent-skills";class r31 extends a4{}class s31 extends v0{listSkills;onDismiss;cwd;constructor(A){super();this.listSkills=A.listSkills,this.onDismiss=A.onDismiss,this.cwd=A.cwd}createState(){return new S4A}}class S4A extends k0{status={kind:"loading"};abortController=null;initState(){this.abortController=new AbortController,this.loadSkills()}dispose(){this.abortController?.abort()}async loadSkills(){try{let A=await this.widget.listSkills(this.abortController?.signal);if(!this.mounted)return;this.setState(()=>{this.status={kind:"ready",skills:A.skills,errors:A.errors}})}catch(A){if(!this.mounted)return;this.setState(()=>{this.status={kind:"error",message:A instanceof Error?A.message:"Unknown error"}})}}build(A){return new k4A({status:this.status,cwd:this.widget.cwd,onDismiss:this.widget.onDismiss})}}class k4A extends I1{status;cwd;onDismiss;constructor(A){super();this.status=A.status,this.cwd=A.cwd,this.onDismiss=A.onDismiss}build(A){return new TA({header:pr5(this.status),onDismiss:this.onDismiss,minWidth:80,maxWidth:120,maxHeight:40,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["↑↓","j/k"],label:"scroll"},{keys:["o"],label:"open manual"}],child:new FA({actions:new Map([[r31,new G4(()=>{K6(A,mr5)})]]),child:new h5({debugLabel:"NeoSkillListShortcuts",shortcuts:new Map([[v1.key("o"),new r31]]),child:dr5(A,this.status,this.cwd)})})})}}function pr5(A){if(A.kind!=="ready")return"Skills";let{skills:Q,errors:B}=A;if(Q.length===0&&B.length===0)return"Skills";if(B.length===0)return`Skills (${Q.length})`;let $=`${B.length} ${K4(B.length,"error")}`;if(Q.length===0)return`Skills (0, ${$})`;return`Skills (${Q.length}, ${$})`}function dr5(A,Q,B){let{colors:$}=_0.of(A);switch(Q.kind){case"loading":return new B1({mainAxisSize:"min",children:[new JH({color:$.primary}),new N0({width:1}),new l({text:new M("Loading skills...",new y({color:$.foreground,dim:!0}))})]});case"error":return new l({text:new M(Q.message,new y({color:$.destructive}))});case"ready":return lr5(A,Q.skills,Q.errors,B)}}var cr5=90;function lr5(A,Q,B,$){let{colors:J,app:Y}=_0.of(A),Z=new y({color:J.foreground,dim:!0});if(Q.length===0&&B.length===0)return new l({text:new M("No skills reported by the executor yet.",Z)});let X=B4.sizeOf(A).width>=cr5;return new JZ({child:new f0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:rr5(Q,B,X,{section:new y({color:J.foreground,bold:!0}),name:new y({color:Y.command}),description:new y({color:J.foreground}),location:Z,errorTitle:new y({color:J.destructive,bold:!0}),errorName:new y({color:J.warning,bold:!0}),errorMessage:new y({color:J.destructive}),cwd:$})})})}var ir5={local:"Local",global:"Global",builtin:"Built-in"},nr5=["local","global","builtin"],ar5={"workspace-agents":"local","workspace-claude":"local","user-agents":"global","user-amp":"global","user-claude":"global",plugin:"global",toolbox:"global","custom-path":"global",builtin:"builtin"};function or5(A){let Q={local:[],global:[],builtin:[]};for(let B of A){let $=B.source??"workspace-agents";Q[ar5[$]].push(B)}return nr5.filter((B)=>Q[B].length>0).map((B)=>({label:ir5[B],skills:Q[B]}))}function rr5(A,Q,B,$){let J=[];if(or5(A).forEach((Y,Z)=>{if(Z>0)J.push(new N0({height:1}));J.push(new l({text:new M(Y.label,$.section)}));for(let X of Y.skills)J.push(new u0({padding:q0.only({left:2}),child:As5(X,B,$)}))}),Q.length>0){if(A.length>0)J.push(new N0({height:1}));J.push(new l({text:new M(`Skipped skills with errors (${Q.length}):`,$.errorTitle)}));for(let Y of Q)J.push(new N0({height:1})),J.push(...tr5(Y,$))}J.push(new N0({height:1})),J.push(new l({text:new M("Create your own:",$.section)}));for(let Y of sr5)J.push(new u0({padding:q0.only({left:2}),child:new l({text:new M(`"${Y}"`,$.description),maxLines:1,overflow:"ellipsis"})}));return J}var sr5=["Create a skill for searching our production logs","Create a user skill for my preferred commit message style"];function tr5(A,Q){let B=[new u0({padding:q0.only({left:2}),child:new l({text:new M(`⚠ ${er5(A.path)}`,Q.errorName)})}),new u0({padding:q0.only({left:4}),child:new l({text:new M(A.error,Q.errorMessage)})})];if(A.hint)B.push(new u0({padding:q0.only({left:4}),child:new l({text:new M(A.hint.split(`
5362
- `)[0]??"",Q.description)})}));return B.push(new u0({padding:q0.only({left:4}),child:new l({text:new M(v4A(A.path,Q.cwd),Q.location),maxLines:1,overflow:"ellipsis"})})),B}function er5(A){try{return new URL(A).pathname.split("/").filter(Boolean).at(-2)??"unknown"}catch{return"unknown"}}function As5(A,Q,B){if(Q)return new B1({crossAxisAlignment:"start",children:[new S1({flex:1,child:new l({text:new M(A.name,B.name),maxLines:1,overflow:"ellipsis"})}),new N0({width:2}),new S1({flex:2,child:new u0({padding:q0.only({right:1}),child:new l({text:new M(A.description,B.description),maxLines:1,overflow:"ellipsis"})})})]});return new f0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new B1({crossAxisAlignment:"start",children:[new l({text:new M(A.name,B.name),maxLines:1,overflow:"ellipsis"}),new S1({child:new l({text:new M(` ${v4A(A.baseDir,B.cwd)}`,B.location),maxLines:1,overflow:"ellipsis"})})]}),new u0({padding:q0.only({left:2,right:1}),child:new l({text:new M(A.description,B.description),maxLines:1,overflow:"ellipsis"})})]})}function v4A(A,Q){if(A.startsWith("builtin://"))return"(builtin)";if(!A.startsWith("file://"))return A;let B=gr5(A),$=ur5(Q,B);if($&&!$.startsWith(".."))return`./${$}`;let J=br5();if(B===J||B.startsWith(J+hr5))return`~${B.slice(J.length)}`;return B}o0();var y4A=256,f4A={kind:"fill",modalRows:14};function x4A(A,Q){return new TA({header:"Rename Thread failed",tone:"error",minWidth:80,maxWidth:80,bodyFit:f4A,footer:"none",onDismiss:Q,child:new l({text:new M(A)})})}function b4A(A){return{noun:"thread",verb:"rename",description:"Rename thread title",get status(){return A()?{type:"enabled"}:{type:"disabled",reason:"Cannot rename an empty thread"}},run:(Q,B,$)=>{if(!A())return;let J=H3.maybeOf(B);Q.push(new Lt({header:"Rename Thread",placeholder:"Enter new thread title",isRequired:!0,bodyFit:f4A,onDismiss:$,onSubmit:(Y)=>{if(Y.length>y4A){Q.push(x4A(`Thread title cannot exceed ${y4A} characters`,$));return}let Z=A();if(!Z){$();return}try{Z.client.setThreadTitle(Y),$(),J?.show("Thread renamed","success")}catch(X){j.error("Failed to rename thread",{error:X}),Q.push(x4A(`Failed to rename thread: ${X instanceof Error?X.message:String(X)}`,$))}}}))}}}o0();class t31 extends I1{reportID;constructor(A){super();this.reportID=A}build(A){let{colors:Q}=_0.of(A),B=0,$=()=>{R4.instance.tuiInstance.clipboard.writeText(this.reportID)};return new A8({onCopy:(J,Y)=>{if(Y&&Date.now()-B<1000)$()},child:new u1({onClick:(J)=>{if(J.clickCount>=2)B=Date.now(),$(),setTimeout($,0)},opaque:!1,child:new f0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new l({text:new M("Copied report ID to the clipboard:"),textAlign:"left",selectable:!0}),new N0({height:1}),new p0({padding:q0.symmetric(1,0),decoration:new x4(void 0,i1.all(new n1(Q.mutedForeground,1,"rounded"))),child:new l({text:new M(this.reportID,new y({color:Q.foreground,bold:!0})),textAlign:"left"})}),new N0({height:1}),new l({text:new M(`Use the report ID when contacting the Amp team via:
5362
+ `)[0]??"",Q.description)})}));return B.push(new u0({padding:q0.only({left:4}),child:new l({text:new M(v4A(A.path,Q.cwd),Q.location),maxLines:1,overflow:"ellipsis"})})),B}function er5(A){try{return new URL(A).pathname.split("/").filter(Boolean).at(-2)??"unknown"}catch{return"unknown"}}function As5(A,Q,B){if(Q)return new B1({crossAxisAlignment:"start",children:[new S1({flex:1,child:new l({text:new M(A.name,B.name),maxLines:1,overflow:"ellipsis"})}),new N0({width:2}),new S1({flex:2,child:new u0({padding:q0.only({right:1}),child:new l({text:new M(A.description,B.description),maxLines:1,overflow:"ellipsis"})})})]});return new f0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new B1({crossAxisAlignment:"start",children:[new l({text:new M(A.name,B.name),maxLines:1,overflow:"ellipsis"}),new S1({child:new l({text:new M(` ${v4A(A.baseDir,B.cwd)}`,B.location),maxLines:1,overflow:"ellipsis"})})]}),new u0({padding:q0.only({left:2,right:1}),child:new l({text:new M(A.description,B.description),maxLines:1,overflow:"ellipsis"})})]})}function v4A(A,Q){if(A.startsWith("builtin://"))return"(builtin)";if(!A.startsWith("file://"))return A;let B=gr5(A),$=ur5(Q,B);if($&&!$.startsWith(".."))return`./${$}`;let J=br5();if(B===J||B.startsWith(J+hr5))return`~${B.slice(J.length)}`;return B}o0();var y4A=256,f4A={kind:"fill",modalRows:14};function x4A(A,Q){return new TA({header:"Rename Thread failed",tone:"error",minWidth:80,maxWidth:80,bodyFit:f4A,footer:"none",onDismiss:Q,child:new l({text:new M(A)})})}function b4A(A){return{noun:"thread",verb:"rename",description:"Rename thread title",get status(){return A()?{type:"enabled"}:{type:"disabled",reason:"Cannot rename an empty thread"}},run:(Q,B,$)=>{if(!A())return;let J=H3.maybeOf(B);Q.push(new Lt({header:"Rename Thread",placeholder:"Enter new thread title",isRequired:!0,bodyFit:f4A,onDismiss:$,onSubmit:(Y)=>{if(Y.length>y4A){Q.push(x4A(`Thread title cannot exceed ${y4A} characters`,$));return}let Z=A();if(!Z){$();return}try{Z.client.setThreadTitle(Y),$(),J?.show("Thread renamed","success")}catch(X){j.error("Failed to rename thread",{error:X}),Q.push(x4A(`Failed to rename thread: ${X instanceof Error?X.message:String(X)}`,$))}}}))}}}o0();class t31 extends I1{reportID;constructor(A){super();this.reportID=A}build(A){let{colors:Q}=_0.of(A),B=0,$=()=>{R4.instance.tuiInstance.clipboard.writeText(this.reportID)};return new A8({onCopy:(J,Y)=>{if(Y&&Date.now()-B<1000)$()},child:new u1({onClick:(J)=>{if(J.clickCount>=2)B=Date.now(),$(),setTimeout($,0)},opaque:!1,child:new f0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new l({text:new M("Copied report ID to the clipboard:"),textAlign:"left",selectable:!0}),new N0({height:1}),new p0({padding:q0.symmetric(1,0),decoration:new x4(void 0,i1.all(new n1(Q.mutedForeground,1,"rounded"))),child:new l({text:new M(this.reportID,new y({color:Q.foreground,bold:!0})),textAlign:"left"})}),new N0({height:1}),new l({text:new M(`Include this report ID when contacting the Amp team via:
5363
5363
 
5364
5364
  `,new y({color:Q.foreground})),textAlign:"left",selectable:!0}),new l({text:new M(`- X (@AmpCode)
5365
5365
  - Email (amp-devs@ampcode.com)
5366
5366
  - A shared Slack channel
5367
- - In person
5367
+ - Real life (in person)
5368
5368
 
5369
5369
  `,new y({color:Q.foreground})),textAlign:"left",selectable:!0}),new l({text:new M("All diagnostics data is deleted after 7 days. Amp team members can only access the diagnostics data if you provide the report ID.",new y({color:Q.foreground,dim:!0})),textAlign:"left",selectable:!0})]})})})}}var h4A={kind:"fill",modalRows:19};function Qs5(A){return new TA({header:"Sending Report",tone:"default",minWidth:80,maxWidth:80,bodyFit:h4A,onDismiss:A,child:new g4A})}class g4A extends I1{build(A){let{colors:Q}=_0.of(A);return new B1({mainAxisSize:"min",children:[new JH({color:Q.primary}),new N0({width:1}),new l({text:new M("Gathering and sending diagnostics data...",new y({color:Q.foreground,dim:!0}))})]})}}function u4A(A){return new TA({header:A.title,tone:A.tone,barrierOpaque:!1,minWidth:80,maxWidth:80,bodyFit:h4A,onDismiss:A.onDismiss,child:A.child})}function m4A(A,Q){return{noun:"feedback",verb:"send report",description:"Send a diagnostic feedback report to Amp support",keywords:["report bug","share with support","support","bug","feedback"],get status(){return Q()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(B,$,J)=>{let Y=Q()?.client.getThreadId();if(!Y)return;B.push(Qs5(J)),A.sendFeedbackReport(Y).then(async(Z)=>{try{await R4.instance.tuiInstance.clipboard.writeText(Z),H3.maybeOf($)?.show("Copied report ID to clipboard","success",3000)}catch(X){j.warn("Failed to copy report ID to clipboard",{error:X,reportID:Z})}B.push(u4A({title:"Report Sent",tone:"success",onDismiss:J,child:new t31(Z)}))}).catch((Z)=>{j.error("Failed to share thread with support",{error:Z,threadID:Y}),B.push(u4A({title:"Report failed",tone:"error",onDismiss:J,child:new l({text:new M(`Failed to send report: ${Z instanceof Error?Z.message:String(Z)}`)})}))})}}}var Bs5=["private","workspace","unlisted","public"];class d4A extends I1{props;constructor(A){super();this.props=A}build(A){let{colors:Q,app:B}=_0.of(A);return new p6({items:Bs5,getLabel:($)=>`${e31($)} ${p4A($)}`,showBorder:!1,onAccept:this.props.onSelect,onDismiss:this.props.onDismiss,renderItem:($,J)=>{let Y=J?B.selectionBackground:void 0,Z=J?B.selectionForeground:Q.foreground,X=J?B.selectionForeground:Q.mutedForeground;return new p0({decoration:Y?{color:Y}:void 0,padding:q0.symmetric(1,0),child:new B1({crossAxisAlignment:"center",children:[new S1({child:new l({text:new M(e31($),new y({color:Z})),maxLines:1,overflow:"ellipsis"})}),new N0({width:2}),new l({text:new M(p4A($),new y({color:X})),maxLines:1,overflow:"ellipsis"})]})})}})}}function e31(A){switch(A){case"private":return"Private";case"workspace":return"Workspace";case"group":return"Group";case"unlisted":return"Unlisted";case"public":return"Public"}}function p4A(A){switch(A){case"private":return"Only you can see this thread";case"workspace":return"Visible to workspace members";case"group":return"Visible to group members";case"unlisted":return"Anyone with the link can view";case"public":return"Searchable and on your public profile"}}function $s5(A){return`New thread visibility set to ${e31(A).toLowerCase()}`}async function Js5(A,Q,B,$){if(!Q){A.setDraftVisibility?.(B),$?.show($s5(B),"success");return}let J=await A.setVisibility(Q,B);if(J instanceof rQ)$?.show(J.message,"success");else $?.show(J.message,"error")}function c4A(A,Q){return{noun:"thread",verb:"set visibility",description:"Set thread visibility",keywords:["share","private","workspace","public","unlisted","team","group"],get status(){return Q()||A.setDraftVisibility?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(B,$,J)=>{let Y=Q(),Z=Y?.client?.getThreadId()??null,X=!Y&&!!A.setDraftVisibility;if(!Z&&!X)return;let F=H3.maybeOf($);B.push(new TA({header:"Set Thread Visibility",autofocus:!1,minWidth:80,maxWidth:80,onDismiss:J,child:new d4A({onDismiss:J,onSelect:(D)=>{J(),Js5(A,Z,D,F)}})}))}}}var Zs5=5000;async function Xs5(A){return new Promise((Q)=>{Ys5("git",["branch","--show-current"],{cwd:A},(B,$)=>{if(B){Q(null);return}let J=$.trim();Q(J||null)})})}function Fs5(A,Q){let B=h1(e0.file(A)),$={workspaceRoot:B,workingDirectory:B};if(Q)$.git={branch:Q};return $}class Q81 extends v0{initialAgentMode;analyzeContextForThread;listSkillsForThread;threadContext;draftThreadSettings;editorController;history;updateDraftThreadSettings;onNewThread;sendFeedbackReport;setThreadVisibility;archiveThread;addThreadLabel;removeThreadLabel;configService;hints;ideStatus;constructor(A){super();this.initialAgentMode=A.initialAgentMode,this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.threadContext=A.threadContext,this.draftThreadSettings=A.draftThreadSettings,this.editorController=A.editorController,this.history=A.history,this.updateDraftThreadSettings=A.updateDraftThreadSettings,this.onNewThread=A.onNewThread,this.sendFeedbackReport=A.sendFeedbackReport,this.setThreadVisibility=A.setThreadVisibility,this.archiveThread=A.archiveThread,this.addThreadLabel=A.addThreadLabel,this.removeThreadLabel=A.removeThreadLabel,this.configService=A.configService,this.hints=A.hints,this.ideStatus=A.ideStatus}createState(){return new l4A}}class l4A extends k0{historyIndex=-1;historyDraft=null;promptHistoryPicker=new ws(this);agentMode;copyOnSelectEnabled=!0;copyOnSelectSubscription=null;expansion=new p51;previousThreadIDForReference=null;emptyThreadVisibility=null;unregisterCommands=null;configSettingsForReasoning={};currentGitBranch=null;useLocalEnvironmentFallbackForActiveThread=!1;fastModeToastID=null;statusMessage=null;statusMessageTimer=null;initState(){this.agentMode=this.widget.initialAgentMode,this.unregisterCommands=this.registerCommands(),this.subscribeToCopyOnSelectEnabled(),this.updateGitBranch()}didUpdateWidget(A){if(A.configService!==this.widget.configService)this.subscribeToCopyOnSelectEnabled();if(A.threadContext?.client!==this.widget.threadContext?.client)if(this.historyIndex=-1,this.historyDraft=null,!this.widget.threadContext)this.previousThreadIDForReference=A.threadContext?.client.getThreadId()??null,this.emptyThreadVisibility=null,this.useLocalEnvironmentFallbackForActiveThread=!0;else this.previousThreadIDForReference=null,this.useLocalEnvironmentFallbackForActiveThread=A.threadContext===null}dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.copyOnSelectSubscription?.unsubscribe(),this.copyOnSelectSubscription=null,this.statusMessageTimer)clearTimeout(this.statusMessageTimer),this.statusMessageTimer=null}updateGitBranch=async()=>{let A=G2.of(this.context).workspaceRoot,Q=await Xs5(A);if(!this.mounted)return;this.setState(()=>{this.currentGitBranch=Q})};registerCommands(){let A=Z$.of(this.context),Q=G2.of(this.context),B=this,$=()=>{return B.widget.threadContext??null},J=()=>{let F=B.widget.threadContext?.client.getThreadId();if(!F)return null;return _B(new URL(Q.ampURL),F).toString()},X=[...m$(void 0,{isInternalUser:Q.isInternalUser}).map(({mode:F})=>({noun:"mode",verb:`use ${F}`,description:`Enable ${F} mode`,get status(){if(B.widget.threadContext)return{type:"hidden"};if(F===B.agentMode)return{type:"disabled",reason:`Already using ${F} mode`};return{type:"enabled"}},run:(D,G,V)=>{B.setAgentMode(F),V()}})),{noun:"speed",get verb(){return`use fast (${B.speedCostMultiplierForMode(B.currentCommandAgentMode())} cost)`},description:"Use fast speed for this thread",keywords:["anthropic","openai","fast","standard","smart","deep"],get status(){return B.speedCommandStatus("fast")},run:(F,D,G)=>{B.setSpeed("fast"),G()}},{noun:"speed",verb:"use normal",description:"Use normal speed for this thread",keywords:["anthropic","openai","normal","standard","smart","deep"],get status(){return B.speedCommandStatus("normal")},run:(F,D,G)=>{B.setSpeed("normal"),G()}},{noun:"thread",verb:"toggle details",description:"Expand or collapse tool and activity details",keywords:["work","tool","activity","expand","collapse"],shortcut:v1.alt("t"),status:{type:"enabled"},run:(F,D,G)=>{B.toggleWorkDetails(),G()}},{noun:"mode",verb:"toggle reasoning effort",description:"Cycle reasoning effort for the active model",keywords:["deep","thinking","reasoning","effort","depth","anthropic","openai","smart","frontier"],shortcut:v1.alt("d"),get status(){if(B.widget.threadContext)return{type:"hidden"};return d$(B.currentCommandAgentMode())?{type:"enabled"}:{type:"hidden"}},run:(F,D,G)=>{B.toggleReasoningEffort(),G()}},{noun:"prompt",verb:"history",description:"Restore a previous prompt",keywords:["recent","reuse","search"],shortcut:v1.ctrl("r"),status:{type:"enabled"},run:(F,D,G)=>{F.pushWithDismiss((V)=>new GU0({entries:this.widget.history.getAll(),currentCwd:A81.cwd(),onAccept:(U)=>{this.restorePromptHistory(U),G()},onDismiss:V}))}},{noun:"thread",verb:"copy ID",description:"Copy thread ID to clipboard",keywords:["identifier","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(F,D,G)=>{let V=$()?.client.getThreadId();if(!V)return;FA.maybeInvoke(D,new Y$(V,"Thread ID copied to clipboard","Failed to copy thread ID")),G()}},{noun:"thread",verb:"copy URL",description:"Copy thread URL to clipboard",keywords:["link","share","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(F,D,G)=>{let V=J();if(!V)return;FA.maybeInvoke(D,new Y$(V,"Thread URL copied to clipboard","Failed to copy thread URL")),G()}},{noun:"thread",verb:"copy markdown",description:"Copy thread as Markdown",keywords:["markdown","export","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(F,D,G)=>{let V=$()?.client.getThreadId();if(!V)return;(async()=>{try{let U=await Q.getThreadMarkdown(V);if(!U){H3.error(D,"Failed to copy thread markdown");return}FA.maybeInvoke(D,new Y$(U,"Thread markdown copied to clipboard","Failed to copy thread markdown"))}catch(U){j.error("Failed to render thread markdown from Neo command palette",{error:U,threadID:V}),H3.error(D,"Failed to copy thread markdown")}finally{G()}})()}},{noun:"thread",verb:"analyze context",description:"Analyze context token usage",keywords:["tokens","usage","window","size","cost"],get status(){let F=B.widget.threadContext;if(!F)return{type:"disabled",reason:"No active thread"};let D=p$(F.observer.agentMode);if(!W0A.includes(D))return{type:"disabled",reason:"Context analysis requires Claude Opus 4.7 (smart) or GPT-5.4 (deep)"};return{type:"enabled"}},run:(F,D,G)=>{let V=$()?.client.getThreadId();if(!V)return;let U=60,K=1;F.push(new TA({header:"Context Usage Analysis",minWidth:U,maxWidth:U,chromePadding:q0.symmetric(K,0),footer:[{keys:["Esc"],label:"close"}],onDismiss:G,child:new jt({embedded:!0,contentWidth:U-2*K,thread:null,dtwAnalyze:(E)=>{return B.widget.analyzeContextForThread(V,E)},onDismiss:G})}))}},{noun:"skills",verb:"list",description:"List available skills for this thread",keywords:["agent","show"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(F,D,G)=>{let V=$()?.client.getThreadId();if(!V)return;F.push(new s31({listSkills:(U)=>B.widget.listSkillsForThread(V,U),onDismiss:G,cwd:Q.workspaceRoot}))}},{noun:"thread",verb:"new",description:"Start new thread",keywords:["create","start","reset","clear"],sortBoost:101,get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"Already on a new thread"}},run:(F,D)=>{FA.maybeInvoke(D,new zt)}},{noun:"thread",verb:"open in browser",description:"Open thread in browser",keywords:["web","view","launch"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(F,D,G)=>{let V=J();if(!V)return;try{await K6(D,V)}finally{G()}}},m4A({sendFeedbackReport:(F)=>{return this.widget.sendFeedbackReport(F)}},$),c4A({setVisibility:(F,D)=>this.widget.setThreadVisibility(F,D),setDraftVisibility:(F)=>this.setEmptyThreadVisibility(F)},$),e1A({archiveThread:(F)=>this.widget.archiveThread(F)},$),b4A($),L4A({configService:this.widget.configService,addLabel:(F,D)=>this.widget.addThreadLabel(F,D)},$),R4A({configService:this.widget.configService,removeLabel:(F,D)=>this.widget.removeThreadLabel(F,D)},$)].map((F)=>A.register(F));return()=>{for(let F of X)F()}}currentCommandAgentMode(){return this.widget.threadContext?.observer.agentMode??this.agentMode}currentThreadSettings(){return this.widget.threadContext?.observer.threadSettings().getValue()??this.widget.draftThreadSettings}speedCostMultiplierForMode(A){return A==="smart"?"6x":"2.5x"}supportsSpeedCommand(A){return A==="smart"||aM(A)}isFastSpeedEnabled(A){let Q=this.currentThreadSettings();if(A==="smart")return Q["anthropic.speed"]==="fast";return aM(A)&&Q["openai.speed"]==="fast"}speedCommandStatus(A){let Q=this.currentCommandAgentMode();if(!this.supportsSpeedCommand(Q))return{type:"hidden"};let B=this.isFastSpeedEnabled(Q);if(A==="fast"&&B)return{type:"disabled",reason:"Already using fast speed"};if(A==="normal"&&!B)return{type:"disabled",reason:"Already using normal speed"};return{type:"enabled"}}setEmptyThreadVisibility(A){this.setState(()=>{this.emptyThreadVisibility=A})}updateThreadSettings(A){let Q=this.widget.threadContext;if(Q){let B=Q.observer.threadSettings().getValue()??{},$=A(B);return Q.client.sendClientUpdateThreadSettings($),this.widget.updateDraftThreadSettings(()=>$),"handled"}return this.widget.updateDraftThreadSettings(A),"handled"}setSpeed(A){let Q=this.currentCommandAgentMode();if(Q==="smart")return this.updateThreadSettings((B)=>{let $={...B};if(A==="normal")delete $["anthropic.speed"];else $["anthropic.speed"]="fast";if(A==="fast")this.showFastModeToast(Q,this.speedCostMultiplierForMode(Q));return $});if(aM(Q))return this.updateThreadSettings((B)=>{let $={...B};if(A==="normal")$["openai.speed"]="standard";else $["openai.speed"]="fast";if(A==="fast")this.showFastModeToast(Q,this.speedCostMultiplierForMode(Q));return $});return"ignored"}showFastModeToast(A,Q){let B=H3.maybeOf(this.context);if(!B)return;if(this.fastModeToastID!==null)B.dismiss(this.fastModeToastID);this.fastModeToastID=B.show(`↯${A} costs ${Q} the standard rate for this mode`,"warning",Zs5)}dismissFastModeToast(){if(this.fastModeToastID===null)return;H3.maybeOf(this.context)?.dismiss(this.fastModeToastID),this.fastModeToastID=null}toggleWorkDetails(){return this.expansion.toggle(!1),"handled"}showStatusMessage(A,Q=2000){if(this.statusMessageTimer)clearTimeout(this.statusMessageTimer),this.statusMessageTimer=null;this.setState(()=>{this.statusMessage=A}),this.statusMessageTimer=setTimeout(()=>{if(this.statusMessageTimer=null,!this.mounted)return;this.setState(()=>{this.statusMessage=null})},Q)}persistReasoningEffortForMode(A,Q){tY((B)=>({...B,lastReasoningEffortByMode:{...B.lastReasoningEffortByMode,[A]:Q}}))}toggleReasoningEffort(){let A=this.currentCommandAgentMode(),Q=d$(A);if(!Q)return"ignored";let B=null,$=this.updateThreadSettings((J)=>{let Y=b11(A,J,this.configSettingsForReasoning),Z=j80(Q,Y);return B=Z,this.persistReasoningEffortForMode(A,Z),{...J,"reasoning.effort":Z}});if(B)this.showStatusMessage(`Reasoning effort: ${B}`);return $}onPromptSubmitted=(A)=>{this.widget.history.add(A,A81.cwd()),this.resetHistory()};restorePromptHistory(A){this.resetHistory(),this.widget.editorController.text=A,this.widget.editorController.moveCursorToEnd()}handlePromptHistorySelection=(A)=>{this.promptHistoryPicker.disable(),this.restorePromptHistory(A)};navigateHistoryPrevious=()=>{let A=this.widget.history.previous();if(A!==null){if(this.historyIndex===-1)this.historyDraft=this.widget.editorController.text;this.historyIndex++,this.widget.editorController.text=A,this.widget.editorController.moveCursorToStart()}return"handled"};navigateHistoryNext=()=>{let A=this.widget.history.next();if(A!==null)this.historyIndex--,this.widget.editorController.text=A,this.widget.editorController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.widget.editorController.text=this.historyDraft||"",this.widget.editorController.moveCursorToEnd(),this.historyDraft=null;return"handled"};resetHistory(){this.widget.history.reset(),this.historyIndex=-1,this.historyDraft=null}setAgentMode=(A)=>{if(this.widget.threadContext)return;if(A!==this.agentMode)this.dismissFastModeToast();this.setState(()=>{this.agentMode=A}),this.widget.updateDraftThreadSettings((Q)=>{let B=f11(G2.of(this.context),A),$={...Q};delete $["reasoning.effort"];let J=B??b11(A,$,this.configSettingsForReasoning);if(J===void 0){let Y={...Q};return delete Y["reasoning.effort"],Y}return{...Q,"reasoning.effort":J}}),tY((Q)=>({...Q,agentMode:A}))};buildActions(){let A=new G4(()=>{return this.promptHistoryPicker.enable(),"handled"}),Q=new G4(()=>{return this.navigateHistoryPrevious()}),B=new G4(()=>{return this.navigateHistoryNext()}),$=new G4((Z)=>{return this.setAgentMode(Z.mode),"handled"}),J=new G4(()=>{return this.toggleReasoningEffort()}),Y=new G4(()=>{return this.toggleWorkDetails()});return new Map([[iW,A],[lV0,B],[cV0,Q],[N51,$],[Ct,J],[mV0,Y]])}build(A){let Q=this.widget.threadContext,B=G2.of(A),$=Fs5(B.workspaceRoot,this.currentGitBranch),Y=[Q?new b31({editorController:this.widget.editorController,copyOnSelectEnabled:this.copyOnSelectEnabled,configSettings:this.configSettingsForReasoning,observingClient:{client:Q.client,observer:Q.observer},hints:this.widget.hints,ideStatus:this.widget.ideStatus,onPromptSubmitted:this.onPromptSubmitted,environmentFallback:this.useLocalEnvironmentFallbackForActiveThread?$:null}):new o31({agentMode:this.agentMode,threadSettings:this.widget.draftThreadSettings,configSettings:this.configSettingsForReasoning,editorController:this.widget.editorController,visibility:this.emptyThreadVisibility,onNewThread:this.widget.onNewThread,onAgentModeChange:this.setAgentMode,previousThreadIDForReference:this.previousThreadIDForReference,hints:this.widget.hints,ideStatus:this.widget.ideStatus,configService:this.widget.configService,environment:$,statusMessage:this.statusMessage})];if(this.promptHistoryPicker.isEnabled())Y.push(new GU0({entries:this.widget.history.getAll(),currentCwd:A81.cwd(),onAccept:this.handlePromptHistorySelection,onDismiss:this.promptHistoryPicker.disable}));let Z=new Map([[v1.ctrl("r"),new iW],[v1.alt("t"),new mV0]]);if(this.promptHistoryPicker.isEnabled())Z.set(v1.ctrl("o"),new iW);else Z.set(v1.ctrl("n"),new lV0),Z.set(v1.ctrl("p"),new cV0);return new FA({actions:this.buildActions(),child:new h5({debugLabel:"NeoThreadShortcuts",shortcuts:Z,child:new $F({controller:this.expansion,child:new t4({children:Y})})})})}subscribeToCopyOnSelectEnabled(){this.copyOnSelectSubscription?.unsubscribe(),this.copyOnSelectSubscription=this.widget.configService.config.subscribe((A)=>{let Q=A.settings["terminal.copyOnSelect"]??!0,B=A.settings["internal.model"],$=this.configSettingsForReasoning["internal.model"]!==B;if(B===void 0)this.configSettingsForReasoning={};else this.configSettingsForReasoning={"internal.model":B};if(this.copyOnSelectEnabled===Q&&!$)return;if(this.copyOnSelectEnabled=Q,this.mounted)this.setState()})}}C3();class B81 extends v0{toolboxes;onDismiss;constructor(A){super();this.toolboxes=A.toolboxes,this.onDismiss=A.onDismiss}createState(){return new n4A}}class n4A extends k0{toolboxes=new x8(this,[]);initState(){this.toolboxes.subscribe(this.widget.toolboxes)}didUpdateWidget(A){if(A.toolboxes!==this.widget.toolboxes)this.toolboxes.subscribe(this.widget.toolboxes)}build(A){return new a4A({toolboxes:this.toolboxes.getValue(),onDismiss:this.widget.onDismiss})}}class a4A extends v0{toolboxes;onDismiss;constructor(A){super();this.toolboxes=A.toolboxes,this.onDismiss=A.onDismiss}createState(){return new o4A}}class o4A extends k0{scrollController=new oA;canScroll=!1;initState(){this.scrollController.followMode=!1,this.scrollController.jumpTo(0),this.scrollController.addListener(this.updateCanScroll)}dispose(){this.scrollController.removeListener(this.updateCanScroll),this.scrollController.dispose()}updateCanScroll=()=>{let A=this.scrollController.maxScrollExtent>0;if(A===this.canScroll)return;this.setState(()=>{this.canScroll=A})};build(A){return new TA({header:"Toolboxes",onDismiss:this.widget.onDismiss,minWidth:80,maxWidth:120,maxHeight:40,autofocus:!1,footer:Ds5(this.canScroll),child:new JZ({controller:this.scrollController,child:Gs5(A,this.widget.toolboxes)})})}}function Ds5(A){let Q=[{keys:["Esc"],label:"close"}];if(A)Q.push({keys:["↑↓","j/k"],label:"scroll"});return Q}function Gs5(A,Q){let B=Vs5(A,Q);return new f0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new l({text:new M("",void 0,B),selectable:!0})]})}function Vs5(A,Q){let B=_0.of(A),{colors:$}=B,J=new y({color:$.foreground,dim:!0}),Y=new y({color:$.foreground,bold:!0});if(Q.length===0)return[new M("No toolboxes found.",J)];let Z=[];for(let X of Q){let F=X.tools.length,D=X.tools.filter((G)=>G.status==="registered").length;if(X.discovering){let G=X.tools.filter((V)=>V.status!=="pending").length;Z.push(new M(X.path,Y)),Z.push(new M(` discovering ${G}/${F}...
5370
5370
  `,J))}else if(Z.push(new M(X.path,Y)),F>0)Z.push(new M(` ${D}/${F} ${K4(F,"tool")}
@@ -5381,7 +5381,7 @@ Ctrl-X, Y, Z to unlock`;if(E){let Q0=G.text.replace(/`([^`]+)`/g,"$1")+`
5381
5381
  */var Mb=9000000000000000,Zw=1e9,F81="0123456789abcdef",HU0="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",zU0="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",D81={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Mb,maxE:Mb,crypto:!1},WAA,FH,cA=!0,NU0="[DecimalError] ",Yw=NU0+"Invalid argument: ",HAA=NU0+"Precision limit exceeded",zAA=NU0+"crypto unavailable",qAA="[object Decimal]",$B=Math.floor,b9=Math.pow,xs5=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,fs5=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,bs5=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,NAA=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,XG=1e7,SA=7,us5=9007199254740991,hs5=HU0.length-1,G81=zU0.length-1,m1={toStringTag:qAA};m1.absoluteValue=m1.abs=function(){var A=new this.constructor(this);if(A.s<0)A.s=1;return DA(A)};m1.ceil=function(){return DA(new this.constructor(this),this.e+1,2)};m1.clampedTo=m1.clamp=function(A,Q){var B,$=this,J=$.constructor;if(A=new J(A),Q=new J(Q),!A.s||!Q.s)return new J(NaN);if(A.gt(Q))throw Error(Yw+Q);return B=$.cmp(A),B<0?A:$.cmp(Q)>0?Q:new J($)};m1.comparedTo=m1.cmp=function(A){var Q,B,$,J,Y=this,Z=Y.d,X=(A=new Y.constructor(A)).d,F=Y.s,D=A.s;if(!Z||!X)return!F||!D?NaN:F!==D?F:Z===X?0:!Z^F<0?1:-1;if(!Z[0]||!X[0])return Z[0]?F:X[0]?-D:0;if(F!==D)return F;if(Y.e!==A.e)return Y.e>A.e^F<0?1:-1;$=Z.length,J=X.length;for(Q=0,B=$<J?$:J;Q<B;++Q)if(Z[Q]!==X[Q])return Z[Q]>X[Q]^F<0?1:-1;return $===J?0:$>J^F<0?1:-1};m1.cosine=m1.cos=function(){var A,Q,B=this,$=B.constructor;if(!B.d)return new $(NaN);if(!B.d[0])return new $(1);return A=$.precision,Q=$.rounding,$.precision=A+Math.max(B.e,B.sd())+SA,$.rounding=1,B=gs5($,LAA($,B)),$.precision=A,$.rounding=Q,DA(FH==2||FH==3?B.neg():B,A,Q,!0)};m1.cubeRoot=m1.cbrt=function(){var A,Q,B,$,J,Y,Z,X,F,D,G=this,V=G.constructor;if(!G.isFinite()||G.isZero())return new V(G);if(cA=!1,Y=G.s*b9(G.s*G,0.3333333333333333),!Y||Math.abs(Y)==1/0){if(B=BQ(G.d),A=G.e,Y=(A-B.length+1)%3)B+=Y==1||Y==-2?"0":"00";if(Y=b9(B,0.3333333333333333),A=$B((A+1)/3)-(A%3==(A<0?-1:2)),Y==1/0)B="5e"+A;else B=Y.toExponential(),B=B.slice(0,B.indexOf("e")+1)+A;$=new V(B),$.s=G.s}else $=new V(Y.toString());Z=(A=V.precision)+3;for(;;)if(X=$,F=X.times(X).times(X),D=F.plus(G),$=P3(D.plus(G).times(X),D.plus(F),Z+2,1),BQ(X.d).slice(0,Z)===(B=BQ($.d)).slice(0,Z))if(B=B.slice(Z-3,Z+1),B=="9999"||!J&&B=="4999"){if(!J){if(DA(X,A+1,0),X.times(X).times(X).eq(G)){$=X;break}}Z+=4,J=1}else{if(!+B||!+B.slice(1)&&B.charAt(0)=="5")DA($,A+1,1),Q=!$.times($).times($).eq(G);break}return cA=!0,DA($,A,V.rounding,Q)};m1.decimalPlaces=m1.dp=function(){var A,Q=this.d,B=NaN;if(Q){if(A=Q.length-1,B=(A-$B(this.e/SA))*SA,A=Q[A],A)for(;A%10==0;A/=10)B--;if(B<0)B=0}return B};m1.dividedBy=m1.div=function(A){return P3(this,new this.constructor(A))};m1.dividedToIntegerBy=m1.divToInt=function(A){var Q=this,B=Q.constructor;return DA(P3(Q,new B(A),0,1,1),B.precision,B.rounding)};m1.equals=m1.eq=function(A){return this.cmp(A)===0};m1.floor=function(){return DA(new this.constructor(this),this.e+1,3)};m1.greaterThan=m1.gt=function(A){return this.cmp(A)>0};m1.greaterThanOrEqualTo=m1.gte=function(A){var Q=this.cmp(A);return Q==1||Q===0};m1.hyperbolicCosine=m1.cosh=function(){var A,Q,B,$,J,Y=this,Z=Y.constructor,X=new Z(1);if(!Y.isFinite())return new Z(Y.s?1/0:NaN);if(Y.isZero())return X;if(B=Z.precision,$=Z.rounding,Z.precision=B+Math.max(Y.e,Y.sd())+4,Z.rounding=1,J=Y.d.length,J<32)A=Math.ceil(J/3),Q=(1/wU0(4,A)).toString();else A=16,Q="2.3283064365386962890625e-10";Y=Lb(Z,1,Y.times(Q),new Z(1),!0);var F,D=A,G=new Z(8);for(;D--;)F=Y.times(Y),Y=X.minus(F.times(G.minus(F.times(G))));return DA(Y,Z.precision=B,Z.rounding=$,!0)};m1.hyperbolicSine=m1.sinh=function(){var A,Q,B,$,J=this,Y=J.constructor;if(!J.isFinite()||J.isZero())return new Y(J);if(Q=Y.precision,B=Y.rounding,Y.precision=Q+Math.max(J.e,J.sd())+4,Y.rounding=1,$=J.d.length,$<3)J=Lb(Y,2,J,J,!0);else{A=1.4*Math.sqrt($),A=A>16?16:A|0,J=J.times(1/wU0(5,A)),J=Lb(Y,2,J,J,!0);var Z,X=new Y(5),F=new Y(16),D=new Y(20);for(;A--;)Z=J.times(J),J=J.times(X.plus(Z.times(F.times(Z).plus(D))))}return Y.precision=Q,Y.rounding=B,DA(J,Q,B,!0)};m1.hyperbolicTangent=m1.tanh=function(){var A,Q,B=this,$=B.constructor;if(!B.isFinite())return new $(B.s);if(B.isZero())return new $(B);return A=$.precision,Q=$.rounding,$.precision=A+7,$.rounding=1,P3(B.sinh(),B.cosh(),$.precision=A,$.rounding=Q)};m1.inverseCosine=m1.acos=function(){var A=this,Q=A.constructor,B=A.abs().cmp(1),$=Q.precision,J=Q.rounding;if(B!==-1)return B===0?A.isNeg()?$K(Q,$,J):new Q(0):new Q(NaN);if(A.isZero())return $K(Q,$+4,J).times(0.5);return Q.precision=$+6,Q.rounding=1,A=new Q(1).minus(A).div(A.plus(1)).sqrt().atan(),Q.precision=$,Q.rounding=J,A.times(2)};m1.inverseHyperbolicCosine=m1.acosh=function(){var A,Q,B=this,$=B.constructor;if(B.lte(1))return new $(B.eq(1)?0:NaN);if(!B.isFinite())return new $(B);return A=$.precision,Q=$.rounding,$.precision=A+Math.max(Math.abs(B.e),B.sd())+4,$.rounding=1,cA=!1,B=B.times(B).minus(1).sqrt().plus(B),cA=!0,$.precision=A,$.rounding=Q,B.ln()};m1.inverseHyperbolicSine=m1.asinh=function(){var A,Q,B=this,$=B.constructor;if(!B.isFinite()||B.isZero())return new $(B);return A=$.precision,Q=$.rounding,$.precision=A+2*Math.max(Math.abs(B.e),B.sd())+6,$.rounding=1,cA=!1,B=B.times(B).plus(1).sqrt().plus(B),cA=!0,$.precision=A,$.rounding=Q,B.ln()};m1.inverseHyperbolicTangent=m1.atanh=function(){var A,Q,B,$,J=this,Y=J.constructor;if(!J.isFinite())return new Y(NaN);if(J.e>=0)return new Y(J.abs().eq(1)?J.s/0:J.isZero()?J:NaN);if(A=Y.precision,Q=Y.rounding,$=J.sd(),Math.max($,A)<2*-J.e-1)return DA(new Y(J),A,Q,!0);return Y.precision=B=$-J.e,J=P3(J.plus(1),new Y(1).minus(J),B+A,1),Y.precision=A+4,Y.rounding=1,J=J.ln(),Y.precision=A,Y.rounding=Q,J.times(0.5)};m1.inverseSine=m1.asin=function(){var A,Q,B,$,J=this,Y=J.constructor;if(J.isZero())return new Y(J);if(Q=J.abs().cmp(1),B=Y.precision,$=Y.rounding,Q!==-1){if(Q===0)return A=$K(Y,B+4,$).times(0.5),A.s=J.s,A;return new Y(NaN)}return Y.precision=B+6,Y.rounding=1,J=J.div(new Y(1).minus(J.times(J)).sqrt().plus(1)).atan(),Y.precision=B,Y.rounding=$,J.times(2)};m1.inverseTangent=m1.atan=function(){var A,Q,B,$,J,Y,Z,X,F,D=this,G=D.constructor,V=G.precision,U=G.rounding;if(!D.isFinite()){if(!D.s)return new G(NaN);if(V+4<=G81)return Z=$K(G,V+4,U).times(0.5),Z.s=D.s,Z}else if(D.isZero())return new G(D);else if(D.abs().eq(1)&&V+4<=G81)return Z=$K(G,V+4,U).times(0.25),Z.s=D.s,Z;G.precision=X=V+10,G.rounding=1,B=Math.min(28,X/SA+2|0);for(A=B;A;--A)D=D.div(D.times(D).plus(1).sqrt().plus(1));cA=!1,Q=Math.ceil(X/SA),$=1,F=D.times(D),Z=new G(D),J=D;for(;A!==-1;)if(J=J.times(F),Y=Z.minus(J.div($+=2)),J=J.times(F),Z=Y.plus(J.div($+=2)),Z.d[Q]!==void 0)for(A=Q;Z.d[A]===Y.d[A]&&A--;);if(B)Z=Z.times(2<<B-1);return cA=!0,DA(Z,G.precision=V,G.rounding=U,!0)};m1.isFinite=function(){return!!this.d};m1.isInteger=m1.isInt=function(){return!!this.d&&$B(this.e/SA)>this.d.length-2};m1.isNaN=function(){return!this.s};m1.isNegative=m1.isNeg=function(){return this.s<0};m1.isPositive=m1.isPos=function(){return this.s>0};m1.isZero=function(){return!!this.d&&this.d[0]===0};m1.lessThan=m1.lt=function(A){return this.cmp(A)<0};m1.lessThanOrEqualTo=m1.lte=function(A){return this.cmp(A)<1};m1.logarithm=m1.log=function(A){var Q,B,$,J,Y,Z,X,F,D=this,G=D.constructor,V=G.precision,U=G.rounding,K=5;if(A==null)A=new G(10),Q=!0;else{if(A=new G(A),B=A.d,A.s<0||!B||!B[0]||A.eq(1))return new G(NaN);Q=A.eq(10)}if(B=D.d,D.s<0||!B||!B[0]||D.eq(1))return new G(B&&!B[0]?-1/0:D.s!=1?NaN:B?0:1/0);if(Q)if(B.length>1)Y=!0;else{for(J=B[0];J%10===0;)J/=10;Y=J!==1}if(cA=!1,X=V+K,Z=Jw(D,X),$=Q?qU0(G,X+10):Jw(A,X),F=P3(Z,$,X,1),ut(F.d,J=V,U))do if(X+=10,Z=Jw(D,X),$=Q?qU0(G,X+10):Jw(A,X),F=P3(Z,$,X,1),!Y){if(+BQ(F.d).slice(J+1,J+15)+1==100000000000000)F=DA(F,V+1,0);break}while(ut(F.d,J+=10,U));return cA=!0,DA(F,V,U)};m1.minus=m1.sub=function(A){var Q,B,$,J,Y,Z,X,F,D,G,V,U,K=this,E=K.constructor;if(A=new E(A),!K.d||!A.d){if(!K.s||!A.s)A=new E(NaN);else if(K.d)A.s=-A.s;else A=new E(A.d||K.s!==A.s?K:NaN);return A}if(K.s!=A.s)return A.s=-A.s,K.plus(A);if(D=K.d,U=A.d,X=E.precision,F=E.rounding,!D[0]||!U[0]){if(U[0])A.s=-A.s;else if(D[0])A=new E(K);else return new E(F===3?-0:0);return cA?DA(A,X,F):A}if(B=$B(A.e/SA),G=$B(K.e/SA),D=D.slice(),Y=G-B,Y){if(V=Y<0,V)Q=D,Y=-Y,Z=U.length;else Q=U,B=G,Z=D.length;if($=Math.max(Math.ceil(X/SA),Z)+2,Y>$)Y=$,Q.length=1;Q.reverse();for($=Y;$--;)Q.push(0);Q.reverse()}else{if($=D.length,Z=U.length,V=$<Z,V)Z=$;for($=0;$<Z;$++)if(D[$]!=U[$]){V=D[$]<U[$];break}Y=0}if(V)Q=D,D=U,U=Q,A.s=-A.s;Z=D.length;for($=U.length-Z;$>0;--$)D[Z++]=0;for($=U.length;$>Y;){if(D[--$]<U[$]){for(J=$;J&&D[--J]===0;)D[J]=XG-1;--D[J],D[$]+=XG}D[$]-=U[$]}for(;D[--Z]===0;)D.pop();for(;D[0]===0;D.shift())--B;if(!D[0])return new E(F===3?-0:0);return A.d=D,A.e=IU0(D,B),cA?DA(A,X,F):A};m1.modulo=m1.mod=function(A){var Q,B=this,$=B.constructor;if(A=new $(A),!B.d||!A.s||A.d&&!A.d[0])return new $(NaN);if(!A.d||B.d&&!B.d[0])return DA(new $(B),$.precision,$.rounding);if(cA=!1,$.modulo==9)Q=P3(B,A.abs(),0,3,1),Q.s*=A.s;else Q=P3(B,A,0,$.modulo,1);return Q=Q.times(A),cA=!0,B.minus(Q)};m1.naturalExponential=m1.exp=function(){return V81(this)};m1.naturalLogarithm=m1.ln=function(){return Jw(this)};m1.negated=m1.neg=function(){var A=new this.constructor(this);return A.s=-A.s,DA(A)};m1.plus=m1.add=function(A){var Q,B,$,J,Y,Z,X,F,D,G,V=this,U=V.constructor;if(A=new U(A),!V.d||!A.d){if(!V.s||!A.s)A=new U(NaN);else if(!V.d)A=new U(A.d||V.s===A.s?V:NaN);return A}if(V.s!=A.s)return A.s=-A.s,V.minus(A);if(D=V.d,G=A.d,X=U.precision,F=U.rounding,!D[0]||!G[0]){if(!G[0])A=new U(V);return cA?DA(A,X,F):A}if(Y=$B(V.e/SA),$=$B(A.e/SA),D=D.slice(),J=Y-$,J){if(J<0)B=D,J=-J,Z=G.length;else B=G,$=Y,Z=D.length;if(Y=Math.ceil(X/SA),Z=Y>Z?Y+1:Z+1,J>Z)J=Z,B.length=1;B.reverse();for(;J--;)B.push(0);B.reverse()}if(Z=D.length,J=G.length,Z-J<0)J=Z,B=G,G=D,D=B;for(Q=0;J;)Q=(D[--J]=D[J]+G[J]+Q)/XG|0,D[J]%=XG;if(Q)D.unshift(Q),++$;for(Z=D.length;D[--Z]==0;)D.pop();return A.d=D,A.e=IU0(D,$),cA?DA(A,X,F):A};m1.precision=m1.sd=function(A){var Q,B=this;if(A!==void 0&&A!==!!A&&A!==1&&A!==0)throw Error(Yw+A);if(B.d){if(Q=IAA(B.d),A&&B.e+1>Q)Q=B.e+1}else Q=NaN;return Q};m1.round=function(){var A=this,Q=A.constructor;return DA(new Q(A),A.e+1,Q.rounding)};m1.sine=m1.sin=function(){var A,Q,B=this,$=B.constructor;if(!B.isFinite())return new $(NaN);if(B.isZero())return new $(B);return A=$.precision,Q=$.rounding,$.precision=A+Math.max(B.e,B.sd())+SA,$.rounding=1,B=ps5($,LAA($,B)),$.precision=A,$.rounding=Q,DA(FH>2?B.neg():B,A,Q,!0)};m1.squareRoot=m1.sqrt=function(){var A,Q,B,$,J,Y,Z=this,X=Z.d,F=Z.e,D=Z.s,G=Z.constructor;if(D!==1||!X||!X[0])return new G(!D||D<0&&(!X||X[0])?NaN:X?Z:1/0);if(cA=!1,D=Math.sqrt(+Z),D==0||D==1/0){if(Q=BQ(X),(Q.length+F)%2==0)Q+="0";if(D=Math.sqrt(Q),F=$B((F+1)/2)-(F<0||F%2),D==1/0)Q="5e"+F;else Q=D.toExponential(),Q=Q.slice(0,Q.indexOf("e")+1)+F;$=new G(Q)}else $=new G(D.toString());B=(F=G.precision)+3;for(;;)if(Y=$,$=Y.plus(P3(Z,Y,B+2,1)).times(0.5),BQ(Y.d).slice(0,B)===(Q=BQ($.d)).slice(0,B))if(Q=Q.slice(B-3,B+1),Q=="9999"||!J&&Q=="4999"){if(!J){if(DA(Y,F+1,0),Y.times(Y).eq(Z)){$=Y;break}}B+=4,J=1}else{if(!+Q||!+Q.slice(1)&&Q.charAt(0)=="5")DA($,F+1,1),A=!$.times($).eq(Z);break}return cA=!0,DA($,F,G.rounding,A)};m1.tangent=m1.tan=function(){var A,Q,B=this,$=B.constructor;if(!B.isFinite())return new $(NaN);if(B.isZero())return new $(B);return A=$.precision,Q=$.rounding,$.precision=A+10,$.rounding=1,B=B.sin(),B.s=1,B=P3(B,new $(1).minus(B.times(B)).sqrt(),A+10,0),$.precision=A,$.rounding=Q,DA(FH==2||FH==4?B.neg():B,A,Q,!0)};m1.times=m1.mul=function(A){var Q,B,$,J,Y,Z,X,F,D,G=this,V=G.constructor,U=G.d,K=(A=new V(A)).d;if(A.s*=G.s,!U||!U[0]||!K||!K[0])return new V(!A.s||U&&!U[0]&&!K||K&&!K[0]&&!U?NaN:!U||!K?A.s/0:A.s*0);if(B=$B(G.e/SA)+$B(A.e/SA),F=U.length,D=K.length,F<D)Y=U,U=K,K=Y,Z=F,F=D,D=Z;Y=[],Z=F+D;for($=Z;$--;)Y.push(0);for($=D;--$>=0;){Q=0;for(J=F+$;J>$;)X=Y[J]+K[$]*U[J-$-1]+Q,Y[J--]=X%XG|0,Q=X/XG|0;Y[J]=(Y[J]+Q)%XG|0}for(;!Y[--Z];)Y.pop();if(Q)++B;else Y.shift();return A.d=Y,A.e=IU0(Y,B),cA?DA(A,V.precision,V.rounding):A};m1.toBinary=function(A,Q){return U81(this,2,A,Q)};m1.toDecimalPlaces=m1.toDP=function(A,Q){var B=this,$=B.constructor;if(B=new $(B),A===void 0)return B;if(_J(A,0,Zw),Q===void 0)Q=$.rounding;else _J(Q,0,8);return DA(B,A+B.e+1,Q)};m1.toExponential=function(A,Q){var B,$=this,J=$.constructor;if(A===void 0)B=JK($,!0);else{if(_J(A,0,Zw),Q===void 0)Q=J.rounding;else _J(Q,0,8);$=DA(new J($),A+1,Q),B=JK($,!0,A+1)}return $.isNeg()&&!$.isZero()?"-"+B:B};m1.toFixed=function(A,Q){var B,$,J=this,Y=J.constructor;if(A===void 0)B=JK(J);else{if(_J(A,0,Zw),Q===void 0)Q=Y.rounding;else _J(Q,0,8);$=DA(new Y(J),A+J.e+1,Q),B=JK($,!1,A+$.e+1)}return J.isNeg()&&!J.isZero()?"-"+B:B};m1.toFraction=function(A){var Q,B,$,J,Y,Z,X,F,D,G,V,U,K=this,E=K.d,W=K.constructor;if(!E)return new W(K);if(D=B=new W(1),$=F=new W(0),Q=new W($),Y=Q.e=IAA(E)-K.e-1,Z=Y%SA,Q.d[0]=b9(10,Z<0?SA+Z:Z),A==null)A=Y>0?Q:D;else{if(X=new W(A),!X.isInt()||X.lt(D))throw Error(Yw+X);A=X.gt(Q)?Y>0?Q:D:X}cA=!1,X=new W(BQ(E)),G=W.precision,W.precision=Y=E.length*SA*2;for(;;){if(V=P3(X,Q,0,1,1),J=B.plus(V.times($)),J.cmp(A)==1)break;B=$,$=J,J=D,D=F.plus(V.times(J)),F=J,J=Q,Q=X.minus(V.times(J)),X=J}return J=P3(A.minus(B),$,0,1,1),F=F.plus(J.times(D)),B=B.plus(J.times($)),F.s=D.s=K.s,U=P3(D,$,Y,1).minus(K).abs().cmp(P3(F,B,Y,1).minus(K).abs())<1?[D,$]:[F,B],W.precision=G,cA=!0,U};m1.toHexadecimal=m1.toHex=function(A,Q){return U81(this,16,A,Q)};m1.toNearest=function(A,Q){var B=this,$=B.constructor;if(B=new $(B),A==null){if(!B.d)return B;A=new $(1),Q=$.rounding}else{if(A=new $(A),Q===void 0)Q=$.rounding;else _J(Q,0,8);if(!B.d)return A.s?B:A;if(!A.d){if(A.s)A.s=B.s;return A}}if(A.d[0])cA=!1,B=P3(B,A,0,Q,1).times(A),cA=!0,DA(B);else A.s=B.s,B=A;return B};m1.toNumber=function(){return+this};m1.toOctal=function(A,Q){return U81(this,8,A,Q)};m1.toPower=m1.pow=function(A){var Q,B,$,J,Y,Z,X=this,F=X.constructor,D=+(A=new F(A));if(!X.d||!A.d||!X.d[0]||!A.d[0])return new F(b9(+X,D));if(X=new F(X),X.eq(1))return X;if($=F.precision,Y=F.rounding,A.eq(1))return DA(X,$,Y);if(Q=$B(A.e/SA),Q>=A.d.length-1&&(B=D<0?-D:D)<=us5)return J=wAA(F,X,B,$),A.s<0?new F(1).div(J):DA(J,$,Y);if(Z=X.s,Z<0){if(Q<A.d.length-1)return new F(NaN);if((A.d[Q]&1)==0)Z=1;if(X.e==0&&X.d[0]==1&&X.d.length==1)return X.s=Z,X}if(B=b9(+X,D),Q=B==0||!isFinite(B)?$B(D*(Math.log("0."+BQ(X.d))/Math.LN10+X.e+1)):new F(B+"").e,Q>F.maxE+1||Q<F.minE-1)return new F(Q>0?Z/0:0);if(cA=!1,F.rounding=X.s=1,B=Math.min(12,(Q+"").length),J=V81(A.times(Jw(X,$+B)),$),J.d){if(J=DA(J,$+5,1),ut(J.d,$,Y)){if(Q=$+10,J=DA(V81(A.times(Jw(X,Q+B)),Q),Q+5,1),+BQ(J.d).slice($+1,$+15)+1==100000000000000)J=DA(J,$+1,0)}}return J.s=Z,cA=!0,F.rounding=Y,DA(J,$,Y)};m1.toPrecision=function(A,Q){var B,$=this,J=$.constructor;if(A===void 0)B=JK($,$.e<=J.toExpNeg||$.e>=J.toExpPos);else{if(_J(A,1,Zw),Q===void 0)Q=J.rounding;else _J(Q,0,8);$=DA(new J($),A,Q),B=JK($,A<=$.e||$.e<=J.toExpNeg,A)}return $.isNeg()&&!$.isZero()?"-"+B:B};m1.toSignificantDigits=m1.toSD=function(A,Q){var B=this,$=B.constructor;if(A===void 0)A=$.precision,Q=$.rounding;else if(_J(A,1,Zw),Q===void 0)Q=$.rounding;else _J(Q,0,8);return DA(new $(B),A,Q)};m1.toString=function(){var A=this,Q=A.constructor,B=JK(A,A.e<=Q.toExpNeg||A.e>=Q.toExpPos);return A.isNeg()&&!A.isZero()?"-"+B:B};m1.truncated=m1.trunc=function(){return DA(new this.constructor(this),this.e+1,1)};m1.valueOf=m1.toJSON=function(){var A=this,Q=A.constructor,B=JK(A,A.e<=Q.toExpNeg||A.e>=Q.toExpPos);return A.isNeg()?"-"+B:B};function BQ(A){var Q,B,$,J=A.length-1,Y="",Z=A[0];if(J>0){Y+=Z;for(Q=1;Q<J;Q++){if($=A[Q]+"",B=SA-$.length,B)Y+=$w(B);Y+=$}if(Z=A[Q],$=Z+"",B=SA-$.length,B)Y+=$w(B)}else if(Z===0)return"0";for(;Z%10===0;)Z/=10;return Y+Z}function _J(A,Q,B){if(A!==~~A||A<Q||A>B)throw Error(Yw+A)}function ut(A,Q,B,$){var J,Y,Z,X;for(Y=A[0];Y>=10;Y/=10)--Q;if(--Q<0)Q+=SA,J=0;else J=Math.ceil((Q+1)/SA),Q%=SA;if(Y=b9(10,SA-Q),X=A[J]%Y|0,$==null)if(Q<3){if(Q==0)X=X/100|0;else if(Q==1)X=X/10|0;Z=B<4&&X==99999||B>3&&X==49999||X==50000||X==0}else Z=(B<4&&X+1==Y||B>3&&X+1==Y/2)&&(A[J+1]/Y/100|0)==b9(10,Q-2)-1||(X==Y/2||X==0)&&(A[J+1]/Y/100|0)==0;else if(Q<4){if(Q==0)X=X/1000|0;else if(Q==1)X=X/100|0;else if(Q==2)X=X/10|0;Z=($||B<4)&&X==9999||!$&&B>3&&X==4999}else Z=(($||B<4)&&X+1==Y||!$&&B>3&&X+1==Y/2)&&(A[J+1]/Y/1000|0)==b9(10,Q-3)-1;return Z}function EU0(A,Q,B){var $,J=[0],Y,Z=0,X=A.length;for(;Z<X;){for(Y=J.length;Y--;)J[Y]*=Q;J[0]+=F81.indexOf(A.charAt(Z++));for($=0;$<J.length;$++)if(J[$]>B-1){if(J[$+1]===void 0)J[$+1]=0;J[$+1]+=J[$]/B|0,J[$]%=B}}return J.reverse()}function gs5(A,Q){var B,$,J;if(Q.isZero())return Q;if($=Q.d.length,$<32)B=Math.ceil($/3),J=(1/wU0(4,B)).toString();else B=16,J="2.3283064365386962890625e-10";A.precision+=B,Q=Lb(A,1,Q.times(J),new A(1));for(var Y=B;Y--;){var Z=Q.times(Q);Q=Z.times(Z).minus(Z).times(8).plus(1)}return A.precision-=B,Q}var P3=function(){function A($,J,Y){var Z,X=0,F=$.length;for($=$.slice();F--;)Z=$[F]*J+X,$[F]=Z%Y|0,X=Z/Y|0;if(X)$.unshift(X);return $}function Q($,J,Y,Z){var X,F;if(Y!=Z)F=Y>Z?1:-1;else for(X=F=0;X<Y;X++)if($[X]!=J[X]){F=$[X]>J[X]?1:-1;break}return F}function B($,J,Y,Z){var X=0;for(;Y--;)$[Y]-=X,X=$[Y]<J[Y]?1:0,$[Y]=X*Z+$[Y]-J[Y];for(;!$[0]&&$.length>1;)$.shift()}return function($,J,Y,Z,X,F){var D,G,V,U,K,E,W,H,z,q,N,I,w,C,O,_,S,T,b,h,x=$.constructor,v=$.s==J.s?1:-1,u=$.d,m=J.d;if(!u||!u[0]||!m||!m[0])return new x(!$.s||!J.s||(u?m&&u[0]==m[0]:!m)?NaN:u&&u[0]==0||!m?v*0:v/0);if(F)K=1,G=$.e-J.e;else F=XG,K=SA,G=$B($.e/K)-$B(J.e/K);b=m.length,S=u.length,z=new x(v),q=z.d=[];for(V=0;m[V]==(u[V]||0);V++);if(m[V]>(u[V]||0))G--;if(Y==null)C=Y=x.precision,Z=x.rounding;else if(X)C=Y+($.e-J.e)+1;else C=Y;if(C<0)q.push(1),E=!0;else{if(C=C/K+2|0,V=0,b==1){U=0,m=m[0],C++;for(;(V<S||U)&&C--;V++)O=U*F+(u[V]||0),q[V]=O/m|0,U=O%m|0;E=U||V<S}else{if(U=F/(m[0]+1)|0,U>1)m=A(m,U,F),u=A(u,U,F),b=m.length,S=u.length;_=b,N=u.slice(0,b),I=N.length;for(;I<b;)N[I++]=0;if(h=m.slice(),h.unshift(0),T=m[0],m[1]>=F/2)++T;do{if(U=0,D=Q(m,N,b,I),D<0){if(w=N[0],b!=I)w=w*F+(N[1]||0);if(U=w/T|0,U>1){if(U>=F)U=F-1;if(W=A(m,U,F),H=W.length,I=N.length,D=Q(W,N,H,I),D==1)U--,B(W,b<H?h:m,H,F)}else{if(U==0)D=U=1;W=m.slice()}if(H=W.length,H<I)W.unshift(0);if(B(N,W,I,F),D==-1){if(I=N.length,D=Q(m,N,b,I),D<1)U++,B(N,b<I?h:m,I,F)}I=N.length}else if(D===0)U++,N=[0];if(q[V++]=U,D&&N[0])N[I++]=u[_]||0;else N=[u[_]],I=1}while((_++<S||N[0]!==void 0)&&C--);E=N[0]!==void 0}if(!q[0])q.shift()}if(K==1)z.e=G,WAA=E;else{for(V=1,U=q[0];U>=10;U/=10)V++;z.e=V+G*K-1,DA(z,X?Y+z.e+1:Y,Z,E)}return z}}();function DA(A,Q,B,$){var J,Y,Z,X,F,D,G,V,U,K=A.constructor;A:if(Q!=null){if(V=A.d,!V)return A;for(J=1,X=V[0];X>=10;X/=10)J++;if(Y=Q-J,Y<0)Y+=SA,Z=Q,G=V[U=0],F=G/b9(10,J-Z-1)%10|0;else if(U=Math.ceil((Y+1)/SA),X=V.length,U>=X)if($){for(;X++<=U;)V.push(0);G=F=0,J=1,Y%=SA,Z=Y-SA+1}else break A;else{G=X=V[U];for(J=1;X>=10;X/=10)J++;Y%=SA,Z=Y-SA+J,F=Z<0?0:G/b9(10,J-Z-1)%10|0}if($=$||Q<0||V[U+1]!==void 0||(Z<0?G:G%b9(10,J-Z-1)),D=B<4?(F||$)&&(B==0||B==(A.s<0?3:2)):F>5||F==5&&(B==4||$||B==6&&(Y>0?Z>0?G/b9(10,J-Z):0:V[U-1])%10&1||B==(A.s<0?8:7)),Q<1||!V[0]){if(V.length=0,D)Q-=A.e+1,V[0]=b9(10,(SA-Q%SA)%SA),A.e=-Q||0;else V[0]=A.e=0;return A}if(Y==0)V.length=U,X=1,U--;else V.length=U+1,X=b9(10,SA-Y),V[U]=Z>0?(G/b9(10,J-Z)%b9(10,Z)|0)*X:0;if(D)for(;;)if(U==0){for(Y=1,Z=V[0];Z>=10;Z/=10)Y++;Z=V[0]+=X;for(X=1;Z>=10;Z/=10)X++;if(Y!=X){if(A.e++,V[0]==XG)V[0]=1}break}else{if(V[U]+=X,V[U]!=XG)break;V[U--]=0,X=1}for(Y=V.length;V[--Y]===0;)V.pop()}if(cA){if(A.e>K.maxE)A.d=null,A.e=NaN;else if(A.e<K.minE)A.e=0,A.d=[0]}return A}function JK(A,Q,B){if(!A.isFinite())return MAA(A);var $,J=A.e,Y=BQ(A.d),Z=Y.length;if(Q){if(B&&($=B-Z)>0)Y=Y.charAt(0)+"."+Y.slice(1)+$w($);else if(Z>1)Y=Y.charAt(0)+"."+Y.slice(1);Y=Y+(A.e<0?"e":"e+")+A.e}else if(J<0){if(Y="0."+$w(-J-1)+Y,B&&($=B-Z)>0)Y+=$w($)}else if(J>=Z){if(Y+=$w(J+1-Z),B&&($=B-J-1)>0)Y=Y+"."+$w($)}else{if(($=J+1)<Z)Y=Y.slice(0,$)+"."+Y.slice($);if(B&&($=B-Z)>0){if(J+1===Z)Y+=".";Y+=$w($)}}return Y}function IU0(A,Q){var B=A[0];for(Q*=SA;B>=10;B/=10)Q++;return Q}function qU0(A,Q,B){if(Q>hs5){if(cA=!0,B)A.precision=B;throw Error(HAA)}return DA(new A(HU0),Q,1,!0)}function $K(A,Q,B){if(Q>G81)throw Error(HAA);return DA(new A(zU0),Q,B,!0)}function IAA(A){var Q=A.length-1,B=Q*SA+1;if(Q=A[Q],Q){for(;Q%10==0;Q/=10)B--;for(Q=A[0];Q>=10;Q/=10)B++}return B}function $w(A){var Q="";for(;A--;)Q+="0";return Q}function wAA(A,Q,B,$){var J,Y=new A(1),Z=Math.ceil($/SA+4);cA=!1;for(;;){if(B%2){if(Y=Y.times(Q),KAA(Y.d,Z))J=!0}if(B=$B(B/2),B===0){if(B=Y.d.length-1,J&&Y.d[B]===0)++Y.d[B];break}Q=Q.times(Q),KAA(Q.d,Z)}return cA=!0,Y}function UAA(A){return A.d[A.d.length-1]&1}function CAA(A,Q,B){var $,J,Y=new A(Q[0]),Z=0;for(;++Z<Q.length;){if(J=new A(Q[Z]),!J.s){Y=J;break}if($=Y.cmp(J),$===B||$===0&&Y.s===B)Y=J}return Y}function V81(A,Q){var B,$,J,Y,Z,X,F,D=0,G=0,V=0,U=A.constructor,K=U.rounding,E=U.precision;if(!A.d||!A.d[0]||A.e>17)return new U(A.d?!A.d[0]?1:A.s<0?0:1/0:A.s?A.s<0?0:A:NaN);if(Q==null)cA=!1,F=E;else F=Q;X=new U(0.03125);while(A.e>-2)A=A.times(X),V+=5;$=Math.log(b9(2,V))/Math.LN10*2+5|0,F+=$,B=Y=Z=new U(1),U.precision=F;for(;;){if(Y=DA(Y.times(A),F,1),B=B.times(++G),X=Z.plus(P3(Y,B,F,1)),BQ(X.d).slice(0,F)===BQ(Z.d).slice(0,F)){J=V;while(J--)Z=DA(Z.times(Z),F,1);if(Q==null)if(D<3&&ut(Z.d,F-$,K,D))U.precision=F+=10,B=Y=X=new U(1),G=0,D++;else return DA(Z,U.precision=E,K,cA=!0);else return U.precision=E,Z}Z=X}}function Jw(A,Q){var B,$,J,Y,Z,X,F,D,G,V,U,K=1,E=10,W=A,H=W.d,z=W.constructor,q=z.rounding,N=z.precision;if(W.s<0||!H||!H[0]||!W.e&&H[0]==1&&H.length==1)return new z(H&&!H[0]?-1/0:W.s!=1?NaN:H?0:W);if(Q==null)cA=!1,G=N;else G=Q;if(z.precision=G+=E,B=BQ(H),$=B.charAt(0),Math.abs(Y=W.e)<1500000000000000){while($<7&&$!=1||$==1&&B.charAt(1)>3)W=W.times(A),B=BQ(W.d),$=B.charAt(0),K++;if(Y=W.e,$>1)W=new z("0."+B),Y++;else W=new z($+"."+B.slice(1))}else return D=qU0(z,G+2,N).times(Y+""),W=Jw(new z($+"."+B.slice(1)),G-E).plus(D),z.precision=N,Q==null?DA(W,N,q,cA=!0):W;V=W,F=Z=W=P3(W.minus(1),W.plus(1),G,1),U=DA(W.times(W),G,1),J=3;for(;;){if(Z=DA(Z.times(U),G,1),D=F.plus(P3(Z,new z(J),G,1)),BQ(D.d).slice(0,G)===BQ(F.d).slice(0,G)){if(F=F.times(2),Y!==0)F=F.plus(qU0(z,G+2,N).times(Y+""));if(F=P3(F,new z(K),G,1),Q==null)if(ut(F.d,G-E,q,X))z.precision=G+=E,D=Z=W=P3(V.minus(1),V.plus(1),G,1),U=DA(W.times(W),G,1),J=X=1;else return DA(F,z.precision=N,q,cA=!0);else return z.precision=N,F}F=D,J+=2}}function MAA(A){return String(A.s*A.s/0)}function WU0(A,Q){var B,$,J;if((B=Q.indexOf("."))>-1)Q=Q.replace(".","");if(($=Q.search(/e/i))>0){if(B<0)B=$;B+=+Q.slice($+1),Q=Q.substring(0,$)}else if(B<0)B=Q.length;for($=0;Q.charCodeAt($)===48;$++);for(J=Q.length;Q.charCodeAt(J-1)===48;--J);if(Q=Q.slice($,J),Q){if(J-=$,A.e=B=B-$-1,A.d=[],$=(B+1)%SA,B<0)$+=SA;if($<J){if($)A.d.push(+Q.slice(0,$));for(J-=SA;$<J;)A.d.push(+Q.slice($,$+=SA));Q=Q.slice($),$=SA-Q.length}else $-=J;for(;$--;)Q+="0";if(A.d.push(+Q),cA){if(A.e>A.constructor.maxE)A.d=null,A.e=NaN;else if(A.e<A.constructor.minE)A.e=0,A.d=[0]}}else A.e=0,A.d=[0];return A}function ms5(A,Q){var B,$,J,Y,Z,X,F,D,G;if(Q.indexOf("_")>-1){if(Q=Q.replace(/(\d)_(?=\d)/g,"$1"),NAA.test(Q))return WU0(A,Q)}else if(Q==="Infinity"||Q==="NaN"){if(!+Q)A.s=NaN;return A.e=NaN,A.d=null,A}if(fs5.test(Q))B=16,Q=Q.toLowerCase();else if(xs5.test(Q))B=2;else if(bs5.test(Q))B=8;else throw Error(Yw+Q);if(Y=Q.search(/p/i),Y>0)F=+Q.slice(Y+1),Q=Q.substring(2,Y);else Q=Q.slice(2);if(Y=Q.indexOf("."),Z=Y>=0,$=A.constructor,Z)Q=Q.replace(".",""),X=Q.length,Y=X-Y,J=wAA($,new $(B),Y,Y*2);D=EU0(Q,B,XG),G=D.length-1;for(Y=G;D[Y]===0;--Y)D.pop();if(Y<0)return new $(A.s*0);if(A.e=IU0(D,G),A.d=D,cA=!1,Z)A=P3(A,J,X*4);if(F)A=A.times(Math.abs(F)<54?b9(2,F):ht.pow(2,F));return cA=!0,A}function ps5(A,Q){var B,$=Q.d.length;if($<3)return Q.isZero()?Q:Lb(A,2,Q,Q);B=1.4*Math.sqrt($),B=B>16?16:B|0,Q=Q.times(1/wU0(5,B)),Q=Lb(A,2,Q,Q);var J,Y=new A(5),Z=new A(16),X=new A(20);for(;B--;)J=Q.times(Q),Q=Q.times(Y.plus(J.times(Z.times(J).minus(X))));return Q}function Lb(A,Q,B,$,J){var Y,Z,X,F,D=1,G=A.precision,V=Math.ceil(G/SA);cA=!1,F=B.times(B),X=new A($);for(;;){if(Z=P3(X.times(F),new A(Q++*Q++),G,1),X=J?$.plus(Z):$.minus(Z),$=P3(Z.times(F),new A(Q++*Q++),G,1),Z=X.plus($),Z.d[V]!==void 0){for(Y=V;Z.d[Y]===X.d[Y]&&Y--;);if(Y==-1)break}Y=X,X=$,$=Z,Z=Y,D++}return cA=!0,Z.d.length=V+1,Z}function wU0(A,Q){var B=A;while(--Q)B*=A;return B}function LAA(A,Q){var B,$=Q.s<0,J=$K(A,A.precision,1),Y=J.times(0.5);if(Q=Q.abs(),Q.lte(Y))return FH=$?4:1,Q;if(B=Q.divToInt(J),B.isZero())FH=$?3:2;else{if(Q=Q.minus(B.times(J)),Q.lte(Y))return FH=UAA(B)?$?2:3:$?4:1,Q;FH=UAA(B)?$?1:4:$?3:2}return Q.minus(J).abs()}function U81(A,Q,B,$){var J,Y,Z,X,F,D,G,V,U,K=A.constructor,E=B!==void 0;if(E)if(_J(B,1,Zw),$===void 0)$=K.rounding;else _J($,0,8);else B=K.precision,$=K.rounding;if(!A.isFinite())G=MAA(A);else{if(G=JK(A),Z=G.indexOf("."),E){if(J=2,Q==16)B=B*4-3;else if(Q==8)B=B*3-2}else J=Q;if(Z>=0)G=G.replace(".",""),U=new K(1),U.e=G.length-Z,U.d=EU0(JK(U),10,J),U.e=U.d.length;V=EU0(G,10,J),Y=F=V.length;for(;V[--F]==0;)V.pop();if(!V[0])G=E?"0p+0":"0";else{if(Z<0)Y--;else A=new K(A),A.d=V,A.e=Y,A=P3(A,U,B,$,0,J),V=A.d,Y=A.e,D=WAA;if(Z=V[B],X=J/2,D=D||V[B+1]!==void 0,D=$<4?(Z!==void 0||D)&&($===0||$===(A.s<0?3:2)):Z>X||Z===X&&($===4||D||$===6&&V[B-1]&1||$===(A.s<0?8:7)),V.length=B,D){for(;++V[--B]>J-1;)if(V[B]=0,!B)++Y,V.unshift(1)}for(F=V.length;!V[F-1];--F);for(Z=0,G="";Z<F;Z++)G+=F81.charAt(V[Z]);if(E){if(F>1)if(Q==16||Q==8){Z=Q==16?4:3;for(--F;F%Z;F++)G+="0";V=EU0(G,J,Q);for(F=V.length;!V[F-1];--F);for(Z=1,G="1.";Z<F;Z++)G+=F81.charAt(V[Z])}else G=G.charAt(0)+"."+G.slice(1);G=G+(Y<0?"p":"p+")+Y}else if(Y<0){for(;++Y;)G="0"+G;G="0."+G}else if(++Y>F)for(Y-=F;Y--;)G+="0";else if(Y<F)G=G.slice(0,Y)+"."+G.slice(Y)}G=(Q==16?"0x":Q==2?"0b":Q==8?"0o":"")+G}return A.s<0?"-"+G:G}function KAA(A,Q){if(A.length>Q)return A.length=Q,!0}function ds5(A){return new this(A).abs()}function cs5(A){return new this(A).acos()}function ls5(A){return new this(A).acosh()}function is5(A,Q){return new this(A).plus(Q)}function ns5(A){return new this(A).asin()}function as5(A){return new this(A).asinh()}function os5(A){return new this(A).atan()}function rs5(A){return new this(A).atanh()}function ss5(A,Q){A=new this(A),Q=new this(Q);var B,$=this.precision,J=this.rounding,Y=$+4;if(!A.s||!Q.s)B=new this(NaN);else if(!A.d&&!Q.d)B=$K(this,Y,1).times(Q.s>0?0.25:0.75),B.s=A.s;else if(!Q.d||A.isZero())B=Q.s<0?$K(this,$,J):new this(0),B.s=A.s;else if(!A.d||Q.isZero())B=$K(this,Y,1).times(0.5),B.s=A.s;else if(Q.s<0)this.precision=Y,this.rounding=1,B=this.atan(P3(A,Q,Y,1)),Q=$K(this,Y,1),this.precision=$,this.rounding=J,B=A.s<0?B.minus(Q):B.plus(Q);else B=this.atan(P3(A,Q,Y,1));return B}function ts5(A){return new this(A).cbrt()}function es5(A){return DA(A=new this(A),A.e+1,2)}function At5(A,Q,B){return new this(A).clamp(Q,B)}function Qt5(A){if(!A||typeof A!=="object")throw Error(NU0+"Object expected");var Q,B,$,J=A.defaults===!0,Y=["precision",1,Zw,"rounding",0,8,"toExpNeg",-Mb,0,"toExpPos",0,Mb,"maxE",0,Mb,"minE",-Mb,0,"modulo",0,9];for(Q=0;Q<Y.length;Q+=3){if(B=Y[Q],J)this[B]=D81[B];if(($=A[B])!==void 0)if($B($)===$&&$>=Y[Q+1]&&$<=Y[Q+2])this[B]=$;else throw Error(Yw+B+": "+$)}if(B="crypto",J)this[B]=D81[B];if(($=A[B])!==void 0)if($===!0||$===!1||$===0||$===1)if($)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[B]=!0;else throw Error(zAA);else this[B]=!1;else throw Error(Yw+B+": "+$);return this}function Bt5(A){return new this(A).cos()}function $t5(A){return new this(A).cosh()}function OAA(A){var Q,B,$;function J(Y){var Z,X,F,D=this;if(!(D instanceof J))return new J(Y);if(D.constructor=J,EAA(Y)){if(D.s=Y.s,cA)if(!Y.d||Y.e>J.maxE)D.e=NaN,D.d=null;else if(Y.e<J.minE)D.e=0,D.d=[0];else D.e=Y.e,D.d=Y.d.slice();else D.e=Y.e,D.d=Y.d?Y.d.slice():Y.d;return}if(F=typeof Y,F==="number"){if(Y===0){D.s=1/Y<0?-1:1,D.e=0,D.d=[0];return}if(Y<0)Y=-Y,D.s=-1;else D.s=1;if(Y===~~Y&&Y<1e7){for(Z=0,X=Y;X>=10;X/=10)Z++;if(cA)if(Z>J.maxE)D.e=NaN,D.d=null;else if(Z<J.minE)D.e=0,D.d=[0];else D.e=Z,D.d=[Y];else D.e=Z,D.d=[Y];return}if(Y*0!==0){if(!Y)D.s=NaN;D.e=NaN,D.d=null;return}return WU0(D,Y.toString())}if(F==="string"){if((X=Y.charCodeAt(0))===45)Y=Y.slice(1),D.s=-1;else{if(X===43)Y=Y.slice(1);D.s=1}return NAA.test(Y)?WU0(D,Y):ms5(D,Y)}if(F==="bigint"){if(Y<0)Y=-Y,D.s=-1;else D.s=1;return WU0(D,Y.toString())}throw Error(Yw+Y)}if(J.prototype=m1,J.ROUND_UP=0,J.ROUND_DOWN=1,J.ROUND_CEIL=2,J.ROUND_FLOOR=3,J.ROUND_HALF_UP=4,J.ROUND_HALF_DOWN=5,J.ROUND_HALF_EVEN=6,J.ROUND_HALF_CEIL=7,J.ROUND_HALF_FLOOR=8,J.EUCLID=9,J.config=J.set=Qt5,J.clone=OAA,J.isDecimal=EAA,J.abs=ds5,J.acos=cs5,J.acosh=ls5,J.add=is5,J.asin=ns5,J.asinh=as5,J.atan=os5,J.atanh=rs5,J.atan2=ss5,J.cbrt=ts5,J.ceil=es5,J.clamp=At5,J.cos=Bt5,J.cosh=$t5,J.div=Jt5,J.exp=Yt5,J.floor=Zt5,J.hypot=Xt5,J.ln=Ft5,J.log=Dt5,J.log10=Vt5,J.log2=Gt5,J.max=Ut5,J.min=Kt5,J.mod=Et5,J.mul=Wt5,J.pow=Ht5,J.random=zt5,J.round=qt5,J.sign=Nt5,J.sin=It5,J.sinh=wt5,J.sqrt=Ct5,J.sub=Mt5,J.sum=Lt5,J.tan=Ot5,J.tanh=jt5,J.trunc=Rt5,A===void 0)A={};if(A){if(A.defaults!==!0){$=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"];for(Q=0;Q<$.length;)if(!A.hasOwnProperty(B=$[Q++]))A[B]=this[B]}}return J.config(A),J}function Jt5(A,Q){return new this(A).div(Q)}function Yt5(A){return new this(A).exp()}function Zt5(A){return DA(A=new this(A),A.e+1,3)}function Xt5(){var A,Q,B=new this(0);cA=!1;for(A=0;A<arguments.length;)if(Q=new this(arguments[A++]),!Q.d){if(Q.s)return cA=!0,new this(1/0);B=Q}else if(B.d)B=B.plus(Q.times(Q));return cA=!0,B.sqrt()}function EAA(A){return A instanceof ht||A&&A.toStringTag===qAA||!1}function Ft5(A){return new this(A).ln()}function Dt5(A,Q){return new this(A).log(Q)}function Gt5(A){return new this(A).log(2)}function Vt5(A){return new this(A).log(10)}function Ut5(){return CAA(this,arguments,-1)}function Kt5(){return CAA(this,arguments,1)}function Et5(A,Q){return new this(A).mod(Q)}function Wt5(A,Q){return new this(A).mul(Q)}function Ht5(A,Q){return new this(A).pow(Q)}function zt5(A){var Q,B,$,J,Y=0,Z=new this(1),X=[];if(A===void 0)A=this.precision;else _J(A,1,Zw);if($=Math.ceil(A/SA),!this.crypto)for(;Y<$;)X[Y++]=Math.random()*1e7|0;else if(crypto.getRandomValues){Q=crypto.getRandomValues(new Uint32Array($));for(;Y<$;)if(J=Q[Y],J>=4290000000)Q[Y]=crypto.getRandomValues(new Uint32Array(1))[0];else X[Y++]=J%1e7}else if(crypto.randomBytes){Q=crypto.randomBytes($*=4);for(;Y<$;)if(J=Q[Y]+(Q[Y+1]<<8)+(Q[Y+2]<<16)+((Q[Y+3]&127)<<24),J>=2140000000)crypto.randomBytes(4).copy(Q,Y);else X.push(J%1e7),Y+=4;Y=$/4}else throw Error(zAA);if($=X[--Y],A%=SA,$&&A)J=b9(10,SA-A),X[Y]=($/J|0)*J;for(;X[Y]===0;Y--)X.pop();if(Y<0)B=0,X=[0];else{B=-1;for(;X[0]===0;B-=SA)X.shift();for($=1,J=X[0];J>=10;J/=10)$++;if($<SA)B-=SA-$}return Z.e=B,Z.d=X,Z}function qt5(A){return DA(A=new this(A),A.e+1,this.rounding)}function Nt5(A){return A=new this(A),A.d?A.d[0]?A.s:0*A.s:A.s||NaN}function It5(A){return new this(A).sin()}function wt5(A){return new this(A).sinh()}function Ct5(A){return new this(A).sqrt()}function Mt5(A,Q){return new this(A).sub(Q)}function Lt5(){var A=0,Q=arguments,B=new this(Q[A]);cA=!1;for(;B.s&&++A<Q.length;)B=B.plus(Q[A]);return cA=!0,DA(B,this.precision,this.rounding)}function Ot5(A){return new this(A).tan()}function jt5(A){return new this(A).tanh()}function Rt5(A){return DA(A=new this(A),A.e+1,1)}m1[Symbol.for("nodejs.util.inspect.custom")]=m1.toString;m1[Symbol.toStringTag]="Decimal";var ht=m1.constructor=OAA(D81);HU0=new ht(HU0);zU0=new ht(zU0);var K81=2;function Pt5(A,Q){let B=Q.decimalPlaces==="more-if-tiny"?Math.abs(A)<0.01?K81+1:K81:Q.decimalPlaces??K81,$=Q.intent==="balance"?A<0?"expand":"trunc":"halfExpand";return{decimalPlaces:B,roundingMode:$}}function Xw(A,Q){let{decimalPlaces:B,roundingMode:$}=Pt5(A,Q),J=A%1===0&&!Q.alwaysShowCents?A.toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:0,roundingMode:$}):A.toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:B,maximumFractionDigits:B,roundingMode:$});return Q.includeCurrencyCode?`${J} USD`:J}function gt(A){if(A>=1e6)return`${Math.round(A/1e6)}M`;if(A>=1000)return`${Math.round(A/1000)}k`;return A.toString()}function _t5(A){if(!A)return"";let Q=A.split("-");if(Q.length>=2)return Q.slice(0,2).join("-");return A}function jAA(A){let Q=[],B=(A.inputTokens??0)+(A.cacheCreationInputTokens??0),$=A.cacheReadInputTokens??0;if(B>0)Q.push(`${gt(B)} in`);if($>0)Q.push(`${gt($)} cache read`);if(A.outputTokens)Q.push(`${gt(A.outputTokens)} out`);if(A.model)Q.push(_t5(A.model));if(Q.length>0)return`(${Q.join(", ")})`;return""}function Fw(A,Q){let{colors:B,dim:$}=Q,J=[];if(A.totalCostUSD===null)return J;let Y=A.costBreakdown,Z=Y?.freeUSD??0,X=Y?.paidUSD??0;if(Z===0&&X===0)return J;let D={decimalPlaces:"more-if-tiny",intent:"cost"};if(X===0)J.push(new M(Xw(Z,D),new y({color:B.foreground,dim:$}))),J.push(new M(" (free)",new y({color:B.foreground,dim:$})));else if(Z>0)J.push(new M(Xw(Z,D),new y({color:B.foreground,dim:$}))),J.push(new M(" (free)",new y({color:B.foreground,dim:$}))),J.push(new M(" + ",new y({color:B.foreground,dim:$}))),J.push(new M(Xw(X,D),new y({color:B.foreground,dim:$,bold:!$})));else J.push(new M(Xw(X,D),new y({color:B.foreground,dim:$,bold:!$})));return J}class E81 extends a4{}class W81 extends a4{}function Tt5(A,Q){if(Q.code==="auth-required")return"You must be logged in to view thread usage. Run `amp login` first.";if(Q.code==="thread-not-found")return`Thread ${A} not found.`;return`Failed to load thread usage: ${Q.message??Q.code}`}function St5(A,Q){let B=_0.of(Q),{colors:$}=B,J=Fw(A,{colors:{foreground:$.foreground}}),Y=[];if(J.length>0)Y.push(new M("Total: ",new y({color:$.mutedForeground}))),Y.push(...J);else if(A.totalCostUSD===null)Y.push(new M("Usage information is currently unavailable."));else Y.push(new M("No usage recorded for this thread yet."));if(A.costBreakdownURL)Y.push(new M(`
5382
5382
 
5383
5383
  `)),Y.push(new M("Details: ",new y({color:$.mutedForeground}))),Y.push(new M(A.costBreakdownURL,new y({color:B.app.link})));return new l({text:new M("",void 0,Y)})}function kt5(A,Q,B){let $=St5(A,Q);if(!A.costBreakdownURL)return new TA({header:"Thread Cost",minWidth:80,maxWidth:100,onDismiss:B,child:$});let J=A.costBreakdownURL,Y=new G4(()=>{return FA.maybeInvoke(Q,new Y$(J,"Cost breakdown URL copied to clipboard","Failed to copy cost breakdown URL")),"handled"}),Z=new G4(()=>{return K6(Q,J),"handled"});return new TA({header:"Thread Cost",minWidth:80,maxWidth:100,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["o"],label:"open in browser"},{keys:["y"],label:"copy url"}],onDismiss:B,child:new FA({actions:new Map([[E81,Y],[W81,Z]]),child:new h5({debugLabel:"ThreadCostShortcuts",shortcuts:new Map([[v1.key("o"),new W81],[v1.key("y"),new E81]]),child:new m4({autofocus:!0,debugLabel:"ThreadCostBody",child:$})})})})}function RAA(A){return{noun:"thread",verb:"show cost",description:"Show usage cost for the active thread",keywords:["usage","credits","billing","spend"],get status(){return A.getActiveThreadID()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(Q,B,$)=>{let J=A.getActiveThreadID();if(!J)return;try{let Y=await VA.threadDisplayCostInfo({threadID:J},{config:A.configService});if(!Y.ok){A.toastController.show(Tt5(J,Y.error),"error",5000),$();return}Q.push(kt5(Y.result,B,$))}catch(Y){j.error("Failed to load Neo thread cost",{error:Y,threadID:J}),A.toastController.show(`Failed to show thread cost: ${Y instanceof Error?Y.message:String(Y)}`,"error",5000),$()}}}}var vt5=250,yt5=2000;function xt5({ampURL:A,threadID:Q,logPath:B}){return[`Debug thread ${_B(new URL(A),Q).toString()} (cli log: ${B}). Start with the CLI log, actor logs, and Rivet DB/inspector as sources of truth. Read thread-actors/docs/debugging-actors.md and thread-actors/scripts/README.md. For dev, actor logs are in .amp/in/thread-actors.json.log; for staging/prod, logs are in gcloud.`,"","Problem: "].join(`
5384
- `)}class H81 extends v0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;showNeoWelcome;onNeoWelcomeDismissed;notificationService;onThreadArchived;initialUserInput;openThreadPickerOnStart;neoContext;constructor(A){super();this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.initialThreadID=A.initialThreadID,this.showNeoWelcome=A.showNeoWelcome??!1,this.onNeoWelcomeDismissed=A.onNeoWelcomeDismissed,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.initialUserInput=A.initialUserInput,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new _AA}}class _AA extends k0{editorController=new I8;commandPalette=new ws(this);commandRegistry=new S51;toastController=new U41;exitHintTimer=new kf(this,1000);ideStatus=new x8(this,{});threadNavigationHistory=new O51;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;pluginIntegration=null;configReloadSubscription=null;configReloadToastTimer=null;pendingConfigReloadToastType=null;lastConfigReloadToast=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.connectToExistingThread(A,{recordNavigation:!0})};sendFeedbackReport=async(A)=>pe4({configService:this.widget.configService,settingsFilePath:this.widget.neoContext.settingsFilePath},A);setThreadVisibility=(A,Q)=>{return de4({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await co4({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await lo4({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 io4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(eB.getInstance().interceptConsole(),this.widget.showNeoWelcome)this.neoWelcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:Q,error:B})=>{if(j.error("Neo failed to connect to thread",{threadID:Q,error:B}),!Q)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configReloadSubscription=this.widget.configService.configReloadEvents.subscribe((Q)=>this.scheduleConfigReloadToast(Q)),this.configSubscription=this.widget.configService.config.subscribe((Q)=>{this.applyDraftThreadSettingsSeed(R80(Q.settings))}),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID){let Q={};if(A)Q.initialUserInput=A;this.connectToExistingThread(this.widget.initialThreadID,Q)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.pluginIntegration=new M51({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=R4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}scheduleConfigReloadToast(A){if(this.pendingConfigReloadToastType=this.pendingConfigReloadToastType==="failed"||A.type==="failed"?"failed":"succeeded",this.configReloadToastTimer)clearTimeout(this.configReloadToastTimer);this.configReloadToastTimer=setTimeout(()=>{this.flushConfigReloadToast()},vt5),this.configReloadToastTimer.unref()}flushConfigReloadToast(){let A=this.pendingConfigReloadToastType;if(this.pendingConfigReloadToastType=null,this.configReloadToastTimer=null,!A)return;let Q=Date.now();if(this.lastConfigReloadToast?.type===A&&Q-this.lastConfigReloadToast.shownAt<yt5)return;switch(this.lastConfigReloadToast={type:A,shownAt:Q},A){case"succeeded":this.toastController.show("Config reloaded","success",1500);break;case"failed":this.toastController.show("Config reload failed","error",5000);break}}registerAppCommands(){let A=this,Q=this.widget.neoContext.pluginService?ue4({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,logFilePath:this.widget.neoContext.logFilePath,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)=>v31({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()}},RAA({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(J,Y,Z)=>{A.navigateForward(),Z()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new m51({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 B81({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 K6(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:()=>{LJ(this.widget.neoContext.settingsFilePath).catch((J)=>{j.error("Failed to open settings file in editor",{error:J})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(J,Y,Z)=>{J.pushWithDismiss((X)=>new h51({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 f51({commands:Z$.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(J,Y,Z)=>{Z(),A.showNeoWelcome()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new TA({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new l({text:new M(Y41({version:"0.0.1777967145-g633c91",buildTimestamp:"2026-05-05T07:49:26.158Z",buildType:"'release'"}))})}))}},{noun:"amp",verb:"reconnect",description:"Disconnect and reconnect the active thread",keywords:["connection","disconnect","socket","debug"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: reconnect with no active thread"}},run:(J,Y,Z)=>{A.reconnectActiveThread(),Z()}},{noun:"amp",verb:"disconnect",description:"Disconnect the active thread without reconnecting",keywords:["connection","socket","debug","dev"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: disconnect with no active thread"}},run:(J,Y,Z)=>{A.disconnectActiveThread(),Z()}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:v1.ctrl("c"),status:{type:"enabled"},run:(J,Y)=>{FA.maybeInvoke(Y,new Vb)}},...Q,...je4(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 Q81({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,sendFeedbackReport:this.sendFeedbackReport,setThreadVisibility:this.setThreadVisibility,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:B}),J=B4.of(A),Z=[new p0({constraints:M1.tight(J.size.width,J.size.height),child:$})];if(this.commandPalette.isEnabled())Z.push(new c4({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new k51({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)Z.push(v31({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)Z.push(new c4({debugLabel:"NeoWelcomeDialogOverlay",child:new X81({onDismiss:this.dismissNeoWelcome})}));if(Z.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)Z.push(new b51({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:mt.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)Z.push(new u51);return new G2({neoContext:this.widget.neoContext,child:new Z$({commandRegistry:this.commandRegistry,child:new sI({completionBuilder:this.widget.completionBuilder,child:new H3({controller:this.toastController,child:new FA({actions:this.buildActions(),child:new h5({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[v1.ctrl("c"),new hV0],[v1.ctrl("o"),new gV0],[v1.alt("i"),new pV0],[v1.alt("p"),new TI],[v1.ctrl("t"),new dV0]]),child:new m4({debugLabel:"AppShellFocus",child:new K41({controller:this.toastController,child:new t4({children:Z})})})})})})})})})}buildActions(){let A=new G4(()=>{if(MJ.hasAnyCopyableSelection())return MJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new G4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new G4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new G4(()=>{return this.startNewDraftThread(),"handled"}),J=new G4(()=>{return R4.instance.stop(),"handled"}),Y=new G4((V)=>{if(!V.text)return"ignored";return R4.instance.tuiInstance.clipboard.writeText(V.text).then(()=>{this.toastController.show(V.successMessage,"success",2000)}).catch((U)=>{j.error("Failed to copy Neo text to clipboard",{error:U}),this.toastController.show(V.failureMessage,"error",2000)}),"handled"}),Z=new G4(()=>{return R4.instance.toggleFrameStatsOverlay(),"handled"}),X=new G4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),F=new G4(()=>{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 Ne0(V).then((U)=>{this.toastController.show(Kh4(U),"success",2000)}).catch((U)=>{let K=U instanceof Error?U.message:String(U);j.error("Failed to copy thread log",{error:U}),this.toastController.show(`Failed to copy thread log: ${K}`,"error",2000)}),"handled"}),D=new G4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";let V=this.activeThreadContext?.client.getThreadId();if(!V)return"handled";return this.prepareThreadIssueInvestigation(V),"handled"}),G=new G4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[hV0,A],[zt,$],[Vb,J],[Y$,Y],[It,B],[gV0,Q],[pV0,X],[yR,F],[wt,D],[TI,Z],[dV0,G]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.writeTerminalTitle(void 0),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),A.prompt!==void 0)this.editorController.text=A.prompt}prepareThreadIssueInvestigation(A){try{let Q=Fr(A);this.startNewDraftThread({prompt:xt5({ampURL:this.widget.neoContext.ampURL,threadID:A,logPath:Q.sourcePath}),hideDebugOverlay:!0})}catch(Q){j.error("Failed to prepare thread issue investigation",{error:Q,threadID:A})}}closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=oD0(await wf(this.widget.configService),{agentMode:this.widget.neoContext.sessionAgentMode,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext});this.applyDraftThreadSettingsSeed(A)}catch(A){j.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=PAA(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(nZ(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=PAA(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(rI);if(this.exitHintTimer.isActive())A.add(Yb);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),R4.instance.stop();else this.exitHintTimer.activate()};dismissNeoWelcome=()=>{if(!this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!1}),this.widget.onNeoWelcomeDismissed?.()};showNeoWelcome=()=>{if(this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!0})};closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,B=null)=>{await this.ensureDraftThreadSettingsInitialized();let $=this.activeThreadContext?.client.getThreadId(),J=A.find((Z)=>Z.type==="text");if(J&&J.type==="text")this.widget.history.add(J.text,mt.cwd()),this.widget.history.reset();let Y=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,B?QZ(B):void 0);this.sendUserMessage(Y,A,Q),this.threadNavigationHistory.recordNavigation($),this.setActiveClient(Y)};sendUserMessage(A,Q,B){let $=HZ0(this.ideStatus.getValue());A.client.sendUserMessage(Q,B,{userState:$})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};appendPluginMessagesToThread=async(A,Q)=>{let B=this.activeThreadContext;if(!B)throw Error("appendToThread is not available - no active thread");let $=B.client.getThreadId();if(Q&&$!==Q)throw Error("thread.append is only available for the active executor thread");for(let J of A)this.sendUserMessage(B,[{type:"text",text:J.content}])};async connectToExistingThread(A,Q={}){let B=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let $=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly});if(this.setActiveClient($),Q.recordNavigation&&B!==A)this.threadNavigationHistory.recordNavigation(B);if(Q.initialUserInput)this.sendUserMessage($,[{type:"text",text:Q.initialUserInput}])}catch($){if(j.error("Failed to load thread",{error:$,threadID:A}),this.toastController.show(`Failed to load ${A}: ${$ instanceof Error?$.message:String($)}`,"error",4000),Q.rethrowError)throw $}finally{this.setState(()=>{this.connectingToThreadID=null})}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}async reconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to reconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Reconnecting ${Q}...`:"Reconnecting thread...","warning",60000);try{let $=await this.widget.clientPool.reconnectClient(A.client);this.toastController.update(B,`Reconnected ${$}`,"success",2000)}catch($){j.error("Failed to reconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Reconnect failed: ${J}`,"error",4000)}}async disconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to disconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Disconnecting ${Q}...`:"Disconnecting thread...","warning",60000);try{let $=await this.widget.clientPool.disconnectClient(A.client);this.toastController.update(B,`Disconnected ${$}`,"success",2000)}catch($){j.error("Failed to disconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Disconnect failed: ${J}`,"error",4000)}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q},this.subscribeTitleUpdates(Q),this.subscribeNotifications(Q)})}subscribeTitleUpdates(A){this.titleSubscription?.unsubscribe(),this.titleSubscription=A.title().subscribe({next:(Q)=>{this.writeTerminalTitle(Q)}})}subscribeNotifications(A){this.widget.notificationService.attach(A.agentState())}writeTerminalTitle(A){let Q=mt.cwd().replace(mt.env.HOME||"","~"),B=A?`amp - ${A} - ${Q}`:"";mt.stdout.write(II(B))}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){j.error("Failed to connect to IDE",{error:Q});let B=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${B}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.titleSubscription?.unsubscribe(),this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.configReloadSubscription?.unsubscribe(),this.configReloadSubscription=null,this.configReloadToastTimer)clearTimeout(this.configReloadToastTimer),this.configReloadToastTimer=null;this.pendingConfigReloadToastType=null,this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.neoWelcomeVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function PAA(A,Q,B){let $={...A};for(let J of ft5(Q,B)){if(!nZ(A[J],Q[J]))continue;let Y=B[J];if(Y===void 0)delete $[J];else $[J]=Y}return $}function ft5(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}d4();function TAA(A,Q,B,$){let J=CS(A),Y="\x1B[0m",Z="\x1B[34m",X="\x1B[90m",F="\x1B[2m",D=[];if(A.archived)D.push("\x1B[90m\x1B[2mArchived\x1B[0m");D.push(`${J}`),D.push(`\x1B[34m${Q}\x1B[0m`),D.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let G=14,V=7,U=new oY(G,V),K=new T9(42),E=new MI(G,V,G,V,G,V,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,H0.default(),K);E.layout(M1.tight(G,V)),E.paint(U,0,0);let W=U.getBuffer().getCells(),H=0;for(let _=0;_<V;_++)if(W[_].some((S)=>S.char!==" ")){H=_;break}let z=V-1;for(let _=V-1;_>=0;_--)if(W[_].some((S)=>S.char!==" ")){z=_;break}function q(_,S){if(!_)return"";if(_.type==="rgb"){let{r:T,g:b,b:h}=_.value;if(B.getColorDepth()>=24)return`\x1B[${S?38:48};2;${T};${b};${h}m`;let x=sj(T,b,h);return`\x1B[${S?38:48};5;${x}m`}return""}let N=[];if(z>=H)for(let _=H;_<=z;_++){let S="";for(let T=0;T<G;T++){let b=W[_][T],h=b.char,x=q(b.style.fg,!0);S+=x+h+"\x1B[0m"}N.push(S)}let I=N.length,w=Math.max(I,D.length),C=Math.floor((w-I)/2),O=Math.floor((w-D.length)/2);for(let _=0;_<w;_++){let S=" ".repeat(G);if(_>=C&&_<C+I)S=N[_-C];let T=" ",b="";if(_>=O&&_<O+D.length)b=D[_-O];B.write(S+T+b+`
5384
+ `)}class H81 extends v0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;showNeoWelcome;onNeoWelcomeDismissed;notificationService;onThreadArchived;initialUserInput;openThreadPickerOnStart;neoContext;constructor(A){super();this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.initialThreadID=A.initialThreadID,this.showNeoWelcome=A.showNeoWelcome??!1,this.onNeoWelcomeDismissed=A.onNeoWelcomeDismissed,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.initialUserInput=A.initialUserInput,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new _AA}}class _AA extends k0{editorController=new I8;commandPalette=new ws(this);commandRegistry=new S51;toastController=new U41;exitHintTimer=new kf(this,1000);ideStatus=new x8(this,{});threadNavigationHistory=new O51;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;pluginIntegration=null;configReloadSubscription=null;configReloadToastTimer=null;pendingConfigReloadToastType=null;lastConfigReloadToast=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.connectToExistingThread(A,{recordNavigation:!0})};sendFeedbackReport=async(A)=>pe4({configService:this.widget.configService,settingsFilePath:this.widget.neoContext.settingsFilePath},A);setThreadVisibility=(A,Q)=>{return de4({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await co4({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await lo4({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 io4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(eB.getInstance().interceptConsole(),this.widget.showNeoWelcome)this.neoWelcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:Q,error:B})=>{if(j.error("Neo failed to connect to thread",{threadID:Q,error:B}),!Q)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configReloadSubscription=this.widget.configService.configReloadEvents.subscribe((Q)=>this.scheduleConfigReloadToast(Q)),this.configSubscription=this.widget.configService.config.subscribe((Q)=>{this.applyDraftThreadSettingsSeed(R80(Q.settings))}),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID){let Q={};if(A)Q.initialUserInput=A;this.connectToExistingThread(this.widget.initialThreadID,Q)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.pluginIntegration=new M51({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=R4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}scheduleConfigReloadToast(A){if(this.pendingConfigReloadToastType=this.pendingConfigReloadToastType==="failed"||A.type==="failed"?"failed":"succeeded",this.configReloadToastTimer)clearTimeout(this.configReloadToastTimer);this.configReloadToastTimer=setTimeout(()=>{this.flushConfigReloadToast()},vt5),this.configReloadToastTimer.unref()}flushConfigReloadToast(){let A=this.pendingConfigReloadToastType;if(this.pendingConfigReloadToastType=null,this.configReloadToastTimer=null,!A)return;let Q=Date.now();if(this.lastConfigReloadToast?.type===A&&Q-this.lastConfigReloadToast.shownAt<yt5)return;switch(this.lastConfigReloadToast={type:A,shownAt:Q},A){case"succeeded":this.toastController.show("Config reloaded","success",1500);break;case"failed":this.toastController.show("Config reload failed","error",5000);break}}registerAppCommands(){let A=this,Q=this.widget.neoContext.pluginService?ue4({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,logFilePath:this.widget.neoContext.logFilePath,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)=>v31({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()}},RAA({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(J,Y,Z)=>{A.navigateForward(),Z()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new m51({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 B81({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 K6(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:()=>{LJ(this.widget.neoContext.settingsFilePath).catch((J)=>{j.error("Failed to open settings file in editor",{error:J})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(J,Y,Z)=>{J.pushWithDismiss((X)=>new h51({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 f51({commands:Z$.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(J,Y,Z)=>{Z(),A.showNeoWelcome()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new TA({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new l({text:new M(Y41({version:"0.0.1777970347-gc2d807",buildTimestamp:"2026-05-05T08:42:39.004Z",buildType:"'release'"}))})}))}},{noun:"amp",verb:"reconnect",description:"Disconnect and reconnect the active thread",keywords:["connection","disconnect","socket","debug"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: reconnect with no active thread"}},run:(J,Y,Z)=>{A.reconnectActiveThread(),Z()}},{noun:"amp",verb:"disconnect",description:"Disconnect the active thread without reconnecting",keywords:["connection","socket","debug","dev"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: disconnect with no active thread"}},run:(J,Y,Z)=>{A.disconnectActiveThread(),Z()}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:v1.ctrl("c"),status:{type:"enabled"},run:(J,Y)=>{FA.maybeInvoke(Y,new Vb)}},...Q,...je4(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 Q81({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,sendFeedbackReport:this.sendFeedbackReport,setThreadVisibility:this.setThreadVisibility,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:B}),J=B4.of(A),Z=[new p0({constraints:M1.tight(J.size.width,J.size.height),child:$})];if(this.commandPalette.isEnabled())Z.push(new c4({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new k51({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)Z.push(v31({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)Z.push(new c4({debugLabel:"NeoWelcomeDialogOverlay",child:new X81({onDismiss:this.dismissNeoWelcome})}));if(Z.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)Z.push(new b51({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:mt.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)Z.push(new u51);return new G2({neoContext:this.widget.neoContext,child:new Z$({commandRegistry:this.commandRegistry,child:new sI({completionBuilder:this.widget.completionBuilder,child:new H3({controller:this.toastController,child:new FA({actions:this.buildActions(),child:new h5({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[v1.ctrl("c"),new hV0],[v1.ctrl("o"),new gV0],[v1.alt("i"),new pV0],[v1.alt("p"),new TI],[v1.ctrl("t"),new dV0]]),child:new m4({debugLabel:"AppShellFocus",child:new K41({controller:this.toastController,child:new t4({children:Z})})})})})})})})})}buildActions(){let A=new G4(()=>{if(MJ.hasAnyCopyableSelection())return MJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new G4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new G4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new G4(()=>{return this.startNewDraftThread(),"handled"}),J=new G4(()=>{return R4.instance.stop(),"handled"}),Y=new G4((V)=>{if(!V.text)return"ignored";return R4.instance.tuiInstance.clipboard.writeText(V.text).then(()=>{this.toastController.show(V.successMessage,"success",2000)}).catch((U)=>{j.error("Failed to copy Neo text to clipboard",{error:U}),this.toastController.show(V.failureMessage,"error",2000)}),"handled"}),Z=new G4(()=>{return R4.instance.toggleFrameStatsOverlay(),"handled"}),X=new G4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),F=new G4(()=>{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 Ne0(V).then((U)=>{this.toastController.show(Kh4(U),"success",2000)}).catch((U)=>{let K=U instanceof Error?U.message:String(U);j.error("Failed to copy thread log",{error:U}),this.toastController.show(`Failed to copy thread log: ${K}`,"error",2000)}),"handled"}),D=new G4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";let V=this.activeThreadContext?.client.getThreadId();if(!V)return"handled";return this.prepareThreadIssueInvestigation(V),"handled"}),G=new G4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[hV0,A],[zt,$],[Vb,J],[Y$,Y],[It,B],[gV0,Q],[pV0,X],[yR,F],[wt,D],[TI,Z],[dV0,G]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.writeTerminalTitle(void 0),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),A.prompt!==void 0)this.editorController.text=A.prompt}prepareThreadIssueInvestigation(A){try{let Q=Fr(A);this.startNewDraftThread({prompt:xt5({ampURL:this.widget.neoContext.ampURL,threadID:A,logPath:Q.sourcePath}),hideDebugOverlay:!0})}catch(Q){j.error("Failed to prepare thread issue investigation",{error:Q,threadID:A})}}closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=oD0(await wf(this.widget.configService),{agentMode:this.widget.neoContext.sessionAgentMode,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext});this.applyDraftThreadSettingsSeed(A)}catch(A){j.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=PAA(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(nZ(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=PAA(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(rI);if(this.exitHintTimer.isActive())A.add(Yb);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),R4.instance.stop();else this.exitHintTimer.activate()};dismissNeoWelcome=()=>{if(!this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!1}),this.widget.onNeoWelcomeDismissed?.()};showNeoWelcome=()=>{if(this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!0})};closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,B=null)=>{await this.ensureDraftThreadSettingsInitialized();let $=this.activeThreadContext?.client.getThreadId(),J=A.find((Z)=>Z.type==="text");if(J&&J.type==="text")this.widget.history.add(J.text,mt.cwd()),this.widget.history.reset();let Y=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,B?QZ(B):void 0);this.sendUserMessage(Y,A,Q),this.threadNavigationHistory.recordNavigation($),this.setActiveClient(Y)};sendUserMessage(A,Q,B){let $=HZ0(this.ideStatus.getValue());A.client.sendUserMessage(Q,B,{userState:$})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};appendPluginMessagesToThread=async(A,Q)=>{let B=this.activeThreadContext;if(!B)throw Error("appendToThread is not available - no active thread");let $=B.client.getThreadId();if(Q&&$!==Q)throw Error("thread.append is only available for the active executor thread");for(let J of A)this.sendUserMessage(B,[{type:"text",text:J.content}])};async connectToExistingThread(A,Q={}){let B=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let $=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly});if(this.setActiveClient($),Q.recordNavigation&&B!==A)this.threadNavigationHistory.recordNavigation(B);if(Q.initialUserInput)this.sendUserMessage($,[{type:"text",text:Q.initialUserInput}])}catch($){if(j.error("Failed to load thread",{error:$,threadID:A}),this.toastController.show(`Failed to load ${A}: ${$ instanceof Error?$.message:String($)}`,"error",4000),Q.rethrowError)throw $}finally{this.setState(()=>{this.connectingToThreadID=null})}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}async reconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to reconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Reconnecting ${Q}...`:"Reconnecting thread...","warning",60000);try{let $=await this.widget.clientPool.reconnectClient(A.client);this.toastController.update(B,`Reconnected ${$}`,"success",2000)}catch($){j.error("Failed to reconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Reconnect failed: ${J}`,"error",4000)}}async disconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to disconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Disconnecting ${Q}...`:"Disconnecting thread...","warning",60000);try{let $=await this.widget.clientPool.disconnectClient(A.client);this.toastController.update(B,`Disconnected ${$}`,"success",2000)}catch($){j.error("Failed to disconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Disconnect failed: ${J}`,"error",4000)}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q},this.subscribeTitleUpdates(Q),this.subscribeNotifications(Q)})}subscribeTitleUpdates(A){this.titleSubscription?.unsubscribe(),this.titleSubscription=A.title().subscribe({next:(Q)=>{this.writeTerminalTitle(Q)}})}subscribeNotifications(A){this.widget.notificationService.attach(A.agentState())}writeTerminalTitle(A){let Q=mt.cwd().replace(mt.env.HOME||"","~"),B=A?`amp - ${A} - ${Q}`:"";mt.stdout.write(II(B))}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){j.error("Failed to connect to IDE",{error:Q});let B=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${B}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.titleSubscription?.unsubscribe(),this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.configReloadSubscription?.unsubscribe(),this.configReloadSubscription=null,this.configReloadToastTimer)clearTimeout(this.configReloadToastTimer),this.configReloadToastTimer=null;this.pendingConfigReloadToastType=null,this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.neoWelcomeVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function PAA(A,Q,B){let $={...A};for(let J of ft5(Q,B)){if(!nZ(A[J],Q[J]))continue;let Y=B[J];if(Y===void 0)delete $[J];else $[J]=Y}return $}function ft5(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}d4();function TAA(A,Q,B,$){let J=CS(A),Y="\x1B[0m",Z="\x1B[34m",X="\x1B[90m",F="\x1B[2m",D=[];if(A.archived)D.push("\x1B[90m\x1B[2mArchived\x1B[0m");D.push(`${J}`),D.push(`\x1B[34m${Q}\x1B[0m`),D.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let G=14,V=7,U=new oY(G,V),K=new T9(42),E=new MI(G,V,G,V,G,V,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,H0.default(),K);E.layout(M1.tight(G,V)),E.paint(U,0,0);let W=U.getBuffer().getCells(),H=0;for(let _=0;_<V;_++)if(W[_].some((S)=>S.char!==" ")){H=_;break}let z=V-1;for(let _=V-1;_>=0;_--)if(W[_].some((S)=>S.char!==" ")){z=_;break}function q(_,S){if(!_)return"";if(_.type==="rgb"){let{r:T,g:b,b:h}=_.value;if(B.getColorDepth()>=24)return`\x1B[${S?38:48};2;${T};${b};${h}m`;let x=sj(T,b,h);return`\x1B[${S?38:48};5;${x}m`}return""}let N=[];if(z>=H)for(let _=H;_<=z;_++){let S="";for(let T=0;T<G;T++){let b=W[_][T],h=b.char,x=q(b.style.fg,!0);S+=x+h+"\x1B[0m"}N.push(S)}let I=N.length,w=Math.max(I,D.length),C=Math.floor((w-I)/2),O=Math.floor((w-D.length)/2);for(let _=0;_<w;_++){let S=" ".repeat(G);if(_>=C&&_<C+I)S=N[_-C];let T=" ",b="";if(_>=O&&_<O+D.length)b=D[_-O];B.write(S+T+b+`
5385
5385
  `)}if($)B.write(`
5386
5386
  \x1B[90m${$}\x1B[0m
5387
5387
  `)}o0();YG0();var bt5=2000;function SAA(A){let Q=!0,B=!0,$=A.configService.config.subscribe((V)=>{Q=V.settings["notifications.enabled"]??!0,B=V.settings["notifications.system.enabled"]!==!1}),J=0,Y=(V)=>{if(!Q)return;let U=Date.now();if(U-J<bt5)return;if(J=U,JR())return;if($D0())JD0();else Bo(V)},Z=(V)=>{if(!Q||!B)return;if(JR()&&!Ks()&&!Uf())return;process.stdout.write(oD(`\x1B]777;notify;Amp;${V}\x1B\\`))},X=null,F=null,D=()=>{X?.unsubscribe(),X=null,F=null};return{attach:(V)=>{D(),X=V.subscribe({next:(U)=>{try{let K=F!==null&&sB(F),E=F==="awaiting_approval";if(U==="awaiting_approval"&&!E)Y("requires-user-input"),Z("Waiting for approval");else if((U==="idle"||U==="error")&&(K||E))Y("idle"),Z("Agent is ready")}catch(K){j.debug("Neo notification handling failed",{error:K})}finally{F=U}},error:(U)=>{j.debug("Neo notification agent state stream errored",{error:U})}})},detach:D,unsubscribe(){D(),$.unsubscribe()}}}o0();CE();e1();O1();function kAA(A,Q){if(!Q)return A;let B=Q.toLowerCase(),$=[];for(let J of A){let Y=ut5(J,B);if(Y>0)$.push({...J,score:Y})}return $.sort((J,Y)=>{let Z=Y.score-J.score;if(Z!==0)return Z;return A.indexOf(J)-A.indexOf(Y)}),$}function ut5(A,Q){let B=ht5(A,Q),$=gt5(A.message.toLowerCase(),Q);return Math.max(B,$)}function ht5(A,Q){let B=A.hash.toLowerCase(),$=A.shortHash.toLowerCase();if($===Q)return 1000;if($.startsWith(Q))return 900;if(B.startsWith(Q))return 850;if(B.includes(Q)||$.includes(Q))return 400;return 0}function gt5(A,Q){if(A===Q)return 800;if(A.startsWith(Q))return 700;let B=A.indexOf(Q);if(B!==-1)return 600-Math.min(B,500);let $=mt5(A,Q);if($>0)return $;return 0}function mt5(A,Q){let B=0,$=0,J=-1;while(B<A.length&&$<Q.length){if(A[B]===Q[$]){if(J===-1)J=B;$++}B++}if($===Q.length)return 250-Math.min(J,150);return 0}var vAA=":";function mR(A,Q){if(!dj())return;j.debug("[file mention completions]",{event:A,...Q})}function Ob(A){return A.length<=80?A:`${A.slice(0,77)}...`}class pR{fuzzyClient;cachedDirtyFiles=[];cachedCommits=[];refreshPromise;refreshCommitsPromise;constructor(A){this.fuzzyClient=A;this.refreshDirtyFilesInBackground(),this.refreshCommitsInBackground()}async buildOptions(A){if(A.trigger==="@"){let Q=A.query;if(Q.toLowerCase().startsWith(vAA)){let Z=Q.slice(vAA.length);return mR("commit_query_detected",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:Z.length,queryPreview:Ob(Z)}),this.buildCommitOptions(Z)}let $=Q.length===0?18:20,J=await this.buildFileOptions(Q,$),Y=this.appendHintOptions(Q,J);return mR("build_options_completed",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:Q.length,queryPreview:Ob(Q),maxResults:$,fileOptionCount:J.filter((Z)=>Z.type==="file").length,hintOptionCount:Y.filter((Z)=>Z.type==="hint").length,finalOptionCount:Y.length,firstFilePaths:Y.filter((Z)=>Z.type==="file").slice(0,5).map((Z)=>Z.path)}),Y}return[]}async buildFileOptions(A,Q){try{let B=await this.getOpenFiles(),$=this.cachedDirtyFiles;this.refreshDirtyFilesInBackground();let J=await this.fuzzyClient.queryCompletions(A,Q,B,$),Y=J.map((Z)=>l0A(Z));return mR("file_options_built",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:Ob(A),maxResults:Q,openFilesCount:B?.length??0,dirtyFilesCount:$.length,completionItemCount:J.length,fileOptionCount:Y.length,firstPaths:Y.slice(0,5).map((Z)=>Z.path)}),Y}catch(B){return mR("file_options_failed",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:Ob(A),maxResults:Q,error:B instanceof Error?B.message:String(B)}),[]}}async getOpenFiles(){let A=await x1(f3.status);if(!A.connected)return;let Q=[];if(A.openFile)Q.push(e0.parse(A.openFile).fsPath);if(A.visibleFiles)for(let B of A.visibleFiles){let $=e0.parse(B).fsPath;if(!Q.includes($))Q.push($)}if(Q.length===0)return;return Q}refreshDirtyFilesInBackground(){if(this.refreshPromise!==void 0)return;this.refreshPromise=SR4(this.fuzzyClient.workspaceRoot).then((A)=>{this.cachedDirtyFiles=A}).catch(()=>{}).finally(()=>{this.refreshPromise=void 0})}async buildCommitOptions(A){this.refreshCommitsInBackground();let Q=this.cachedCommits;if(!Q.length)return mR("commit_options_empty_cache",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:Ob(A)}),[];let B=kAA(Q,A).slice(0,20);return mR("commit_options_built",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:Ob(A),commitCacheCount:Q.length,resultCount:B.length,firstCommitHashes:B.slice(0,5).map(($)=>$.shortHash)}),B.map(($)=>({type:"commit",hash:$.hash,shortHash:$.shortHash,message:$.message,relativeDate:$.relativeDate}))}refreshCommitsInBackground(){if(this.refreshCommitsPromise!==void 0)return;this.refreshCommitsPromise=kR4(this.fuzzyClient.workspaceRoot).then((A)=>{this.cachedCommits=A}).catch(()=>{}).finally(()=>{this.refreshCommitsPromise=void 0})}appendHintOptions(A,Q){if(A.length>0)return Q;let B=[{type:"hint",kind:"commit",message:"mention a commit"},{type:"hint",kind:"thread",message:"mention a thread"}];return mR("hint_options_appended",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,fileOptionCount:Q.filter(($)=>$.type==="file").length,hintOptionCount:B.length,hintOnly:Q.length===0,firstFilePaths:Q.filter(($)=>$.type==="file").slice(0,5).map(($)=>$.path)}),[...Q,...B]}}var dt5=[{long:"neo",description:"Use the Neo TUI",type:"boolean",default:!1},{long:"url",short:"u",description:"Amp server URL",type:"string",default:""},{long:"dangerously-allow-all",description:"Disable all command confirmation prompts (agent will execute all commands without asking)",type:"boolean",default:!1},{long:"observe",description:"Connect to an existing thread as observer only (no local executor). Accepts a thread ID or thread URL.",type:"string",default:""}],IC2=ui4({name:"amp neo",description:"Start the Neo TUI",options:dt5,positionals:[],action:async({options:A})=>{let Q=yAA(A);if(A.observe){let B=y3(A.observe)??pQ(A.observe);await CU0(Q,{initialThreadID:B,observerOnly:!0});return}await CU0(Q)},subcommands:[{name:"threads",alias:"t",description:"List and manage threads",options:[],positionals:[],subcommands:[{name:"continue",alias:"c",description:"Continue an existing thread",options:[],positionals:[{name:"thread-id",description:"Thread ID to continue"}],action:async({globalOptions:A,positionals:Q})=>{let $=yAA(A);if(!Q["thread-id"]){await CU0($,{openThreadPickerOnStart:!0});return}let J=y3(Q["thread-id"]);if(!J)throw"invalid thread ID";await CU0($,{initialThreadID:J})}}]}]});function ct5(A){if(A)return A;if(process.env.AMP_URL)return process.env.AMP_URL;return U9}function lt5(A){if(process.env.RIVET_PUBLIC_ENDPOINT)return process.env.RIVET_PUBLIC_ENDPOINT;return zJ(A)}var xAA=e0.file(pt5.homedir()),it5=process.env.XDG_CONFIG_HOME?e0.file(process.env.XDG_CONFIG_HOME):V1.joinPath(xAA,".config");function nt5({initialUserInput:A,showNeoWelcome:Q,neoWelcomeDismissed:B}){if(Q)return{show:!0,markDismissedOnDismiss:!0};let $=!A&&!B;return{show:$,markDismissedOnDismiss:$}}async function at5(A){await tY((Q)=>tD0(Q,A,"interactive"))}function yAA(A){return{url:A.url,dangerouslyAllowAll:A["dangerously-allow-all"]}}async function CU0(A,Q={}){let{initialThreadID:B,openThreadPickerOnStart:$=!1,observerOnly:J=!1}=Q,Y=ct5(A.url),Z={dataDir:void 0,getHook:(S,T)=>{if(S==="url")return Promise.resolve(Y);return T()}},X=await DD0(Z),F=sD0(await Tr(Z,X)),D=lt5(Y);if(A.dangerouslyAllowAll)jB("dangerouslyAllowAll",!0);let G=await F.get("apiKey",Y);if(!G)throw new r1("API key required. Please run `amp login` first.",1);let V=PS({storage:X,secretStorage:F,workspaceRoot:m0.of(e0.file(process.cwd())),defaultAmpURL:Y,homeDir:xAA,userConfigDir:it5}),U=rL(V,{usesThreadActors:!0}),K=sZ0({configService:V}),E=new If({configService:V});E.pluginExecutorKind="local";let W=kc({configService:V,fileSystem:P5,platform:E,loadGlobalPlugins:jr(V),pluginFilter:"all"}),H=v70({pluginService:W,toolService:K.toolService}),z=ia({configService:V,filesystem:P5,spawn:$x}),q=na({toolService:K.toolService,providers:[z]}),N=kQ0({configService:V,filesystem:P5}),I={registerToolsWithToolService:()=>({dispose:()=>{}}),getClient:()=>{return},servers:m0.of([]),getPrompt:async()=>null,searchResources:async()=>[],searchPrompts:()=>m0.of([]),getToolsForServer:async()=>{return}},w=process.cwd(),C=async({uri:S})=>{return VI({fileSystem:P5,workspaceRoot:w},S)},O=new Zf(w,{},!0),_=new pR(O);await z81({ampURL:Y,apiKey:G,rivetEndpoint:D,configService:V,toolService:K.toolService,pluginPlatform:E,pluginService:W,skillService:N,mcpService:I,readFileSystemDirectory:C,completionBuilder:_,workspaceRoot:w,listThreads:()=>U.listThreads(),getThreadFromServer:(S)=>U.getThread(S),toolboxes:z.toolboxes,isInternalUser:!1,settingsFilePath:X.getSettingsFilePath(),dispose:()=>{for(let S of q.values())S.dispose();return z.dispose(),O.dispose(),H.dispose(),K.dispose(),W.dispose()}},{initialThreadID:B,openThreadPickerOnStart:$,observerOnly:J})}async function z81(A,Q={}){let{initialThreadID:B,initialUserInput:$,openThreadPickerOnStart:J=!1,observerOnly:Y=!1,initialAgentMode:Z,initialReasoningEffort:X,showNeoWelcome:F=!1}=Q,D=async(I)=>{let w=await A.getThreadFromServer(I);if(!w)return null;return gF0(w)},G=async(I)=>{let w=await A.getThreadFromServer(I);if(!w)throw Error(`Thread ${I} not found`);let C=await iY(I,A.configService,A.apiKey,{usesThreadActors:!0}),S=await TU({endpoint:A.rivetEndpoint}).threadActor.getOrCreate([I],{params:{wsToken:C.wsToken},createWithInput:{threadId:C.threadId,threadVersion:C.threadVersion,ownerUserId:C.ownerUserId,...C.agentMode?{agentMode:C.agentMode}:{}}}).fetch("/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({thread:Um4(w)}),skipReadyWait:!0});if(S.ok||S.status===409)return;throw Error(`Thread import failed (${S.status}): ${await S.text()}`)},V=new u11(A.rivetEndpoint,A.apiKey,A.configService,{clientID:DI.parse(`neo-${crypto.randomUUID()}`),toolService:A.toolService,skillService:A.skillService,requestPluginToolCall:(I)=>A.pluginService.event.toolCall(I),requestPluginToolResult:(I)=>A.pluginService.event.toolResult(I),pluginService:A.pluginService,invokeTool:async(I,w)=>{let C=typeof w.args==="object"&&w.args!==null?w.args:{},O=await KI({toolName:w.toolName,configService:A.configService,toolService:A.toolService,mcpService:A.mcpService,skillService:A.skillService,toolUseID:w.toolCallId,threadID:I});return A.toolService.invokeTool(w.toolName,{args:C},O)},persistLastThreadID:at5,readFileSystemDirectory:A.readFileSystemDirectory},D,G),U=await PI(),K=nt5({initialUserInput:$,showNeoWelcome:F,neoWelcomeDismissed:U.neoWelcomeDismissed}),E={ampURL:A.ampURL,configService:A.configService,getThreadMarkdown:async(I)=>{let w=await A.getThreadFromServer(I);return w?fV(w):null},isInternalUser:A.isInternalUser,listThreads:A.listThreads,logFilePath:Xr,mcpServers:A.mcpService.servers,pluginPlatform:A.pluginPlatform,pluginService:A.pluginService,toolboxes:A.toolboxes,observerOnly:Y,sessionAgentMode:Z??U.agentMode,explicitReasoningEffort:X,lastReasoningEffortByMode:U.lastReasoningEffortByMode,settingsFilePath:A.settingsFilePath,splashOrbVisualStyle:Q.splashOrbVisualStyle??"neo",workspaceRoot:A.workspaceRoot},W=(I,w)=>{return Sx({ampURL:A.ampURL,configService:A.configService,threadID:I,signal:w})},H=(I,w)=>{return ll4({ampURL:A.ampURL,configService:A.configService,threadID:I,signal:w})},z=new J41,q=SAA({configService:A.configService}),N=new Set;try{await Es(new H81({clientPool:V,analyzeContextForThread:W,listSkillsForThread:H,completionBuilder:A.completionBuilder,history:new Ir,ideManager:z,configService:A.configService,initialThreadID:B,notificationService:q,initialUserInput:$,openThreadPickerOnStart:J,neoContext:E,showNeoWelcome:K.show,onNeoWelcomeDismissed:K.markDismissedOnDismiss?()=>{tY(ol4).catch((w)=>{j.warn("Failed to mark Neo welcome as dismissed",{error:w})})}:void 0,onThreadArchived:(w)=>{N.add(w)}}));let I=V.lastActiveObservingClient;if(I){let{client:w,observer:C}=I,O=w.getThreadId();if(O){let _={id:O,title:C.title().getValue(),agentMode:C.agentMode,archived:N.has(O)},S=`${A.ampURL.replace(/\/$/,"")}/threads/${O}`;TAA(_,S,process.stdout)}}}finally{process.stdout.write(II("")),q.unsubscribe(),V.dispose(),await A.dispose?.()}process.exit(0)}jd();FE();async function ot5(A,Q,B){let $=U20(A);if(!$.success)throw Error(`Invalid permission format: ${$.error.message}`);if($.data.length===0)throw Error("No permission entry provided");let J=dz($.data);if(!J.success){let F=J.error.issues.map((D)=>D.message).join(", ");throw Error(`Invalid permission entry: ${F}`)}let Y=await Q.get("permissions",B)??[],X=[$.data[0],...Y];await Q.set("permissions",X,B)}async function fAA(A){try{let Q=A.args.map((B)=>{if(/[\s/\\*?[\]{}()"]/.test(B))return`"${B}"`;return B}).join(" ");await ot5(Q,A.settings,A.scope),A.exit(0)}catch(Q){let B=Q instanceof Error?Q.message:"Unknown error";A.stderr.write(`Error: ${B}
@@ -6151,7 +6151,7 @@ ${J}`,Q);this.line=B,this.column=$,this.codeblock=J}}/*!
6151
6151
  `),Y=[];for(let Z=0;Z<J.length;Z++){let D=J[Z].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let G of D)if(G.startsWith("\x00")&&G.endsWith("\x01"))Y.push(new M(G.slice(1,-1),new y({color:$.app.keybind,bold:!0})));else Y.push(new M(G,new y({color:B.colorScheme.foreground})));if(Z<J.length-1)Y.push(new M(`
6152
6152
  `))}return new p0({decoration:{color:B.colorScheme.background,border:i1.all(new n1($.app.keybind,1,"rounded"))},child:new u0({padding:q0.symmetric(0,1),child:new l({text:new M(void 0,void 0,Y)})})})}}class M21 extends e3{chartData;highlightIndex;showAxes;colors;constructor({key:A,chartData:Q,highlightIndex:B=null,showAxes:$=!0,colors:J=yK0}){super(A?{key:A}:{});this.chartData=Q,this.highlightIndex=B,this.showAxes=$,this.colors=J}createRenderObject(){return new w21({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 a3A(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?h8: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?h8: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 s63(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?h8: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?h8: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 t63(A){let Q=0;for(let B of A)for(let $ of B.points)if($.value>Q)Q=$.value;return Q||1}function e63(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 A53(A,Q,B,$,J,Y,Z){let X;try{let E=k1.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 y({color:X.foreground,bold:!0}),D=new y({color:X.foreground}),G=new y({color:X.foreground,dim:!0}),V=[],U=new y({color:X.foreground,underline:!0}),K=(E,W)=>new M(W,U,void 0,CD0(E),()=>{K6(A,E)});if($.length<=1){if(V.push(new M(`${Q.label}: `,F)),Q.link)V.push(K(Q.link,Y(Q.value)));else V.push(new M(Y(Q.value),D));if(Q.meta)V.push(new M(` (${Q.meta})`,G))}else{let E=Z==="stacked-bar"||Z==="stacked-area";V.push(new M(`${Q.label}
6153
6153
  `,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 M("● ",new y({color:N}))),V.push(new M(`${z.name}: `,G)),q.link)V.push(K(q.link,Y(q.value)));else V.push(new M(Y(q.value),D));if(H<$.length-1||E)V.push(new M(`
6154
- `))}if(E)V.push(new M(" ",G)),V.push(new M("Total: ",G)),V.push(new M(Y(W),D))}return new p0({decoration:{color:X.background,border:i1.all(new n1(X.border,1,"rounded"))},child:new l({text:new M(void 0,void 0,V)})})}o0();C3();cz();a8();A3();IQ();rn();S7();r9();n2();kB();xV();d4();zv();iT();O1();o0();r9();class L21{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.1777967145-g633c91"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await C80(Q,this.configService)}catch(Q){j.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class Iw extends v0{props;constructor(A){super();this.props=A}createState(){return new o3A}}class o3A 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 r3A extends k0{controller=new I8;focusNode=new Z6({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=i1.all(new n1(B.foreground,1,"solid")),F=new A$({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(K)=>{let E=K.trim();if(J&&E.length===0)return;this.widget.props.onSubmit(E)},autofocus:!0,style:{textColor:B.foreground,border:null},maxLines:1}),D=new B1({children:[new p0({decoration:{color:B.background},child:new l({text:new M(">",new y({color:B.foreground}))})}),new S1({child:F})]}),G=new p0({padding:q0.symmetric(1,0),child:new l({text:this.widget.props.title?new M(this.widget.props.title,new y({color:$.command,bold:!0})):new M("",void 0,[new M("Command: ",new y({color:B.foreground})),new M(this.widget.props.commandName,new y({color:$.command,bold:!0}))])})}),V=[];if(Z)V.push(new M("Enter",new y({color:$.keybind}))),V.push(new M(" to submit, ",new y({color:B.foreground,dim:!0})));V.push(new M("Esc",new y({color:$.keybind}))),V.push(new M(" to cancel",new y({color:B.foreground,dim:!0})));let U=new p0({padding:q0.symmetric(1,0),child:new l({text:new M("",void 0,V)})});return new p0({decoration:{border:X,color:B.background},padding:q0.all(1),child:new f0({children:[G,new N0({height:1}),D,new Y5,U]})})}}class Je extends v0{props;constructor(A){super();this.props=A}createState(){return new r3A}}kB();class s3A extends k0{controller=new I8;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new Z6({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>=e9)return!1;let Q=await JF(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=B4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),X=new ZG({controller:this.controller,triggers:[new PJ],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:R4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),F=new m4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:X}),D=new p0({constraints:new M1({maxHeight:Z}),padding:q0.symmetric(1,0),child:F}),G=new p0({padding:q0.symmetric(1,0),child:new l({text:new M("",void 0,[new M("Command: ",new y({color:B.foreground})),new M(this.widget.props.commandName,new y({color:$.command,bold:!0}))])})}),V=new p0({padding:q0.symmetric(1,0),child:new l({text:this.isConfirmingClearInput?new M("",void 0,[new M("Esc",new y({color:$.keybind})),new M(" again to clear input",new y({color:B.foreground,dim:!0}))]):new M("",void 0,[new M("Press ",new y({color:B.foreground,dim:!0})),new M("Enter",new y({color:$.keybind})),new M(" to submit, ",new y({color:B.foreground,dim:!0})),new M("Esc",new y({color:$.keybind})),new M(" to clear",new y({color:B.foreground,dim:!0}))])})}),U=[G,new N0({height:1}),new S1({child:D}),new N0({height:1}),V];return new p0({decoration:{border:i1.all(new n1(B.foreground,1,"solid")),color:B.background},padding:q0.all(1),child:new f0({children:U})})}}class O21 extends v0{props;constructor(A){super();this.props=A}createState(){return new s3A}}function t3A(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 j21 extends I1{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)=>t3A(J.pubDate).length));return new p6({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 N0({width:H,child:B1.end([new l({text:new M(W,new y({color:K}))})])});return new p0({decoration:V?{color:V}:void 0,padding:q0.symmetric(2,0),child:new B1({children:[new S1({child:new l({text:new M(J.title,new y({color:U})),overflow:"ellipsis",maxLines:1})}),new N0({width:2}),E(t3A(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()}}o0();class e3A extends k0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){j.error("Failed to load labels",A.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=A.result,this.isLoading=!1,this.setState()}catch(A){j.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let B=this.widget.props.currentLabels||[],$=this.labels.some((Y)=>Y.name===Q),J=B.includes(Q);return!$&&!J}build(A){let Q=_0.of(A),{app:B,colors:$}=Q,J=this.currentQuery.trim().toLowerCase(),Y=J.length>0?this.getValidationError(J):null,Z=this.getAvailableLabels(),F=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...Z];return new p6({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:q0.symmetric(2,0),child:new l({text:new M("",void 0,[new M("Create new label: ",new y({color:E})),new M(H,new y({color:E,bold:!0}))])})})}return new p0({decoration:K?{color:K}:void 0,padding:q0.symmetric(2,0),child:new l({text:new M(D.name,new y({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 R21 extends v0{props;constructor(A){super();this.props=A}createState(){return new e3A}}class DG extends v0{props;constructor(A){super();this.props=A}createState(){return new A8A}}class A8A extends k0{_spinner=new H6;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=i1.all(new n1(B.foreground,1,"solid")),Y=this._spinner.toBraille(),Z=new l({textAlign:"center",text:new M("",void 0,[new M(Y,new y({color:$.processing})),new M(" ",void 0),new M(this.widget.props.message,new y({color:B.foreground}))])}),F=[new S1({child:new f0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)F.push(new N0({height:2,child:new p0({padding:q0.symmetric(2,0),child:new l({text:new M("",new y({dim:!0}),[new M("Press ",new y({color:B.foreground})),new M("Esc",new y({color:B.info})),new M(" to cancel",new y({color:B.foreground}))])})})}));let D=new p0({decoration:new x4(B.background,J),child:new N0({width:60,height:7,child:new f0({mainAxisAlignment:"start",children:F})})});if(this.widget.props.onAbort)return new c4({debugLabel:"LoadingDialog",child:new m4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class XK extends v0{props;constructor(A){super();this.props=A}createState(){return new Q8A}}class Q8A extends k0{scrollController=new oA;scrollAreaKey=new Y2("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 y2}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=hG0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=i1.all(new n1(Q.colors.border,1,"solid")),Z=new p0({padding:q0.symmetric(1,0),child:new l({text:new M($.title,new y({color:J,bold:!0}))})}),X=this.isWidgetMessage(B)?B.widget:new l({text:new M($.description,new y({color:Q.colors.foreground})),selectable:!0}),F=new S1({child:new A8({child:new p0({padding:q0.symmetric(1,0),child:new B1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new S1({child:new _A({controller:this.scrollController,autofocus:!0,child:X})}),new D2({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:q0.symmetric(1,0),child:new l({text:(()=>{if(this.widget.props.onRetry)return new M("",void 0,[new M("Press ",new y({color:Q.colors.foreground,dim:!0})),new M("R",new y({color:Q.app.keybind})),new M(" to retry, ",new y({color:Q.colors.foreground,dim:!0})),new M("Esc",new y({color:Q.app.keybind})),new M(" to cancel",new y({color:Q.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new M("",new y({color:Q.colors.foreground,dim:!0}));if(G==="help"){let V=new y({color:Q.app.keybind}),U=new y({color:Q.colors.foreground,dim:!0});return new M("",U,[new M("Press ",U),new M("Escape",V),new M(" to close • Use ",U),new M("↑↓",V),new M(" or ",U),new M("j/k",V),new M(" to scroll",U)])}return new M("Press any key to close",new y({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new c4({debugLabel:"MessageDialog",child:new t4({fit:"expand",children:[new u1({onClick:()=>{},child:new N0}),new m4({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:q0.all(1),child:new f0({mainAxisAlignment:"center",children:[Z,new N0({height:1}),F,D]})})})]})})}}C3();class B8A extends v0{props;constructor(A){super();this.props=A}createState(){return new $8A}}class $8A 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=f8.default(),{colors:B,app:$}=Q;switch(A){case"loading":return{icon:"◌",color:B.warning};case"active":return{icon:"✓",color:$.toolSuccess};case"error":return{icon:"✗",color:$.toolError}}}build(A){let Q=_0.of(A),{app:B}=Q;if(this.plugins.length===0)return new l({text:new M("No plugins found.",new y({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((F)=>F.status==="active").length,Z=this.plugins.reduce((F,D)=>F+D.registeredCommands.length,0),X=this.plugins.reduce((F,D)=>F+D.registeredTools.length,0);if($.push(new M(`${Y}/${J} ${K4(J,"plugin")} active`,new y({bold:!0}))),Z>0||X>0)$.push(new M(` (${Z} ${K4(Z,"command")}, ${X} ${K4(X,"tool")})`,new y({dim:!0})));$.push(new M(`
6154
+ `))}if(E)V.push(new M(" ",G)),V.push(new M("Total: ",G)),V.push(new M(Y(W),D))}return new p0({decoration:{color:X.background,border:i1.all(new n1(X.border,1,"rounded"))},child:new l({text:new M(void 0,void 0,V)})})}o0();C3();cz();a8();A3();IQ();rn();S7();r9();n2();kB();xV();d4();zv();iT();O1();o0();r9();class L21{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.1777970347-gc2d807"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await C80(Q,this.configService)}catch(Q){j.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class Iw extends v0{props;constructor(A){super();this.props=A}createState(){return new o3A}}class o3A 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 r3A extends k0{controller=new I8;focusNode=new Z6({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=i1.all(new n1(B.foreground,1,"solid")),F=new A$({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(K)=>{let E=K.trim();if(J&&E.length===0)return;this.widget.props.onSubmit(E)},autofocus:!0,style:{textColor:B.foreground,border:null},maxLines:1}),D=new B1({children:[new p0({decoration:{color:B.background},child:new l({text:new M(">",new y({color:B.foreground}))})}),new S1({child:F})]}),G=new p0({padding:q0.symmetric(1,0),child:new l({text:this.widget.props.title?new M(this.widget.props.title,new y({color:$.command,bold:!0})):new M("",void 0,[new M("Command: ",new y({color:B.foreground})),new M(this.widget.props.commandName,new y({color:$.command,bold:!0}))])})}),V=[];if(Z)V.push(new M("Enter",new y({color:$.keybind}))),V.push(new M(" to submit, ",new y({color:B.foreground,dim:!0})));V.push(new M("Esc",new y({color:$.keybind}))),V.push(new M(" to cancel",new y({color:B.foreground,dim:!0})));let U=new p0({padding:q0.symmetric(1,0),child:new l({text:new M("",void 0,V)})});return new p0({decoration:{border:X,color:B.background},padding:q0.all(1),child:new f0({children:[G,new N0({height:1}),D,new Y5,U]})})}}class Je extends v0{props;constructor(A){super();this.props=A}createState(){return new r3A}}kB();class s3A extends k0{controller=new I8;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new Z6({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>=e9)return!1;let Q=await JF(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=B4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),X=new ZG({controller:this.controller,triggers:[new PJ],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:R4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),F=new m4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:X}),D=new p0({constraints:new M1({maxHeight:Z}),padding:q0.symmetric(1,0),child:F}),G=new p0({padding:q0.symmetric(1,0),child:new l({text:new M("",void 0,[new M("Command: ",new y({color:B.foreground})),new M(this.widget.props.commandName,new y({color:$.command,bold:!0}))])})}),V=new p0({padding:q0.symmetric(1,0),child:new l({text:this.isConfirmingClearInput?new M("",void 0,[new M("Esc",new y({color:$.keybind})),new M(" again to clear input",new y({color:B.foreground,dim:!0}))]):new M("",void 0,[new M("Press ",new y({color:B.foreground,dim:!0})),new M("Enter",new y({color:$.keybind})),new M(" to submit, ",new y({color:B.foreground,dim:!0})),new M("Esc",new y({color:$.keybind})),new M(" to clear",new y({color:B.foreground,dim:!0}))])})}),U=[G,new N0({height:1}),new S1({child:D}),new N0({height:1}),V];return new p0({decoration:{border:i1.all(new n1(B.foreground,1,"solid")),color:B.background},padding:q0.all(1),child:new f0({children:U})})}}class O21 extends v0{props;constructor(A){super();this.props=A}createState(){return new s3A}}function t3A(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 j21 extends I1{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)=>t3A(J.pubDate).length));return new p6({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 N0({width:H,child:B1.end([new l({text:new M(W,new y({color:K}))})])});return new p0({decoration:V?{color:V}:void 0,padding:q0.symmetric(2,0),child:new B1({children:[new S1({child:new l({text:new M(J.title,new y({color:U})),overflow:"ellipsis",maxLines:1})}),new N0({width:2}),E(t3A(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()}}o0();class e3A extends k0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){j.error("Failed to load labels",A.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=A.result,this.isLoading=!1,this.setState()}catch(A){j.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let B=this.widget.props.currentLabels||[],$=this.labels.some((Y)=>Y.name===Q),J=B.includes(Q);return!$&&!J}build(A){let Q=_0.of(A),{app:B,colors:$}=Q,J=this.currentQuery.trim().toLowerCase(),Y=J.length>0?this.getValidationError(J):null,Z=this.getAvailableLabels(),F=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...Z];return new p6({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:q0.symmetric(2,0),child:new l({text:new M("",void 0,[new M("Create new label: ",new y({color:E})),new M(H,new y({color:E,bold:!0}))])})})}return new p0({decoration:K?{color:K}:void 0,padding:q0.symmetric(2,0),child:new l({text:new M(D.name,new y({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 R21 extends v0{props;constructor(A){super();this.props=A}createState(){return new e3A}}class DG extends v0{props;constructor(A){super();this.props=A}createState(){return new A8A}}class A8A extends k0{_spinner=new H6;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=i1.all(new n1(B.foreground,1,"solid")),Y=this._spinner.toBraille(),Z=new l({textAlign:"center",text:new M("",void 0,[new M(Y,new y({color:$.processing})),new M(" ",void 0),new M(this.widget.props.message,new y({color:B.foreground}))])}),F=[new S1({child:new f0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)F.push(new N0({height:2,child:new p0({padding:q0.symmetric(2,0),child:new l({text:new M("",new y({dim:!0}),[new M("Press ",new y({color:B.foreground})),new M("Esc",new y({color:B.info})),new M(" to cancel",new y({color:B.foreground}))])})})}));let D=new p0({decoration:new x4(B.background,J),child:new N0({width:60,height:7,child:new f0({mainAxisAlignment:"start",children:F})})});if(this.widget.props.onAbort)return new c4({debugLabel:"LoadingDialog",child:new m4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class XK extends v0{props;constructor(A){super();this.props=A}createState(){return new Q8A}}class Q8A extends k0{scrollController=new oA;scrollAreaKey=new Y2("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 y2}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=hG0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=i1.all(new n1(Q.colors.border,1,"solid")),Z=new p0({padding:q0.symmetric(1,0),child:new l({text:new M($.title,new y({color:J,bold:!0}))})}),X=this.isWidgetMessage(B)?B.widget:new l({text:new M($.description,new y({color:Q.colors.foreground})),selectable:!0}),F=new S1({child:new A8({child:new p0({padding:q0.symmetric(1,0),child:new B1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new S1({child:new _A({controller:this.scrollController,autofocus:!0,child:X})}),new D2({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:q0.symmetric(1,0),child:new l({text:(()=>{if(this.widget.props.onRetry)return new M("",void 0,[new M("Press ",new y({color:Q.colors.foreground,dim:!0})),new M("R",new y({color:Q.app.keybind})),new M(" to retry, ",new y({color:Q.colors.foreground,dim:!0})),new M("Esc",new y({color:Q.app.keybind})),new M(" to cancel",new y({color:Q.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new M("",new y({color:Q.colors.foreground,dim:!0}));if(G==="help"){let V=new y({color:Q.app.keybind}),U=new y({color:Q.colors.foreground,dim:!0});return new M("",U,[new M("Press ",U),new M("Escape",V),new M(" to close • Use ",U),new M("↑↓",V),new M(" or ",U),new M("j/k",V),new M(" to scroll",U)])}return new M("Press any key to close",new y({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new c4({debugLabel:"MessageDialog",child:new t4({fit:"expand",children:[new u1({onClick:()=>{},child:new N0}),new m4({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:q0.all(1),child:new f0({mainAxisAlignment:"center",children:[Z,new N0({height:1}),F,D]})})})]})})}}C3();class B8A extends v0{props;constructor(A){super();this.props=A}createState(){return new $8A}}class $8A 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=f8.default(),{colors:B,app:$}=Q;switch(A){case"loading":return{icon:"◌",color:B.warning};case"active":return{icon:"✓",color:$.toolSuccess};case"error":return{icon:"✗",color:$.toolError}}}build(A){let Q=_0.of(A),{app:B}=Q;if(this.plugins.length===0)return new l({text:new M("No plugins found.",new y({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((F)=>F.status==="active").length,Z=this.plugins.reduce((F,D)=>F+D.registeredCommands.length,0),X=this.plugins.reduce((F,D)=>F+D.registeredTools.length,0);if($.push(new M(`${Y}/${J} ${K4(J,"plugin")} active`,new y({bold:!0}))),Z>0||X>0)$.push(new M(` (${Z} ${K4(Z,"command")}, ${X} ${K4(X,"tool")})`,new y({dim:!0})));$.push(new M(`
6155
6155
 
6156
6156
  `));for(let F of this.plugins){let{icon:D,color:G}=this.statusIcon(F.status),V=this.getRelativePath(F.uri.toString());if($.push(new M(`${D} `,new y({color:G}))),$.push(new M(V,new y({bold:!0}))),$.push(new M(` ${F.status}`,new y({dim:!0}))),$.push(new M(`
6157
6157
  `)),F.status==="active"&&F.registeredEvents.length>0)$.push(new M(" Events: ",new y({dim:!0}))),$.push(new M(F.registeredEvents.join(", "),new y({color:B.link}))),$.push(new M(`
@@ -6329,7 +6329,7 @@ ${s.content||""}`:s.content||"",b0=[],$1=s.baseDir.startsWith("file://")?DE0(s.b
6329
6329
  `)}function g9A(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=z44({settings:{url:Y.ampURL,proxy:Z},secrets:{getToken:(D,G)=>Y.secrets.get(D,G)}}),F=await VA.userDisplayBalanceInfo({},{config:X});if(!F.ok){if(F.error.code==="auth-required")process.stderr.write(s0.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(s0.red("Error: ")+F.error.message+`
6330
6330
  `),process.exit(1)}process.stdout.write(await H23(F.result.displayText)+`
6331
6331
  `),process.exit(0)})}var uB3=me.join(iZ,"logs","headless.log"),TQ1=me.join(Ff,"device-id.json"),hB3=`cli-tui-${K$A(16).toString("hex")}`;async function gB3(){for(let A of sM)try{if((await A.listConfigs()).length>0)return A}catch(Q){j.debug("Failed to detect query-based IDE integration",{ideName:A.ideName,error:Q})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => C4(Eu(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){fJ.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
6332
- `)}function mB3(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 u2(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")jB("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")jB("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)jB("internal.model",cB3(Q.model))}function X$A(A){let Q=A.indexOf(":");if(Q===-1)throw new r1(`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 r1(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function pB3(A){if(A===void 0)return;let Q=A.trim();if(J44(Q))return Q;throw new r1(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function dB3(A,Q){if(iF(A,Q))return;let B=d$(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new r1(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function cB3(A){if(!A.includes("="))return X$A(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new r1(`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 r1(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new r1(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);X$A(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new r1("No valid model overrides found in --model flag value.",1);return Q}function lB3(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 iB3(A){try{return await E$A(A,"utf-8")}catch{return A}}async function SQ1(A,Q,B){let $=lB3(A,Q);if(!$)return;let J=OA(B)?B.features:[],Y=OA(B)?B.user.email:void 0;if(!Wu(J,l8.HARNESS_SYSTEM_PROMPT)&&!(Y&&T7(Y)))throw new r1("You are not allowed to do this.",1);jB("systemPrompt",await iB3($))}function Wu(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function nB3(A){return A!=="pending"}function FP(A){if(!OA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function aB3(A){let Q=FP(A);if(Q)return Q.id;if(cF(A))throw Error(A.error.message);throw Error("unreachable")}function oB3(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 rB3(A){let $=oB3(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 r1(`Couldn't connect to the Amp server at ${A}.`,1,$)}function pe(A,Q){let B=we0(Error(A.error.message));if(B.message===V7.networkOffline||B.message===V7.networkTimeout)return rB3(Q);if(B.message!==V7.internalBug)return new r1(B.message,1,B.suggestion);return new r1(A.error.message.replace(/^Error: /,""),1)}var F$A=[{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??aX,description:`Custom settings file path (overrides the default location ${aX})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Xr})`},{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:Y9(),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:oM.SMART.key,description:`Set the agent mode (${m$({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(m$().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neoOrb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],D$A=(A)=>("deprecated"in A)&&A.deprecated===!0,sB3=(A)=>("hidden"in A)&&A.hidden===!0,tB3=(A)=>("default"in A),eB3=(A)=>("default"in A)?A.default:void 0;function tE0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=pB3(Q.effort);if(B!==void 0)dB3(Q.mode,B);return B}function A$3(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 r1(V7.unknownCommand(B),1,Z)}}async function QW0(A){return{...A,getThreadEnvironment:SW,getEnvironmentData:(Q,B)=>KD({filesystem:A.fileSystem},Q,B),osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new vL(A.fileSystem),generateThreadTitle:GD4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>NQ(A.configService),pluginService:A.pluginService}}function W$A(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:SW,getEnvironmentData:(Q,B)=>KD({filesystem:A.fileSystem},Q,B),filesystem:A.fileSystem,threadService:A.threadService}}var eE0=e0.file(bB3.homedir()),kQ1=process.env.XDG_CONFIG_HOME?e0.file(process.env.XDG_CONFIG_HOME):V1.joinPath(eE0,".config");function Q$3(A){return p_4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if($D0())JD0();else if(process.platform==="darwin"&&Q==="idle"&&A.isTUIVoiceNotifEnabled())m_4();else Bo(Q);let B=JR(),$=Ks();if((!B||$||Uf())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(oD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(oD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(JR()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function g8(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;o14("0.0.1777967145-g633c91");let Y=PS({storage:A.settings,secretStorage:A.secrets,workspaceRoot:m0.of(e0.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:eE0,userConfigDir:kQ1});A6A(Y);let Z=await Y.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let X=!1;{let d=await A.secrets.get("apiKey",A.ampURL);if(X=Boolean(d),j.info("API key lookup before login",{found:Boolean(d),ampURL:A.ampURL,deferAuth:$}),!d)if($)j.info("No API key found, continuing startup with deferred auth");else{D5.write(`No API key found. Starting login flow...
6332
+ `)}function mB3(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 u2(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")jB("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")jB("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)jB("internal.model",cB3(Q.model))}function X$A(A){let Q=A.indexOf(":");if(Q===-1)throw new r1(`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 r1(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function pB3(A){if(A===void 0)return;let Q=A.trim();if(J44(Q))return Q;throw new r1(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function dB3(A,Q){if(iF(A,Q))return;let B=d$(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new r1(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function cB3(A){if(!A.includes("="))return X$A(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new r1(`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 r1(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new r1(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);X$A(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new r1("No valid model overrides found in --model flag value.",1);return Q}function lB3(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 iB3(A){try{return await E$A(A,"utf-8")}catch{return A}}async function SQ1(A,Q,B){let $=lB3(A,Q);if(!$)return;let J=OA(B)?B.features:[],Y=OA(B)?B.user.email:void 0;if(!Wu(J,l8.HARNESS_SYSTEM_PROMPT)&&!(Y&&T7(Y)))throw new r1("You are not allowed to do this.",1);jB("systemPrompt",await iB3($))}function Wu(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function nB3(A){return A!=="pending"}function FP(A){if(!OA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function aB3(A){let Q=FP(A);if(Q)return Q.id;if(cF(A))throw Error(A.error.message);throw Error("unreachable")}function oB3(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 rB3(A){let $=oB3(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 r1(`Couldn't connect to the Amp server at ${A}.`,1,$)}function pe(A,Q){let B=we0(Error(A.error.message));if(B.message===V7.networkOffline||B.message===V7.networkTimeout)return rB3(Q);if(B.message!==V7.internalBug)return new r1(B.message,1,B.suggestion);return new r1(A.error.message.replace(/^Error: /,""),1)}var F$A=[{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??aX,description:`Custom settings file path (overrides the default location ${aX})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Xr})`},{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:Y9(),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:oM.SMART.key,description:`Set the agent mode (${m$({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(m$().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neoOrb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],D$A=(A)=>("deprecated"in A)&&A.deprecated===!0,sB3=(A)=>("hidden"in A)&&A.hidden===!0,tB3=(A)=>("default"in A),eB3=(A)=>("default"in A)?A.default:void 0;function tE0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=pB3(Q.effort);if(B!==void 0)dB3(Q.mode,B);return B}function A$3(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 r1(V7.unknownCommand(B),1,Z)}}async function QW0(A){return{...A,getThreadEnvironment:SW,getEnvironmentData:(Q,B)=>KD({filesystem:A.fileSystem},Q,B),osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new vL(A.fileSystem),generateThreadTitle:GD4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>NQ(A.configService),pluginService:A.pluginService}}function W$A(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:SW,getEnvironmentData:(Q,B)=>KD({filesystem:A.fileSystem},Q,B),filesystem:A.fileSystem,threadService:A.threadService}}var eE0=e0.file(bB3.homedir()),kQ1=process.env.XDG_CONFIG_HOME?e0.file(process.env.XDG_CONFIG_HOME):V1.joinPath(eE0,".config");function Q$3(A){return p_4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if($D0())JD0();else if(process.platform==="darwin"&&Q==="idle"&&A.isTUIVoiceNotifEnabled())m_4();else Bo(Q);let B=JR(),$=Ks();if((!B||$||Uf())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(oD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(oD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(JR()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function g8(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;o14("0.0.1777970347-gc2d807");let Y=PS({storage:A.settings,secretStorage:A.secrets,workspaceRoot:m0.of(e0.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:eE0,userConfigDir:kQ1});A6A(Y);let Z=await Y.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let X=!1;{let d=await A.secrets.get("apiKey",A.ampURL);if(X=Boolean(d),j.info("API key lookup before login",{found:Boolean(d),ampURL:A.ampURL,deferAuth:$}),!d)if($)j.info("No API key found, continuing startup with deferred auth");else{D5.write(`No API key found. Starting login flow...
6333
6333
  `);let g=await B$3(A),n=await A.secrets.get("apiKey",A.ampURL);if(j.info("Login flow completed",{success:g,storedKeyPresent:Boolean(n),ampURL:A.ampURL}),!g)await uW(),process.exit(1);X=!0}}{let d=await Y.getLatest(),g=d.settings.url,n=d.secrets.isSet?.[g];j.info("Config secrets state after login",{configURL:g,apiKeySet:n?.apiKey??!1})}let F=x1(NQ(Y).pipe(E5(nB3))),D=$?"pending":await F;if(!$)j.info("Server status resolved",{status:"ready",isAuthenticated:OA(D),isError:cF(D),errorMessage:cF(D)?D.error.message:void 0});let G=F.then((d)=>aB3(d));G.catch(()=>{return});let U=!A.executeMode&&!Q.takeMeBack&&OA(D)&&Wu(D.features,l8.THREAD_ACTORS_TUI)?"all":process.env.PLUGINS??"permissions",{toolService:K,dispose:E}=sZ0({configService:Y}),W=new Map,H=()=>W.clear(),z=new xb0(Y,A.settings.getWorkspaceRootPath()),q=kQ0({configService:Y,filesystem:P5}),N=xB4({configService:Y,trustStore:z,skillMCPServers:q.skillMCPServers,createOAuthProvider:async(d,g,n)=>{let c=`${d}:${g}`,Q0=W.get(c);if(Q0)return j.debug("Reusing existing OAuth provider for server",{serverName:d,serverUrl:g}),Q0;j.debug("Creating OAuth provider for server",{serverName:d,serverUrl:g});let W0=(async()=>{let i=new $L(A.secrets),$0=await i.getClientInfo(d,g),U0=n?.scopes??$0?.scopes,E0=kp4();j.info("OAuth headless mode check",{useHeadless:E0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:D5.isTTY});let e;if(E0)e=A.executeMode?Sp4():Tp4(d);let Y0=new iv0({storage:i,serverName:d,serverUrl:g,clientId:n?.clientId??$0?.clientId,clientSecret:n?.clientSecret??$0?.clientSecret,authUrl:n?.authUrl??$0?.authUrl,tokenUrl:n?.tokenUrl??$0?.tokenUrl,scopes:U0,headlessAuthHandler:e});return j.debug("OAuth provider created",{serverName:d,serverUrl:g,hasManualClientId:!!(n?.clientId??$0?.clientId),willUseDCR:!(n?.clientId??$0?.clientId),scopes:U0,headlessMode:E0,executeMode:A.executeMode}),Y0})();return W.set(c,W0),W0}}),I=ia({configService:Y,filesystem:P5,spawn:$x}),w;if(J)w=new Map;else if(A.executeMode){let d=await GR4({toolService:K,providers:[N,I],initialTimeout:15000});w=d.registrations;for(let[g,n]of d.initErrors)j.warn(`${g} provider initialization slow or failed:`,n)}else w=na({toolService:K,providers:[N,I]});if(Q.jetbrains)lM("JetBrains");else if(Q.ide&&Wd4())lM("VS Code");else if(Q.ide&&Hd4())lM("Neovim");else if(Q.ide){let d=await gB3();if(d){let g=u80(d.ideName);if(g)lM(g)}}if(A.executeMode)r14(!0);let C,O=f3.status.pipe(L1((d)=>Boolean(d.connected&&d.authenticated&&d.ideName&&n44(d.ideName))),S4()).subscribe((d)=>{if(d){if(!C)C=K.registerTool(DR4)}else C?.dispose(),C=void 0}),_;if(!A.executeMode){let d=await A.settings.get("fuzzy.alwaysIncludePaths")??[];_=new Zf(process.cwd(),{alwaysIncludePaths:d},!0)}else _=new class extends Zf{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let S=new tg0(rL(Y,{usesThreadActors:!1}),{maxThreads:200});j.info("Starting Amp background services");let T=new M81,b=Q.headless?dl4():void 0,h=b??new If({configService:Y}),x=h instanceof If?h:void 0;if(x)x.pluginExecutorKind="local";let v=kc({configService:Y,fileSystem:P5,platform:h,loadGlobalPlugins:jr(Y),pluginFilter:U}),u=v70({pluginService:v,toolService:K}),m={configService:Y,toolService:K,mcpService:N,skillService:q,toolboxService:I,trustStore:z,threadService:S,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:_,fileSystem:P5,terminal:T,pluginService:v,pluginPlatform:x,headlessPluginPlatform:b,serverStatus:D,serverStatusPromise:F,viewerUserIDPromise:G,hasAPIKeyAtStartup:X};return{...m,async asyncDispose(){if(m.mcpService.hasAuthenticatingClients())j.info("Waiting for OAuth authentication to complete before exit..."),await m.mcpService.waitForAuthentication();for(let d of w.values())d.dispose();await m.mcpService.dispose(),H(),await m.threadService.asyncDispose(),m.configService.unsubscribe(),E(),m.fuzzyServer.dispose(),m.settingsStorage[Symbol.dispose](),O.unsubscribe(),C?.dispose(),u.dispose(),await m.pluginService.dispose()}}}async function B$3(A){if(!A.executeMode){if(!await nD0("Would you like to log in to Amp? [(y)es, (n)o]: "))return D5.write(`Login cancelled. Run the command again to retry.
6334
6334
  `),!1}return await H$A(A)}async function H$A(A){let Q=K$A(32).toString("hex"),B=await Nf(A.ampURL,Q),$=new AbortController;try{await uF(B,$.signal)}catch(Y){j.error("Error opening browser",{error:Y})}let J=await Nf(A.ampURL,Q,!1);D5.write(`If your browser does not open automatically, visit:
6335
6335
 
@@ -6337,7 +6337,7 @@ ${s0.blue.bold(J)}
6337
6337
 
6338
6338
  `);try{return await Tl4(A.ampURL,Q,A.secrets,$),D5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(Y){return j.error("Login failed",{error:Y}),fJ.write(`
6339
6339
  Login failed: ${Y instanceof Error?Y.message:String(Y)}
6340
- `),!1}}async function $$3(A,Q,B){let $=await Q.get("apiKey",A);if(!$)throw new r1("No Amp API key found. Run `amp login` first.",1);let J=yB3("curl",["-H",`Authorization: Bearer ${$}`,...B],{stdio:"inherit"});process.exitCode=await new Promise((Y,Z)=>{J.on("error",Z),J.on("close",(X)=>Y(X??1))})}function J$3(A){let Q=new aN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)fj(),process.exit(0);let z=H.originalError??H;Ch4(z)}),gi4(Q,{version:"0.0.1777967145-g633c91",buildTimestamp:"2026-05-05T07:49:26.158Z",buildType:"'release'"}),Q.addHelpText("after",Ud4()),Q.configureHelp({formatHelp:Kd4}),Q.command("logout").description("Log out by removing stored API key").action(async(H,z)=>{let q=z.optsWithGlobals(),N=await m5(q);await K$3(N)}),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(H,z)=>{let q=z.optsWithGlobals(),N=await m5(q);await U$3(N,await Tr(q,N.settings))}),Nh4(Q,m5);let $=Q.command("internal",{hidden:!0}).description("Internal commands").command("curl [args...]").description("Internal: run curl with the current Amp API key as a bearer token").allowUnknownOption(!0).allowExcessArguments(!0).action(async(...H)=>{let z=H.find((w)=>typeof w==="object"&&w!==null&&typeof w.optsWithGlobals==="function")??$,q=H.filter((w)=>w!==z).flatMap((w)=>Array.isArray(w)?w:typeof w==="string"?[w]:[]),N=z.optsWithGlobals(),I=await m5(N);await $$3(I.ampURL,I.secrets,q),process.exit(process.exitCode??0)});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(H,z,q)=>{let N=q.optsWithGlobals(),I=await m5(N);await Cp4(H??"get",I.ampURL,I.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(H,z)=>{let q=z.optsWithGlobals(),N=await m5(q);await Mp4(N.ampURL,N.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(H)=>{await Sc4({raw:H.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(H)=>{await Uh4(H),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(`
6340
+ `),!1}}async function $$3(A,Q,B){let $=await Q.get("apiKey",A);if(!$)throw new r1("No Amp API key found. Run `amp login` first.",1);let J=yB3("curl",["-H",`Authorization: Bearer ${$}`,...B],{stdio:"inherit"});process.exitCode=await new Promise((Y,Z)=>{J.on("error",Z),J.on("close",(X)=>Y(X??1))})}function J$3(A){let Q=new aN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)fj(),process.exit(0);let z=H.originalError??H;Ch4(z)}),gi4(Q,{version:"0.0.1777970347-gc2d807",buildTimestamp:"2026-05-05T08:42:39.004Z",buildType:"'release'"}),Q.addHelpText("after",Ud4()),Q.configureHelp({formatHelp:Kd4}),Q.command("logout").description("Log out by removing stored API key").action(async(H,z)=>{let q=z.optsWithGlobals(),N=await m5(q);await K$3(N)}),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(H,z)=>{let q=z.optsWithGlobals(),N=await m5(q);await U$3(N,await Tr(q,N.settings))}),Nh4(Q,m5);let $=Q.command("internal",{hidden:!0}).description("Internal commands").command("curl [args...]").description("Internal: run curl with the current Amp API key as a bearer token").allowUnknownOption(!0).allowExcessArguments(!0).action(async(...H)=>{let z=H.find((w)=>typeof w==="object"&&w!==null&&typeof w.optsWithGlobals==="function")??$,q=H.filter((w)=>w!==z).flatMap((w)=>Array.isArray(w)?w:typeof w==="string"?[w]:[]),N=z.optsWithGlobals(),I=await m5(N);await $$3(I.ampURL,I.secrets,q),process.exit(process.exitCode??0)});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(H,z,q)=>{let N=q.optsWithGlobals(),I=await m5(N);await Cp4(H??"get",I.ampURL,I.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(H,z)=>{let q=z.optsWithGlobals(),N=await m5(q);await Mp4(N.ampURL,N.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(H)=>{await Sc4({raw:H.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(H)=>{await Uh4(H),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(`
6341
6341
  `)).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(H,z,q)=>{if(H&&z.apply)throw new r1("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let N=z.apply??H;if(!N||N.trim().length===0)D5.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.
6342
6342
 
6343
6343
  `),q.outputHelp(),process.exit(0);let I=y3(N)??pQ(N),w=q.optsWithGlobals(),C=await m5(w);u2(q,w);let O=await g8(C,w),_=!1;try{if(z.checkout&&z.skipCheckout)throw new r1("Choose either --checkout or --skip-checkout, not both.",1);if(cF(O.serverStatus))throw pe(O.serverStatus,C.ampURL);let S=OA(O.serverStatus)?O.serverStatus.features:void 0;if(!Wu(S,l8.V2))throw new r1("live-sync is not enabled for your user",1);await Nl4({ampURL:C.ampURL,threadId:I,configService:O.configService,threadService:O.threadService,apiKey:process.env.AMP_API_KEY,applyOnce:typeof z.apply==="string",checkoutMode:z.checkout?"always":z.skipCheckout?"never":"prompt",promptForYesNo:nD0}),_=!0}finally{if(await O.asyncDispose(),_)process.exit(0)}});let J=async(H,z,q)=>{PS({storage:z.settings,secretStorage:z.secrets,workspaceRoot:m0.of(e0.file(process.cwd())),defaultAmpURL:z.ampURL,homeDir:eE0,userConfigDir:kQ1});let N={...z,executeMode:!1};await AW0(N,{...H,openThreadSwitcher:!0},q,A)},Y=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(H,z)=>{let q=z.optsWithGlobals(),N=await m5(q);await U$A(q,N,z)});Y.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(H,z)=>{let q=z.optsWithGlobals(),N=await m5(q);await L$3(q,N,z)}),Y.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(H,z,q)=>{let N=q.optsWithGlobals(),I=await m5(N);if(z.pick)fJ.write(`${s0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
@@ -6370,8 +6370,8 @@ ${C}
6370
6370
  `))}),z.args.length>0)A$3(N,z);await AW0(N,q,z,A)}),nd4(Q),Q}async function Hu(A,Q){await tY((B)=>tD0(B,A,Q))}async function G$A(A,Q,B){let $=Date.now(),[J,Y]=await Promise.all([VA.getThreadLinkInfo({thread:A},{config:Q}),B]);if(j.info(`[fetchAndStartThread] Ownership check in ${Date.now()-$}ms`),J.ok){let Z=J.result.creatorUserID;if(Z&&Z!==Y&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new r1(`Cannot resume thread created by another user.
6371
6371
 
6372
6372
  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 z$A(A){if(A.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof A.execute==="string"){let Q=(await LU0()).trimEnd();return{userInput:A.execute,stdinInput:Q||null}}return{userInput:(await LU0()).trimEnd(),stdinInput:null}}function q$A(A,Q,B){if(A.streamJson&&!Q)throw new r1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new r1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new r1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new r1("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 r1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archive&&!Q)throw new r1("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 r1("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 r1("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"
6373
- Or pipe via stdin: echo "your message" | amp --execute`)}function Y$3(A,Q){if(N54([g30.parse({tool:"*",action:"allow"})]),G54({bypass:!0}),mAA(A.settings))j.debug("Enabling permissions plugin"),Q.registerInternalPlugin({name:"permissions",entryPoint:q81})}async function AW0(A,Q,B,$){if(Q.headless)return Z$3(A,Q,B);let J=await g8(A,Q),Y=await J.serverStatusPromise,Z=await J.configService.getLatest(),X=OA(Y)&&Wu(Y.features,l8.THREAD_ACTORS_TUI),F=X&&!Q.takeMeBack;if(Q.showWelcome&&!X)throw await J.asyncDispose(),new r1("--show-welcome is only available with the new Amp CLI feature flag",1);if(F)return Y$3(Z,J.pluginService),X$3(A,Q,B,J);else{if(Q.threadId&&n9(Q.threadId)){let D=await VA.getThreadLinkInfo({thread:Q.threadId},{config:J.configService}).catch(()=>null);if(D?.ok&&D.result.usesThreadActors)throw await J.asyncDispose(),new r1(`Thread ${Q.threadId} was created with the Neo TUI and cannot be continued in the legacy CLI.`,1,"Re-run without --take-me-back to continue this thread.")}return F$3(A,Q,B,$,{dependencies:J})}}async function Z$3(A,Q,B){let $=(z,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=vs0();j.info("Startup phase",{phase:z,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};u2(B,Q);let J=process.hrtime.bigint(),Y=await g8(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(cF(Z))throw pe(Z,A.ampURL);let X=OA(Z)?Z:null,F=X?.user.email;await SQ1(B,Q,Z);let D=FP(Z),G=Is(Q,D);if(G instanceof Error)x5(G.message);if(X&&!jS(Q.mode,F))throw new r1(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!F||!T7(F)))throw new r1("Headless executor mode is only available for Amp employees",1);IF0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new r1("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&&!n9(K))throw new r1(`Invalid thread ID: ${K}`,1);let E=K?void 0:await C$3({dependencies:Y,apiKey:U,visibility:G??void 0}),W=K??E?.threadId;if(!W)throw new r1("Failed to resolve headless thread ID",1);let H=await fp4(W);if(H.status==="already-running")await Y.asyncDispose(),await uW(),process.exit(0);try{await Rp4({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 uW(),process.exit(0)}async function X$3(A,Q,B,$){let{userInput:J,stdinInput:Y}=await z$A(Q),Z=!!Q.streamJson||!!Q.streamJsonThinking;q$A({...Q,streamJson:Z},A.executeMode,J),u2(B,Q);let X=Q.threadId&&n9(Q.threadId)?Q.threadId:void 0,F=Q.observe?y3(Q.observe)??pQ(Q.observe):void 0,D=await $.serverStatusPromise;if(cF(D))throw pe(D,A.ampURL);let G=await $.secretStorage.get("apiKey",A.ampURL);if(!G)throw new r1("API key required. Please run `amp login` first.",1);let V=OA(D)&&T7(D.user.email);if(V)IF0();if(A.executeMode){y11($.mcpService,A.settings);try{let U=tE0(B,Q),K=await PI(),E=X?U:aD0({agentMode:Q.mode,explicitEffort:U,sessionState:K}),W=X?void 0:oD0(await wf($.configService),{agentMode:Q.mode,explicitEffort:U,sessionState:K}),H=await lm4({apiKey:G,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:$,userInput:J,stdinInput:Y,stats:!!Q.stats,streamJson:Z,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:E,labels:Q.label,initialThreadID:X,initialSettings:W});if(await Hu(H,"execute"),Q.archive)await $.threadService.archive(H,!0)}finally{await $.asyncDispose()}await uW(),process.exit(0)}else{let U=tE0(B,Q),K=rL($.configService,{usesThreadActors:!0}),E=new pR($.fuzzyServer),W=process.cwd();await z81({ampURL:A.ampURL,apiKey:G,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??zJ(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:H})=>VI({fileSystem:$.fileSystem,workspaceRoot:W},H),completionBuilder:E,workspaceRoot:W,listThreads:()=>K.listThreads(),getThreadFromServer:(H)=>K.getThread(H),toolboxes:$.toolboxService.toolboxes,isInternalUser:V,settingsFilePath:$.settingsStorage.getSettingsFilePath()},{initialThreadID:F??X,initialUserInput:J||void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!F,splashOrbVisualStyle:"neo",showNeoWelcome:Q.showWelcome,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:U}),process.exit(0)}}async function F$3(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(E0,e)=>{let Y0=Number(process.hrtime.bigint()-e)/1e6,a=vs0();j.info("Startup phase",{phase:E0,phaseMs:Math.round(Y0),sinceMainMs:a===null?void 0:Math.round(a)})},{userInput:X,stdinInput:F}=await z$A(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;q$A({...Q,streamJson:D},A.executeMode,X),u2(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await g8(A,Q),U=V.hasAPIKeyAtStartup,K=V.serverStatus==="pending";if(j.info("Interactive auth startup mode",{deferInteractiveAuth:K,hasAPIKeyAtStartup:U,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!J)Z("runMainThread:createThreadDependencies",G);let{serverStatus:E}=V;if(!K&&cF(E))throw pe(E,A.ampURL);let W=OA(E)?E:null,H=W?.user.email,z=!!(H&&T7(H));if(z)IF0();if(!K)await SQ1(B,Q,E);let q=FP(E),N=q?.features??[],I=q?.team??null,w=Is(Q,q);if(w instanceof Error)x5(w.message);if(W&&!jS(Q.mode,H))throw new r1(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let C=Q.threadId&&n9(Q.threadId)?Q.threadId:void 0;G=process.hrtime.bigint();let O=await QW0(V);Z("runMainThread:createWorkerDeps",G);let _=A.executeMode?void 0:async(E0)=>Hu(E0,"interactive"),S={threadService:V.threadService,workerDeps:O,createThread:async(E0)=>{let e=K?await V.serverStatusPromise:E,Y0=await wF0(A.settings,process.cwd(),FP(e),w);if(Y0 instanceof Error)x5(Y0.message);return $71(O,{threadMeta:Y0?QZ(Y0):void 0,agentMode:E0??Q.mode,onFirstAssistantMessage:_})},validateThreadOwnership:async(E0,e)=>{if(e?.nonBlockingOwnershipCheck){G$A(E0,V.configService,V.viewerUserIDPromise).catch((Y0)=>{if(Y0 instanceof r1){if(e.onOwnershipError){e.onOwnershipError(Y0,E0);return}hW(Y0,E0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Y0})});return}try{await G$A(E0,V.configService,V.viewerUserIDPromise)}catch(Y0){if(Y0 instanceof r1)throw Y0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Y0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:_,handleError:hW},T=async()=>{try{return f9A(S,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(E0){if(E0 instanceof r1)throw E0;throw await hW(E0,Q.threadId),Error("handleError should have called process.exit()")}},b=(async()=>{if(K){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let E0=await V.configService.getLatest(),e=Np(E0),Y0=await VA.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(e)});if(Y0.ok)return j.info("User free tier status:",Y0),Y0.result;return}catch(E0){j.error("Failed to fetch free tier status:",E0);return}})(),x=!A.executeMode?new P81:null,v,u=null;if(x)v=x,u=(async()=>{let E0=K?await V.serverStatusPromise:V.serverStatus;if(cF(E0))throw pe(E0,A.ampURL);await SQ1(B,Q,E0);let e=process.hrtime.bigint(),Y0=await T();if(Z("runMainThread:createThreadPool",e),x.attach(Y0),X){let a=await x1(Y0.threadHandles$);if(!a)throw new r1("No active thread is available yet.",1);await a.sendMessage({content:[{type:"text",text:X}]})}})(),u.catch(async(E0)=>{let e=E0 instanceof Error?E0:Error(String(E0));x.setInitError(e),await hW(E0,Q.threadId)});else G=process.hrtime.bigint(),v=await T(),Z("runMainThread:createThreadPool",G);let m=Q.notifications!==void 0?Q.notifications:!A.executeMode,d=W!==null&&Wu(W.features,l8.TUI_VOICE_NOTIF);if(K)V.serverStatusPromise.then((E0)=>{d=OA(E0)&&Wu(E0.features,l8.TUI_VOICE_NOTIF)}).catch((E0)=>{j.debug("Failed to resolve TUI voice notification feature flag",{error:E0})});G=process.hrtime.bigint();let g=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),Q$3({configService:V.configService,threadService:V.threadService,config:g,useNotificationsForService:m,isTUIVoiceNotifEnabled:()=>d,threadViewStates$:()=>v.threadHandles$.pipe(u4((E0)=>{if(!E0)return m0.of({});return P6(E0.thread$,E0.threadViewState$).pipe(L1(([e,Y0])=>({[e.id]:Y0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){y11(V.mcpService,A.settings);let E0=tE0(B,Q),e=await PI(),Y0=C?E0:aD0({agentMode:Q.mode,explicitEffort:E0,sessionState:e}),a={userInput:X,stdinInput:F,dependencies:V,streamJson:D,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:z,agentMode:Q.mode,reasoningEffort:Y0,labels:Q.label},r=await dh4({threadPool:v,...a});if(await Hu(r,"execute"),Q.archive)await V.threadService.archive(r,!0);await V.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Q.jetbrains||Q.ide){await h80();let E0=await oF({jetbrainsOnly:Q.jetbrains});if(E0.length===0){if(Q.jetbrains)n=!await V.configService.get("jetbrains.skipInstall")}else if(E0.length===1){let e=E0[0];if(e)f3.selectConfig(e)}else c=!0}G=process.hrtime.bigint();let Q0=A11("0.0.1777967145-g633c91",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let W0=new x11(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),X&&A.executeMode){let E0=await x1(v.threadHandles$);if(!E0)throw new r1("No active thread is available yet.",1);await E0.sendMessage({content:[{type:"text",text:X}]})}G=process.hrtime.bigint();let i=await PI();Z("runMainThread:loadSessionState",G),j.info("Loaded session state:",i);let $0=tE0(B,Q),U0={...i,launchCount:i.launchCount+1,lastReasoningEffortByMode:$0?{...i.lastReasoningEffortByMode,[Q.mode]:$0}:i.lastReasoningEffortByMode};tY((E0)=>({...E0,launchCount:E0.launchCount+1}));try{if(G=process.hrtime.bigint(),await a6A({history:new Ir,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:VA,threadPool:v,createSystemPromptDeps:async()=>W$A(V),ideClient:f3,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:W0,updateService:Q0,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:hB3,logFile:{path:$},sessionState:U0,freeTierStatusPromise:b,workspace:I??null,features:N,isInternalUser:z,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-05T07:49:26.158Z"},(E0)=>new x81({...E0,threadPool:E0.threadPool},(e)=>new Q71({...e,threadState:e.threadState}))),Z("runMainThread:mountApp-returned",G),u)await u}finally{await v.dispose().catch((E0)=>{j.error("Failed to dispose thread pool during shutdown",E0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function m5(A){if(j.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)fJ.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6374
- `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await gB4({get:async(X)=>{if(X!==Cc)return;try{let F=await E$A(TQ1,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(X,F)=>{if(X!==Cc)return;await xB3(me.dirname(TQ1),{recursive:!0}),await fB3(TQ1,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:D70()});s14($);let J=await DD0({...A,workspaceTrust:{current:!0,changes:cS0},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 gl4(A.mcpConfig);J=ml4(J,X)}let Y=me.dirname(J.getSettingsFilePath());g_4(Ff,Y),J=_e1(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=U9;if(j.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!pz(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:sD0(await Tr(A,J))}}function D$3(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 G$3(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=me.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?uB3:Xr));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function V$3(){ty4();let A=D$3(process.argv),Q=G$3(process.argv,A),B=Zh4(Q),$=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)s0.level=0;if(mB3(j),j.info("Starting Amp CLI.",{version:"0.0.1777967145-g633c91",buildTimestamp:"2026-05-05T07:49:26.158Z"}),process.platform==="win32"&&ij())yd4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new r1(V7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await J$3(B).parseAsync(process.argv)}u_4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await V$3().catch(hW)});async function U$3(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"),D5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6373
+ Or pipe via stdin: echo "your message" | amp --execute`)}function Y$3(A,Q){if(N54([g30.parse({tool:"*",action:"allow"})]),G54({bypass:!0}),mAA(A.settings))j.debug("Enabling permissions plugin"),Q.registerInternalPlugin({name:"permissions",entryPoint:q81})}async function AW0(A,Q,B,$){if(Q.headless)return Z$3(A,Q,B);let J=await g8(A,Q),Y=await J.serverStatusPromise,Z=await J.configService.getLatest(),X=OA(Y)&&Wu(Y.features,l8.THREAD_ACTORS_TUI),F=X&&!Q.takeMeBack;if(Q.showWelcome&&!X)throw await J.asyncDispose(),new r1("--show-welcome is only available with the new Amp CLI feature flag",1);if(F)return Y$3(Z,J.pluginService),X$3(A,Q,B,J);else{if(Q.threadId&&n9(Q.threadId)){let D=await VA.getThreadLinkInfo({thread:Q.threadId},{config:J.configService}).catch(()=>null);if(D?.ok&&D.result.usesThreadActors)throw await J.asyncDispose(),new r1(`Thread ${Q.threadId} was created with the Neo TUI and cannot be continued in the legacy CLI.`,1,"Re-run without --take-me-back to continue this thread.")}return F$3(A,Q,B,$,{dependencies:J})}}async function Z$3(A,Q,B){let $=(z,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=vs0();j.info("Startup phase",{phase:z,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};u2(B,Q);let J=process.hrtime.bigint(),Y=await g8(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(cF(Z))throw pe(Z,A.ampURL);let X=OA(Z)?Z:null,F=X?.user.email;await SQ1(B,Q,Z);let D=FP(Z),G=Is(Q,D);if(G instanceof Error)x5(G.message);if(X&&!jS(Q.mode,F))throw new r1(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!F||!T7(F)))throw new r1("Headless executor mode is only available for Amp employees",1);IF0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new r1("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&&!n9(K))throw new r1(`Invalid thread ID: ${K}`,1);let E=K?void 0:await C$3({dependencies:Y,apiKey:U,visibility:G??void 0}),W=K??E?.threadId;if(!W)throw new r1("Failed to resolve headless thread ID",1);let H=await fp4(W);if(H.status==="already-running")await Y.asyncDispose(),await uW(),process.exit(0);try{await Rp4({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 uW(),process.exit(0)}async function X$3(A,Q,B,$){let{userInput:J,stdinInput:Y}=await z$A(Q),Z=!!Q.streamJson||!!Q.streamJsonThinking;q$A({...Q,streamJson:Z},A.executeMode,J),u2(B,Q);let X=Q.threadId&&n9(Q.threadId)?Q.threadId:void 0,F=Q.observe?y3(Q.observe)??pQ(Q.observe):void 0,D=await $.serverStatusPromise;if(cF(D))throw pe(D,A.ampURL);let G=await $.secretStorage.get("apiKey",A.ampURL);if(!G)throw new r1("API key required. Please run `amp login` first.",1);let V=OA(D)&&T7(D.user.email);if(V)IF0();if(A.executeMode){y11($.mcpService,A.settings);try{let U=tE0(B,Q),K=await PI(),E=X?U:aD0({agentMode:Q.mode,explicitEffort:U,sessionState:K}),W=X?void 0:oD0(await wf($.configService),{agentMode:Q.mode,explicitEffort:U,sessionState:K}),H=await lm4({apiKey:G,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:$,userInput:J,stdinInput:Y,stats:!!Q.stats,streamJson:Z,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:E,labels:Q.label,initialThreadID:X,initialSettings:W});if(await Hu(H,"execute"),Q.archive)await $.threadService.archive(H,!0)}finally{await $.asyncDispose()}await uW(),process.exit(0)}else{let U=tE0(B,Q),K=rL($.configService,{usesThreadActors:!0}),E=new pR($.fuzzyServer),W=process.cwd();await z81({ampURL:A.ampURL,apiKey:G,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??zJ(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:H})=>VI({fileSystem:$.fileSystem,workspaceRoot:W},H),completionBuilder:E,workspaceRoot:W,listThreads:()=>K.listThreads(),getThreadFromServer:(H)=>K.getThread(H),toolboxes:$.toolboxService.toolboxes,isInternalUser:V,settingsFilePath:$.settingsStorage.getSettingsFilePath()},{initialThreadID:F??X,initialUserInput:J||void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!F,splashOrbVisualStyle:"neo",showNeoWelcome:Q.showWelcome,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:U}),process.exit(0)}}async function F$3(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(E0,e)=>{let Y0=Number(process.hrtime.bigint()-e)/1e6,a=vs0();j.info("Startup phase",{phase:E0,phaseMs:Math.round(Y0),sinceMainMs:a===null?void 0:Math.round(a)})},{userInput:X,stdinInput:F}=await z$A(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;q$A({...Q,streamJson:D},A.executeMode,X),u2(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await g8(A,Q),U=V.hasAPIKeyAtStartup,K=V.serverStatus==="pending";if(j.info("Interactive auth startup mode",{deferInteractiveAuth:K,hasAPIKeyAtStartup:U,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!J)Z("runMainThread:createThreadDependencies",G);let{serverStatus:E}=V;if(!K&&cF(E))throw pe(E,A.ampURL);let W=OA(E)?E:null,H=W?.user.email,z=!!(H&&T7(H));if(z)IF0();if(!K)await SQ1(B,Q,E);let q=FP(E),N=q?.features??[],I=q?.team??null,w=Is(Q,q);if(w instanceof Error)x5(w.message);if(W&&!jS(Q.mode,H))throw new r1(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let C=Q.threadId&&n9(Q.threadId)?Q.threadId:void 0;G=process.hrtime.bigint();let O=await QW0(V);Z("runMainThread:createWorkerDeps",G);let _=A.executeMode?void 0:async(E0)=>Hu(E0,"interactive"),S={threadService:V.threadService,workerDeps:O,createThread:async(E0)=>{let e=K?await V.serverStatusPromise:E,Y0=await wF0(A.settings,process.cwd(),FP(e),w);if(Y0 instanceof Error)x5(Y0.message);return $71(O,{threadMeta:Y0?QZ(Y0):void 0,agentMode:E0??Q.mode,onFirstAssistantMessage:_})},validateThreadOwnership:async(E0,e)=>{if(e?.nonBlockingOwnershipCheck){G$A(E0,V.configService,V.viewerUserIDPromise).catch((Y0)=>{if(Y0 instanceof r1){if(e.onOwnershipError){e.onOwnershipError(Y0,E0);return}hW(Y0,E0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Y0})});return}try{await G$A(E0,V.configService,V.viewerUserIDPromise)}catch(Y0){if(Y0 instanceof r1)throw Y0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Y0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:_,handleError:hW},T=async()=>{try{return f9A(S,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(E0){if(E0 instanceof r1)throw E0;throw await hW(E0,Q.threadId),Error("handleError should have called process.exit()")}},b=(async()=>{if(K){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let E0=await V.configService.getLatest(),e=Np(E0),Y0=await VA.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(e)});if(Y0.ok)return j.info("User free tier status:",Y0),Y0.result;return}catch(E0){j.error("Failed to fetch free tier status:",E0);return}})(),x=!A.executeMode?new P81:null,v,u=null;if(x)v=x,u=(async()=>{let E0=K?await V.serverStatusPromise:V.serverStatus;if(cF(E0))throw pe(E0,A.ampURL);await SQ1(B,Q,E0);let e=process.hrtime.bigint(),Y0=await T();if(Z("runMainThread:createThreadPool",e),x.attach(Y0),X){let a=await x1(Y0.threadHandles$);if(!a)throw new r1("No active thread is available yet.",1);await a.sendMessage({content:[{type:"text",text:X}]})}})(),u.catch(async(E0)=>{let e=E0 instanceof Error?E0:Error(String(E0));x.setInitError(e),await hW(E0,Q.threadId)});else G=process.hrtime.bigint(),v=await T(),Z("runMainThread:createThreadPool",G);let m=Q.notifications!==void 0?Q.notifications:!A.executeMode,d=W!==null&&Wu(W.features,l8.TUI_VOICE_NOTIF);if(K)V.serverStatusPromise.then((E0)=>{d=OA(E0)&&Wu(E0.features,l8.TUI_VOICE_NOTIF)}).catch((E0)=>{j.debug("Failed to resolve TUI voice notification feature flag",{error:E0})});G=process.hrtime.bigint();let g=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),Q$3({configService:V.configService,threadService:V.threadService,config:g,useNotificationsForService:m,isTUIVoiceNotifEnabled:()=>d,threadViewStates$:()=>v.threadHandles$.pipe(u4((E0)=>{if(!E0)return m0.of({});return P6(E0.thread$,E0.threadViewState$).pipe(L1(([e,Y0])=>({[e.id]:Y0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){y11(V.mcpService,A.settings);let E0=tE0(B,Q),e=await PI(),Y0=C?E0:aD0({agentMode:Q.mode,explicitEffort:E0,sessionState:e}),a={userInput:X,stdinInput:F,dependencies:V,streamJson:D,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:z,agentMode:Q.mode,reasoningEffort:Y0,labels:Q.label},r=await dh4({threadPool:v,...a});if(await Hu(r,"execute"),Q.archive)await V.threadService.archive(r,!0);await V.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Q.jetbrains||Q.ide){await h80();let E0=await oF({jetbrainsOnly:Q.jetbrains});if(E0.length===0){if(Q.jetbrains)n=!await V.configService.get("jetbrains.skipInstall")}else if(E0.length===1){let e=E0[0];if(e)f3.selectConfig(e)}else c=!0}G=process.hrtime.bigint();let Q0=A11("0.0.1777970347-gc2d807",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let W0=new x11(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),X&&A.executeMode){let E0=await x1(v.threadHandles$);if(!E0)throw new r1("No active thread is available yet.",1);await E0.sendMessage({content:[{type:"text",text:X}]})}G=process.hrtime.bigint();let i=await PI();Z("runMainThread:loadSessionState",G),j.info("Loaded session state:",i);let $0=tE0(B,Q),U0={...i,launchCount:i.launchCount+1,lastReasoningEffortByMode:$0?{...i.lastReasoningEffortByMode,[Q.mode]:$0}:i.lastReasoningEffortByMode};tY((E0)=>({...E0,launchCount:E0.launchCount+1}));try{if(G=process.hrtime.bigint(),await a6A({history:new Ir,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:VA,threadPool:v,createSystemPromptDeps:async()=>W$A(V),ideClient:f3,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:W0,updateService:Q0,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:hB3,logFile:{path:$},sessionState:U0,freeTierStatusPromise:b,workspace:I??null,features:N,isInternalUser:z,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-05T08:42:39.004Z"},(E0)=>new x81({...E0,threadPool:E0.threadPool},(e)=>new Q71({...e,threadState:e.threadState}))),Z("runMainThread:mountApp-returned",G),u)await u}finally{await v.dispose().catch((E0)=>{j.error("Failed to dispose thread pool during shutdown",E0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function m5(A){if(j.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)fJ.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6374
+ `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await gB4({get:async(X)=>{if(X!==Cc)return;try{let F=await E$A(TQ1,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(X,F)=>{if(X!==Cc)return;await xB3(me.dirname(TQ1),{recursive:!0}),await fB3(TQ1,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:D70()});s14($);let J=await DD0({...A,workspaceTrust:{current:!0,changes:cS0},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 gl4(A.mcpConfig);J=ml4(J,X)}let Y=me.dirname(J.getSettingsFilePath());g_4(Ff,Y),J=_e1(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=U9;if(j.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!pz(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:sD0(await Tr(A,J))}}function D$3(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 G$3(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=me.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?uB3:Xr));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function V$3(){ty4();let A=D$3(process.argv),Q=G$3(process.argv,A),B=Zh4(Q),$=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)s0.level=0;if(mB3(j),j.info("Starting Amp CLI.",{version:"0.0.1777970347-gc2d807",buildTimestamp:"2026-05-05T08:42:39.004Z"}),process.platform==="win32"&&ij())yd4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new r1(V7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await J$3(B).parseAsync(process.argv)}u_4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await V$3().catch(hW)});async function U$3(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"),D5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6375
6375
  `);else if(!pz(A.ampURL))D5.write(`Logging in to ${new URL(A.ampURL).hostname}
6376
6376
  `);let $=process.env.AMP_API_KEY;if($)D5.write(`API key found in environment variable, storing...
6377
6377
  `),await Q.set("apiKey",$,A.ampURL),D5.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1777967145-g633c91",
3
+ "version": "0.0.1777970347-gc2d807",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {