@sourcegraph/amp 0.0.1777979451-gaec852 → 0.0.1777983419-g88aeb8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +12 -12
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -4819,12 +4819,12 @@ ${E}`))}},error:(K)=>{if(!U)U=!0,F(Error(`Failed to spawn brew: ${K.message}`))}
|
|
|
4819
4819
|
${E}`;if(Y==="pnpm"&&E.includes("Unable to find the global bin directory"))W+=`
|
|
4820
4820
|
|
|
4821
4821
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
4822
|
-
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=ur(A,D),V=G<0,U,K;if(F.time){let E=F.time[A],W=F.time[D],z=Date.now();if(E)U=Math.floor((z-new Date(E).getTime())/3600000);if(W)K=Math.floor((z-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 XS5="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(`${XS5}?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=ur(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 FS5=604800000;function ld4(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>FS5)return{ageMs:B};return null}function ur(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?BU(B):void 0;return{sha:$,age:J}}catch{return null}}j1();o0();import{readFile as DS5,realpath as GS5}from"node:fs/promises";import{homedir as VS5}from"node:os";import{dirname as id4,join as e01}from"node:path";async function nd4(A){switch(A){case"binary":case"brew":return US5(yr());case"npm":case"pnpm":case"yarn":case"bun":return KS5();case"bootstrap":return ES5()}}async function US5(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 KS5(){try{let A=process.argv[1];if(!A)return null;let Q=await GS5(A),B=id4(id4(Q));return await ad4(e01(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function ES5(){try{let A=process.env.AMP_HOME??e01(VS5(),".amp");return await ad4(e01(A,"package","package.json"))}catch(A){return j.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function ad4(A){let Q=await DS5(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,zS5=5000;function A11(A,Q,B={}){let $=new h4,J=$.pipe(lA({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??WS5,X=!1,F=()=>{X=!0};return setImmediate(async()=>{let D=new wB().scoped("update");if(Y>0){if(await QU(Y),X)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!X){let U=await HS5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await QU(zS5),X)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!X){let W=Math.min(K,E);await QU(W),E-=W}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:F}}async function HS5(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 Vf(),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 aj();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 nd4(Z);if(V&&ur(V,F.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:F.latestVersion}),J.updatedTo=V,ur(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!==yr()){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 br(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 od4(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.
|
|
4822
|
+
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=ur(A,D),V=G<0,U,K;if(F.time){let E=F.time[A],W=F.time[D],z=Date.now();if(E)U=Math.floor((z-new Date(E).getTime())/3600000);if(W)K=Math.floor((z-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 XS5="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(`${XS5}?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=ur(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 FS5=604800000;function ld4(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>FS5)return{ageMs:B};return null}function ur(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?BU(B):void 0;return{sha:$,age:J}}catch{return null}}j1();o0();import{readFile as DS5,realpath as GS5}from"node:fs/promises";import{homedir as VS5}from"node:os";import{dirname as id4,join as e01}from"node:path";async function nd4(A){switch(A){case"binary":case"brew":return US5(yr());case"npm":case"pnpm":case"yarn":case"bun":return KS5();case"bootstrap":return ES5()}}async function US5(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 KS5(){try{let A=process.argv[1];if(!A)return null;let Q=await GS5(A),B=id4(id4(Q));return await ad4(e01(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function ES5(){try{let A=process.env.AMP_HOME??e01(VS5(),".amp");return await ad4(e01(A,"package","package.json"))}catch(A){return j.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function ad4(A){let Q=await DS5(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,zS5=5000;function A11(A,Q,B={}){let $=new h4,J=$.pipe(lA({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??WS5,X=!1,F=()=>{X=!0};return setImmediate(async()=>{let D=new wB().scoped("update");if(Y>0){if(await QU(Y),X)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!X){let U=await HS5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await QU(zS5),X)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!X){let W=Math.min(K,E);await QU(W),E-=W}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:F}}async function HS5(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 Vf(),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 aj();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 nd4(Z);if(V&&ur(V,F.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:F.latestVersion}),J.updatedTo=V,ur(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!==yr()){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 br(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 od4(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.1777983419-g88aeb8"),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 NS5($.targetVersion)});A.addCommand(B)}function qS5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
|
|
4823
4823
|
`),$=!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 NS5(A){let B=process.platform==="win32"&&nj()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:$,renderProgress:J}=qS5(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.
|
|
4824
4824
|
|
|
4825
4825
|
`));try{if(!A){nD.write(s0.blue(`Checking for updates...
|
|
4826
|
-
`));let X=!1,F;if(nj()){let D=await WD0("0.0.
|
|
4827
|
-
`));let V=await pW("0.0.
|
|
4826
|
+
`));let X=!1,F;if(nj()){let D=await WD0("0.0.1777983419-g88aeb8");X=D.hasUpdate,F=D.latestVersion}else{let D=await aj(),G=await ED0("0.0.1777983419-g88aeb8",D);X=G.hasUpdate,F=G.latestVersion}if(!X){let D=t01("0.0.1777983419-g88aeb8"),G=D?.age?`released ${D.age} ago`:`built ${BU(new Date("2026-05-05T12:20:45.183Z"))} ago`;nD.write(s0.green(`✓ Amp is already up to date on version ${"0.0.1777983419-g88aeb8"} (${G})
|
|
4827
|
+
`));let V=await pW("0.0.1777983419-g88aeb8",B);if(V.warning)nD.write(`
|
|
4828
4828
|
`+s0.yellow(V.warning)+`
|
|
4829
4829
|
`);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}...
|
|
4830
4830
|
`)),await br(A,void 0,(X)=>{$(),nD.write(s0.dim(`Running: ${X}
|
|
@@ -5267,7 +5267,7 @@ ${$}`).join(`
|
|
|
5267
5267
|
`)}function yi5(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 xi5(A){let Q=nI.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 fi5(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}${xi5(J)}`,Z=nI.join(A,Y);try{await Yb(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 bi5(A,Q,B=[]){let $=["# Bug Report","","## Issue Description","",A,""];if(B.length>0){for(let[J,Y]of B.entries())$.push(``);$.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(Zb(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"),Zb(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(`
|
|
5268
5268
|
`)}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($8(Q)):void 0,currentWorkspacePath:W5($8(A.currentWorkspace)),clientId:A.clientId,logFile:A.logFile,pid:process.pid}}async function st4(A){try{let Q=nI.join("/tmp",`amp-thread-${A.thread.id}-${Date.now()}.json`),B=JSON.stringify(A.thread,null,2);await Yb(Q,B,"utf-8"),await IJ(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 tt4(A){try{let Q=nI.join("/tmp",`amp-thread-${A.thread.id}-${Date.now()}.yaml`),B=D51.default.stringify(A.thread);await Yb(Q,B,"utf-8"),await IJ(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 et4(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{L4.instance.tuiInstance.suspend(),Xt(J,{stdio:"inherit"})}finally{process.stdout.write("\x1B[?25l"),L4.instance.tuiInstance.resume()}j.info("Opened filtered CLI logs",{command:J,pid:process.pid,logFile:Ft(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 E6(A.context??A.contextFallback,V51(A.thread.id));return}case"cloudflare-data-studio":{await E6(A.context??A.contextFallback,G51(A.thread.id));return}default:return Error(`Unknown log option: ${Q}`)}}async function Ae4(A){let Q=E51(A),B=rt4(Q),$=!1;try{await L4.instance.tuiInstance.clipboard.writeText(B),$=!0}catch(J){j.error("Failed to copy debug prompt",{error:J})}return new k2(new PA({child:new S6({markdown:[$?"**Copied Markdown debug prompt to clipboard.**":"**Clipboard copy failed. Select and copy manually.**","",B].join(`
|
|
5269
5269
|
`)})}),"Debug Prompt","info","help",{width:100,height:28})}function ui5(A){return typeof A==="object"&&A!==null&&"label"in A&&typeof A.label==="string"&&"command"in A&&typeof A.command==="string"}async function Qe4(A,Q){if(!ui5(Q))return Error("Select a command from the picker");try{await L4.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 Be4(A){return new k2(new PA({child:new S6({markdown:yV0(E51(A))})}),"Thread Diagnostics","info","help",{width:100,height:26})}async function $e4(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=Ft(B),Z=process.pid,X=yi5($)||"debug-package",F=_i5.tmpdir(),D=nI.join(F,`amp-${X}`),G=`${D}.zip`;A.showStatusMessage("Building debug package...");try{Xt(`mkdir -p ${D}`);let V=`select(.pid == ${Z})`,U=Xt(`cat ${Y} | jq -c '${V}'`,{encoding:"utf-8",maxBuffer:52428800});await Yb(nI.join(D,"cli-logs.json"),U,"utf-8"),await Yb(nI.join(D,"thread.yaml"),D51.default.stringify(A.thread),"utf-8");let K=await fi5(D,J),E=bi5($,E51(A),K);await Yb(nI.join(D,"agent-read-this.md"),E,"utf-8"),Xt(`zip -j ${G} ${D}/*`),Xt(`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})}}n8();var hi5=80,gi5=20,Je4=4,mi5=42,De4=420,Ge4=640,pi5=Math.max(32,iU),Ye4="░▒▓█▁▂▃▄▅▆▇∿∾∽≋≈∼",xV0=["▁","▂","▃","▄","▅","▆","▇","█"],di5=["▏","▎","▍","▌","▋","▊","▉","█"],ci5=["▕","▐","▉","▊","▋","▌","▍","▎"],li5=q0.symmetric(1,0),ii5=q0.all(1),ni5=q0.all(1),ai5={primary:{r:102,g:102,b:102},secondary:{r:255,g:255,b:255}},oi5={primary:{r:77,g:0,b:10},secondary:{r:255,g:77,b:95}};function ri5(A){return{borderShape:A?.borderShape??"notched",borderAnimation:A?.borderAnimation??"subtle",titleAnimation:A?.titleAnimation??"none",timeMs:A?.timeMs,animate:A?.animate,seed:A?.seed??mi5}}function Ve4(A){switch(A){case"notched":return ii5;case"classic":return li5}}class _A 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=ri5(this.props.visualStyle),Y=this.props.bodyFit??{kind:"shrink"},Z=Jn5(this.props,Y,B,J.borderShape),X=Fn5($,Q),F=i1.all(new n1(X.border,1,"rounded")),D=z51(this.props.header,J.borderShape),G=H51(this.props.footer,J.borderShape),V=Dn5(D===void 0?this.props.header:void 0,X.header,J),U=Kn5(this.props.child,Y),K=G===void 0?En5(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",z=this.props.autofocus??!0,H=this.props.chromePadding??Ve4(J.borderShape),q=D===void 0&&typeof this.props.header==="string"?1:0,N=G===void 0?Pe4(this.props.footer):0,I=new d4({autofocus:z,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:H,child:I}):ei5({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:H,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:ni5,child:C});return new t4({fit:"expand",children:[new Ue4,new b1({onClick:()=>{},opaque:this.props.barrierOpaque??!0,child:N0.expand()}),new e1({child:O})]})}}class Ue4 extends t3{createRenderObject(){return new Ke4}}class Ke4 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||si5(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 si5(A){return A.char===" "&&A.width===1&&A.hyperlink===void 0&&ti5(A.style)}function ti5(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 z51(A,Q){return Q==="notched"&&typeof A==="string"?A:void 0}function H51(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 ei5(A){if(A.timeMs!==void 0)return Ze4(A,A.timeMs);if(!(A.animate??An5(A)))return Ze4(A,0);return new Ee4({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 Ze4(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 An5(A){return A.titleAnimation!=="none"||A.borderAnimation!=="none"}class Ee4 extends v0{props;constructor(A){super();this.props=A}createState(){return new We4}}class We4 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()},iU),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>=Le4(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 S9(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 S9(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=Vn5(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=ze4(Z,{fg:this.props.footerKeyColor,bg:this.props.background},{fg:this.props.footerHintColor,bg:this.props.background,dim:!0}),F=He4(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=Bn5($,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 di5[B]??"▏";if(A==="right")return ci5[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+Dt(A)*0.82;switch(this.props.tone){case"default":return oQ(Q,void 0,ai5);case"warning":return oQ(Q,Qq);case"success":return oQ(Q,void 0);case"error":return oQ(Q,void 0,oi5)}}sampleBorderIntensity(A,Q,B,$){let J=Math.max(1,B*2+$*2-4),Y=Qn5(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 Dt(F*0.58+V*0.54)}}function Qn5(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 ze4(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 He4(A){return qe4(A).reduce((Q,B)=>Q+B.width,0)}function Bn5(A,Q){if(Q<=0)return[];let B=[],$=0;for(let J of qe4(A)){if($+J.width>Q)return $n5(B,$,Q,J.style);B.push(J),$+=J.width}return B}function qe4(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 $n5(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 Dt(A){return Math.max(0,Math.min(1,A))}function Jn5(A,Q,B,$){let J=Math.max(0,B.size.width-Je4),Y=Math.max(0,B.size.height-Je4),Z=Math.max(A.minWidth??0,Yn5(A,$)),X=Math.max(0,Math.min(A.maxWidth??hi5,J));if(Q.kind==="fill"){let G=Zn5(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??gi5,Y)),D=Math.min(A.minHeight??0,F);return new M1(Math.min(Z,X),X,D,F)}function Yn5(A,Q){if(Q!=="notched")return 0;let B=0,$=z51(A.header,Q);if($)B=Math.max(B,4+a4(` ${$} `));let J=H51(A.footer,Q);if(J)B=Math.max(B,4+He4(ze4(J,{},{})));return B}function Zn5(A,Q){let B=A.chromePadding??Ve4(Q),$=z51(A.header,Q),J=H51(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?Xn5(A.footer):0,D=J===void 0?Pe4(A.footer):0,G=1;return 2+B.top+B.bottom+Z+X+1+D+F}function Xn5(A){if(A===void 0)return 1;if(A==="none")return 0;if(fV0(A))return A.length===0?0:1;return 1}function Fn5(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 Dn5(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 e1({child:Gn5(A,Q,B)})});return A}function Gn5(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:we4(A,Q,B.titleAnimation,$)});return new Ne4({title:A,color:Q,animation:B.titleAnimation})}class Ne4 extends v0{props;constructor(A){super();this.props=A}createState(){return new Ie4}}class Ie4 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()},pi5),this.timer.unref()}stopTimer(){if(!this.timer)return;clearInterval(this.timer),this.timer=null}animationComplete(){return Date.now()-this.startedAt>=Le4(this.widget.props.animation)}build(A){return new l({text:we4(this.widget.props.title,this.widget.props.color,this.widget.props.animation,Date.now()-this.startedAt)})}}function we4(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,Xe4(J,Ce4(J,$),Y,Z));case"scramble":return new M("",void 0,Xe4(J,Me4(J,$),Y,Z))}}function Vn5(A,Q,B){let $=f4(A);switch(Q){case"none":return A;case"wipe":return Ce4($,B).join("");case"scramble":return Me4($,B).join("")}}function Xe4(A,Q,B,$){return Q.map((J,Y)=>{let Z=J===A[Y]?B:$;return new M(J,Z)})}function Ce4(A,Q){let B=Oe4(Dt(Q/De4)),$=Math.floor(B*(A.length+1));return A.map((J,Y)=>{if(Y<$)return J;if(Y===$)return"▒";return" "})}function Me4(A,Q){let $=Oe4(Dt(Q/Ge4))*(A.length+5),J=Math.floor(Q/45);return A.map((Y,Z)=>{if(Dt(($-Z)/5)>=1)return Y;return Un5(Z,J)})}function Un5(A,Q){return Ye4[(A*7+Q*11)%Ye4.length]??"░"}function Le4(A){if(A==="scramble")return Ge4;return De4}function Oe4(A){return 1-(1-A)**3}function Kn5(A,Q){let B=Q.kind==="fill"?"tight":"loose";return new Y9({fit:B,child:new je4({child:A})})}class je4 extends q5{constructor({child:A}){super({child:A})}createRenderObject(){return new Re4}}class Re4 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 En5(A,Q){if(A===void 0)return Fe4([{keys:["Esc"],label:"close"}],Q);if(fV0(A))return A.length===0?new N0({height:0}):Fe4(A,Q);if(A==="none")return new N0({height:0});return A}function fV0(A){return Array.isArray(A)}function Pe4(A){return A===void 0||fV0(A)&&A.length>0?1:0}function Fe4(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 e1({child:l.spans(J)})}function zn5(A){return[{label:"cli: copy tail logs",command:aI("tail",process.pid,{path:A})},{label:"cli: copy logs snapshot",command:aI("snapshot",process.pid,{path:A})},{label:"cli: htop",command:`htop -p ${process.pid}`}]}async function Hn5(A,Q){try{await L4.instance.tuiInstance.clipboard.writeText(A.command)}catch(B){j.error("Failed to copy debug command from Neo command palette",{error:B})}finally{Q()}}function qn5(A,Q){let B=vV0(process.pid,{path:A},"less -R +G");Q();try{L4.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"),L4.instance.tuiInstance.resume()}}function _e4(A){return[{noun:"debug",verb:"page logs",description:"View CLI logs in pager",status:{type:"enabled"},run:(Q,B,$)=>{qn5(A,$)}},{noun:"debug",verb:"copy command",description:"Copy debug command to clipboard",status:{type:"enabled"},run:(Q,B,$)=>{Q.pushWithDismiss((J)=>new _A({header:"Debug: Copy Command",minWidth:80,maxWidth:80,autofocus:!1,footer:"none",onDismiss:J,child:new p6({items:zn5(A),getLabel:(Y)=>Y.label,showBorder:!1,onAccept:(Y)=>{Hn5(Y,$)},onDismiss:J})}))}}]}var Xb="exit-app-key-pressed",Fb="cancel-key-pressed",oI="loading-thread",Db="previous-thread-reference",Gb="double-enter-steer";class Vt extends i4{}class bV0 extends i4{}class uV0 extends i4{}class Ut extends i4{}class hV0 extends i4{}class Kt extends i4{}class Vb extends i4{}class Ub extends i4{}class Et extends i4{}class Wt extends i4{}class zt extends i4{}class Kb extends i4{}class $$ extends i4{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 i4{}class Ht extends i4{}class mV0 extends i4{}class pV0 extends i4{}class qt extends i4{}class Nt extends i4{}class It extends i4{}class dV0 extends i4{}class cV0 extends i4{}class lV0 extends i4{}class fR extends i4{}class wt extends i4{}class N51 extends i4{mode;constructor(A){super();this.mode=A}}C3();var Te4=process.platform==="win32"?" ":"█",Se4=process.platform==="win32"?"░":"█";class F2 extends v0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:A,controller:Q,getScrollInfo:B,thickness:$=1,trackChar:J=Te4,thumbChar:Y=Se4,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 ke4}}class ke4 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 b1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?N5.POINTER:N5.DEFAULT,child:new ve4({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 ve4 extends wI{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:A,controller:Q,getScrollInfo:B,thickness:$=1,trackChar:J=Te4,thumbChar:Y=Se4,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 ye4(this)}updateRenderObject(A){A.updateWidget(this)}}class ye4 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),z=Math.floor(W*8);K=V[z]||"█",E=!1}else if(U===Math.floor(G)){let W=1-(G-U),z=Math.floor(W*8);K=V[z]||"█"}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 xe4=1;class BZ extends v0{props;constructor(A){super();this.props=A}createState(){return new fe4}}class fe4 extends k0{ownership;viewportHeight=0;initState(){let A=this.widget.props.controller;if(A)this.ownership={controller:A,owned:!1};else{let Q=new aA;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 be4({thickness:xe4,onMeasured:this.setMeasuredHeight,scrollable:new PA({controller:B,autofocus:this.widget.props.autofocus??!0,keyboardScrolling:!0,child:this.widget.props.child}),scrollbar:new F2({controller:B,thickness:xe4,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:this.getScrollInfo})})}__testing={isOwned:()=>this.ownership.owned,controller:()=>this.ownership.controller}}class be4 extends T9{thickness;onMeasured;constructor({scrollable:A,scrollbar:Q,thickness:B,onMeasured:$}){super({children:[A,Q]});this.thickness=B,this.onMeasured=$}createRenderObject(){return new ue4(this.thickness,this.onMeasured)}}class ue4 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 he4=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 ge4}}class ge4 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(he4)}`;return` ${`${A}:`.padEnd(he4," ")}`}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} ${E4(this.plugins.length,"plugin")} active (${B} ${E4(B,"command")}, ${$} ${E4($,"tool")})`;return new _A({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 Y9({fit:"loose",child:new BZ({child:new f0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:this.pluginRows(A)})})})]})})}}function me4(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:(Q,B,$)=>{A.pluginService.reload(),A.toastController.show("Reloading plugins..."),$()}}]}o0();class Ct extends i4{}class Eb extends i4{}class w51 extends v0{props;constructor(A){super();this.props=A}createState(){return new pe4}}class pe4 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 _A({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([[Ct,new G4(()=>B())],[Eb,new G4(()=>$())]]),child:new h5({debugLabel:"NeoConfirmDialogShortcuts",shortcuts:Nn5(),child:new BZ({child:Y})})})})}}function Nn5(){return new Map([[v1.key("y"),new Ct],[v1.shift("Y"),new Ct],[v1.shift("y"),new Ct],[v1.key("n"),new Eb],[v1.shift("N"),new Eb],[v1.shift("n"),new Eb],[v1.key("Escape"),new Eb]])}class Mt extends v0{props;constructor(A){super();this.props=A}createState(){return new de4}}class de4 extends k0{controller=new N8;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 tB({controller:this.controller,placeholder:this.widget.props.placeholder??"",autofocus:!0,maxLines:1,style:{textColor:Q.foreground,border:null},onSubmitted:()=>this.handleSubmit()})})]})),new _A({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 _A({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:In5(this.props)})}}function In5(A){let Q=A.options.options.map((B)=>({value:B,label:B}));return new Z9({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 Mt({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()}
|
|
5270
|
-
${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()}}$i();i2();import{readFile as wn5}from"node:fs/promises";import L51 from"node:os";async function ce4(A,Q){try{return{path:Q,contents:xg0(await wn5(A,"utf8"))}}catch{return null}}async function le4(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(QJ(J),null,2)});let Y=await ce4(cx(Q),`logs/${Q}.log`);if(Y)B.push(Y);let Z=await ce4(A.settingsFilePath,"settings/global.json");if(Z)B.push(Z);let X=await Vf()??"unknown",F=await VA.sendReport({threadID:Q,files:B,metadata:{clientVersion:"0.0.1777979451-gaec852",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();s9();i2();async function ie4(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:eY(B)},{config:A.configService});if(!J.ok)throw Error(J.error.message);let Y=!1;if(B!=="private"){let X=RB(new URL(A.ampURL),Q).toString();try{await L4.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 ne4}}class ne4 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 AR,B=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:B})})}pushWithDismiss(A){let Q=new AR,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 d4({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=Cn5(Q);return new _A({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=IR($.item.verb.toLowerCase(),Y),X=IR(J.item.verb.toLowerCase(),Y);if(Z!==X)return X-Z;let F=IR(_51($.item),Y),D=IR(_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 ae4({command:$,isSelected:J,isDisabled:Y,categoryWidth:B,buildContext:Z}),onAccept:($)=>{this.props.onAccept($)},onDismiss:this.props.onDismiss})})}}class ae4 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:Mn5(Q.shortcut,Z,$)});return new oe4({columns:W,padding:q0.horizontal(1),backgroundColor:D})}}function _51(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function Cn5(A){return A.reduce((Q,B)=>{return B.noun?Math.max(Q,a4(B.noun)):Q},0)}function Mn5(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 oe4 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 H6{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 re4}}class re4 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 se4}}class se4 extends k0{scrollController;initState(){this.scrollController=new aA,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,z=Math.max(40,Math.min(80,E)),H=new Set(["permissions-disable"]),N=[...this.widget.commands.filter((O)=>{let _=O.noun?.toLowerCase();return _!=="dev"&&_!=="debug"&&!O.id.startsWith("debug-")&&!H.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 PA({autofocus:!0,controller:this.scrollController,child:new p0({constraints:new M1(z,z,0,Number.POSITIVE_INFINITY),child:new f0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new e1({child:new l({text:new M(`Amp CLI - Help & Keyboard Shortcuts
|
|
5270
|
+
${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()}}$i();i2();import{readFile as wn5}from"node:fs/promises";import L51 from"node:os";async function ce4(A,Q){try{return{path:Q,contents:xg0(await wn5(A,"utf8"))}}catch{return null}}async function le4(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(QJ(J),null,2)});let Y=await ce4(cx(Q),`logs/${Q}.log`);if(Y)B.push(Y);let Z=await ce4(A.settingsFilePath,"settings/global.json");if(Z)B.push(Z);let X=await Vf()??"unknown",F=await VA.sendReport({threadID:Q,files:B,metadata:{clientVersion:"0.0.1777983419-g88aeb8",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();s9();i2();async function ie4(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:eY(B)},{config:A.configService});if(!J.ok)throw Error(J.error.message);let Y=!1;if(B!=="private"){let X=RB(new URL(A.ampURL),Q).toString();try{await L4.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 ne4}}class ne4 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 AR,B=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:B})})}pushWithDismiss(A){let Q=new AR,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 d4({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=Cn5(Q);return new _A({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=IR($.item.verb.toLowerCase(),Y),X=IR(J.item.verb.toLowerCase(),Y);if(Z!==X)return X-Z;let F=IR(_51($.item),Y),D=IR(_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 ae4({command:$,isSelected:J,isDisabled:Y,categoryWidth:B,buildContext:Z}),onAccept:($)=>{this.props.onAccept($)},onDismiss:this.props.onDismiss})})}}class ae4 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:Mn5(Q.shortcut,Z,$)});return new oe4({columns:W,padding:q0.horizontal(1),backgroundColor:D})}}function _51(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function Cn5(A){return A.reduce((Q,B)=>{return B.noun?Math.max(Q,a4(B.noun)):Q},0)}function Mn5(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 oe4 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 H6{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 re4}}class re4 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 se4}}class se4 extends k0{scrollController;initState(){this.scrollController=new aA,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,z=Math.max(40,Math.min(80,E)),H=new Set(["permissions-disable"]),N=[...this.widget.commands.filter((O)=>{let _=O.noun?.toLowerCase();return _!=="dev"&&_!=="debug"&&!O.id.startsWith("debug-")&&!H.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 PA({autofocus:!0,controller:this.scrollController,child:new p0({constraints:new M1(z,z,0,Number.POSITIVE_INFINITY),child:new f0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new e1({child:new l({text:new M(`Amp CLI - Help & Keyboard Shortcuts
|
|
5271
5271
|
`,Z)})}),new N0({height:1}),new u0({padding:q0.horizontal(2),child:new l({text:new M(`Editor Shortcuts
|
|
5272
5272
|
`,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
|
|
5273
5273
|
`,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
|
|
@@ -5321,7 +5321,7 @@ Recent keys (newest first)
|
|
|
5321
5321
|
`),F=Z.length>10?`
|
|
5322
5322
|
... ${Z.length-10} more lines`:"";Y.push(new l({text:new M(X+F,$),selectable:!0}))}break}case"find-thread":{if(A.status!=="done")break;let Z=A.threads.length,X=Z===0?"No threads found":`${Z}${A.hasMore?"+":""} ${E4(Z,"thread")}`;Y.push(new l({text:new M(X,$),selectable:!0}));for(let F of A.threads)Y.push(new HA({uri:new URL(`/threads/${F.id}`,B).toString(),text:F.title?.trim()||F.id,style:new y({color:Q.app.link,underline:!0})}));if(A.hasMore)Y.push(new l({text:new M("More threads available...",new y({color:Q.colors.foreground,dim:!0,italic:!0})),selectable:!0}));break}case"painter":{for(let[Z,X]of A.images.entries())if(Y.push(new Pt({image:X,index:Z,imageCount:A.images.length,expanded:!0})),Z<A.images.length-1)Y.push(new N0({height:1}));break}case"generic":{if(A.args)Y.push(new l({text:new M(A.args,$),selectable:!0}));break}}if(Y.length===0)return null;return new u0({padding:q0.only({left:2}),child:new f0({crossAxisAlignment:"start",children:Y})})}class $31 extends I1{props;constructor(A){super();this.props=A}build(A){let{message:Q,isSelected:B,onShowImagePreview:$}=this.props,J=_0.of(A),{colors:Y}=J,{text:Z,images:X}=Q,F=Y.success,D=F,G=B?J.app.selectedMessage:F,V=new y({color:D,italic:!0}),U=[];if(Q.role==="user"){let E=X,z=za5(A,E,V,(H)=>{let q=E[H];if(q)$(q,H)});if(z)U.push(z)}if(Z){if(U.length>0)U.push(new N0({height:1}));U.push(Ha5(Z,V,!1,Y.warning))}let K;if(U.length===0)K=new p0;else if(U.length===1)K=U[0];else K=new f0({mainAxisSize:"min",crossAxisAlignment:"start",children:U});if(B){let E=new p0({decoration:{color:Y.background,border:i1.all(new n1(G,2,"solid"))},padding:q0.only({left:1,right:1}),width:1/0,child:K}),W=[new M("e",new y({color:J.app.keybind})),new M(" to edit",new y({color:Y.foreground,dim:!0}))];return new SI({child:new t4({children:[E,new EA({left:2,right:0,bottom:0,child:new l({text:new M("",void 0,W)})})]})})}return new p0({decoration:{color:Y.background,border:new i1(void 0,void 0,void 0,new n1(G,2,"solid"))},padding:q0.only({left:1}),child:K})}}function za5(A,Q,B,$){if(Q.length===0)return null;let Y=_0.maybeOf(A)?.colors??k1.of(A).colorScheme,Z=[new l({text:new M("Images: ",new y({color:Y.foreground,dim:!0}))})];for(let X=0;X<Q.length;X++){let F=X;if(Z.push(new b1({onClick:()=>$(F),cursor:"pointer",child:new l({text:new M(`[image ${X+1}]`,new y({color:B.color,italic:B.italic,underline:!0}))})})),X<Q.length-1)Z.push(new l({text:new M(" ")}))}return new u0({padding:q0.only({}),child:new B1({mainAxisSize:"min",children:Z})})}function Ha5(A,Q,B,$){let J=[];if(J.push(new M(A,Q)),B)J.push(new M(" (interrupted)",new y({color:$,italic:!0})));return new l({text:new M("",void 0,J),selectable:!0})}o0();TB();import{randomBytes as qa5}from"node:crypto";import Na5 from"node:fs";import{writeFile as Ia5}from"node:fs/promises";import{tmpdir as wa5}from"node:os";import AU0 from"node:path";function Ca5(A){let Q=A.trim().replace(/^["']|["']$/g,"");if(Q=Q.replace(/\\(.)/g,"$1"),Q=Q.replace(/u\{([0-9a-fA-F]+)\}/g,($,J)=>String.fromCodePoint(parseInt(J,16))),!/\.(png|jpe?g|gif|webp)$/i.test(Q))return null;if(!AU0.isAbsolute(Q))return null;return j.debug("Extracted image path",{original:A,extracted:Q}),Q}function d0A(A){let Q=A.trim().replace(/^["']|["']$/g,""),B=Q.split(`
|
|
5323
5323
|
`).filter(Boolean);if(B.length===1)B=Q.split(/(?<=\.(?:png|jpe?g|gif|webp))\s+(?=["']?\/)/i);return B.map(($)=>Ca5($)).filter(($)=>$!==null)}async function Ma5(A,Q){let B=AU0.extname(A).toLowerCase()||".png",$=`amp-img-${qa5(8).toString("hex")}${B}`,J=AU0.join(wa5(),$);return await Ia5(J,Q),J}async function $F(A){try{let Q;try{Q=Na5.readFileSync(A)}catch(Y){return j.error(`Failed to read image file ${A}:`,Y),`Failed to read image file: ${Y instanceof Error?Y.message:"unknown error"}`}let B=CV(Q);if(!B){let Y=AU0.extname(A).toLowerCase();if(B=Td(Y),!B)return j.warn("Unsupported image format",{imagePath:A}),"Unsupported image format"}let $=_B({source:{type:"file",path:A,data:Q}});if($!==null)return j.warn("Image validation failed",{error:$}),$;let J=await Ma5(A,Q);return La5(Q,B,J)}catch(Q){return j.error("Error handling image file path",{imagePath:A,error:Q}),`Error handling image file: ${Q instanceof Error?Q.message:"unknown error"}`}}function La5(A,Q,B){return{type:"image",source:{type:"base64",data:A.toString("base64"),mediaType:Q},sourcePath:B}}import{mkdtemp as Ra5,readFile as Pa5,rmdir as _a5,unlink as Ta5,writeFile as Sa5}from"node:fs/promises";import{tmpdir as ka5}from"node:os";import s0A from"node:path";o0();o0();class QU0{_listeners=new Set;_disposed=!1;addListener(A){if(this._disposed)throw Error("Cannot add listener to disposed ChangeNotifier");this._listeners.add(A)}removeListener(A){this._listeners.delete(A)}notifyListeners(){if(this._disposed)return;let A=Array.from(this._listeners);for(let Q of A)try{Q()}catch(B){}}dispose(){this._disposed=!0,this._listeners.clear()}get disposed(){return this._disposed}get hasListeners(){return this._listeners.size>0}}class hR extends QU0{_value;constructor(A){super();this._value=A}get value(){return this._value}set value(A){let Q=typeof A==="object"||this._value!==A;if(this._value=A,Q)this.notifyListeners()}}function c0A(A,Q){let B=()=>{Q()};return A.addListener(B),{dispose:()=>A.removeListener(B)}}class J31 extends q5{link;showWhenUnlinked;offset;constructor({key:A,link:Q,showWhenUnlinked:B=!0,offset:$={x:0,y:0},child:J}){super({key:A,child:J});this.link=Q,this.showWhenUnlinked=B,this.offset=$}createElement(){return new dU(this)}createRenderObject(){return new l0A(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(A){A.link=this.link,A.showWhenUnlinked=this.showWhenUnlinked,A.setFollowerOffset(this.offset)}}class l0A extends Y4{_link;_showWhenUnlinked;_followerOffset;_cachedPosition=null;constructor(A,Q,B){super();this._link=A,this._showWhenUnlinked=Q,this._followerOffset=B}get link(){return this._link}set link(A){this._link=A,this._cachedPosition=null,this.markNeedsLayout()}get showWhenUnlinked(){return this._showWhenUnlinked}set showWhenUnlinked(A){if(this._showWhenUnlinked!==A)this._showWhenUnlinked=A,this.markNeedsLayout()}setFollowerOffset(A){if(this._followerOffset.x!==A.x||this._followerOffset.y!==A.y)this._followerOffset={...A},this.markNeedsLayout()}calculatePosition(){let A=this._link.getTargetTransform();if(!A)return null;return{x:A.position.x+this._followerOffset.x,y:A.position.y+this._followerOffset.y}}getParentGlobalOffset(){let A=0,Q=0,B=this.parent;while(B&&B instanceof Y4)A+=B.offset.x,Q+=B.offset.y,B=B.parent;return{x:A,y:Q}}shouldShow(){return this._link.target!==null||this._showWhenUnlinked}performLayout(){let A=this._lastConstraints;if(N4(!!A,"performLayout called without constraints"),!this.shouldShow()){this.setSize(0,0),super.performLayout();return}let Q=this.calculatePosition();if(this._cachedPosition=Q,Q){let B=this.getParentGlobalOffset();this.setOffset(Q.x-B.x,Q.y-B.y)}if(this.children.length>0){let B=this.children[0];B.layout(A.loosen());let $=B.size;this.setSize($.width,$.height)}else this.setSize(0,0);super.performLayout()}getCurrentPosition(){return this._cachedPosition}setOffset(A,Q){super.setOffset(A,Q)}paint(A,Q=0,B=0){super.paint(A,Q,B)}}class Y31 extends q5{link;constructor({key:A,link:Q,child:B}){super({key:A,child:B});this.link=Q}createElement(){return new dU(this)}createRenderObject(){return new i0A(this.link)}updateRenderObject(A){A.link=this.link}}class i0A extends Y4{_link;_globalPosition={x:0,y:0};constructor(A){super();this._link=A}get link(){return this._link}set link(A){if(this._link===A)return;this._link._setTarget(null),this._link=A,this._link._setTarget(this)}attach(){super.attach(),this._link._setTarget(this)}detach(){this._link._setTarget(null),super.detach()}getGlobalPosition(){let A=this.offset.x,Q=this.offset.y,B=this.parent;while(B&&B instanceof Y4)A+=B.offset.x,Q+=B.offset.y,B=B.parent;return{x:A,y:Q}}getSize(){let A=this.size;return{width:A.width,height:A.height}}updateGlobalPosition(){let A={...this._globalPosition};if(this._globalPosition=this.getGlobalPosition(),A.x!==this._globalPosition.x||A.y!==this._globalPosition.y)this._link._notifyFollowers()}performLayout(){let A=this._lastConstraints;if(N4(!!A,"performLayout called without constraints"),this.children.length>0){let Q=this.children[0];Q.layout(A);let B=Q.size;this.setSize(B.width,B.height)}else this.setSize(0,0);this.updateGlobalPosition(),super.performLayout()}}o0();class Z31{_target=null;_followers=new Set;get target(){return this._target}_setTarget(A){if(this._target===A)return;this._target=A,this._notifyFollowers()}_addFollower(A){this._followers.add(A)}_removeFollower(A){this._followers.delete(A)}_notifyFollowers(){for(let A of this._followers)try{A()}catch(Q){j.error("Error in LayerLink follower callback:",Q)}}getTargetTransform(){if(!this._target)return null;return{position:this._target.getGlobalPosition(),size:this._target.getSize()}}}o0();var Oa5=500;class X31{_state;_textController=null;_lastText="";_triggers=[];_optionsBuilder=null;_onSelected=null;_pendingBuildTimer=null;_disposed=!1;constructor(){let A={trigger:null,options:[],selectedIndex:-1,isActive:!1,generationId:0};this._state=new hR(A)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:A,triggers:Q,optionsBuilder:B,onSelected:$}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=A,this._lastText=A.text,this._triggers=Q,this._optionsBuilder=B,this._onSelected=$||null,this._textController.addListener(this._handleTextChange)}selectNext(){let A=this.currentState;if(!A.isActive||A.options.length===0)return;let Q=A.selectedIndex<A.options.length-1?A.selectedIndex+1:0;this._updateState({selectedIndex:Q})}selectPrevious(){let A=this.currentState;if(!A.isActive||A.options.length===0)return;let Q=A.selectedIndex>0?A.selectedIndex-1:A.options.length-1;this._updateState({selectedIndex:Q})}acceptSelected(){let A=this.currentState;if(!A.isActive||A.selectedIndex<0||A.selectedIndex>=A.options.length)return;let Q=A.options[A.selectedIndex];if(!Q)return;if(this.dismiss(),this._onSelected)this._onSelected(Q)}dismiss(){this._clearPendingBuildTimer(),this._updateState({trigger:null,options:[],selectedIndex:-1,isActive:!1})}dispose(){this._disposed=!0,this._cleanup(),this._state.dispose()}_handleTextChange=()=>{if(!this._textController||!this._optionsBuilder)return;let A=this.currentState.trigger,Q=this._textController.text,B=Q!==this._lastText;if(this._lastText=Q,!B&&!this.currentState.isActive)return;let $=this._textController.cursorPosition,J=null;for(let X of this._triggers){let F=X.detect(Q,$);if(F&&(!J||F.start>J.start))J=F}if(!this.currentState.isActive&&J&&J.query.length>0){let X=f4(Q),F=$,D=F;while(D<X.length){let G=X[D];if(G&&/[\s)\]}@]/.test(G))break;D++}if(D>F){let V=[...X.slice(0,F),...X.slice(D)].join("");this._textController.text=V,this._textController.cursorPosition=$;return}}if(!J){if(this.currentState.isActive)this.dismiss();else this._clearPendingBuildTimer();return}let Y=B&&this._shouldDebounceBuild(A,J),Z=this.currentState.generationId+1;if(this._updateState({trigger:J,generationId:Z,options:Y?[]:this.currentState.options,isActive:!Y,selectedIndex:-1}),Y){this._scheduleDebouncedBuild(J.query,Z);return}this._clearPendingBuildTimer(),this._buildOptions(J.query,Z)};async _buildOptions(A,Q){if(!this._optionsBuilder)return;try{let B=await this._optionsBuilder(A);if(this.currentState.generationId===Q&&!this._disposed)this._updateState({options:B,selectedIndex:B.length>0?0:-1,isActive:B.length>0})}catch(B){if(j.error("Error building autocomplete options:",B),this.currentState.generationId===Q&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_scheduleDebouncedBuild(A,Q){this._clearPendingBuildTimer(),this._pendingBuildTimer=setTimeout(()=>{this._pendingBuildTimer=null,this._buildOptions(A,Q)},Oa5)}_shouldDebounceBuild(A,Q){if(!A)return!1;if(A.trigger!==Q.trigger||A.start!==Q.start)return!1;return Q.query.length<A.query.length}_clearPendingBuildTimer(){if(this._pendingBuildTimer)clearTimeout(this._pendingBuildTimer),this._pendingBuildTimer=null}_updateState(A){if(this._disposed)return;this._state.value={...this.currentState,...A}}_cleanup(){if(this._clearPendingBuildTimer(),this._textController)this._textController.removeListener(this._handleTextChange)}}class _t{}class Tt{}class St{}class BU0{}class $U0 extends v0{props;constructor(A){super({key:A.key});this.props=A}createState(){return new n0A(this.props)}}class n0A extends k0{props;controller;stateListener=null;overlayEntry=null;layerLink=new Z31;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(A){super();this.props=A}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new X6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new X31,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=c0A(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.handle)this.props.handle.dismiss=()=>this.controller.dismiss()}didUpdateWidget(A){super.didUpdateWidget(A);let Q=A.props,B=this.widget.props;if(this.props=B,Q.controller!==B.controller||Q.triggers!==B.triggers||Q.optionsBuilder!==B.optionsBuilder||Q.textFieldProps!==B.textFieldProps||Q.onSelected!==B.onSelected)this.controller.initialize({textController:B.controller,triggers:B.triggers,optionsBuilder:B.optionsBuilder,onSelected:B.onSelected});if(Q.handle!==B.handle){if(B.handle)B.handle.dismiss=()=>this.controller.dismiss()}this.setState(()=>{})}dispose(){this.removeOverlay(),this.stateListener?.dispose(),this.controller.dispose(),this._effectiveFocusNode.dispose(),super.dispose()}invoke=(A)=>{if(!this.controller.currentState.isActive)return"ignored";if(A instanceof _t)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(A instanceof Tt)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(A instanceof St)return this.controller.acceptSelected(),"handled";if(A instanceof BU0)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let A=this.controller.currentState;if(!A.isActive||A.selectedIndex<0)return;let Q=A.selectedIndex,B=A.options.length,$=this._cachedMaxVisibleOptions||B;if($>=B){this.scrollOffset=0;return}let J=Q-this.scrollOffset,Y=1,Z=this.scrollOffset;if(J>=$-Y)Z=Math.max(0,Q-($-Y-1));if(J<Y)Z=Math.max(0,Q-Y);let X=Math.max(0,B-$);Z=Math.min(Z,X),this.scrollOffset=Z}build(A){let Q=new tB({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:this.props.autofocus??!0}),B=new h5({shortcuts:new Map([[new v1("ArrowDown"),new _t],[new v1("ArrowUp"),new Tt],[new v1("n",{ctrl:!0}),new _t],[new v1("p",{ctrl:!0}),new Tt],[new v1("Enter"),new St],[new v1("Escape"),new BU0],[new v1("Tab"),new St]]),focusNode:this._effectiveFocusNode,child:Q}),$=new FA({actions:new Map([[_t,new G4(this.invoke)],[Tt,new G4(this.invoke)],[St,new G4(this.invoke)],[BU0,new G4(this.invoke)]]),child:B});return new Y31({link:this.layerLink,child:$})}updateOverlay(){let A=this.controller.currentState;if(A.isActive&&A.options.length>0)if(!this.overlayEntry)this.createOverlay();else this.overlayEntry.markNeedsBuild();else this.removeOverlay()}createOverlay(){if(this.overlayEntry)return;this.overlayEntry=new Yz((A)=>{let Q=this.controller.currentState;return this.buildOverlayContent(A,Q)});try{J$.of(this.context).insert(this.overlayEntry)}catch(A){j.error("Failed to insert autocomplete overlay:",A),this.overlayEntry=null}}removeOverlay(){if(this.overlayEntry)this.overlayEntry.remove(),this.overlayEntry=null}buildOverlayHints(A,Q){if(this.props.overlayHint!==void 0){if(this.props.overlayHint===null)return[];let{prefix:B,suffix:$}=this.props.overlayHint,J=[];if(B)J.push(new M(B,new y({color:_0.of(A).app.command})),new M(" ",new y({color:Q})));return J.push(new M($,new y({color:Q}))),[{child:new l({text:new M(" ",new y({dim:!0}),J)}),position:"top",alignment:"center"}]}return[]}buildOverlayContent(A,Q){let B=k1.maybeOf(A),$=B?.colorScheme.background??z0.default(),J=this.props.overlayBorderColor??B?.colorScheme.border??z0.default(),Y=Q.options.length,Z=B4.sizeOf(A).height,X=0;try{let _=this.layerLink.getTargetTransform();if(_)X=_.position.y}catch{}let F=this.props.autoOverlayPosition?X<Z/3:!1,D=2,G;if(F){let _=this.props.controller.getCursorVisualRow(),S=X+_+1;G=Z-S-D}else G=X-D;Y=Math.min(Y,Math.max(1,G)),this._cachedMaxVisibleOptions=Y,this.updateScrollPosition();let V=this.scrollOffset,U=Math.min(Q.options.length,V+Y),K=[],E=0;for(let _=V;_<U;_++){let S=Q.options[_];if(!S)continue;let T=_===Q.selectedIndex,b,h;if(this.props.optionViewBuilder){b=this.props.optionViewBuilder(A,S,T);let u=this.props.displayStringForOption?.(S)??String(S),m="",d=u,g=S;if(g&&typeof g==="object"&&"type"in g)switch(g.type){case"file":m="@",d=g.path||u;break;case"artifact":m="",d=g.label||u;break}h=m+d}else{let u=this.props.displayStringForOption?.(S)??String(S),m=B?.colorScheme.selection??z0.default(),d=B?.colorScheme.foreground??z0.default();b=new l({text:new M(u,new y({color:d,backgroundColor:T?m:void 0}))}),h=u}let x=B4.of(A),v=a4(h,x.supportsEmojiWidth);E=Math.max(E,v),K.push(b)}let W=B4.sizeOf(A).width,z=E+4,H=Math.floor(W*0.9),q=Math.max(Math.min(z,H),Math.min(30,H)),w=K.length+2,C;if(F)C=this.props.controller.getCursorVisualRow()+1;else C=-w;let O=new N0({width:q,child:new p0({height:w,decoration:new x4($),child:new q8({decoration:{border:i1.all(new n1(J,1,"rounded"))},padding:q0.symmetric(1,0),overlays:this.buildOverlayHints(A,J),child:new f0({crossAxisAlignment:"start",children:K})})})});return new J31({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:C},child:O})}}function a0A(A){if(A.kind!=="file"&&A.kind!=="folder")throw Error("Invalid completion item: missing path or kind");return{type:"file",path:A.path,kind:A.kind}}function o0A(A){switch(A.type){case"file":return A.path;case"hint":return`${ja5(A.kind)} ${A.message}`;case"commit":return`${A.shortHash} ${A.message} (${A.relativeDate})`}}function r0A(A){switch(A.type){case"file":return;case"hint":return;case"commit":return}}function ja5(A){switch(A){case"commit":return"@:";case"thread":return"@@"}}class LJ{detect(A,Q){if(!A||Q<1)return null;let B=f4(A);if(Q>B.length)return null;let $=this.findWordStart(B,Q);if($>=B.length||B[$]!=="@")return null;let J=B.slice($+1,Q).join("");if(J.includes(" ")||J.includes("\t")||J.includes(`
|
|
5324
|
-
`))return null;return{start:$,end:Q,query:J,trigger:"@"}}findWordStart(A,Q){let B=Q;for(let $=Q-1;$>=0;$--){let J=A[$];if(!J||/[\s([{]/.test(J)){B=$+1;break}if($===0)B=0}return B}}async function F31(A,Q=A.text){try{let B=await Ra5(s0A.join(ka5(),"amp-edit-")),$=s0A.join(B,"message.amp.md");await Sa5($,Q,"utf-8"),await IJ($);try{A.text=await Pa5($,"utf-8")}catch(J){if(J?.code!=="ENOENT")j.error("Failed to read temporary file",J)}try{await Ta5($),await _a5(B)}catch(J){j.warn("Failed to clean up temporary file",J)}}catch(B){j.error("Error opening editor:",B)}}class ZG extends v0{props;constructor(A){super({key:A.key});this.props=A}createState(){return new t0A(this.props)}}var va5=":";class t0A extends k0{props;_effectiveFocusNode;_textChangeListener=null;_isCommitMode=!1;_imageUploadSpinner=new z6;_imageUploadSpinnerInterval=null;constructor(A){super();this.props=A}buildOptions=async(A)=>{let Q=this.props.controller.text,B=this.props.controller.cursorPosition,J=new LJ().detect(Q,B);if(J&&this.props.completionBuilder){if(J.query==="@"&&this.props.onDoubleAtTrigger)return this.props.onDoubleAtTrigger(this.props.controller),[];let X=J.query.toLowerCase().startsWith(va5);if(X!==this._isCommitMode)this._isCommitMode=X,this.setState();return await this.props.completionBuilder.buildOptions(J)}if(this._isCommitMode)this._isCommitMode=!1,this.setState();return[]};defaultOnOptionSelected=(A)=>{switch(A.type){case"hint":{let Q=this.props.controller.text,B=this.props.controller.cursorPosition,J=Q.slice(0,B).lastIndexOf("@");if(J!==-1){let Y=Q.slice(0,J),Z=Q.slice(B),X=A.kind==="commit"?"@:":"@@",F=Y+X+Z;this.props.controller.clear(),this.props.controller.insertText(F),this.props.controller.cursorPosition=J+X.length}return}case"file":{let Q=this.props.controller.text,B=this.props.controller.cursorPosition,J=Q.slice(0,B).lastIndexOf("@");if(J!==-1){let Y=Q.slice(0,J),Z=Q.slice(B),X=Y+`@${A.path} `+Z;this.props.controller.clear(),this.props.controller.insertText(X),this.props.controller.cursorPosition=J+1+A.path.length+1}break}case"commit":{let Q=this.props.controller.text,B=this.props.controller.cursorPosition,J=Q.slice(0,B).lastIndexOf("@");if(J!==-1){let Y=Q.slice(0,J),Z=Q.slice(B),X=`git-commit(${A.hash})`,F=Y+X+" "+Z;this.props.controller.clear(),this.props.controller.insertText(F),this.props.controller.cursorPosition=J+X.length+1}break}}};initState(){super.initState(),this._effectiveFocusNode=this.props.focusNode||new X6({debugLabel:"PromptEditorFocus"}),this._textChangeListener=()=>{this.setState()},this.props.controller.addListener(this._textChangeListener),this.props.controller.onInsertText=(A,Q)=>{if(A.length<=3)return!0;let B=d0A(A);if(B.length===0)return!0;if(this.props.onInsertImage){for(let $ of B)this.props.onInsertImage($);return!1}return!0},this.syncImageUploadSpinner()}didUpdateWidget(A){super.didUpdateWidget(A),this.props=this.widget.props,this.syncImageUploadSpinner()}dispose(){if(this._imageUploadSpinnerInterval)clearInterval(this._imageUploadSpinnerInterval),this._imageUploadSpinnerInterval=null;if(this._textChangeListener)this.props.controller.removeListener(this._textChangeListener),this._textChangeListener=null;if(!this.props.focusNode)this._effectiveFocusNode.dispose();super.dispose()}syncImageUploadSpinner(){if((this.props.uploadingImageIndices?.size??0)>0){if(!this._imageUploadSpinnerInterval)this._imageUploadSpinnerInterval=setInterval(()=>{this._imageUploadSpinner.step(),this.setState()},120);return}if(this._imageUploadSpinnerInterval)clearInterval(this._imageUploadSpinnerInterval),this._imageUploadSpinnerInterval=null}_handleOpenInEditor=async(A)=>{await F31(this.props.controller,A)};_handleBackspaceAtStart=()=>{if(this.props.imageAttachments.length>0&&this.props.popImage)return this.props.popImage(),!0;if((this.props.pendingSkills??[]).length>0&&this.props.popSkill)return this.props.popSkill(),!0;return!1};_handleSubmitted=(A)=>{if(this.props.previousThreadId&&A.trim()===""){this.props.onPreviousThreadHintAccepted?.();return}this.props.onSubmitted?.(A)};build(A){let Q=this.props.theme,B=this.props.pendingSkills??[],$=this.props.imageAttachments.length>0,J=B.length>0?new B1({mainAxisSize:"min",children:[new l({text:new M("Skills: ",new y({color:Q.foreground,dim:!0}))}),...B.flatMap((F,D)=>{let G=new b1({onClick:()=>{this.props.onSkillClick?.(D)},cursor:"pointer",child:new l({text:new M(F.name,new y({color:Q.success,underline:!0}))})});if(D<B.length-1)return[G,new l({text:new M(" ")})];return[G]})]}):null,Y=$?new B1({mainAxisSize:"min",children:[new l({text:new M("Images: ",new y({color:Q.foreground,dim:!0}))}),...this.props.imageAttachments.flatMap((F,D)=>{let G=this.props.uploadingImageIndices?.has(D)===!0,V=this.props.onImageClick!==void 0&&!G,U=G?`[Image ${this._imageUploadSpinner.toBraille()}]`:`[Image ${D+1}]`,K=new b1({onClick:V?()=>{this.props.onImageClick?.(D)}:void 0,cursor:V?"pointer":void 0,child:new l({text:new M(U,new y({color:G?Q.foreground:Q.success,underline:!G,dim:G}))})});if(D<this.props.imageAttachments.length-1)return[K,new l({text:new M(" ")})];return[K]})]}):null,Z=new $U0({controller:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.buildOptions,onSelected:this.props.onOptionSelected??this.defaultOnOptionSelected,displayStringForOption:(F)=>o0A(F),overlayBorderColor:Q.border,focusNode:this._effectiveFocusNode,autofocus:this.props.autofocus??!0,autoOverlayPosition:this.props.autoOverlayPosition,handle:this.props.autocompleteHandle,textFieldProps:{placeholder:this.props.placeholder,wrap:!0,minLines:this.props.minLines??3,maxLines:null,expands:!0,autofocus:!1,enabled:this.props.enabled??!0,onSubmitted:this._handleSubmitted,onOpenInEditor:this._handleOpenInEditor,submitKey:this.props.submitKey??{character:"Enter"},prompts:this.props.shellPromptRules,style:{backgroundColor:Q.background,border:null,padding:q0.all(0),textColor:this.props.textColor??Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,selectionBackgroundColor:Q.selection},clipboard:this.props.clipboard,onCopy:this.props.onCopy,copyOnSelectionEnabled:!0,onBackspaceWhenEmpty:this._handleBackspaceAtStart},optionViewBuilder:(F,D,G)=>{let V=G?Q.selection:void 0,U=Q.secondary,K=Q.foreground,E=Q.foreground,W=Q.warning;if(D.type==="commit")return new p0({decoration:new x4(V),child:new B1({children:[new S1({child:new l({text:new M("",void 0,[new M(D.shortHash,new y({color:Q.secondary})),new M(" ",new y({})),new M(D.message,new y({color:K}))]),maxLines:1,overflow:"ellipsis"})}),new l({text:new M(` ${D.relativeDate}`,new y({color:E,dim:!0}))})]})});let z=[];switch(D.type){case"file":z.push(new M("@",new y({color:U}))),z.push(new M(D.path,new y({color:K})));break;case"hint":z.push(new M(D.kind==="commit"?"@:":"@@",new y({color:W}))),z.push(new M(" ",new y({}))),z.push(new M(D.message,new y({color:W})));break}let H=r0A(D);if(H)z.push(new M(" - ",new y({color:E,dim:!0}))),z.push(new M(H,new y({color:E,dim:!0})));return new p0({decoration:new x4(V),child:new l({text:new M("",void 0,z),maxLines:1,overflow:"ellipsis"})})}}),X=[];if(this.props.topWidget)X.push(this.props.topWidget);if(J||Y){let F=[];if(J)F.push(J);if(J&&Y)F.push(new l({text:new M(" ")}));if(Y)F.push(Y);let D=new p0({padding:q0.only({bottom:1}),child:new B1({mainAxisSize:"min",children:F})});X.push(D)}if(X.push(new Y9({fit:this.props.fillAvailableHeight===!1?"loose":"tight",child:Z})),this.props.bottomWidget)X.push(this.props.bottomWidget);return new f0({mainAxisSize:"min",crossAxisAlignment:"start",children:X})}requestFocus(){this._effectiveFocusNode.requestFocus()}}class D31 extends v0{controller;initialImages;onSubmitted;onShowImagePreview;constructor(A){super();this.controller=A.controller,this.initialImages=A.initialImages,this.onSubmitted=A.onSubmitted,this.onShowImagePreview=A.onShowImagePreview}createState(){return new e0A}}class e0A extends k0{imageAttachments=[];initState(){this.imageAttachments=[...this.widget.initialImages]}handleSubmit=(A)=>{this.widget.onSubmitted(A,this.imageAttachments)};handleInsertImage=async(A)=>{let Q=await $F(A);if(typeof Q==="object")this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q]});return!1};handlePopImage=()=>{if(this.imageAttachments.length===0)return;this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};handleImageClick=(A)=>{let Q=this.imageAttachments[A];if(Q)this.widget.onShowImagePreview(Q,A)};build(A){let Q=_0.of(A),B=Q.colors,$=Q.app.selectedMessage,J=new ZG({controller:this.widget.controller,triggers:[new LJ],completionBuilder:rI.of(A),onSubmitted:this.handleSubmit,theme:B,placeholder:"",enabled:!0,autofocus:!0,imageAttachments:this.imageAttachments,onInsertImage:this.handleInsertImage,popImage:this.handlePopImage,onImageClick:this.handleImageClick,minLines:1,textColor:$,autoOverlayPosition:!0,submitKey:{character:"Enter"}}),Y=[new M("esc",new y({color:Q.app.keybind})),new M(" to cancel",new y({color:B.foreground,dim:!0}))];return new d4({debugLabel:"Neo Message Editing",child:new SI({child:new t4({children:[new p0({decoration:{color:B.background,border:i1.all(new n1($,2,"solid"))},padding:q0.only({left:1,right:1}),width:1/0,child:J}),new EA({left:2,right:0,bottom:0,child:new l({text:new M("",void 0,Y)})})]})})})}}class G31 extends v0{threadController;copyOnSelectEnabled;onShowImagePreview;editingMessageId;editingController;onSubmitEdit;constructor(A){super();this.threadController=A.threadController,this.copyOnSelectEnabled=A.copyOnSelectEnabled,this.onShowImagePreview=A.onShowImagePreview,this.editingMessageId=A.editingMessageId,this.editingController=A.editingController,this.onSubmitEdit=A.onSubmitEdit}createState(){return new A1A}}class A1A extends k0{scrollController=new aA;listViewKey=new J2("neo-message-view-list");threadControllerUnsubscription;initState(){this.setupThreadController(this.widget.threadController)}didUpdateWidget(A){if(A.threadController!==this.widget.threadController)this.unsubscribeCurrentThreadController(),this.setupThreadController(this.widget.threadController)}dispose(){this.unsubscribeCurrentThreadController(),this.scrollController.dispose()}build(A){let Q=this.widget.threadController.entries;return new l51({key:this.listViewKey,position:"bottom",autofocus:!1,controller:this.scrollController,itemCount:Q.length,itemBuilder:(B,$)=>{let J=Q[$];if(N4(!!J,"NeoMessageView missing transcript entry for realized list index"),!J)return new N0;return new u0({padding:q0.horizontal(1),child:this.entryToWidget(J,$)})},itemSpacing:1,enableSelection:!0,copyOnSelectEnabled:this.widget.copyOnSelectEnabled,onCopy:this.onCopy,showScrollbar:!0})}onCopy=(A)=>{if(!A)return;FA.maybeInvoke(this.context,new $$(A))};entryToWidget(A,Q){switch(A.type){case"message":if(A.role==="user"){let B=ya5(A.sourceMessageID);if(B!==void 0&&B===this.widget.editingMessageId&&this.widget.editingController)return new D31({controller:this.widget.editingController,initialImages:A.images,onSubmitted:($,J)=>this.widget.onSubmitEdit(B,$,J),onShowImagePreview:($,J)=>this.widget.onShowImagePreview(this.context,$,J)});return new $31({message:A,onShowImagePreview:($,J)=>this.widget.onShowImagePreview(this.context,$,J),isSelected:Q===this.widget.threadController.selectedMessageIndex})}return new n51({message:A});case"tool":return this.toolEntryToWidget(A);case"activity-group":return new i51({group:A});case"compaction":return new l({text:new M("Compacted",new y({color:_0.of(this.context).colors.foreground,dim:!0,italic:!0}))});case"thinking":return new N0}}toolEntryToWidget(A){let Q=this.widget.threadController.getSubagentForToolEntry(A);if(Q!==null)return new a51({tool:Q.tool,name:oZ(Q.tool.name),entries:Q.entries,getSubagentEntriesForToolRowID:this.widget.threadController.getSubagentEntriesForToolRowID.bind(this.widget.threadController)});return new B31(m0A(A))}setupThreadController(A){A.onSelectionChange=this.onSelectionChange,A.onScrollToBottom=this.scrollToBottom,A.onPageUp=this.pageUp,A.onPageDown=this.pageDown,this.threadControllerUnsubscription=A.subscribe(this.onThreadControllerUpdate)}unsubscribeCurrentThreadController(){this.threadControllerUnsubscription?.()}scrollToBottom=()=>{this.scrollController.enableFollowMode(),this.scrollController.scrollToBottom()};pageUp=()=>{let A=this.listViewKey.getCurrentState()?.viewportHeight;if(A)this.scrollController.animatePageUp(A)};pageDown=()=>{let A=this.listViewKey.getCurrentState()?.viewportHeight;if(A)this.scrollController.animatePageDown(A)};onSelectionChange=(A)=>{if(A!==null){let Q=this.listViewKey.getCurrentState();N4(!!Q,"NeoMessageView expected mounted ListViewState before scrolling");let B=Q.getEstimatedOffsetForIndex(A);this.scrollController.animateTo(B,{duration:150,curve:"easeInOutCubic"})}else this.scrollToBottom()};onThreadControllerUpdate=()=>{if(!this.mounted)return;this.setState()}}function ya5(A){return g6.safeParse(A).data}l4();class qb extends I1{props;constructor(A){super();this.props=A}static rowText(A){return A.queuedMessage.content.filter(y14).map((Q)=>Q.text).join(" ").trim()}build(A){let{queuedMessages:Q,selectedIndex:B,bottomRightLabel:$}=this.props,J=k1.of(A),Y=_0.of(A),Z=new n1(J.colorScheme.border,1,"rounded"),X=[];if($)X.push({child:$,position:"bottom",alignment:"right",offsetX:-1});let F=Q.filter((E)=>E.steer),D=Q.filter((E)=>!E.steer),G=F.length>0,V=D.length>0,U=[],K=0;if(G)U.push(...this.buildRows(F,K,B,J,Y)),K+=F.length;if(G&&V)U.push(new $1A({borderSide:Z}));if(V)U.push(...this.buildRows(D,K,B,J,Y));return new q8({decoration:new x4(void 0,i1.all(Z)),overlays:X,child:new u0({padding:q0.horizontal(1),child:new f0({mainAxisSize:"max",crossAxisAlignment:"stretch",children:U})})})}buildRows(A,Q,B,$,J){return A.map((Y,Z)=>{let F=Q+Z===B,D=Y.steer===!0,G=F?$.colorScheme.foreground:$.colorScheme.mutedForeground,V=new y({color:G,bold:F,dim:Y.pendingRemoval}),U=F?new y({dim:!0}):new y({bold:!0}),K=qb.rowText(Y),E=F?fa5($,J,D):xa5($);return new B1({children:[new S1({child:D?new Q1A({text:K,baseStyle:V,pulseStyle:U}):new l({text:new M("",void 0,[new M(K,V)]),maxLines:1,overflow:"ellipsis"})}),...E?[new u0({padding:q0.only({left:3}),child:E})]:[]]})})}}function xa5(A){return new l({text:new M("queued",new y({color:A.colorScheme.mutedForeground,dim:!0})),maxLines:1,overflow:"clip"})}function fa5(A,Q,B){let $=new y({color:A.colorScheme.mutedForeground}),J=new y({color:Q.app.keybind}),Y=B?[new M("Steering, ",new y({color:A.colorScheme.mutedForeground,dim:!0}))]:[new M("Enter",J),new M(" to steer, ",$)];return new l({text:new M("",void 0,[...Y,new M("Backspace",J),new M(" to dequeue",$)]),maxLines:1,overflow:"clip"})}var V31=10,ba5=34;function ua5(A){return 0.5-Math.cos(A*Math.PI)/2}class Q1A extends v0{props;constructor(A){super();this.props=A}createState(){return new B1A}}class B1A extends k0{frame=0;intervalId=null;initState(){super.initState(),this.intervalId=setInterval(()=>{this.setState(()=>{this.frame++})},45)}dispose(){if(this.intervalId)clearInterval(this.intervalId),this.intervalId=null;super.dispose()}build(){let A=f4(this.widget.props.text),Q=Math.max(5,Math.ceil(A.length/4)),B=this.frame%(V31+ba5),$=ua5(B/V31),J=B<V31?Math.floor($*(A.length+Q))-Q:A.length,Y=J+Q,Z=A.map((X,F)=>new M(X,F>=J&&F<Y?this.widget.props.baseStyle.merge(this.widget.props.pulseStyle):this.widget.props.baseStyle));return new l({text:new M("",void 0,Z),maxLines:1,overflow:"ellipsis"})}}class $1A extends I1{props;constructor(A){super();this.props=A}build(){return new p0({height:1,decoration:{border:new i1(this.props.borderSide)}})}}n8();var JU0=220,ha5=40,ga5=5,U31=30;function K31(A,Q){let B=D8(A),$=(B?.displayName??A).toLowerCase();if(Q!==void 0){let J=B?.reasoningEffortControl?.levels.indexOf(Q);if(J===1)return{base:$,superscript:"²",plainReasoningIndex:"2",text:`${$}²`};if(J===2)return{base:$,superscript:"³",plainReasoningIndex:"3",text:`${$}³`};if(J===3)return{base:$,superscript:"⁴",plainReasoningIndex:"4",text:`${$}⁴`}}return{base:$,superscript:"",plainReasoningIndex:void 0,text:$}}class W31 extends I1{agentMode;reasoningEffort;speedCostMultiplier;colorOverride;animate;reasoningEffortAnimation;horizontalPadding;constructor(A){super();this.agentMode=A.agentMode,this.reasoningEffort=A.reasoningEffort,this.speedCostMultiplier=A.speedCostMultiplier,this.colorOverride=A.color,this.animate=A.animate??!0,this.reasoningEffortAnimation=A.reasoningEffortAnimation??"promote",this.horizontalPadding=A.horizontalPadding??0}build(A){let Q=this.colorOverride??aW(this.agentMode),B=new J1A({agentMode:this.agentMode,reasoningEffort:this.reasoningEffort,speedCostMultiplier:this.speedCostMultiplier,color:Q,animate:this.animate,reasoningEffortAnimation:this.reasoningEffortAnimation,horizontalPadding:this.horizontalPadding}),$=this.buildToggleModeHandler(A);if(!$)return new b1({child:B});return new b1({onClick:$,cursor:"pointer",child:B})}buildToggleModeHandler(A){return FA.handler(A,new fR)??void 0}}class J1A extends v0{props;constructor(A){super();this.props=A}createState(){return new Y1A}}class Y1A extends k0{effortAnimation=null;previousMode=null;timer=null;initState(){this.previousMode=this.widget.props.agentMode}didUpdateWidget(A){let Q=A.props.agentMode!==this.widget.props.agentMode,B=A.props.reasoningEffort!==this.widget.props.reasoningEffort;if(Q||!this.widget.props.animate)this.stopTimer(),this.effortAnimation=null;else if(B&&this.widget.props.reasoningEffortAnimation==="swipe")this.stopTimer(),this.effortAnimation=null;else if(B){let $=K31(A.props.agentMode,A.props.reasoningEffort),J=K31(this.widget.props.agentMode,this.widget.props.reasoningEffort);if($.text!==J.text)this.effortAnimation={startedAt:Date.now(),from:$,to:J},this.startTimer();else this.stopTimer(),this.effortAnimation=null}this.previousMode=A.props.agentMode}dispose(){this.stopTimer()}build(A){let Q=this.widget.props,B=K31(Q.agentMode,Q.reasoningEffort),$=this.effortAnimation?Date.now()-this.effortAnimation.startedAt:0,J=this.buildFrame(A,B,$),Y=da5(J),X=this.previousMode!==null&&this.previousMode!==Q.agentMode||Q.reasoningEffortAnimation==="swipe"?`${Q.agentMode}:${Q.reasoningEffort??""}`:Q.agentMode,F=Q.animate&&!this.effortAnimation;return new N0({width:J.width,height:J.height,child:F?new oW({child:Y.richText,contentKey:X}):Y.widget})}buildFrame(A,Q,B){let $=this.widget.props;return pa5({parts:Q,plan:ma5(Q,this.effortAnimation,B),modeColor:$.color,warningColor:k1.of(A).colorScheme.warning,horizontalPadding:$.horizontalPadding,speedCostMultiplier:$.speedCostMultiplier})}startTimer(){if(this.timer)return;this.timer=setInterval(()=>{if(!this.effortAnimation){this.stopTimer();return}if(Date.now()-this.effortAnimation.startedAt>=JU0){this.stopTimer(),this.setState(()=>{this.effortAnimation=null});return}this.setState()},ha5)}stopTimer(){if(this.timer)clearInterval(this.timer),this.timer=null}}function ma5(A,Q,B){if(!Q)return E31(A.superscript);if(Q.to.plainReasoningIndex){if(B>=JU0)return E31(Q.to.superscript);let J=Q.from.superscript==="",Y=J?Math.max(0,B-U31):B,Z=J?JU0-U31:JU0;return{suffix:"",reserveSuffixCell:!J||B>=U31,incomingNumber:{value:Q.to.superscript,progress:na5(Z1A(Y/Z))}}}return E31(Q.to.superscript)}function E31(A){return{suffix:A,reserveSuffixCell:!1,incomingNumber:null}}function pa5({parts:A,plan:Q,modeColor:B,warningColor:$,horizontalPadding:J,speedCostMultiplier:Y}){let Z=new y({color:B}),X=[],F=[],D=0,G=(K,E)=>{if(!K)return;X.push({text:K,x:D,style:E}),D+=a4(K)},V=" ".repeat(J);if(G(V,void 0),Y)G("↯",new y({color:$}));G(A.base,Z);let U=D;if(Q.suffix)G(Q.suffix,Z);else if(Q.reserveSuffixCell)G(" ",void 0);if(G(V,void 0),Q.incomingNumber){let K=U+ga5,E=Math.round(U+(K-U)*(1-Q.incomingNumber.progress));F.push({text:Q.incomingNumber.value,x:E,yOffset:0,style:new y({color:B,bold:!0})})}return{segments:X,overlays:F,width:Math.max(1,D),height:1}}function da5(A){let Q=new l({text:new M("",void 0,A.segments.map((B)=>new M(B.text,B.style))),maxLines:1,overflow:"clip"});if(A.height===1&&A.overlays.length===0&&ca5(A))return{richText:Q,widget:Q};return{richText:Q,widget:new t4({children:[new N0({width:A.width,height:A.height}),...A.segments.map(la5),...A.overlays.map(ia5)]})}}function ca5(A){let Q=0;for(let B of A.segments){if(B.x!==Q)return!1;Q+=a4(B.text)}return Q===A.width}function la5(A){return new EA({left:A.x,top:0,width:a4(A.text),height:1,child:new l({text:new M(A.text,A.style),maxLines:1,overflow:"clip"})})}function ia5(A){return new EA({left:A.x,top:A.yOffset,width:a4(A.text),height:1,child:new l({text:new M(A.text,A.style),maxLines:1,overflow:"clip"})})}function Z1A(A){return Math.max(0,Math.min(1,A))}function na5(A){return 1-(1-Z1A(A))**2}YU();class z31 extends v0{error;onResponse;presentationOptions;constructor({key:A,error:Q,onResponse:B,presentationOptions:$}){super({key:A});this.error=Q,this.onResponse=B,this.presentationOptions=$??{}}createState(){return new F1A}}class F1A extends k0{hideAddCreditsActionForCurrentError=!1;didCopy=!1;countdownInterval=null;initState(){this.startCountdownIfNeeded()}didUpdateWidget(A){if(A.error.retryAt!==this.widget.error.retryAt)this.startCountdownIfNeeded();if(A.error.message===this.widget.error.message)return;this.hideAddCreditsActionForCurrentError=!1,this.didCopy=!1}dispose(){this.stopCountdown()}startCountdownIfNeeded(){this.stopCountdown();let{retryAt:A}=this.widget.error;if(A===void 0||A<=Date.now())return;this.countdownInterval=setInterval(()=>{if(this.widget.error.retryAt===void 0){this.stopCountdown();return}if(this.widget.error.retryAt<=Date.now())this.stopCountdown();this.setState()},1000)}stopCountdown(){if(this.countdownInterval!==null)clearInterval(this.countdownInterval),this.countdownInterval=null}computeRetryCountdown(){let{retryAt:A}=this.widget.error;if(A===void 0)return;return Math.max(0,Math.ceil((A-Date.now())/1000))}buildClipboardText(A){let Q=JU(X1A(this.widget.error)).trim(),B=[A.title,A.description];if(Q&&Q!==A.description)B.push(`Original error: ${Q}`);return B.join(`
|
|
5324
|
+
`))return null;return{start:$,end:Q,query:J,trigger:"@"}}findWordStart(A,Q){let B=Q;for(let $=Q-1;$>=0;$--){let J=A[$];if(!J||/[\s([{]/.test(J)){B=$+1;break}if($===0)B=0}return B}}async function F31(A,Q=A.text){try{let B=await Ra5(s0A.join(ka5(),"amp-edit-")),$=s0A.join(B,"message.amp.md");await Sa5($,Q,"utf-8"),await IJ($);try{A.text=await Pa5($,"utf-8")}catch(J){if(J?.code!=="ENOENT")j.error("Failed to read temporary file",J)}try{await Ta5($),await _a5(B)}catch(J){j.warn("Failed to clean up temporary file",J)}}catch(B){j.error("Error opening editor:",B)}}class ZG extends v0{props;constructor(A){super({key:A.key});this.props=A}createState(){return new t0A(this.props)}}var va5=":";class t0A extends k0{props;_effectiveFocusNode;_textChangeListener=null;_isCommitMode=!1;_imageUploadSpinner=new z6;_imageUploadSpinnerInterval=null;constructor(A){super();this.props=A}buildOptions=async(A)=>{let Q=this.props.controller.text,B=this.props.controller.cursorPosition,J=new LJ().detect(Q,B);if(J&&this.props.completionBuilder){if(J.query==="@"&&this.props.onDoubleAtTrigger)return this.props.onDoubleAtTrigger(this.props.controller),[];let X=J.query.toLowerCase().startsWith(va5);if(X!==this._isCommitMode)this._isCommitMode=X,this.setState();return await this.props.completionBuilder.buildOptions(J)}if(this._isCommitMode)this._isCommitMode=!1,this.setState();return[]};defaultOnOptionSelected=(A)=>{switch(A.type){case"hint":{let Q=this.props.controller.text,B=this.props.controller.cursorPosition,J=Q.slice(0,B).lastIndexOf("@");if(J!==-1){let Y=Q.slice(0,J),Z=Q.slice(B),X=A.kind==="commit"?"@:":"@@",F=Y+X+Z;this.props.controller.clear(),this.props.controller.insertText(F),this.props.controller.cursorPosition=J+X.length}return}case"file":{let Q=this.props.controller.text,B=this.props.controller.cursorPosition,J=Q.slice(0,B).lastIndexOf("@");if(J!==-1){let Y=Q.slice(0,J),Z=Q.slice(B),X=Y+`@${A.path} `+Z;this.props.controller.clear(),this.props.controller.insertText(X),this.props.controller.cursorPosition=J+1+A.path.length+1}break}case"commit":{let Q=this.props.controller.text,B=this.props.controller.cursorPosition,J=Q.slice(0,B).lastIndexOf("@");if(J!==-1){let Y=Q.slice(0,J),Z=Q.slice(B),X=`git-commit(${A.hash})`,F=Y+X+" "+Z;this.props.controller.clear(),this.props.controller.insertText(F),this.props.controller.cursorPosition=J+X.length+1}break}}};initState(){super.initState(),this._effectiveFocusNode=this.props.focusNode||new X6({debugLabel:"PromptEditorFocus"}),this._textChangeListener=()=>{this.setState()},this.props.controller.addListener(this._textChangeListener),this.props.controller.onInsertText=(A,Q)=>{if(A.length<=3)return!0;let B=d0A(A);if(B.length===0)return!0;if(this.props.onInsertImage){for(let $ of B)this.props.onInsertImage($);return!1}return!0},this.syncImageUploadSpinner()}didUpdateWidget(A){super.didUpdateWidget(A),this.props=this.widget.props,this.syncImageUploadSpinner()}dispose(){if(this._imageUploadSpinnerInterval)clearInterval(this._imageUploadSpinnerInterval),this._imageUploadSpinnerInterval=null;if(this._textChangeListener)this.props.controller.removeListener(this._textChangeListener),this._textChangeListener=null;if(!this.props.focusNode)this._effectiveFocusNode.dispose();super.dispose()}syncImageUploadSpinner(){if((this.props.uploadingImageIndices?.size??0)>0){if(!this._imageUploadSpinnerInterval)this._imageUploadSpinnerInterval=setInterval(()=>{this._imageUploadSpinner.step(),this.setState()},120);return}if(this._imageUploadSpinnerInterval)clearInterval(this._imageUploadSpinnerInterval),this._imageUploadSpinnerInterval=null}_handleOpenInEditor=async(A)=>{await F31(this.props.controller,A)};_handleBackspaceAtStart=()=>{if(this.props.imageAttachments.length>0&&this.props.popImage)return this.props.popImage(),!0;if((this.props.pendingSkills??[]).length>0&&this.props.popSkill)return this.props.popSkill(),!0;return!1};_handleSubmitted=(A)=>{if(this.props.previousThreadId&&A.trim()===""){this.props.onPreviousThreadHintAccepted?.();return}this.props.onSubmitted?.(A)};build(A){let Q=this.props.theme,B=this.props.pendingSkills??[],$=this.props.imageAttachments.length>0,J=B.length>0?new B1({mainAxisSize:"min",children:[new l({text:new M("Skills: ",new y({color:Q.foreground,dim:!0}))}),...B.flatMap((F,D)=>{let G=new b1({onClick:()=>{this.props.onSkillClick?.(D)},cursor:"pointer",child:new l({text:new M(F.name,new y({color:Q.success,underline:!0}))})});if(D<B.length-1)return[G,new l({text:new M(" ")})];return[G]})]}):null,Y=$?new B1({mainAxisSize:"min",children:[new l({text:new M("Images: ",new y({color:Q.foreground,dim:!0}))}),...this.props.imageAttachments.flatMap((F,D)=>{let G=this.props.uploadingImageIndices?.has(D)===!0,V=this.props.onImageClick!==void 0&&!G,U=G?`[Image ${this._imageUploadSpinner.toBraille()}]`:`[Image ${D+1}]`,K=new b1({onClick:V?()=>{this.props.onImageClick?.(D)}:void 0,cursor:V?"pointer":void 0,child:new l({text:new M(U,new y({color:G?Q.foreground:Q.success,underline:!G,dim:G}))})});if(D<this.props.imageAttachments.length-1)return[K,new l({text:new M(" ")})];return[K]})]}):null,Z=new $U0({controller:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.buildOptions,onSelected:this.props.onOptionSelected??this.defaultOnOptionSelected,displayStringForOption:(F)=>o0A(F),overlayBorderColor:Q.border,focusNode:this._effectiveFocusNode,autofocus:this.props.autofocus??!0,autoOverlayPosition:this.props.autoOverlayPosition,handle:this.props.autocompleteHandle,textFieldProps:{placeholder:this.props.placeholder,wrap:!0,minLines:this.props.minLines??3,maxLines:null,expands:!0,autofocus:!1,enabled:this.props.enabled??!0,onSubmitted:this._handleSubmitted,onOpenInEditor:this._handleOpenInEditor,submitKey:this.props.submitKey??{character:"Enter"},prompts:this.props.shellPromptRules,style:{backgroundColor:Q.background,border:null,padding:q0.all(0),textColor:this.props.textColor??Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,selectionBackgroundColor:Q.selection},clipboard:this.props.clipboard,onCopy:this.props.onCopy,copyOnSelectionEnabled:!0,onBackspaceWhenEmpty:this._handleBackspaceAtStart},optionViewBuilder:(F,D,G)=>{let V=G?Q.selection:void 0,U=Q.secondary,K=Q.foreground,E=Q.foreground,W=Q.warning;if(D.type==="commit")return new p0({decoration:new x4(V),child:new B1({children:[new S1({child:new l({text:new M("",void 0,[new M(D.shortHash,new y({color:Q.secondary})),new M(" ",new y({})),new M(D.message,new y({color:K}))]),maxLines:1,overflow:"ellipsis"})}),new l({text:new M(` ${D.relativeDate}`,new y({color:E,dim:!0}))})]})});let z=[];switch(D.type){case"file":z.push(new M("@",new y({color:U}))),z.push(new M(D.path,new y({color:K})));break;case"hint":z.push(new M(D.kind==="commit"?"@:":"@@",new y({color:W}))),z.push(new M(" ",new y({}))),z.push(new M(D.message,new y({color:W})));break}let H=r0A(D);if(H)z.push(new M(" - ",new y({color:E,dim:!0}))),z.push(new M(H,new y({color:E,dim:!0})));return new p0({decoration:new x4(V),child:new l({text:new M("",void 0,z),maxLines:1,overflow:"ellipsis"})})}}),X=[];if(this.props.topWidget)X.push(this.props.topWidget);if(J||Y){let F=[];if(J)F.push(J);if(J&&Y)F.push(new l({text:new M(" ")}));if(Y)F.push(Y);let D=new p0({padding:q0.only({bottom:1}),child:new B1({mainAxisSize:"min",children:F})});X.push(D)}if(X.push(new Y9({fit:this.props.fillAvailableHeight===!1?"loose":"tight",child:Z})),this.props.bottomWidget)X.push(this.props.bottomWidget);return new f0({mainAxisSize:"min",crossAxisAlignment:"start",children:X})}requestFocus(){this._effectiveFocusNode.requestFocus()}}class D31 extends v0{controller;initialImages;onSubmitted;onShowImagePreview;constructor(A){super();this.controller=A.controller,this.initialImages=A.initialImages,this.onSubmitted=A.onSubmitted,this.onShowImagePreview=A.onShowImagePreview}createState(){return new e0A}}class e0A extends k0{imageAttachments=[];initState(){this.imageAttachments=[...this.widget.initialImages]}handleSubmit=(A)=>{this.widget.onSubmitted(A,this.imageAttachments)};handleInsertImage=async(A)=>{let Q=await $F(A);if(typeof Q==="object")this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q]});return!1};handlePopImage=()=>{if(this.imageAttachments.length===0)return;this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};handleImageClick=(A)=>{let Q=this.imageAttachments[A];if(Q)this.widget.onShowImagePreview(Q,A)};build(A){let Q=_0.of(A),B=Q.colors,$=Q.app.selectedMessage,J=new ZG({controller:this.widget.controller,triggers:[new LJ],completionBuilder:rI.of(A),onSubmitted:this.handleSubmit,theme:B,placeholder:"",enabled:!0,autofocus:!0,imageAttachments:this.imageAttachments,onInsertImage:this.handleInsertImage,popImage:this.handlePopImage,onImageClick:this.handleImageClick,minLines:1,textColor:$,autoOverlayPosition:!0,submitKey:{character:"Enter"}}),Y=[new M("esc",new y({color:Q.app.keybind})),new M(" to cancel",new y({color:B.foreground,dim:!0}))];return new d4({debugLabel:"Neo Message Editing",child:new SI({child:new t4({children:[new p0({decoration:{color:B.background,border:i1.all(new n1($,2,"solid"))},padding:q0.only({left:1,right:1}),width:1/0,child:J}),new EA({left:2,right:0,bottom:0,child:new l({text:new M("",void 0,Y)})})]})})})}}class G31 extends v0{threadController;copyOnSelectEnabled;onShowImagePreview;editingMessageId;editingController;onSubmitEdit;constructor(A){super();this.threadController=A.threadController,this.copyOnSelectEnabled=A.copyOnSelectEnabled,this.onShowImagePreview=A.onShowImagePreview,this.editingMessageId=A.editingMessageId,this.editingController=A.editingController,this.onSubmitEdit=A.onSubmitEdit}createState(){return new A1A}}class A1A extends k0{scrollController=new aA;listViewKey=new J2("neo-message-view-list");threadControllerUnsubscription;initState(){this.setupThreadController(this.widget.threadController)}didUpdateWidget(A){if(A.threadController!==this.widget.threadController)this.unsubscribeCurrentThreadController(),this.setupThreadController(this.widget.threadController)}dispose(){this.unsubscribeCurrentThreadController(),this.scrollController.dispose()}build(A){let Q=this.widget.threadController.entries;return new l51({key:this.listViewKey,position:"bottom",autofocus:!1,controller:this.scrollController,itemCount:Q.length,itemBuilder:(B,$)=>{let J=Q[$];if(N4(!!J,"NeoMessageView missing transcript entry for realized list index"),!J)return new N0;return new u0({padding:q0.horizontal(1),child:this.entryToWidget(J,$)})},itemSpacing:1,enableSelection:!0,copyOnSelectEnabled:this.widget.copyOnSelectEnabled,onCopy:this.onCopy,showScrollbar:!0})}onCopy=(A)=>{if(!A)return;FA.maybeInvoke(this.context,new $$(A))};entryToWidget(A,Q){switch(A.type){case"message":if(A.role==="user"){let B=ya5(A.sourceMessageID);if(B!==void 0&&B===this.widget.editingMessageId&&this.widget.editingController)return new D31({controller:this.widget.editingController,initialImages:A.images,onSubmitted:($,J)=>this.widget.onSubmitEdit(B,$,J),onShowImagePreview:($,J)=>this.widget.onShowImagePreview(this.context,$,J)});return new $31({message:A,onShowImagePreview:($,J)=>this.widget.onShowImagePreview(this.context,$,J),isSelected:Q===this.widget.threadController.selectedMessageIndex})}return new n51({message:A});case"tool":return this.toolEntryToWidget(A);case"activity-group":return new i51({group:A});case"compaction":return new l({text:new M("Compacted",new y({color:_0.of(this.context).colors.foreground,dim:!0,italic:!0}))});case"thinking":return new N0}}toolEntryToWidget(A){let Q=this.widget.threadController.getSubagentForToolEntry(A);if(Q!==null)return new a51({tool:Q.tool,name:oZ(Q.tool.name),entries:Q.entries,getSubagentEntriesForToolRowID:this.widget.threadController.getSubagentEntriesForToolRowID.bind(this.widget.threadController)});return new B31(m0A(A))}setupThreadController(A){A.onSelectionChange=this.onSelectionChange,A.onScrollToBottom=this.scrollToBottom,A.onPageUp=this.pageUp,A.onPageDown=this.pageDown,this.threadControllerUnsubscription=A.subscribe(this.onThreadControllerUpdate)}unsubscribeCurrentThreadController(){this.threadControllerUnsubscription?.()}scrollToBottom=()=>{this.scrollController.enableFollowMode(),this.scrollController.scrollToBottom()};pageUp=()=>{let A=this.listViewKey.getCurrentState()?.viewportHeight;if(A)this.scrollController.animatePageUp(A)};pageDown=()=>{let A=this.listViewKey.getCurrentState()?.viewportHeight;if(A)this.scrollController.animatePageDown(A)};onSelectionChange=(A)=>{if(A!==null){let Q=this.listViewKey.getCurrentState();N4(!!Q,"NeoMessageView expected mounted ListViewState before scrolling");let B=Q.getEstimatedOffsetForIndex(A);this.scrollController.animateTo(B,{duration:150,curve:"easeInOutCubic"})}else this.scrollToBottom()};onThreadControllerUpdate=()=>{if(!this.mounted)return;this.setState()}}function ya5(A){return g6.safeParse(A).data}l4();class qb extends I1{props;constructor(A){super();this.props=A}static rowText(A){return A.queuedMessage.content.filter(y14).map((Q)=>Q.text).join(" ").trim()}build(A){let{queuedMessages:Q,selectedIndex:B,bottomRightLabel:$}=this.props,J=k1.of(A),Y=_0.of(A),Z=new n1(J.colorScheme.border,1,"rounded"),X=[];if($)X.push({child:$,position:"bottom",alignment:"right",offsetX:-1});let F=Q.filter((E)=>E.steer),D=Q.filter((E)=>!E.steer),G=F.length>0,V=D.length>0,U=[],K=0;if(G)U.push(...this.buildRows(F,K,B,J,Y)),K+=F.length;if(G&&V)U.push(new $1A({borderSide:Z}));if(V)U.push(...this.buildRows(D,K,B,J,Y));return new q8({decoration:new x4(void 0,i1.all(Z)),overlays:X,child:new u0({padding:q0.horizontal(1),child:new f0({mainAxisSize:"max",crossAxisAlignment:"stretch",children:U})})})}buildRows(A,Q,B,$,J){return A.map((Y,Z)=>{let F=Q+Z===B,D=Y.steer===!0,G=F?$.colorScheme.foreground:$.colorScheme.mutedForeground,V=new y({color:G,bold:F,dim:Y.pendingRemoval}),U=F?new y({dim:!0}):new y({bold:!0}),K=qb.rowText(Y),E=F?fa5($,J,D):xa5($,D);return new B1({children:[new S1({child:D?new Q1A({text:K,baseStyle:V,pulseStyle:U}):new l({text:new M("",void 0,[new M(K,V)]),maxLines:1,overflow:"ellipsis"})}),...E?[new u0({padding:q0.only({left:3}),child:E})]:[]]})})}}function xa5(A,Q){return new l({text:new M(Q?"steering":"queued",new y({color:A.colorScheme.mutedForeground,dim:!0})),maxLines:1,overflow:"clip"})}function fa5(A,Q,B){let $=new y({color:A.colorScheme.mutedForeground}),J=new y({color:Q.app.keybind}),Y=B?[new M("Steering, ",new y({color:A.colorScheme.mutedForeground,dim:!0}))]:[new M("Enter",J),new M(" to steer, ",$)];return new l({text:new M("",void 0,[...Y,new M("Backspace",J),new M(" to dequeue",$)]),maxLines:1,overflow:"clip"})}var V31=10,ba5=34;function ua5(A){return 0.5-Math.cos(A*Math.PI)/2}class Q1A extends v0{props;constructor(A){super();this.props=A}createState(){return new B1A}}class B1A extends k0{frame=0;intervalId=null;initState(){super.initState(),this.intervalId=setInterval(()=>{this.setState(()=>{this.frame++})},45)}dispose(){if(this.intervalId)clearInterval(this.intervalId),this.intervalId=null;super.dispose()}build(){let A=f4(this.widget.props.text),Q=Math.max(5,Math.ceil(A.length/4)),B=this.frame%(V31+ba5),$=ua5(B/V31),J=B<V31?Math.floor($*(A.length+Q))-Q:A.length,Y=J+Q,Z=A.map((X,F)=>new M(X,F>=J&&F<Y?this.widget.props.baseStyle.merge(this.widget.props.pulseStyle):this.widget.props.baseStyle));return new l({text:new M("",void 0,Z),maxLines:1,overflow:"ellipsis"})}}class $1A extends I1{props;constructor(A){super();this.props=A}build(){return new p0({height:1,decoration:{border:new i1(this.props.borderSide)}})}}n8();var JU0=220,ha5=40,ga5=5,U31=30;function K31(A,Q){let B=D8(A),$=(B?.displayName??A).toLowerCase();if(Q!==void 0){let J=B?.reasoningEffortControl?.levels.indexOf(Q);if(J===1)return{base:$,superscript:"²",plainReasoningIndex:"2",text:`${$}²`};if(J===2)return{base:$,superscript:"³",plainReasoningIndex:"3",text:`${$}³`};if(J===3)return{base:$,superscript:"⁴",plainReasoningIndex:"4",text:`${$}⁴`}}return{base:$,superscript:"",plainReasoningIndex:void 0,text:$}}class W31 extends I1{agentMode;reasoningEffort;speedCostMultiplier;colorOverride;animate;reasoningEffortAnimation;horizontalPadding;constructor(A){super();this.agentMode=A.agentMode,this.reasoningEffort=A.reasoningEffort,this.speedCostMultiplier=A.speedCostMultiplier,this.colorOverride=A.color,this.animate=A.animate??!0,this.reasoningEffortAnimation=A.reasoningEffortAnimation??"promote",this.horizontalPadding=A.horizontalPadding??0}build(A){let Q=this.colorOverride??aW(this.agentMode),B=new J1A({agentMode:this.agentMode,reasoningEffort:this.reasoningEffort,speedCostMultiplier:this.speedCostMultiplier,color:Q,animate:this.animate,reasoningEffortAnimation:this.reasoningEffortAnimation,horizontalPadding:this.horizontalPadding}),$=this.buildToggleModeHandler(A);if(!$)return new b1({child:B});return new b1({onClick:$,cursor:"pointer",child:B})}buildToggleModeHandler(A){return FA.handler(A,new fR)??void 0}}class J1A extends v0{props;constructor(A){super();this.props=A}createState(){return new Y1A}}class Y1A extends k0{effortAnimation=null;previousMode=null;timer=null;initState(){this.previousMode=this.widget.props.agentMode}didUpdateWidget(A){let Q=A.props.agentMode!==this.widget.props.agentMode,B=A.props.reasoningEffort!==this.widget.props.reasoningEffort;if(Q||!this.widget.props.animate)this.stopTimer(),this.effortAnimation=null;else if(B&&this.widget.props.reasoningEffortAnimation==="swipe")this.stopTimer(),this.effortAnimation=null;else if(B){let $=K31(A.props.agentMode,A.props.reasoningEffort),J=K31(this.widget.props.agentMode,this.widget.props.reasoningEffort);if($.text!==J.text)this.effortAnimation={startedAt:Date.now(),from:$,to:J},this.startTimer();else this.stopTimer(),this.effortAnimation=null}this.previousMode=A.props.agentMode}dispose(){this.stopTimer()}build(A){let Q=this.widget.props,B=K31(Q.agentMode,Q.reasoningEffort),$=this.effortAnimation?Date.now()-this.effortAnimation.startedAt:0,J=this.buildFrame(A,B,$),Y=da5(J),X=this.previousMode!==null&&this.previousMode!==Q.agentMode||Q.reasoningEffortAnimation==="swipe"?`${Q.agentMode}:${Q.reasoningEffort??""}`:Q.agentMode,F=Q.animate&&!this.effortAnimation;return new N0({width:J.width,height:J.height,child:F?new oW({child:Y.richText,contentKey:X}):Y.widget})}buildFrame(A,Q,B){let $=this.widget.props;return pa5({parts:Q,plan:ma5(Q,this.effortAnimation,B),modeColor:$.color,warningColor:k1.of(A).colorScheme.warning,horizontalPadding:$.horizontalPadding,speedCostMultiplier:$.speedCostMultiplier})}startTimer(){if(this.timer)return;this.timer=setInterval(()=>{if(!this.effortAnimation){this.stopTimer();return}if(Date.now()-this.effortAnimation.startedAt>=JU0){this.stopTimer(),this.setState(()=>{this.effortAnimation=null});return}this.setState()},ha5)}stopTimer(){if(this.timer)clearInterval(this.timer),this.timer=null}}function ma5(A,Q,B){if(!Q)return E31(A.superscript);if(Q.to.plainReasoningIndex){if(B>=JU0)return E31(Q.to.superscript);let J=Q.from.superscript==="",Y=J?Math.max(0,B-U31):B,Z=J?JU0-U31:JU0;return{suffix:"",reserveSuffixCell:!J||B>=U31,incomingNumber:{value:Q.to.superscript,progress:na5(Z1A(Y/Z))}}}return E31(Q.to.superscript)}function E31(A){return{suffix:A,reserveSuffixCell:!1,incomingNumber:null}}function pa5({parts:A,plan:Q,modeColor:B,warningColor:$,horizontalPadding:J,speedCostMultiplier:Y}){let Z=new y({color:B}),X=[],F=[],D=0,G=(K,E)=>{if(!K)return;X.push({text:K,x:D,style:E}),D+=a4(K)},V=" ".repeat(J);if(G(V,void 0),Y)G("↯",new y({color:$}));G(A.base,Z);let U=D;if(Q.suffix)G(Q.suffix,Z);else if(Q.reserveSuffixCell)G(" ",void 0);if(G(V,void 0),Q.incomingNumber){let K=U+ga5,E=Math.round(U+(K-U)*(1-Q.incomingNumber.progress));F.push({text:Q.incomingNumber.value,x:E,yOffset:0,style:new y({color:B,bold:!0})})}return{segments:X,overlays:F,width:Math.max(1,D),height:1}}function da5(A){let Q=new l({text:new M("",void 0,A.segments.map((B)=>new M(B.text,B.style))),maxLines:1,overflow:"clip"});if(A.height===1&&A.overlays.length===0&&ca5(A))return{richText:Q,widget:Q};return{richText:Q,widget:new t4({children:[new N0({width:A.width,height:A.height}),...A.segments.map(la5),...A.overlays.map(ia5)]})}}function ca5(A){let Q=0;for(let B of A.segments){if(B.x!==Q)return!1;Q+=a4(B.text)}return Q===A.width}function la5(A){return new EA({left:A.x,top:0,width:a4(A.text),height:1,child:new l({text:new M(A.text,A.style),maxLines:1,overflow:"clip"})})}function ia5(A){return new EA({left:A.x,top:A.yOffset,width:a4(A.text),height:1,child:new l({text:new M(A.text,A.style),maxLines:1,overflow:"clip"})})}function Z1A(A){return Math.max(0,Math.min(1,A))}function na5(A){return 1-(1-Z1A(A))**2}YU();class z31 extends v0{error;onResponse;presentationOptions;constructor({key:A,error:Q,onResponse:B,presentationOptions:$}){super({key:A});this.error=Q,this.onResponse=B,this.presentationOptions=$??{}}createState(){return new F1A}}class F1A extends k0{hideAddCreditsActionForCurrentError=!1;didCopy=!1;countdownInterval=null;initState(){this.startCountdownIfNeeded()}didUpdateWidget(A){if(A.error.retryAt!==this.widget.error.retryAt)this.startCountdownIfNeeded();if(A.error.message===this.widget.error.message)return;this.hideAddCreditsActionForCurrentError=!1,this.didCopy=!1}dispose(){this.stopCountdown()}startCountdownIfNeeded(){this.stopCountdown();let{retryAt:A}=this.widget.error;if(A===void 0||A<=Date.now())return;this.countdownInterval=setInterval(()=>{if(this.widget.error.retryAt===void 0){this.stopCountdown();return}if(this.widget.error.retryAt<=Date.now())this.stopCountdown();this.setState()},1000)}stopCountdown(){if(this.countdownInterval!==null)clearInterval(this.countdownInterval),this.countdownInterval=null}computeRetryCountdown(){let{retryAt:A}=this.widget.error;if(A===void 0)return;return Math.max(0,Math.ceil((A-Date.now())/1000))}buildClipboardText(A){let Q=JU(X1A(this.widget.error)).trim(),B=[A.title,A.description];if(Q&&Q!==A.description)B.push(`Original error: ${Q}`);return B.join(`
|
|
5325
5325
|
|
|
5326
5326
|
`)}copyErrorToClipboard(A,Q){let B=this.buildClipboardText(Q);FA.maybeInvoke(A,new $$(B)),this.setState(()=>{this.didCopy=!0})}build(A){let Q=_0.of(A),B=this.widget.presentationOptions.ampURL??X9.of(A).ampURL,$=lN(X1A(this.widget.error),this.widget.presentationOptions),J=this.hideAddCreditsActionForCurrentError?$.actions.filter((F)=>F!=="add-credits"):$.actions,Y=this.computeRetryCountdown(),Z=J.filter((F)=>F!=="dismiss"&&F!=="handoff"&&F!=="new-thread").map((F)=>({value:F,label:$x(F,{ampURL:B,retryCountdown:Y})}));Z.push({value:"copy",label:this.didCopy?"Copy to Clipboard ✓":"Copy to Clipboard"}),Z.push({value:"dismiss",label:$x("dismiss")});let X=this.buildBodyWithLinks(A,$.description);return new Z9({title:$.title,body:X,options:Z,onSelect:(F)=>{let D=F??"dismiss";if(D==="copy"){this.copyErrorToClipboard(A,$);return}if(D==="add-credits"){if(E6(A,new URL("/pay",B)),!this.hideAddCreditsActionForCurrentError)this.setState(()=>{this.hideAddCreditsActionForCurrentError=!0});this.widget.onResponse(D);return}if(this.hideAddCreditsActionForCurrentError)this.setState(()=>{this.hideAddCreditsActionForCurrentError=!1});this.widget.onResponse(D)},borderColor:Q.colors.destructive,autofocus:!0,showDismissalMessage:!1,enableMouseInteraction:!1})}buildBodyWithLinks(A,Q){if(!Q)return;let B=/(https?:\/\/[^\s]+)/g,$=[],J=0;for(let Y of Q.matchAll(B)){let Z=Y[0],X=Y.index??0;if(X>J)$.push(new M(Q.slice(J,X)));let F=HA.createSpan(Z,Z);$.push(new M(F.text,F.style,F.children,F.hyperlink,()=>{E6(A,Z)})),J=X+Z.length}if(J<Q.length)$.push(new M(Q.slice(J)));return new e3({child:new l({text:new M(void 0,void 0,$),selectable:!0})})}}function X1A(A){return{message:A.message}}t1();import{homedir as aa5}from"node:os";import Aw from"node:path";function oa5(A,Q,B){if(!A)return null;let $=A.workingDirectory??A.workspaceRoot;if(!$)return null;let J;try{J=e0.parse($).fsPath}catch{return null}let Y=ra5(J),Z=sa5(Y),X=A.git?.branch;return ta5(Z,X,Q,B)}function ra5(A){let Q=aa5();if(A===Q)return"~";if(A.startsWith(Q+Aw.sep))return"~"+A.slice(Q.length);return A}function sa5(A){let Q=A.split(Aw.sep).filter(Boolean);if(Q.length<=5)return A;return[Q.slice(0,2).join(Aw.sep),"…",Q.slice(-2).join(Aw.sep)].join(Aw.sep)}function ta5(A,Q,B,$){if(B<=0)return"";let J=Q?` (${Q})`:"",Y=A+J;if(a4(Y,$)<=B)return Y;let Z=A.split(Aw.sep);if(Z.length>2){let F=[Z[0],"…",Z[Z.length-1]].join(Aw.sep)+J;if(a4(F,$)<=B)return F}return oX(Y,B,$)}function D1A(A,Q){let B=B4.of(A),$=k1.of(A),J=Math.max(0,B.size.width-10),Y=oa5(Q,J,B.supportsEmojiWidth);if(!Y)return;let Z=new y({color:$.colorScheme.foreground,dim:!0});return new B1({mainAxisSize:"min",children:[new l({text:new M(" ")}),new l({text:new M(Y,Z)}),new l({text:new M(" ")})]})}var G1A=[Db,Gb,oI,Fb,Xb],ea5=150;function E1A(A){return H1A(A)!==null}function W1A(A,Q){let B=H1A(A);return B?a4(B,Q):0}class q31 extends I1{hints;agentLoopState;compactionState;connectionState;pendingSend;cancelling;connectionError;statusMessage;constructor(A){super();this.hints=A.hints,this.agentLoopState=A.agentLoopState,this.compactionState=A.compactionState,this.connectionState=A.connectionState,this.pendingSend=A.pendingSend,this.cancelling=A.cancelling,this.connectionError=A.connectionError??null,this.statusMessage=A.statusMessage??null}build(A){let Q=_0.of(A),B=[H31()],$=q1A(this.agentLoopState,this.compactionState,this.connectionState,this.pendingSend,this.cancelling),J=this.connectionError,Y=this.statusMessage,Z=z1A(this.hints);if(J)Qo5(Q,J,B);else if(Y)U1A(Q,Y,B);else if(Z){if($||Z===oI)V1A(Q,B);Bo5(B,$o5(Z,A))}else if($)V1A(Q,B),U1A(Q,$,B);if(B.length===1)return new N0({width:0,height:0});return B.push(H31()),new B1({children:B,mainAxisSize:"max",mainAxisAlignment:"start"})}}function z1A(A){for(let Q=G1A.length-1;Q>=0;Q--){let B=G1A[Q];if(A.has(B))return B}return}function H1A(A){let Q=q1A(A.agentLoopState,A.compactionState,A.connectionState,A.pendingSend,A.cancelling),B=z1A(A.hints);if(A.connectionError)return` ${A.connectionError} `;if(A.statusMessage)return` ${A.statusMessage} `;if(B)return` ${Q||B===oI?"∼ ":""}${Ao5(B)} `;if(Q)return` ∼ ${Q} `;return null}function Ao5(A){switch(A){case Xb:return"Ctrl+C again to exit";case Fb:return"Esc again to cancel";case oI:return"Loading thread";case Db:return"Enter to reference previous thread";case Gb:return"Enter to steer"}}function V1A(A,Q){Q.push(new Jz({color:A.colors.primary})),Q.push(H31())}function H31(){return new l({text:new M(" ")})}function N31(A){return new oW({durationMs:ea5,child:new l({text:A,textAlign:"left",maxLines:1,overflow:"clip"})})}function U1A(A,Q,B){B.push(N31(new M(Q,new y({color:A.colors.foreground,dim:!0}))))}function Qo5(A,Q,B){B.push(N31(new M(Q,new y({color:A.colors.destructive}))))}function Bo5(A,Q){A.push(N31(Q))}function $o5(A,Q){let B=_0.of(Q),$=new y({color:B.app.keybind}),J=new y({color:B.colors.foreground,dim:!0});switch(A){case Xb:return new M("",void 0,[new M("Ctrl+C",$),new M(" again to exit",J)]);case Fb:return new M("",void 0,[new M("Esc",$),new M(" again to cancel",J)]);case oI:return new M("Loading thread",J);case Db:return new M("",void 0,[new M("Enter",$),new M(" to reference previous thread",J)]);case Gb:return new M("",void 0,[new M("Enter",$),new M(" to steer",J)])}}function Jo5(A){switch(A){case"working":case"streaming":case"tool_use":case"running_tools":case"awaiting_approval":return!0;case"idle":case"error":return!1}}function K1A(A){switch(A){case"connected":return null;case"authenticating":return"Authenticating";case"disconnected":return"Disconnected";case"connecting":case"reconnecting":return"Connecting"}}function q1A(A,Q,B,$,J){if(J)return"Cancelling";if(Q==="compacting")return"Auto-compacting";if($&&A==="idle")return K1A(B)??"Sending";if(Jo5(A)){let Y=K1A(B);if(Y)return Y}switch(A){case"working":return"Waiting for response";case"streaming":return"Streaming";case"tool_use":case"running_tools":return"Running tools";case"awaiting_approval":return"Waiting for approval";case"error":return"Error";case"idle":return null}}var Yo5=!1;class I31 extends I1{build(A){if(!Yo5)return new N0;let Q=_0.of(A);return new p0({decoration:new x4(Q.app.smartModeColor),child:new u0({padding:q0.horizontal(1),child:new l({text:new M("DEVELOPMENT BUILD (neo)",new y({color:Q.app.selectionForeground,bold:!0})),textAlign:"center"})})})}}o0();TB();o0();s9();var Zo5=$f,Xo5=["unable to connect","failed to connect","connection refused","econnrefused","enotfound","fetch failed","networkerror"];function N1A(A){if(!(A instanceof Error))return!1;let Q=A.message.toLowerCase();return Xo5.some((B)=>Q.includes(B))}function I1A(A){return nF0(A,Zo5)}function Fo5(A){if(typeof A!=="object"||A===null)return!1;return typeof Reflect.get(A,"url")==="string"}function Do5(A){if(typeof A!=="object"||A===null)return!1;return typeof Reflect.get(A,"error")==="string"}function w1A(A){try{let Q=new URL(A);if(Q.protocol!=="http:"&&Q.protocol!=="https:")return!1;let B=Q.hostname.toLowerCase();return B==="localhost"||B==="127.0.0.1"||B==="::1"||B.endsWith(".localhost")}catch{return!1}}async function Go5(A,Q){let B=await r9("/api/attachments",{method:"POST",body:JSON.stringify({data:A.data,mediaType:A.mediaType})},Q),$=null;try{$=await B.json()}catch{$=null}if(!B.ok){if(Do5($))throw Error($.error);throw Error(`Failed to upload image (HTTP ${B.status})`)}if(!Fo5($))throw Error("Failed to upload image: invalid response from server");return $.url}async function C1A(A,Q){let B=0;while(!0)try{return await Go5(A,Q)}catch($){B+=1;let J=I1A(B);if(!N1A($)||J===null)throw $;j.warn(`Attachment upload attempt ${B} failed; retrying in ${J}ms`,$),await new Promise((Y)=>setTimeout(Y,J))}}o0();import{execFile as Vo5}from"node:child_process";import{randomBytes as Uo5}from"node:crypto";import{existsSync as Ko5}from"node:fs";import{copyFile as Eo5,stat as C31,unlink as M1A,writeFile as L1A}from"node:fs/promises";import{platform as O1A,tmpdir as Wo5}from"node:os";import{join as zo5}from"node:path";import{promisify as Ho5}from"node:util";var gR=Ho5(Vo5),M31=[{extension:"png",osascriptClass:"«class PNGf»",mimeType:"image/png"},{extension:"jpg",osascriptClass:"«class JPEG»",mimeType:"image/jpeg"},{extension:"gif",osascriptClass:"«class GIFf»",mimeType:"image/gif"},{extension:"webp",mimeType:"image/webp"}];async function w31(A){try{return await gR("which",[A]),!0}catch{return!1}}function YU0(A){let Q=`amp-paste-${Uo5(8).toString("hex")}.${A}`;return zo5(Wo5(),Q)}function qo5(){if(O1A()!=="linux")return!1;return Boolean(process.env.WSL_DISTRO_NAME)||Ko5("/proc/sys/fs/binfmt_misc/WSLInterop")}var No5='Add-Type -AssemblyName System.Windows.Forms; Add-Type -AssemblyName System.Drawing; if (-not [System.Windows.Forms.Clipboard]::ContainsImage()) { exit 2 }; $image = [System.Windows.Forms.Clipboard]::GetImage(); if ($null -eq $image) { exit 3 }; $tempFile = Join-Path ([System.IO.Path]::GetTempPath()) ("amp-paste-{0}.png" -f [System.Guid]::NewGuid().ToString("N")); $image.Save($tempFile, [System.Drawing.Imaging.ImageFormat]::Png); Write-Output $tempFile';function Io5(A){return A.split(/\r?\n/u).map((B)=>B.trim()).filter((B)=>B.length>0).at(-1)??null}async function j1A(){try{let{stdout:A}=await gR("powershell.exe",["-NoProfile","-STA","-Command",No5],{timeout:3000}),Q=Io5(A);if(!Q)return j.debug("PowerShell did not return a file path for clipboard image"),null;return Q}catch(A){return j.debug("Failed to paste image with PowerShell",{error:A}),null}}function wo5(A){return A.replaceAll("'","''")}async function Co5(A){let B=`Remove-Item -LiteralPath '${wo5(A)}' -Force -ErrorAction SilentlyContinue`;try{await gR("powershell.exe",["-NoProfile","-Command",B],{timeout:3000})}catch{}}async function Mo5(A){try{let{stdout:Q}=await gR("wslpath",["-u",A],{timeout:3000}),B=Q.trim();return B.length>0?B:null}catch(Q){return j.debug("Failed to convert Windows clipboard path to WSL path",{error:Q,windowsPath:A}),null}}async function Lo5(){for(let A of M31){if(!A.osascriptClass)continue;let Q=YU0(A.extension),B=`
|
|
5327
5327
|
try
|
|
@@ -5367,10 +5367,10 @@ Ctrl-X, Y, Z to unlock`;if(E){let Q0=G.text.replace(/`([^`]+)`/g,"$1")+`
|
|
|
5367
5367
|
*/var Ob=9000000000000000,Yw=1e9,F81="0123456789abcdef",zU0="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",HU0="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",D81={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Ob,maxE:Ob,crypto:!1},qAA,Fz,cA=!0,NU0="[DecimalError] ",Jw=NU0+"Invalid argument: ",NAA=NU0+"Precision limit exceeded",IAA=NU0+"crypto unavailable",wAA="[object Decimal]",$B=Math.floor,u9=Math.pow,Ts5=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,Ss5=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,ks5=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,CAA=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,XG=1e7,TA=7,vs5=9007199254740991,ys5=zU0.length-1,G81=HU0.length-1,m1={toStringTag:wAA};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(Jw+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())+TA,$.rounding=1,B=xs5($,RAA($,B)),$.precision=A,$.rounding=Q,DA(Fz==2||Fz==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*u9(G.s*G,0.3333333333333333),!Y||Math.abs(Y)==1/0){if(B=$Q(G.d),A=G.e,Y=(A-B.length+1)%3)B+=Y==1||Y==-2?"0":"00";if(Y=u9(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),$Q(X.d).slice(0,Z)===(B=$Q($.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/TA))*TA,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=jb(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=jb(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=jb(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()?JK(Q,$,J):new Q(0):new Q(NaN);if(A.isZero())return JK(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=JK(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=JK(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=JK(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/TA+2|0);for(A=B;A;--A)D=D.div(D.times(D).plus(1).sqrt().plus(1));cA=!1,Q=Math.ceil(X/TA),$=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/TA)>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=$w(D,X),$=Q?qU0(G,X+10):$w(A,X),F=P3(Z,$,X,1),bt(F.d,J=V,U))do if(X+=10,Z=$w(D,X),$=Q?qU0(G,X+10):$w(A,X),F=P3(Z,$,X,1),!Y){if(+$Q(F.d).slice(J+1,J+15)+1==100000000000000)F=DA(F,V+1,0);break}while(bt(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/TA),G=$B(K.e/TA),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/TA),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 $w(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/TA),$=$B(A.e/TA),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/TA),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(Jw+A);if(B.d){if(Q=MAA(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())+TA,$.rounding=1,B=bs5($,RAA($,B)),$.precision=A,$.rounding=Q,DA(Fz>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=$Q(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),$Q(Y.d).slice(0,B)===(Q=$Q($.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(Fz==2||Fz==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/TA)+$B(A.e/TA),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(OJ(A,0,Yw),Q===void 0)Q=$.rounding;else OJ(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=YK($,!0);else{if(OJ(A,0,Yw),Q===void 0)Q=J.rounding;else OJ(Q,0,8);$=DA(new J($),A+1,Q),B=YK($,!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=YK(J);else{if(OJ(A,0,Yw),Q===void 0)Q=Y.rounding;else OJ(Q,0,8);$=DA(new Y(J),A+J.e+1,Q),B=YK($,!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=MAA(E)-K.e-1,Z=Y%TA,Q.d[0]=u9(10,Z<0?TA+Z:Z),A==null)A=Y>0?Q:D;else{if(X=new W(A),!X.isInt()||X.lt(D))throw Error(Jw+X);A=X.gt(Q)?Y>0?Q:D:X}cA=!1,X=new W($Q(E)),G=W.precision,W.precision=Y=E.length*TA*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 OJ(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(u9(+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/TA),Q>=A.d.length-1&&(B=D<0?-D:D)<=vs5)return J=LAA(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=u9(+X,D),Q=B==0||!isFinite(B)?$B(D*(Math.log("0."+$Q(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($w(X,$+B)),$),J.d){if(J=DA(J,$+5,1),bt(J.d,$,Y)){if(Q=$+10,J=DA(V81(A.times($w(X,Q+B)),Q),Q+5,1),+$Q(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=YK($,$.e<=J.toExpNeg||$.e>=J.toExpPos);else{if(OJ(A,1,Yw),Q===void 0)Q=J.rounding;else OJ(Q,0,8);$=DA(new J($),A,Q),B=YK($,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(OJ(A,1,Yw),Q===void 0)Q=$.rounding;else OJ(Q,0,8);return DA(new $(B),A,Q)};m1.toString=function(){var A=this,Q=A.constructor,B=YK(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=YK(A,A.e<=Q.toExpNeg||A.e>=Q.toExpPos);return A.isNeg()?"-"+B:B};function $Q(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=TA-$.length,B)Y+=Bw(B);Y+=$}if(Z=A[Q],$=Z+"",B=TA-$.length,B)Y+=Bw(B)}else if(Z===0)return"0";for(;Z%10===0;)Z/=10;return Y+Z}function OJ(A,Q,B){if(A!==~~A||A<Q||A>B)throw Error(Jw+A)}function bt(A,Q,B,$){var J,Y,Z,X;for(Y=A[0];Y>=10;Y/=10)--Q;if(--Q<0)Q+=TA,J=0;else J=Math.ceil((Q+1)/TA),Q%=TA;if(Y=u9(10,TA-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)==u9(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)==u9(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 xs5(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=jb(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,z,H,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=TA,G=$B($.e/K)-$B(J.e/K);b=m.length,S=u.length,H=new x(v),q=H.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),z=W.length,I=N.length,D=Q(W,N,z,I),D==1)U--,B(W,b<z?h:m,z,F)}else{if(U==0)D=U=1;W=m.slice()}if(z=W.length,z<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)H.e=G,qAA=E;else{for(V=1,U=q[0];U>=10;U/=10)V++;H.e=V+G*K-1,DA(H,X?Y+H.e+1:Y,Z,E)}return H}}();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+=TA,Z=Q,G=V[U=0],F=G/u9(10,J-Z-1)%10|0;else if(U=Math.ceil((Y+1)/TA),X=V.length,U>=X)if($){for(;X++<=U;)V.push(0);G=F=0,J=1,Y%=TA,Z=Y-TA+1}else break A;else{G=X=V[U];for(J=1;X>=10;X/=10)J++;Y%=TA,Z=Y-TA+J,F=Z<0?0:G/u9(10,J-Z-1)%10|0}if($=$||Q<0||V[U+1]!==void 0||(Z<0?G:G%u9(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/u9(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]=u9(10,(TA-Q%TA)%TA),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=u9(10,TA-Y),V[U]=Z>0?(G/u9(10,J-Z)%u9(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 YK(A,Q,B){if(!A.isFinite())return jAA(A);var $,J=A.e,Y=$Q(A.d),Z=Y.length;if(Q){if(B&&($=B-Z)>0)Y=Y.charAt(0)+"."+Y.slice(1)+Bw($);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."+Bw(-J-1)+Y,B&&($=B-Z)>0)Y+=Bw($)}else if(J>=Z){if(Y+=Bw(J+1-Z),B&&($=B-J-1)>0)Y=Y+"."+Bw($)}else{if(($=J+1)<Z)Y=Y.slice(0,$)+"."+Y.slice($);if(B&&($=B-Z)>0){if(J+1===Z)Y+=".";Y+=Bw($)}}return Y}function IU0(A,Q){var B=A[0];for(Q*=TA;B>=10;B/=10)Q++;return Q}function qU0(A,Q,B){if(Q>ys5){if(cA=!0,B)A.precision=B;throw Error(NAA)}return DA(new A(zU0),Q,1,!0)}function JK(A,Q,B){if(Q>G81)throw Error(NAA);return DA(new A(HU0),Q,B,!0)}function MAA(A){var Q=A.length-1,B=Q*TA+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 Bw(A){var Q="";for(;A--;)Q+="0";return Q}function LAA(A,Q,B,$){var J,Y=new A(1),Z=Math.ceil($/TA+4);cA=!1;for(;;){if(B%2){if(Y=Y.times(Q),zAA(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),zAA(Q.d,Z)}return cA=!0,Y}function WAA(A){return A.d[A.d.length-1]&1}function OAA(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(u9(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)),$Q(X.d).slice(0,F)===$Q(Z.d).slice(0,F)){J=V;while(J--)Z=DA(Z.times(Z),F,1);if(Q==null)if(D<3&&bt(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 $w(A,Q){var B,$,J,Y,Z,X,F,D,G,V,U,K=1,E=10,W=A,z=W.d,H=W.constructor,q=H.rounding,N=H.precision;if(W.s<0||!z||!z[0]||!W.e&&z[0]==1&&z.length==1)return new H(z&&!z[0]?-1/0:W.s!=1?NaN:z?0:W);if(Q==null)cA=!1,G=N;else G=Q;if(H.precision=G+=E,B=$Q(z),$=B.charAt(0),Math.abs(Y=W.e)<1500000000000000){while($<7&&$!=1||$==1&&B.charAt(1)>3)W=W.times(A),B=$Q(W.d),$=B.charAt(0),K++;if(Y=W.e,$>1)W=new H("0."+B),Y++;else W=new H($+"."+B.slice(1))}else return D=qU0(H,G+2,N).times(Y+""),W=$w(new H($+"."+B.slice(1)),G-E).plus(D),H.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 H(J),G,1)),$Q(D.d).slice(0,G)===$Q(F.d).slice(0,G)){if(F=F.times(2),Y!==0)F=F.plus(qU0(H,G+2,N).times(Y+""));if(F=P3(F,new H(K),G,1),Q==null)if(bt(F.d,G-E,q,X))H.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,H.precision=N,q,cA=!0);else return H.precision=N,F}F=D,J+=2}}function jAA(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)%TA,B<0)$+=TA;if($<J){if($)A.d.push(+Q.slice(0,$));for(J-=TA;$<J;)A.d.push(+Q.slice($,$+=TA));Q=Q.slice($),$=TA-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 fs5(A,Q){var B,$,J,Y,Z,X,F,D,G;if(Q.indexOf("_")>-1){if(Q=Q.replace(/(\d)_(?=\d)/g,"$1"),CAA.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(Ss5.test(Q))B=16,Q=Q.toLowerCase();else if(Ts5.test(Q))B=2;else if(ks5.test(Q))B=8;else throw Error(Jw+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=LAA($,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?u9(2,F):ut.pow(2,F));return cA=!0,A}function bs5(A,Q){var B,$=Q.d.length;if($<3)return Q.isZero()?Q:jb(A,2,Q,Q);B=1.4*Math.sqrt($),B=B>16?16:B|0,Q=Q.times(1/wU0(5,B)),Q=jb(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 jb(A,Q,B,$,J){var Y,Z,X,F,D=1,G=A.precision,V=Math.ceil(G/TA);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 RAA(A,Q){var B,$=Q.s<0,J=JK(A,A.precision,1),Y=J.times(0.5);if(Q=Q.abs(),Q.lte(Y))return Fz=$?4:1,Q;if(B=Q.divToInt(J),B.isZero())Fz=$?3:2;else{if(Q=Q.minus(B.times(J)),Q.lte(Y))return Fz=WAA(B)?$?2:3:$?4:1,Q;Fz=WAA(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(OJ(B,1,Yw),$===void 0)$=K.rounding;else OJ($,0,8);else B=K.precision,$=K.rounding;if(!A.isFinite())G=jAA(A);else{if(G=YK(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(YK(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=qAA;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 zAA(A,Q){if(A.length>Q)return A.length=Q,!0}function us5(A){return new this(A).abs()}function hs5(A){return new this(A).acos()}function gs5(A){return new this(A).acosh()}function ms5(A,Q){return new this(A).plus(Q)}function ps5(A){return new this(A).asin()}function ds5(A){return new this(A).asinh()}function cs5(A){return new this(A).atan()}function ls5(A){return new this(A).atanh()}function is5(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=JK(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?JK(this,$,J):new this(0),B.s=A.s;else if(!A.d||Q.isZero())B=JK(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=JK(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 ns5(A){return new this(A).cbrt()}function as5(A){return DA(A=new this(A),A.e+1,2)}function os5(A,Q,B){return new this(A).clamp(Q,B)}function rs5(A){if(!A||typeof A!=="object")throw Error(NU0+"Object expected");var Q,B,$,J=A.defaults===!0,Y=["precision",1,Yw,"rounding",0,8,"toExpNeg",-Ob,0,"toExpPos",0,Ob,"maxE",0,Ob,"minE",-Ob,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(Jw+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(IAA);else this[B]=!1;else throw Error(Jw+B+": "+$);return this}function ss5(A){return new this(A).cos()}function ts5(A){return new this(A).cosh()}function PAA(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,HAA(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 CAA.test(Y)?WU0(D,Y):fs5(D,Y)}if(F==="bigint"){if(Y<0)Y=-Y,D.s=-1;else D.s=1;return WU0(D,Y.toString())}throw Error(Jw+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=rs5,J.clone=PAA,J.isDecimal=HAA,J.abs=us5,J.acos=hs5,J.acosh=gs5,J.add=ms5,J.asin=ps5,J.asinh=ds5,J.atan=cs5,J.atanh=ls5,J.atan2=is5,J.cbrt=ns5,J.ceil=as5,J.clamp=os5,J.cos=ss5,J.cosh=ts5,J.div=es5,J.exp=At5,J.floor=Qt5,J.hypot=Bt5,J.ln=$t5,J.log=Jt5,J.log10=Zt5,J.log2=Yt5,J.max=Xt5,J.min=Ft5,J.mod=Dt5,J.mul=Gt5,J.pow=Vt5,J.random=Ut5,J.round=Kt5,J.sign=Et5,J.sin=Wt5,J.sinh=zt5,J.sqrt=Ht5,J.sub=qt5,J.sum=Nt5,J.tan=It5,J.tanh=wt5,J.trunc=Ct5,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 es5(A,Q){return new this(A).div(Q)}function At5(A){return new this(A).exp()}function Qt5(A){return DA(A=new this(A),A.e+1,3)}function Bt5(){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 HAA(A){return A instanceof ut||A&&A.toStringTag===wAA||!1}function $t5(A){return new this(A).ln()}function Jt5(A,Q){return new this(A).log(Q)}function Yt5(A){return new this(A).log(2)}function Zt5(A){return new this(A).log(10)}function Xt5(){return OAA(this,arguments,-1)}function Ft5(){return OAA(this,arguments,1)}function Dt5(A,Q){return new this(A).mod(Q)}function Gt5(A,Q){return new this(A).mul(Q)}function Vt5(A,Q){return new this(A).pow(Q)}function Ut5(A){var Q,B,$,J,Y=0,Z=new this(1),X=[];if(A===void 0)A=this.precision;else OJ(A,1,Yw);if($=Math.ceil(A/TA),!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(IAA);if($=X[--Y],A%=TA,$&&A)J=u9(10,TA-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-=TA)X.shift();for($=1,J=X[0];J>=10;J/=10)$++;if($<TA)B-=TA-$}return Z.e=B,Z.d=X,Z}function Kt5(A){return DA(A=new this(A),A.e+1,this.rounding)}function Et5(A){return A=new this(A),A.d?A.d[0]?A.s:0*A.s:A.s||NaN}function Wt5(A){return new this(A).sin()}function zt5(A){return new this(A).sinh()}function Ht5(A){return new this(A).sqrt()}function qt5(A,Q){return new this(A).sub(Q)}function Nt5(){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 It5(A){return new this(A).tan()}function wt5(A){return new this(A).tanh()}function Ct5(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 ut=m1.constructor=PAA(D81);zU0=new ut(zU0);HU0=new ut(HU0);var K81=2;function Mt5(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 Zw(A,Q){let{decimalPlaces:B,roundingMode:$}=Mt5(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 ht(A){if(A>=1e6)return`${Math.round(A/1e6)}M`;if(A>=1000)return`${Math.round(A/1000)}k`;return A.toString()}function Lt5(A){if(!A)return"";let Q=A.split("-");if(Q.length>=2)return Q.slice(0,2).join("-");return A}function _AA(A){let Q=[],B=(A.inputTokens??0)+(A.cacheCreationInputTokens??0),$=A.cacheReadInputTokens??0;if(B>0)Q.push(`${ht(B)} in`);if($>0)Q.push(`${ht($)} cache read`);if(A.outputTokens)Q.push(`${ht(A.outputTokens)} out`);if(A.model)Q.push(Lt5(A.model));if(Q.length>0)return`(${Q.join(", ")})`;return""}function Xw(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(Zw(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(Zw(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(Zw(X,D),new y({color:B.foreground,dim:$,bold:!$})));else J.push(new M(Zw(X,D),new y({color:B.foreground,dim:$,bold:!$})));return J}class E81 extends i4{}class W81 extends i4{}function Ot5(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 jt5(A,Q){let B=_0.of(Q),{colors:$}=B,J=Xw(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(`
|
|
5368
5368
|
|
|
5369
5369
|
`)),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 Rt5(A,Q,B){let $=jt5(A,Q);if(!A.costBreakdownURL)return new _A({header:"Thread Cost",minWidth:80,maxWidth:100,onDismiss:B,child:$});let J=A.costBreakdownURL,Y=new G4(()=>{return FA.maybeInvoke(Q,new $$(J,"Cost breakdown URL copied to clipboard","Failed to copy cost breakdown URL")),"handled"}),Z=new G4(()=>{return E6(Q,J),"handled"});return new _A({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 TAA(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(Ot5(J,Y.error),"error",5000),$();return}Q.push(Rt5(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 Pt5=250,_t5=2000;function Tt5({ampURL:A,threadID:Q,logPath:B}){return[`Debug thread ${RB(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(`
|
|
5370
|
-
`)}class z81 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 kAA}}class kAA extends k0{editorController=new N8;commandPalette=new qs(this);commandRegistry=new S51;toastController=new U41;exitHintTimer=new yf(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)=>le4({configService:this.widget.configService,settingsFilePath:this.widget.neoContext.settingsFilePath},A);setThreadVisibility=(A,Q)=>{return ie4({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await no4({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await ao4({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 oo4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(sB.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(j80(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=L4.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()},Pt5),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<_t5)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?me4({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()}},TAA({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 E6(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:()=>{IJ(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 _A({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new l({text:new M(Y41({version:"0.0.1777979451-gaec852",buildTimestamp:"2026-05-05T11:14:30.119Z",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 Kb)}},...Q,..._e4(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 d4({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 d4({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:gt.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)Z.push(new u51);return new X9({neoContext:this.widget.neoContext,child:new $Z({commandRegistry:this.commandRegistry,child:new rI({completionBuilder:this.widget.completionBuilder,child:new z3({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 _I],[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(NJ.hasAnyCopyableSelection())return NJ.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 L4.instance.stop(),"handled"}),Y=new G4((U)=>{if(!U.text)return"ignored";return L4.instance.tuiInstance.clipboard.writeText(U.text).then(()=>{this.toastController.show(U.successMessage,"success",2000)}).catch((K)=>{j.error("Failed to copy Neo text to clipboard",{error:K}),this.toastController.show(U.failureMessage,"error",2000)}),"handled"}),Z=new G4(()=>{return L4.instance.toggleFrameStatsOverlay(),"handled"}),X=new G4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),F=new G4(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";let K=cx(U);return L4.instance.tuiInstance.clipboard.writeText(K).then(()=>{this.toastController.show("Copied log path to clipboard","success",2000)}).catch((E)=>{j.error("Failed to copy thread log path",{error:E,threadID:U,logPath:K}),this.toastController.show("Failed to copy log path","error",2000)}),"handled"}),D=new G4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";let U=this.activeThreadContext?.client.getThreadId();if(!U)return"handled";return this.prepareThreadIssueInvestigation(U),"handled"}),G=new G4(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";return this.toastController.show("Sending report...","success",2000),this.sendFeedbackReport(U).then(async(K)=>{try{await L4.instance.tuiInstance.clipboard.writeText(K),this.toastController.show("Sent report and copied report ID","success",3000)}catch(E){j.warn("Failed to copy report ID to clipboard",{error:E,reportID:K}),this.toastController.show(`Sent report ${K}`,"success",3000)}}).catch((K)=>{j.error("Failed to send report from debug overlay",{error:K,threadID:U}),this.toastController.show("Failed to send report","error",3000)}),"handled"}),V=new G4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[hV0,A],[Et,$],[Kb,J],[$$,Y],[Ht,B],[gV0,Q],[pV0,X],[qt,F],[Nt,D],[It,G],[_I,Z],[dV0,V]])}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{this.startNewDraftThread({prompt:Tt5({ampURL:this.widget.neoContext.ampURL,threadID:A,logPath:cx(A)}),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 Mf(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=SAA(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(iZ(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=SAA(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(oI);if(this.exitHintTimer.isActive())A.add(Xb);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),L4.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,gt.cwd()),this.widget.history.reset();let Y=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,B?eY(B):void 0);this.sendUserMessage(Y,A,Q),this.threadNavigationHistory.recordNavigation($),this.setActiveClient(Y)};sendUserMessage(A,Q,B){let $=WZ0(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=gt.cwd().replace(gt.env.HOME||"","~"),B=A?`amp - ${A} - ${Q}`:"";gt.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 SAA(A,Q,B){let $={...A};for(let J of St5(Q,B)){if(!iZ(A[J],Q[J]))continue;let Y=B[J];if(Y===void 0)delete $[J];else $[J]=Y}return $}function St5(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}l4();function vAA(A,Q,B,$){let J=MS(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 nY(G,V),K=new S9(42),E=new MI(G,V,G,V,G,V,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,z0.default(),K);E.layout(M1.tight(G,V)),E.paint(U,0,0);let W=U.getBuffer().getCells(),z=0;for(let _=0;_<V;_++)if(W[_].some((S)=>S.char!==" ")){z=_;break}let H=V-1;for(let _=V-1;_>=0;_--)if(W[_].some((S)=>S.char!==" ")){H=_;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=tj(T,b,h);return`\x1B[${S?38:48};5;${x}m`}return""}let N=[];if(H>=z)for(let _=z;_<=H;_++){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+`
|
|
5370
|
+
`)}class z81 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 kAA}}class kAA extends k0{editorController=new N8;commandPalette=new qs(this);commandRegistry=new S51;toastController=new U41;exitHintTimer=new yf(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)=>le4({configService:this.widget.configService,settingsFilePath:this.widget.neoContext.settingsFilePath},A);setThreadVisibility=(A,Q)=>{return ie4({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await no4({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await ao4({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 oo4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(sB.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(j80(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=L4.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()},Pt5),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<_t5)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?me4({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()}},TAA({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 E6(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:()=>{IJ(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 _A({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new l({text:new M(Y41({version:"0.0.1777983419-g88aeb8",buildTimestamp:"2026-05-05T12:20:45.183Z",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 Kb)}},...Q,..._e4(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 d4({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 d4({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:gt.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)Z.push(new u51);return new X9({neoContext:this.widget.neoContext,child:new $Z({commandRegistry:this.commandRegistry,child:new rI({completionBuilder:this.widget.completionBuilder,child:new z3({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 _I],[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(NJ.hasAnyCopyableSelection())return NJ.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 L4.instance.stop(),"handled"}),Y=new G4((U)=>{if(!U.text)return"ignored";return L4.instance.tuiInstance.clipboard.writeText(U.text).then(()=>{this.toastController.show(U.successMessage,"success",2000)}).catch((K)=>{j.error("Failed to copy Neo text to clipboard",{error:K}),this.toastController.show(U.failureMessage,"error",2000)}),"handled"}),Z=new G4(()=>{return L4.instance.toggleFrameStatsOverlay(),"handled"}),X=new G4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),F=new G4(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";let K=cx(U);return L4.instance.tuiInstance.clipboard.writeText(K).then(()=>{this.toastController.show("Copied log path to clipboard","success",2000)}).catch((E)=>{j.error("Failed to copy thread log path",{error:E,threadID:U,logPath:K}),this.toastController.show("Failed to copy log path","error",2000)}),"handled"}),D=new G4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";let U=this.activeThreadContext?.client.getThreadId();if(!U)return"handled";return this.prepareThreadIssueInvestigation(U),"handled"}),G=new G4(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";return this.toastController.show("Sending report...","success",2000),this.sendFeedbackReport(U).then(async(K)=>{try{await L4.instance.tuiInstance.clipboard.writeText(K),this.toastController.show("Sent report and copied report ID","success",3000)}catch(E){j.warn("Failed to copy report ID to clipboard",{error:E,reportID:K}),this.toastController.show(`Sent report ${K}`,"success",3000)}}).catch((K)=>{j.error("Failed to send report from debug overlay",{error:K,threadID:U}),this.toastController.show("Failed to send report","error",3000)}),"handled"}),V=new G4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[hV0,A],[Et,$],[Kb,J],[$$,Y],[Ht,B],[gV0,Q],[pV0,X],[qt,F],[Nt,D],[It,G],[_I,Z],[dV0,V]])}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{this.startNewDraftThread({prompt:Tt5({ampURL:this.widget.neoContext.ampURL,threadID:A,logPath:cx(A)}),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 Mf(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=SAA(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(iZ(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=SAA(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(oI);if(this.exitHintTimer.isActive())A.add(Xb);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),L4.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,gt.cwd()),this.widget.history.reset();let Y=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,B?eY(B):void 0);this.sendUserMessage(Y,A,Q),this.threadNavigationHistory.recordNavigation($),this.setActiveClient(Y)};sendUserMessage(A,Q,B){let $=WZ0(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=gt.cwd().replace(gt.env.HOME||"","~"),B=A?`amp - ${A} - ${Q}`:"";gt.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 SAA(A,Q,B){let $={...A};for(let J of St5(Q,B)){if(!iZ(A[J],Q[J]))continue;let Y=B[J];if(Y===void 0)delete $[J];else $[J]=Y}return $}function St5(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}l4();function vAA(A,Q,B,$){let J=MS(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 nY(G,V),K=new S9(42),E=new MI(G,V,G,V,G,V,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,z0.default(),K);E.layout(M1.tight(G,V)),E.paint(U,0,0);let W=U.getBuffer().getCells(),z=0;for(let _=0;_<V;_++)if(W[_].some((S)=>S.char!==" ")){z=_;break}let H=V-1;for(let _=V-1;_>=0;_--)if(W[_].some((S)=>S.char!==" ")){H=_;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=tj(T,b,h);return`\x1B[${S?38:48};5;${x}m`}return""}let N=[];if(H>=z)for(let _=z;_<=H;_++){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+`
|
|
5371
5371
|
`)}if($)B.write(`
|
|
5372
5372
|
\x1B[90m${$}\x1B[0m
|
|
5373
|
-
`)}o0();YG0();var kt5=2000;function yAA(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<kt5)return;if(J=U,ZR())return;if($D0())JD0();else Qo(V)},Z=(V)=>{if(!Q||!B)return;if(ZR()&&!Gs()&&!Ef())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&&oB(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();t1();j1();function xAA(A,Q){if(!Q)return A;let B=Q.toLowerCase(),$=[];for(let J of A){let Y=vt5(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 vt5(A,Q){let B=yt5(A,Q),$=xt5(A.message.toLowerCase(),Q);return Math.max(B,$)}function yt5(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 xt5(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 $=ft5(A,Q);if($>0)return $;return 0}function ft5(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 fAA=":";function pR(A,Q){if(!cj())return;j.debug("[file mention completions]",{event:A,...Q})}function Rb(A){return A.length<=80?A:`${A.slice(0,77)}...`}class dR{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(fAA)){let Z=Q.slice(fAA.length);return pR("commit_query_detected",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:Z.length,queryPreview:Rb(Z)}),this.buildCommitOptions(Z)}let $=Q.length===0?18:20,J=await this.buildFileOptions(Q,$),Y=this.appendHintOptions(Q,J);return pR("build_options_completed",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:Q.length,queryPreview:Rb(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)=>a0A(Z));return pR("file_options_built",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:Rb(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 pR("file_options_failed",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:Rb(A),maxResults:Q,error:B instanceof Error?B.message:String(B)}),[]}}async getOpenFiles(){let A=await y1(x3.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=fR4(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 pR("commit_options_empty_cache",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:Rb(A)}),[];let B=xAA(Q,A).slice(0,20);return pR("commit_options_built",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:Rb(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=bR4(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 pR("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 ut5=[{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:""}],XC2=mi4({name:"amp neo",description:"Start the Neo TUI",options:ut5,positionals:[],action:async({options:A})=>{let Q=bAA(A);if(A.observe){let B=X8(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 $=bAA(A);if(!Q["thread-id"]){await CU0($,{openThreadPickerOnStart:!0});return}let J=X8(Q["thread-id"]);if(!J)throw"invalid thread ID";await CU0($,{initialThreadID:J})}}]}]});function ht5(A){if(A)return A;if(process.env.AMP_URL)return process.env.AMP_URL;return K9}function gt5(A){if(process.env.RIVET_PUBLIC_ENDPOINT)return process.env.RIVET_PUBLIC_ENDPOINT;return KJ(A)}var uAA=e0.file(bt5.homedir()),mt5=process.env.XDG_CONFIG_HOME?e0.file(process.env.XDG_CONFIG_HOME):V1.joinPath(uAA,".config");function pt5({initialUserInput:A,showNeoWelcome:Q,neoWelcomeDismissed:B}){if(Q)return{show:!0,markDismissedOnDismiss:!0};let $=!A&&!B;return{show:$,markDismissedOnDismiss:$}}async function dt5(A){await rY((Q)=>tD0(Q,A,"interactive"))}function bAA(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=ht5(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 Rr(Z,X)),D=gt5(Y);if(A.dangerouslyAllowAll)LB("dangerouslyAllowAll",!0);let G=await F.get("apiKey",Y);if(!G)throw new Q4("API key required. Please run `amp login` first.",1);let V=_S({storage:X,secretStorage:F,workspaceRoot:m0.of(e0.file(process.cwd())),defaultAmpURL:Y,homeDir:uAA,userConfigDir:mt5}),U=rL(V,{usesThreadActors:!0}),K=rZ0({configService:V}),E=new Cf({configService:V});E.pluginExecutorKind="local";let W=yc({configService:V,fileSystem:P5,platform:E,loadGlobalPlugins:Mr(V),pluginFilter:"all"}),z=k70({pluginService:W,toolService:K.toolService}),H=la({configService:V,filesystem:P5,spawn:Jx}),q=ia({toolService:K.toolService,providers:[H]}),N=SQ0({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 Ff(w,{},!0),_=new dR(O);await H81({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:H.toolboxes,isInternalUser:!1,settingsFilePath:X.getSettingsFilePath(),dispose:()=>{for(let S of q.values())S.dispose();return H.dispose(),O.dispose(),z.dispose(),K.dispose(),W.dispose()}},{initialThreadID:B,openThreadPickerOnStart:$,observerOnly:J})}async function H81(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 cY(I,A.configService,A.apiKey,{usesThreadActors:!0}),S=await SU({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:Em4(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:dt5,readFileSystemDirectory:A.readFileSystemDirectory},D,G),U=await RI(),K=pt5({initialUserInput:$,showNeoWelcome:F,neoWelcomeDismissed:U.neoWelcomeDismissed}),E={ampURL:A.ampURL,configService:A.configService,getThreadMarkdown:async(I)=>{let w=await A.getThreadFromServer(I);return w?bV(w):null},isInternalUser:A.isInternalUser,listThreads:A.listThreads,logFilePath:Yr,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 kx({ampURL:A.ampURL,configService:A.configService,threadID:I,signal:w})},z=(I,w)=>{return al4({ampURL:A.ampURL,configService:A.configService,threadID:I,signal:w})},H=new J41,q=yAA({configService:A.configService}),N=new Set;try{await Vs(new z81({clientPool:V,analyzeContextForThread:W,listSkillsForThread:z,completionBuilder:A.completionBuilder,history:new Hr,ideManager:H,configService:A.configService,initialThreadID:B,notificationService:q,initialUserInput:$,openThreadPickerOnStart:J,neoContext:E,showNeoWelcome:K.show,onNeoWelcomeDismissed:K.markDismissedOnDismiss?()=>{rY(tl4).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}`;vAA(_,S,process.stdout)}}}finally{process.stdout.write(II("")),q.unsubscribe(),V.dispose(),await A.dispose?.()}process.exit(0)}Pd();DE();async function ct5(A,Q,B){let $=V20(A);if(!$.success)throw Error(`Invalid permission format: ${$.error.message}`);if($.data.length===0)throw Error("No permission entry provided");let J=dH($.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 hAA(A){try{let Q=A.args.map((B)=>{if(/[\s/\\*?[\]{}()"]/.test(B))return`"${B}"`;return B}).join(" ");await ct5(Q,A.settings,A.scope),A.exit(0)}catch(Q){let B=Q instanceof Error?Q.message:"Unknown error";A.stderr.write(`Error: ${B}
|
|
5373
|
+
`)}o0();YG0();var kt5=2000;function yAA(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<kt5)return;if(J=U,ZR())return;if($D0())JD0();else Qo(V)},Z=(V)=>{if(!Q||!B)return;if(ZR()&&!Gs()&&!Ef())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&&oB(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();t1();j1();function xAA(A,Q){if(!Q)return A;let B=Q.toLowerCase(),$=[];for(let J of A){let Y=vt5(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 vt5(A,Q){let B=yt5(A,Q),$=xt5(A.message.toLowerCase(),Q);return Math.max(B,$)}function yt5(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 xt5(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 $=ft5(A,Q);if($>0)return $;return 0}function ft5(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 fAA=":";function pR(A,Q){if(!cj())return;j.debug("[file mention completions]",{event:A,...Q})}function Rb(A){return A.length<=80?A:`${A.slice(0,77)}...`}class dR{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(fAA)){let Z=Q.slice(fAA.length);return pR("commit_query_detected",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:Z.length,queryPreview:Rb(Z)}),this.buildCommitOptions(Z)}let $=Q.length===0?18:20,J=await this.buildFileOptions(Q,$),Y=this.appendHintOptions(Q,J);return pR("build_options_completed",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:Q.length,queryPreview:Rb(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)=>a0A(Z));return pR("file_options_built",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:Rb(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 pR("file_options_failed",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:Rb(A),maxResults:Q,error:B instanceof Error?B.message:String(B)}),[]}}async getOpenFiles(){let A=await y1(x3.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=fR4(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 pR("commit_options_empty_cache",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:Rb(A)}),[];let B=xAA(Q,A).slice(0,20);return pR("commit_options_built",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:Rb(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=bR4(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 pR("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 ut5=[{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:""}],XC2=mi4({name:"amp neo",description:"Start the Neo TUI",options:ut5,positionals:[],action:async({options:A})=>{let Q=bAA(A);if(A.observe){let B=X8(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 $=bAA(A);if(!Q["thread-id"]){await CU0($,{openThreadPickerOnStart:!0});return}let J=X8(Q["thread-id"]);if(!J)throw"invalid thread ID";await CU0($,{initialThreadID:J})}}]}]});function ht5(A){if(A)return A;if(process.env.AMP_URL)return process.env.AMP_URL;return K9}function gt5(A){if(process.env.RIVET_PUBLIC_ENDPOINT)return process.env.RIVET_PUBLIC_ENDPOINT;return KJ(A)}var uAA=e0.file(bt5.homedir()),mt5=process.env.XDG_CONFIG_HOME?e0.file(process.env.XDG_CONFIG_HOME):V1.joinPath(uAA,".config");function pt5({initialUserInput:A,showNeoWelcome:Q,neoWelcomeDismissed:B}){if(Q)return{show:!0,markDismissedOnDismiss:!0};let $=!A&&!B;return{show:$,markDismissedOnDismiss:$}}async function dt5(A){await rY((Q)=>tD0(Q,A,"interactive"))}function bAA(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=ht5(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 Rr(Z,X)),D=gt5(Y);if(A.dangerouslyAllowAll)LB("dangerouslyAllowAll",!0);let G=await F.get("apiKey",Y);if(!G)throw new Q4("API key required. Please run `amp login` first.",1);let V=_S({storage:X,secretStorage:F,workspaceRoot:m0.of(e0.file(process.cwd())),defaultAmpURL:Y,homeDir:uAA,userConfigDir:mt5}),U=rL(V),K=rZ0({configService:V}),E=new Cf({configService:V});E.pluginExecutorKind="local";let W=yc({configService:V,fileSystem:P5,platform:E,loadGlobalPlugins:Mr(V),pluginFilter:"all"}),z=k70({pluginService:W,toolService:K.toolService}),H=la({configService:V,filesystem:P5,spawn:Jx}),q=ia({toolService:K.toolService,providers:[H]}),N=SQ0({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 Ff(w,{},!0),_=new dR(O);await H81({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:H.toolboxes,isInternalUser:!1,settingsFilePath:X.getSettingsFilePath(),dispose:()=>{for(let S of q.values())S.dispose();return H.dispose(),O.dispose(),z.dispose(),K.dispose(),W.dispose()}},{initialThreadID:B,openThreadPickerOnStart:$,observerOnly:J})}async function H81(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 cY(I,A.configService,A.apiKey,{usesThreadActors:!0}),S=await SU({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:Em4(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:dt5,readFileSystemDirectory:A.readFileSystemDirectory},D,G),U=await RI(),K=pt5({initialUserInput:$,showNeoWelcome:F,neoWelcomeDismissed:U.neoWelcomeDismissed}),E={ampURL:A.ampURL,configService:A.configService,getThreadMarkdown:async(I)=>{let w=await A.getThreadFromServer(I);return w?bV(w):null},isInternalUser:A.isInternalUser,listThreads:A.listThreads,logFilePath:Yr,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 kx({ampURL:A.ampURL,configService:A.configService,threadID:I,signal:w})},z=(I,w)=>{return al4({ampURL:A.ampURL,configService:A.configService,threadID:I,signal:w})},H=new J41,q=yAA({configService:A.configService}),N=new Set;try{await Vs(new z81({clientPool:V,analyzeContextForThread:W,listSkillsForThread:z,completionBuilder:A.completionBuilder,history:new Hr,ideManager:H,configService:A.configService,initialThreadID:B,notificationService:q,initialUserInput:$,openThreadPickerOnStart:J,neoContext:E,showNeoWelcome:K.show,onNeoWelcomeDismissed:K.markDismissedOnDismiss?()=>{rY(tl4).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}`;vAA(_,S,process.stdout)}}}finally{process.stdout.write(II("")),q.unsubscribe(),V.dispose(),await A.dispose?.()}process.exit(0)}Pd();DE();async function ct5(A,Q,B){let $=V20(A);if(!$.success)throw Error(`Invalid permission format: ${$.error.message}`);if($.data.length===0)throw Error("No permission entry provided");let J=dH($.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 hAA(A){try{let Q=A.args.map((B)=>{if(/[\s/\\*?[\]{}()"]/.test(B))return`"${B}"`;return B}).join(" ");await ct5(Q,A.settings,A.scope),A.exit(0)}catch(Q){let B=Q instanceof Error?Q.message:"Unknown error";A.stderr.write(`Error: ${B}
|
|
5374
5374
|
`),A.exit(1)}}D20();Pd();async function gAA(A){let Q=A.builtinOnly?nS:await A.settings.get("permissions",A.scope)??[];if(A.json)A.stdout.write(JSON.stringify(Q,null,2));else{let B=Rd(Q);A.stdout.write(B),A.stdout.write(`
|
|
5375
5375
|
`)}A.exit(0)}D20();iS();aS();DE();var lt5={outputResult(A,Q,B){let $={tool:A.toolName,arguments:Q,...A.context&&{context:A.context},...A.threadId&&{threadId:A.threadId},...B};A.stdout.write(JSON.stringify($,null,2))},outputError(A,Q,B){let $={tool:A.toolName,arguments:Q,...A.context&&{context:A.context},...A.threadId&&{threadId:A.threadId},...B};A.stdout.write(JSON.stringify($,null,2))}},it5={outputResult(A,Q,B){if(A.stdout.write(`tool: ${A.toolName}
|
|
5376
5376
|
`),A.stdout.write(`arguments: ${JSON.stringify(Q)}
|
|
@@ -6147,7 +6147,7 @@ ${J}`,Q);this.line=B,this.column=$,this.codeblock=J}}/*!
|
|
|
6147
6147
|
`),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(`
|
|
6148
6148
|
`))}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 L21 extends t3{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 C21({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 s3A(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 o63(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 r63(A){let Q=0;for(let B of A)for(let $ of B.points)if($.value>Q)Q=$.value;return Q||1}function s63(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 t63(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),()=>{E6(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}
|
|
6149
6149
|
`,F));let W=0;for(let z=0;z<$.length;z++){let H=$[z],q=H.points[B];if(!q)continue;W+=q.value;let N=H.color??J[z%J.length]??X.foreground;if(V.push(new M("● ",new y({color:N}))),V.push(new M(`${H.name}: `,G)),q.link)V.push(K(q.link,Y(q.value)));else V.push(new M(Y(q.value),D));if(z<$.length-1||E)V.push(new M(`
|
|
6150
|
-
`))}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();fM();n8();A3();IQ();k7();s9();i2();TB();fV();l4();qv();nT();j1();o0();s9();class O21{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.1777979451-gaec852"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await w80(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 Nw extends v0{props;constructor(A){super();this.props=A}createState(){return new t3A}}class t3A 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 e3A extends k0{controller=new N8;focusNode=new X6({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 tB({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 $e extends v0{props;constructor(A){super();this.props=A}createState(){return new e3A}}TB();class A8A extends k0{controller=new N8;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new X6({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>=A7)return!1;let Q=await $F(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 LJ],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:L4.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 j21 extends v0{props;constructor(A){super();this.props=A}createState(){return new A8A}}function Q8A(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 R21 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)=>Q8A(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,z)=>new N0({width:z,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(Q8A(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 B8A 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 z=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(z,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 P21 extends v0{props;constructor(A){super();this.props=A}createState(){return new B8A}}class DG extends v0{props;constructor(A){super();this.props=A}createState(){return new $8A}}class $8A extends k0{_spinner=new z6;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 d4({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 FK extends v0{props;constructor(A){super();this.props=A}createState(){return new J8A}}class J8A extends k0{scrollController=new aA;scrollAreaKey=new J2("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 k2}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 e3({child:new p0({padding:q0.symmetric(1,0),child:new B1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new S1({child:new PA({controller:this.scrollController,autofocus:!0,child:X})}),new F2({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 d4({debugLabel:"MessageDialog",child:new t4({fit:"expand",children:[new b1({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 Y8A extends v0{props;constructor(A){super();this.props=A}createState(){return new Z8A}}class Z8A 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} ${E4(J,"plugin")} active`,new y({bold:!0}))),Z>0||X>0)$.push(new M(` (${Z} ${E4(Z,"command")}, ${X} ${E4(X,"tool")})`,new y({dim:!0})));$.push(new M(`
|
|
6150
|
+
`))}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();fM();n8();A3();IQ();k7();s9();i2();TB();fV();l4();qv();nT();j1();o0();s9();class O21{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.1777983419-g88aeb8"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await w80(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 Nw extends v0{props;constructor(A){super();this.props=A}createState(){return new t3A}}class t3A 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 e3A extends k0{controller=new N8;focusNode=new X6({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 tB({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 $e extends v0{props;constructor(A){super();this.props=A}createState(){return new e3A}}TB();class A8A extends k0{controller=new N8;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new X6({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>=A7)return!1;let Q=await $F(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 LJ],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:L4.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 j21 extends v0{props;constructor(A){super();this.props=A}createState(){return new A8A}}function Q8A(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 R21 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)=>Q8A(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,z)=>new N0({width:z,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(Q8A(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 B8A 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 z=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(z,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 P21 extends v0{props;constructor(A){super();this.props=A}createState(){return new B8A}}class DG extends v0{props;constructor(A){super();this.props=A}createState(){return new $8A}}class $8A extends k0{_spinner=new z6;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 d4({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 FK extends v0{props;constructor(A){super();this.props=A}createState(){return new J8A}}class J8A extends k0{scrollController=new aA;scrollAreaKey=new J2("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 k2}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 e3({child:new p0({padding:q0.symmetric(1,0),child:new B1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new S1({child:new PA({controller:this.scrollController,autofocus:!0,child:X})}),new F2({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 d4({debugLabel:"MessageDialog",child:new t4({fit:"expand",children:[new b1({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 Y8A extends v0{props;constructor(A){super();this.props=A}createState(){return new Z8A}}class Z8A 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} ${E4(J,"plugin")} active`,new y({bold:!0}))),Z>0||X>0)$.push(new M(` (${Z} ${E4(Z,"command")}, ${X} ${E4(X,"tool")})`,new y({dim:!0})));$.push(new M(`
|
|
6151
6151
|
|
|
6152
6152
|
`));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(`
|
|
6153
6153
|
`)),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(`
|
|
@@ -6325,7 +6325,7 @@ ${s.content||""}`:s.content||"",b0=[],$1=s.baseDir.startsWith("file://")?DE0(s.b
|
|
|
6325
6325
|
`)}function d9A(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=q44({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+`
|
|
6326
6326
|
`),process.exit(1)}process.stdout.write(await W23(F.result.displayText)+`
|
|
6327
6327
|
`),process.exit(0)})}var bB3=ge.join(lZ,"logs","headless.log"),SQ1=ge.join(Gf,"device-id.json"),uB3=`cli-tui-${z$A(16).toString("hex")}`;async function hB3(){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(zu(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){kJ.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
|
|
6328
|
-
`)}function gB3(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 f2(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")LB("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")LB("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)LB("internal.model",dB3(Q.model))}function G$A(A){let Q=A.indexOf(":");if(Q===-1)throw new Q4(`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 Q4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function mB3(A){if(A===void 0)return;let Q=A.trim();if(Y44(Q))return Q;throw new Q4(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function pB3(A,Q){if(iF(A,Q))return;let B=h$(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new Q4(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function dB3(A){if(!A.includes("="))return G$A(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new Q4(`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 Q4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new Q4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);G$A(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new Q4("No valid model overrides found in --model flag value.",1);return Q}function cB3(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 lB3(A){try{return await H$A(A,"utf-8")}catch{return A}}async function kQ1(A,Q,B){let $=cB3(A,Q);if(!$)return;let J=vA(B)?B.features:[],Y=vA(B)?B.user.email:void 0;if(!Hu(J,m2.HARNESS_SYSTEM_PROMPT)&&!(Y&&S7(Y)))throw new Q4("You are not allowed to do this.",1);LB("systemPrompt",await lB3($))}function Hu(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function iB3(A){return A!=="pending"}function DP(A){if(!vA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function nB3(A){let Q=DP(A);if(Q)return Q.id;if(cF(A))throw Error(A.error.message);throw Error("unreachable")}function aB3(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 oB3(A){let $=aB3(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 Q4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function me(A,Q){let B=we0(Error(A.error.message));if(B.message===U7.networkOffline||B.message===U7.networkTimeout)return oB3(Q);if(B.message!==U7.internalBug)return new Q4(B.message,1,B.suggestion);return new Q4(A.error.message.replace(/^Error: /,""),1)}var V$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??nX,description:`Custom settings file path (overrides the default location ${nX})`},{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 ${Yr})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:J9(),description:(A)=>A?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(A)=>A?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(A)=>A?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:oM.SMART.key,description:`Set the agent mode (${b$({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(b$().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}],U$A=(A)=>("deprecated"in A)&&A.deprecated===!0,rB3=(A)=>("hidden"in A)&&A.hidden===!0,sB3=(A)=>("default"in A),tB3=(A)=>("default"in A)?A.default:void 0;function tE0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=mB3(Q.effort);if(B!==void 0)pB3(Q.mode,B);return B}function eB3(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 Q4(U7.unknownCommand(B),1,Z)}}async function QW0(A){return{...A,getThreadEnvironment:TW,getEnvironmentData:(Q,B)=>KD({filesystem:A.fileSystem},Q,B),osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new vL(A.fileSystem),generateThreadTitle:KD4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>NQ(A.configService),pluginService:A.pluginService}}function q$A(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:TW,getEnvironmentData:(Q,B)=>KD({filesystem:A.fileSystem},Q,B),filesystem:A.fileSystem,threadService:A.threadService}}var eE0=e0.file(fB3.homedir()),vQ1=process.env.XDG_CONFIG_HOME?e0.file(process.env.XDG_CONFIG_HOME):V1.joinPath(eE0,".config");function A$3(A){return n_4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if($D0())JD0();else if(process.platform==="darwin"&&Q==="idle"&&A.isTUIVoiceNotifEnabled())i_4();else Qo(Q);let B=ZR(),$=Gs();if((!B||$||Ef())&&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(ZR()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function g8(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;r14("0.0.
|
|
6328
|
+
`)}function gB3(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 f2(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")LB("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")LB("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)LB("internal.model",dB3(Q.model))}function G$A(A){let Q=A.indexOf(":");if(Q===-1)throw new Q4(`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 Q4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function mB3(A){if(A===void 0)return;let Q=A.trim();if(Y44(Q))return Q;throw new Q4(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function pB3(A,Q){if(iF(A,Q))return;let B=h$(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new Q4(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function dB3(A){if(!A.includes("="))return G$A(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new Q4(`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 Q4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new Q4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);G$A(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new Q4("No valid model overrides found in --model flag value.",1);return Q}function cB3(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 lB3(A){try{return await H$A(A,"utf-8")}catch{return A}}async function kQ1(A,Q,B){let $=cB3(A,Q);if(!$)return;let J=vA(B)?B.features:[],Y=vA(B)?B.user.email:void 0;if(!Hu(J,m2.HARNESS_SYSTEM_PROMPT)&&!(Y&&S7(Y)))throw new Q4("You are not allowed to do this.",1);LB("systemPrompt",await lB3($))}function Hu(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function iB3(A){return A!=="pending"}function DP(A){if(!vA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function nB3(A){let Q=DP(A);if(Q)return Q.id;if(cF(A))throw Error(A.error.message);throw Error("unreachable")}function aB3(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 oB3(A){let $=aB3(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 Q4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function me(A,Q){let B=we0(Error(A.error.message));if(B.message===U7.networkOffline||B.message===U7.networkTimeout)return oB3(Q);if(B.message!==U7.internalBug)return new Q4(B.message,1,B.suggestion);return new Q4(A.error.message.replace(/^Error: /,""),1)}var V$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??nX,description:`Custom settings file path (overrides the default location ${nX})`},{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 ${Yr})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:J9(),description:(A)=>A?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(A)=>A?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(A)=>A?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:oM.SMART.key,description:`Set the agent mode (${b$({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(b$().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}],U$A=(A)=>("deprecated"in A)&&A.deprecated===!0,rB3=(A)=>("hidden"in A)&&A.hidden===!0,sB3=(A)=>("default"in A),tB3=(A)=>("default"in A)?A.default:void 0;function tE0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=mB3(Q.effort);if(B!==void 0)pB3(Q.mode,B);return B}function eB3(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 Q4(U7.unknownCommand(B),1,Z)}}async function QW0(A){return{...A,getThreadEnvironment:TW,getEnvironmentData:(Q,B)=>KD({filesystem:A.fileSystem},Q,B),osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new vL(A.fileSystem),generateThreadTitle:KD4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>NQ(A.configService),pluginService:A.pluginService}}function q$A(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:TW,getEnvironmentData:(Q,B)=>KD({filesystem:A.fileSystem},Q,B),filesystem:A.fileSystem,threadService:A.threadService}}var eE0=e0.file(fB3.homedir()),vQ1=process.env.XDG_CONFIG_HOME?e0.file(process.env.XDG_CONFIG_HOME):V1.joinPath(eE0,".config");function A$3(A){return n_4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if($D0())JD0();else if(process.platform==="darwin"&&Q==="idle"&&A.isTUIVoiceNotifEnabled())i_4();else Qo(Q);let B=ZR(),$=Gs();if((!B||$||Ef())&&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(ZR()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function g8(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;r14("0.0.1777983419-g88aeb8");let Y=_S({storage:A.settings,secretStorage:A.secrets,workspaceRoot:m0.of(e0.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:eE0,userConfigDir:vQ1});$6A(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...
|
|
6329
6329
|
`);let g=await Q$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=y1(NQ(Y).pipe(E5(iB3))),D=$?"pending":await F;if(!$)j.info("Server status resolved",{status:"ready",isAuthenticated:vA(D),isError:cF(D),errorMessage:cF(D)?D.error.message:void 0});let G=F.then((d)=>nB3(d));G.catch(()=>{return});let U=!A.executeMode&&!Q.takeMeBack&&vA(D)&&Hu(D.features,m2.THREAD_ACTORS_TUI)?"all":process.env.PLUGINS??"permissions",{toolService:K,dispose:E}=rZ0({configService:Y}),W=new Map,z=()=>W.clear(),H=new xb0(Y,A.settings.getWorkspaceRootPath()),q=SQ0({configService:Y,filesystem:P5}),N=bB4({configService:Y,trustStore:H,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=yp4();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?vp4():kp4(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=la({configService:Y,filesystem:P5,spawn:Jx}),w;if(J)w=new Map;else if(A.executeMode){let d=await KR4({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=ia({toolService:K,providers:[N,I]});if(Q.jetbrains)lM("JetBrains");else if(Q.ide&&Hd4())lM("VS Code");else if(Q.ide&&qd4())lM("Neovim");else if(Q.ide){let d=await hB3();if(d){let g=b80(d.ideName);if(g)lM(g)}}if(A.executeMode)s14(!0);let C,O=x3.status.pipe(L1((d)=>Boolean(d.connected&&d.authenticated&&d.ideName&&a44(d.ideName))),k4()).subscribe((d)=>{if(d){if(!C)C=K.registerTool(UR4)}else C?.dispose(),C=void 0}),_;if(!A.executeMode){let d=await A.settings.get("fuzzy.alwaysIncludePaths")??[];_=new Ff(process.cwd(),{alwaysIncludePaths:d},!0)}else _=new class extends Ff{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 L81,b=Q.headless?il4():void 0,h=b??new Cf({configService:Y}),x=h instanceof Cf?h:void 0;if(x)x.pluginExecutorKind="local";let v=yc({configService:Y,fileSystem:P5,platform:h,loadGlobalPlugins:Mr(Y),pluginFilter:U}),u=k70({pluginService:v,toolService:K}),m={configService:Y,toolService:K,mcpService:N,skillService:q,toolboxService:I,trustStore:H,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(),z(),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 Q$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.
|
|
6330
6330
|
`),!1}return await N$A(A)}async function N$A(A){let Q=z$A(32).toString("hex"),B=await wf(A.ampURL,Q),$=new AbortController;try{await uF(B,$.signal)}catch(Y){j.error("Error opening browser",{error:Y})}let J=await wf(A.ampURL,Q,!1);D5.write(`If your browser does not open automatically, visit:
|
|
6331
6331
|
|
|
@@ -6333,7 +6333,7 @@ ${s0.blue.bold(J)}
|
|
|
6333
6333
|
|
|
6334
6334
|
`);try{return await kl4(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}),kJ.write(`
|
|
6335
6335
|
Login failed: ${Y instanceof Error?Y.message:String(Y)}
|
|
6336
|
-
`),!1}}async function B$3(A,Q,B){let $=await Q.get("apiKey",A);if(!$)throw new Q4("No Amp API key found. Run `amp login` first.",1);let J=vB3("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 $$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((z)=>{if(z.code==="commander.help"||z.code==="commander.version"||z.exitCode===0)bj(),process.exit(0);let H=z.originalError??z;Lh4(H)}),di4(Q,{version:"0.0.
|
|
6336
|
+
`),!1}}async function B$3(A,Q,B){let $=await Q.get("apiKey",A);if(!$)throw new Q4("No Amp API key found. Run `amp login` first.",1);let J=vB3("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 $$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((z)=>{if(z.code==="commander.help"||z.code==="commander.version"||z.exitCode===0)bj(),process.exit(0);let H=z.originalError??z;Lh4(H)}),di4(Q,{version:"0.0.1777983419-g88aeb8",buildTimestamp:"2026-05-05T12:20:45.183Z",buildType:"'release'"}),Q.addHelpText("after",Ed4()),Q.configureHelp({formatHelp:Wd4}),Q.command("logout").description("Log out by removing stored API key").action(async(z,H)=>{let q=H.optsWithGlobals(),N=await m5(q);await U$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(z,H)=>{let q=H.optsWithGlobals(),N=await m5(q);await V$3(N,await Rr(q,N.settings))}),wh4(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(...z)=>{let H=z.find((w)=>typeof w==="object"&&w!==null&&typeof w.optsWithGlobals==="function")??$,q=z.filter((w)=>w!==H).flatMap((w)=>Array.isArray(w)?w:typeof w==="string"?[w]:[]),N=H.optsWithGlobals(),I=await m5(N);await B$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(z,H,q)=>{let N=q.optsWithGlobals(),I=await m5(N);await Lp4(z??"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(z,H)=>{let q=H.optsWithGlobals(),N=await m5(q);await Op4(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(z)=>{await vc4({raw:z.raw===!0}),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(`
|
|
6337
6337
|
`)).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(z,H,q)=>{if(z&&H.apply)throw new Q4("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let N=H.apply??z;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.
|
|
6338
6338
|
|
|
6339
6339
|
`),q.outputHelp(),process.exit(0);let I=X8(N)??pQ(N),w=q.optsWithGlobals(),C=await m5(w);f2(q,w);let O=await g8(C,w),_=!1;try{if(H.checkout&&H.skipCheckout)throw new Q4("Choose either --checkout or --skip-checkout, not both.",1);if(cF(O.serverStatus))throw me(O.serverStatus,C.ampURL);let S=vA(O.serverStatus)?O.serverStatus.features:void 0;if(!Hu(S,m2.V2))throw new Q4("live-sync is not enabled for your user",1);await wl4({ampURL:C.ampURL,threadId:I,configService:O.configService,threadService:O.threadService,apiKey:process.env.AMP_API_KEY,applyOnce:typeof H.apply==="string",checkoutMode:H.checkout?"always":H.skipCheckout?"never":"prompt",promptForYesNo:nD0}),_=!0}finally{if(await O.asyncDispose(),_)process.exit(0)}});let J=async(z,H,q)=>{_S({storage:H.settings,secretStorage:H.secrets,workspaceRoot:m0.of(e0.file(process.cwd())),defaultAmpURL:H.ampURL,homeDir:eE0,userConfigDir:vQ1});let N={...H,executeMode:!1};await AW0(N,{...z,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(z,H)=>{let q=H.optsWithGlobals(),N=await m5(q);await W$A(q,N,H)});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(z,H)=>{let q=H.optsWithGlobals(),N=await m5(q);await M$3(q,N,H)}),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(z,H,q)=>{let N=q.optsWithGlobals(),I=await m5(N);if(H.pick)kJ.write(`${s0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
|
|
@@ -6366,8 +6366,8 @@ ${C}
|
|
|
6366
6366
|
`))}),H.args.length>0)eB3(N,H);await AW0(N,q,H,A)}),od4(Q),Q}async function qu(A,Q){await rY((B)=>tD0(B,A,Q))}async function K$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 Q4(`Cannot resume thread created by another user.
|
|
6367
6367
|
|
|
6368
6368
|
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 I$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 w$A(A,Q,B){if(A.streamJson&&!Q)throw new Q4("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new Q4("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new Q4("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new Q4("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 Q4("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archive&&!Q)throw new Q4("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 Q4("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 Q4("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"
|
|
6369
|
-
Or pipe via stdin: echo "your message" | amp --execute`)}function J$3(A,Q){if(w54([h30.parse({tool:"*",action:"allow"})]),V54({bypass:!0}),cAA(A.settings))j.debug("Enabling permissions plugin"),Q.registerInternalPlugin({name:"permissions",entryPoint:N81})}async function AW0(A,Q,B,$){if(Q.headless)return Y$3(A,Q,B);let J=await g8(A,Q),Y=await J.serverStatusPromise,Z=await J.configService.getLatest(),X=vA(Y)&&Hu(Y.features,m2.THREAD_ACTORS_TUI),F=X&&!Q.takeMeBack;if(Q.showWelcome&&!X)throw await J.asyncDispose(),new Q4("--show-welcome is only available with the new Amp CLI feature flag",1);if(F)return J$3(Z,J.pluginService),Z$3(A,Q,B,J);else{if(Q.threadId&&zQ(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 Q4(`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 X$3(A,Q,B,$,{dependencies:J})}}async function Y$3(A,Q,B){let $=(H,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=ys0();j.info("Startup phase",{phase:H,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};f2(B,Q);let J=process.hrtime.bigint(),Y=await g8(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(cF(Z))throw me(Z,A.ampURL);let X=vA(Z)?Z:null,F=X?.user.email;await kQ1(B,Q,Z);let D=DP(Z),G=Hs(Q,D);if(G instanceof Error)x5(G.message);if(X&&!RS(Q.mode,F))throw new Q4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!F||!S7(F)))throw new Q4("Headless executor mode is only available for Amp employees",1);IF0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new Q4("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&&!zQ(K))throw new Q4(`Invalid thread ID: ${K}`,1);let E=K?void 0:await w$3({dependencies:Y,apiKey:U,visibility:G??void 0}),W=K??E?.threadId;if(!W)throw new Q4("Failed to resolve headless thread ID",1);let z=await up4(W);if(z.status==="already-running")await Y.asyncDispose(),await uW(),process.exit(0);try{await _p4({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 z.release(),await Y.asyncDispose()}await uW(),process.exit(0)}async function Z$3(A,Q,B,$){let{userInput:J,stdinInput:Y}=await I$A(Q),Z=!!Q.streamJson||!!Q.streamJsonThinking;w$A({...Q,streamJson:Z},A.executeMode,J),f2(B,Q),Uh4(),IF0();let X=Q.threadId&&zQ(Q.threadId)?Q.threadId:void 0,F=Q.observe?X8(Q.observe)??pQ(Q.observe):void 0,D=await $.serverStatusPromise;if(cF(D))throw me(D,A.ampURL);let G=await $.secretStorage.get("apiKey",A.ampURL);if(!G)throw new Q4("API key required. Please run `amp login` first.",1);let V=vA(D)&&S7(D.user.email);if(A.executeMode){y11($.mcpService,A.settings);try{let U=tE0(B,Q),K=await RI(),E=X?U:aD0({agentMode:Q.mode,explicitEffort:U,sessionState:K}),W=X?void 0:oD0(await Mf($.configService),{agentMode:Q.mode,explicitEffort:U,sessionState:K}),z=await nm4({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 qu(z,"execute"),Q.archive)await $.threadService.archive(z,!0)}finally{await $.asyncDispose()}await uW(),process.exit(0)}else{let U=tE0(B,Q),K=rL($.configService,{usesThreadActors:!0}),E=new dR($.fuzzyServer),W=process.cwd();await H81({ampURL:A.ampURL,apiKey:G,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??KJ(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:z})=>VI({fileSystem:$.fileSystem,workspaceRoot:W},z),completionBuilder:E,workspaceRoot:W,listThreads:()=>K.listThreads(),getThreadFromServer:(z)=>K.getThread(z),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 X$3(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(E0,e)=>{let Y0=Number(process.hrtime.bigint()-e)/1e6,a=ys0();j.info("Startup phase",{phase:E0,phaseMs:Math.round(Y0),sinceMainMs:a===null?void 0:Math.round(a)})},{userInput:X,stdinInput:F}=await I$A(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;w$A({...Q,streamJson:D},A.executeMode,X),f2(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 me(E,A.ampURL);let W=vA(E)?E:null,z=W?.user.email,H=!!(z&&S7(z));if(H)IF0();if(!K)await kQ1(B,Q,E);let q=DP(E),N=q?.features??[],I=q?.team??null,w=Hs(Q,q);if(w instanceof Error)x5(w.message);if(W&&!RS(Q.mode,z))throw new Q4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let C=Q.threadId&&zQ(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)=>qu(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(),DP(e),w);if(Y0 instanceof Error)x5(Y0.message);return J71(O,{threadMeta:Y0?eY(Y0):void 0,agentMode:E0??Q.mode,onFirstAssistantMessage:_})},validateThreadOwnership:async(E0,e)=>{if(e?.nonBlockingOwnershipCheck){K$A(E0,V.configService,V.viewerUserIDPromise).catch((Y0)=>{if(Y0 instanceof Q4){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 K$A(E0,V.configService,V.viewerUserIDPromise)}catch(Y0){if(Y0 instanceof Q4)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 h9A(S,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(E0){if(E0 instanceof Q4)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=wp(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 _81:null,v,u=null;if(x)v=x,u=(async()=>{let E0=K?await V.serverStatusPromise:V.serverStatus;if(cF(E0))throw me(E0,A.ampURL);await kQ1(B,Q,E0);let e=process.hrtime.bigint(),Y0=await T();if(Z("runMainThread:createThreadPool",e),x.attach(Y0),X){let a=await y1(Y0.threadHandles$);if(!a)throw new Q4("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&&Hu(W.features,m2.TUI_VOICE_NOTIF);if(K)V.serverStatusPromise.then((E0)=>{d=vA(E0)&&Hu(E0.features,m2.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(),A$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 RI(),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:H,agentMode:Q.mode,reasoningEffort:Y0,labels:Q.label},r=await lh4({threadPool:v,...a});if(await qu(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 u80();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)x3.selectConfig(e)}else c=!0}G=process.hrtime.bigint();let Q0=A11("0.0.1777979451-gaec852",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 y1(v.threadHandles$);if(!E0)throw new Q4("No active thread is available yet.",1);await E0.sendMessage({content:[{type:"text",text:X}]})}G=process.hrtime.bigint();let i=await RI();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};rY((E0)=>({...E0,launchCount:E0.launchCount+1}));try{if(G=process.hrtime.bigint(),await s6A({history:new Hr,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:VA,threadPool:v,createSystemPromptDeps:async()=>q$A(V),ideClient:x3,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:uB3,logFile:{path:$},sessionState:U0,freeTierStatusPromise:b,workspace:I??null,features:N,isInternalUser:H,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-05T11:14:30.119Z"},(E0)=>new f81({...E0,threadPool:E0.threadPool},(e)=>new B71({...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)kJ.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
6370
|
-
`);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 pB4({get:async(X)=>{if(X!==Lc)return;try{let F=await H$A(SQ1,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(X,F)=>{if(X!==Lc)return;await yB3(ge.dirname(SQ1),{recursive:!0}),await xB3(SQ1,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:F70()});t14($);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 pl4(A.mcpConfig);J=dl4(J,X)}let Y=ge.dirname(J.getSettingsFilePath());l_4(Gf,Y),J=Te1(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=K9;if(j.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!pH(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:sD0(await Rr(A,J))}}function F$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 D$3(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=ge.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?bB3:Yr));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function G$3(){$x4();let A=F$3(process.argv),Q=D$3(process.argv,A),B=Kh4(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(gB3(j),j.info("Starting Amp CLI.",{version:"0.0.
|
|
6369
|
+
Or pipe via stdin: echo "your message" | amp --execute`)}function J$3(A,Q){if(w54([h30.parse({tool:"*",action:"allow"})]),V54({bypass:!0}),cAA(A.settings))j.debug("Enabling permissions plugin"),Q.registerInternalPlugin({name:"permissions",entryPoint:N81})}async function AW0(A,Q,B,$){if(Q.headless)return Y$3(A,Q,B);let J=await g8(A,Q),Y=await J.serverStatusPromise,Z=await J.configService.getLatest(),X=vA(Y)&&Hu(Y.features,m2.THREAD_ACTORS_TUI),F=X&&!Q.takeMeBack;if(Q.showWelcome&&!X)throw await J.asyncDispose(),new Q4("--show-welcome is only available with the new Amp CLI feature flag",1);if(F)return J$3(Z,J.pluginService),Z$3(A,Q,B,J);else{if(Q.threadId&&zQ(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 Q4(`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 X$3(A,Q,B,$,{dependencies:J})}}async function Y$3(A,Q,B){let $=(H,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=ys0();j.info("Startup phase",{phase:H,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};f2(B,Q);let J=process.hrtime.bigint(),Y=await g8(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(cF(Z))throw me(Z,A.ampURL);let X=vA(Z)?Z:null,F=X?.user.email;await kQ1(B,Q,Z);let D=DP(Z),G=Hs(Q,D);if(G instanceof Error)x5(G.message);if(X&&!RS(Q.mode,F))throw new Q4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!F||!S7(F)))throw new Q4("Headless executor mode is only available for Amp employees",1);IF0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new Q4("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&&!zQ(K))throw new Q4(`Invalid thread ID: ${K}`,1);let E=K?void 0:await w$3({dependencies:Y,apiKey:U,visibility:G??void 0}),W=K??E?.threadId;if(!W)throw new Q4("Failed to resolve headless thread ID",1);let z=await up4(W);if(z.status==="already-running")await Y.asyncDispose(),await uW(),process.exit(0);try{await _p4({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 z.release(),await Y.asyncDispose()}await uW(),process.exit(0)}async function Z$3(A,Q,B,$){let{userInput:J,stdinInput:Y}=await I$A(Q),Z=!!Q.streamJson||!!Q.streamJsonThinking;w$A({...Q,streamJson:Z},A.executeMode,J),f2(B,Q),Uh4(),IF0();let X=Q.threadId&&zQ(Q.threadId)?Q.threadId:void 0,F=Q.observe?X8(Q.observe)??pQ(Q.observe):void 0,D=await $.serverStatusPromise;if(cF(D))throw me(D,A.ampURL);let G=await $.secretStorage.get("apiKey",A.ampURL);if(!G)throw new Q4("API key required. Please run `amp login` first.",1);let V=vA(D)&&S7(D.user.email);if(A.executeMode){y11($.mcpService,A.settings);try{let U=tE0(B,Q),K=await RI(),E=X?U:aD0({agentMode:Q.mode,explicitEffort:U,sessionState:K}),W=X?void 0:oD0(await Mf($.configService),{agentMode:Q.mode,explicitEffort:U,sessionState:K}),z=await nm4({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 qu(z,"execute"),Q.archive)await $.threadService.archive(z,!0)}finally{await $.asyncDispose()}await uW(),process.exit(0)}else{let U=tE0(B,Q),K=rL($.configService),E=new dR($.fuzzyServer),W=process.cwd();await H81({ampURL:A.ampURL,apiKey:G,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??KJ(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:z})=>VI({fileSystem:$.fileSystem,workspaceRoot:W},z),completionBuilder:E,workspaceRoot:W,listThreads:()=>K.listThreads(),getThreadFromServer:(z)=>K.getThread(z),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 X$3(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(E0,e)=>{let Y0=Number(process.hrtime.bigint()-e)/1e6,a=ys0();j.info("Startup phase",{phase:E0,phaseMs:Math.round(Y0),sinceMainMs:a===null?void 0:Math.round(a)})},{userInput:X,stdinInput:F}=await I$A(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;w$A({...Q,streamJson:D},A.executeMode,X),f2(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 me(E,A.ampURL);let W=vA(E)?E:null,z=W?.user.email,H=!!(z&&S7(z));if(H)IF0();if(!K)await kQ1(B,Q,E);let q=DP(E),N=q?.features??[],I=q?.team??null,w=Hs(Q,q);if(w instanceof Error)x5(w.message);if(W&&!RS(Q.mode,z))throw new Q4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let C=Q.threadId&&zQ(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)=>qu(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(),DP(e),w);if(Y0 instanceof Error)x5(Y0.message);return J71(O,{threadMeta:Y0?eY(Y0):void 0,agentMode:E0??Q.mode,onFirstAssistantMessage:_})},validateThreadOwnership:async(E0,e)=>{if(e?.nonBlockingOwnershipCheck){K$A(E0,V.configService,V.viewerUserIDPromise).catch((Y0)=>{if(Y0 instanceof Q4){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 K$A(E0,V.configService,V.viewerUserIDPromise)}catch(Y0){if(Y0 instanceof Q4)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 h9A(S,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(E0){if(E0 instanceof Q4)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=wp(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 _81:null,v,u=null;if(x)v=x,u=(async()=>{let E0=K?await V.serverStatusPromise:V.serverStatus;if(cF(E0))throw me(E0,A.ampURL);await kQ1(B,Q,E0);let e=process.hrtime.bigint(),Y0=await T();if(Z("runMainThread:createThreadPool",e),x.attach(Y0),X){let a=await y1(Y0.threadHandles$);if(!a)throw new Q4("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&&Hu(W.features,m2.TUI_VOICE_NOTIF);if(K)V.serverStatusPromise.then((E0)=>{d=vA(E0)&&Hu(E0.features,m2.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(),A$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 RI(),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:H,agentMode:Q.mode,reasoningEffort:Y0,labels:Q.label},r=await lh4({threadPool:v,...a});if(await qu(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 u80();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)x3.selectConfig(e)}else c=!0}G=process.hrtime.bigint();let Q0=A11("0.0.1777983419-g88aeb8",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 y1(v.threadHandles$);if(!E0)throw new Q4("No active thread is available yet.",1);await E0.sendMessage({content:[{type:"text",text:X}]})}G=process.hrtime.bigint();let i=await RI();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};rY((E0)=>({...E0,launchCount:E0.launchCount+1}));try{if(G=process.hrtime.bigint(),await s6A({history:new Hr,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:VA,threadPool:v,createSystemPromptDeps:async()=>q$A(V),ideClient:x3,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:uB3,logFile:{path:$},sessionState:U0,freeTierStatusPromise:b,workspace:I??null,features:N,isInternalUser:H,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-05T12:20:45.183Z"},(E0)=>new f81({...E0,threadPool:E0.threadPool},(e)=>new B71({...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)kJ.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
6370
|
+
`);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 pB4({get:async(X)=>{if(X!==Lc)return;try{let F=await H$A(SQ1,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(X,F)=>{if(X!==Lc)return;await yB3(ge.dirname(SQ1),{recursive:!0}),await xB3(SQ1,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:F70()});t14($);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 pl4(A.mcpConfig);J=dl4(J,X)}let Y=ge.dirname(J.getSettingsFilePath());l_4(Gf,Y),J=Te1(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=K9;if(j.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!pH(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:sD0(await Rr(A,J))}}function F$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 D$3(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=ge.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?bB3:Yr));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function G$3(){$x4();let A=F$3(process.argv),Q=D$3(process.argv,A),B=Kh4(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(gB3(j),j.info("Starting Amp CLI.",{version:"0.0.1777983419-g88aeb8",buildTimestamp:"2026-05-05T12:20:45.183Z"}),process.platform==="win32"&&nj())fd4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new Q4(U7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await $$3(B).parseAsync(process.argv)}d_4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await G$3().catch(hW)});async function V$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}
|
|
6371
6371
|
`);else if(!pH(A.ampURL))D5.write(`Logging in to ${new URL(A.ampURL).hostname}
|
|
6372
6372
|
`);let $=process.env.AMP_API_KEY;if($)D5.write(`API key found in environment variable, storing...
|
|
6373
6373
|
`),await Q.set("apiKey",$,A.ampURL),D5.write(`API key successfully stored.
|