@sourcegraph/amp 0.0.1777184774-g5a2bb8 → 0.0.1777185893-gae6d40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +20 -9
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -1456,6 +1456,14 @@ Spawn multiple ${h3} subagents in the same turn when fanning out across genuinel
1456
1456
  Avoid duplicating work that subagents are already doing. When a subagent finishes, summarize its result for the user since the user cannot see subagent output directly.
1457
1457
  </using_subagents>
1458
1458
 
1459
+ <file_links>
1460
+ When referencing files in your response, prefer "fluent" linking style. Do not show the user the actual URL, but instead use it to add links to relevant files or code snippets. Whenever you mention a file by name, you MUST link to it in this way.
1461
+
1462
+ When linking a file, the URL should use \`file\` as the scheme, the absolute path to the file as the path, and an optional fragment with the line range. Always URL-encode special characters in file paths (spaces become \`%20\`, parentheses become \`%28\` and \`%29\`, etc.).
1463
+
1464
+ For example, if the user asks for a link to \`~/src/app/routes/(app)/threads/+page.svelte\`, respond with [~/src/app/routes/(app)/threads/+page.svelte](file:///Users/bob/src/app/routes/%28app%29/threads/+page.svelte). You can also reference specific lines within a file like "The [auth logic](file:///Users/alice/project/config/auth.js#L15-L23) calls [validateToken](file:///Users/alice/project/config/validate.js#L45)".
1465
+ </file_links>
1466
+
1459
1467
  `}var DT4=J0(()=>{f5();y4()});function GT4(){return`
1460
1468
  You are pair programming with a user to solve their coding task. Treat every user message — including interruptions, corrections, and short replies — as an addition to the original specification that refines your direction. When the user redirects you, adapt immediately without defensiveness. Your main goal is to follow the user's instructions and verify that the result works.
1461
1469
 
@@ -2955,6 +2963,9 @@ ${R3(oY5)}
2955
2963
  - On Windows, use PowerShell commands and \`\\\` path separators
2956
2964
  - ALWAYS quote file paths: \`cat "path with spaces/file.txt"\`
2957
2965
  - When searching for text or files, prefer using \`rg\` or \`rg --files\` respectively because \`rg\` is much faster than alternatives like \`grep\`. (If the \`rg\` command is not found, then use alternatives.)
2966
+ - Do NOT run \`find\` (or any recursive search) from \`/\`, \`~\`, or another large unrelated root; scope it to the workspace or a specific directory you have reason to search, otherwise it will be extremely slow and waste tokens
2967
+ - When using \`find\` or \`grep -r\`, exclude heavy directories like \`node_modules\`, \`.git\`, \`dist\`, \`build\`, and \`target\` (\`rg\` already skips these via gitignore)
2968
+ - Do NOT pipe \`cat file | grep/awk/sed/...\`; pass the file directly to the command (e.g. \`grep pattern file\`)
2958
2969
  - When using \`grep\`, pass \`-E\` (or use \`egrep\`) to enable extended regular expressions; \`rg\` uses extended regex by default.
2959
2970
  - Only run \`git commit\` and \`git push\` if explicitly instructed by the user.
2960
2971
  `,bk4={spec:{name:I6,description:dZ5,inputSchema:{type:"object",properties:{cmd:{type:"string",description:"The shell command to execute"},cwd:{type:"string",description:"Absolute path to a directory where the command will be executed (must be absolute, not relative)"}},required:["cmd"]},source:"builtin",meta:{disableTimeout:!0},executionProfile:{serial:!0,resourceKeys:()=>[]}},fn:rX0,preprocessArgs:(A,Q)=>{let B;if(/(?<!&)\s*&\s*$/u.test(A.cmd))B={...A,cmd:A.cmd.replace(/(?<!&)\s*&\s*$/u,"").trim()},A=B;if(A.cwd?.startsWith("~")){if(typeof process<"u"){let $=process.env.HOME||process.env.USERPROFILE;if($)B={...A,cwd:A.cwd.replace(/^~/,$)},A=B}}if(B)return B;if(A.cwd)return;try{let[$,J]=vD(A.cmd),Y=$&&$.arguments.length===1&&typeof $.arguments[0]?.value==="string"?$.arguments[0].value:void 0;if($?.program.value==="cd"&&Y&&J){let Z=Y;if(Y.startsWith("~")&&typeof process<"u"){let F=process.env.HOME||process.env.USERPROFILE;if(F)Z=Y.replace(/^~/,F)}return z70(Q.dir),{...A,cwd:G1.resolvePath(Q.dir,Z).fsPath,cmd:A.cmd.slice(J.program.start.offset)}}}catch{return}}};O1();y4();var cZ5=`Render a chart visualization by running a command that produces JSON data. The chart is displayed inline to the user.
@@ -4640,12 +4651,12 @@ ${E}`))}},error:(K)=>{if(!U)U=!0,X(Error(`Failed to spawn brew: ${K.message}`))}
4640
4651
  ${E}`;if(Y==="pnpm"&&E.includes("Unable to find the global bin directory"))W+=`
4641
4652
 
4642
4653
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
4643
- npm install -g @sourcegraph/amp`;X(Error(W))}},error:(K)=>{if(!V)V=!0,X(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,F()}})})}l0();l0();KI();async function sU0(A,Q){let J=`${Q||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,Y=new AbortController,Z=setTimeout(()=>Y.abort(),5000);try{let F=await fetch(J,{signal:Y.signal});if(!F.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let X=await F.json(),D=X.version??X["dist-tags"]?.latest;if(!D)return{hasUpdate:!1,currentVersion:A,source:"npm"};let G=Ye(A,D),V=G<0,U,K;if(X.time){let E=X.time[A],W=X.time[D],H=Date.now();if(E)U=Math.floor((H-new Date(E).getTime())/3600000);if(W)K=Math.floor((H-new Date(W).getTime())/3600000)}return T.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(F){return T.debug("Error checking npm version",{error:F}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var wi5="https://static.ampcode.com/cli/cli-version.txt";async function tU0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${wi5}?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=Ye(A,J),Z=Y<0;return T.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return T.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var Mi5=604800000;function us4(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>Mi5)return{ageMs:B};return null}function Ye(A,Q){let B=(Z)=>{let[F,X]=Z.split("-");return{parts:F?.split(".").map(Number)||[],label:X}},$=B(A),J=B(Q),Y=Math.max($.parts.length,J.parts.length);for(let Z=0;Z<Y;Z++){let F=$.parts[Z]||0,X=J.parts[Z]||0;if(F<X)return-1;if(F>X)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 S81(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?yU(B):void 0;return{sha:$,age:J}}catch{return null}}O1();l0();import{readFile as Li5,realpath as Oi5}from"node:fs/promises";import{homedir as ji5}from"node:os";import{dirname as hs4,join as k81}from"node:path";async function gs4(A){switch(A){case"binary":case"brew":return Ri5(Qe());case"npm":case"pnpm":case"yarn":case"bun":return Pi5();case"bootstrap":return _i5()}}async function Ri5(A){let Q=await _G(A,["--version"],5000);if(Q.reason!=="success")return T.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function Pi5(){try{let A=process.argv[1];if(!A)return null;let Q=await Oi5(A),B=hs4(hs4(Q));return await ms4(k81(B,"package.json"))}catch(A){return T.debug("failed to read installed version from package.json",{error:A}),null}}async function _i5(){try{let A=process.env.AMP_HOME??k81(ji5(),".amp");return await ms4(k81(A,"package","package.json"))}catch(A){return T.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function ms4(A){let Q=await Li5(A,"utf8"),B=JSON.parse(Q);if(B.name!=="@sourcegraph/amp")return T.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var Ti5=3600000,Si5=5000;function v81(A,Q,B={}){let $=new HA,J=$.pipe(sA({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??Ti5,F=!1,X=()=>{F=!0};return setImmediate(async()=>{let D=new UD().scoped("update");if(Y>0){if(await vU(Y),F)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!F){let U=await ki5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await vU(Si5),F)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!F){let W=Math.min(K,E);await vU(W),E-=W}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:X}}async function ki5(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 oU0(),F=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:F});let X;if(F)X=await tU0(A);else{let V=await HP();X=await sU0(A,V)}if(!(X.latestVersion&&X.hasUpdate))return B.debug("no update available"),J;let D=(V)=>{$.next(V),J.emittedVisibleState=!0};if(Z){let V=await gs4(Z);if(V&&Ye(V,X.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:X.latestVersion}),J.updatedTo=V,Ye(A,V)<0){let U=await yH(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(X.currentVersionAge!==void 0&&X.latestVersionAge!==void 0){let V=X.currentVersionAge-X.latestVersionAge,U=0.5;if(Math.abs(V)<0.5)return B.debug("versions too close together, suppressing update warning",{currentVersionAge:X.currentVersionAge,latestVersionAge:X.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!==Qe()){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 Je(X.latestVersion,Z),J.updatedTo=X.latestVersion;let V=await yH(X.latestVersion),U={from:X.currentVersion,to:X.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}}KI();import{stderr as TG}from"node:process";function ps4(A){let Q=new bI().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 N81($.force||!1,$.verbose||!1,"0.0.1777184774-g5a2bb8"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new bI("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 yi5($.targetVersion)});A.addCommand(B)}function vi5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
4654
+ npm install -g @sourcegraph/amp`;X(Error(W))}},error:(K)=>{if(!V)V=!0,X(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,F()}})})}l0();l0();KI();async function sU0(A,Q){let J=`${Q||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,Y=new AbortController,Z=setTimeout(()=>Y.abort(),5000);try{let F=await fetch(J,{signal:Y.signal});if(!F.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let X=await F.json(),D=X.version??X["dist-tags"]?.latest;if(!D)return{hasUpdate:!1,currentVersion:A,source:"npm"};let G=Ye(A,D),V=G<0,U,K;if(X.time){let E=X.time[A],W=X.time[D],H=Date.now();if(E)U=Math.floor((H-new Date(E).getTime())/3600000);if(W)K=Math.floor((H-new Date(W).getTime())/3600000)}return T.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(F){return T.debug("Error checking npm version",{error:F}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var wi5="https://static.ampcode.com/cli/cli-version.txt";async function tU0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${wi5}?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=Ye(A,J),Z=Y<0;return T.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return T.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var Mi5=604800000;function us4(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>Mi5)return{ageMs:B};return null}function Ye(A,Q){let B=(Z)=>{let[F,X]=Z.split("-");return{parts:F?.split(".").map(Number)||[],label:X}},$=B(A),J=B(Q),Y=Math.max($.parts.length,J.parts.length);for(let Z=0;Z<Y;Z++){let F=$.parts[Z]||0,X=J.parts[Z]||0;if(F<X)return-1;if(F>X)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 S81(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?yU(B):void 0;return{sha:$,age:J}}catch{return null}}O1();l0();import{readFile as Li5,realpath as Oi5}from"node:fs/promises";import{homedir as ji5}from"node:os";import{dirname as hs4,join as k81}from"node:path";async function gs4(A){switch(A){case"binary":case"brew":return Ri5(Qe());case"npm":case"pnpm":case"yarn":case"bun":return Pi5();case"bootstrap":return _i5()}}async function Ri5(A){let Q=await _G(A,["--version"],5000);if(Q.reason!=="success")return T.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function Pi5(){try{let A=process.argv[1];if(!A)return null;let Q=await Oi5(A),B=hs4(hs4(Q));return await ms4(k81(B,"package.json"))}catch(A){return T.debug("failed to read installed version from package.json",{error:A}),null}}async function _i5(){try{let A=process.env.AMP_HOME??k81(ji5(),".amp");return await ms4(k81(A,"package","package.json"))}catch(A){return T.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function ms4(A){let Q=await Li5(A,"utf8"),B=JSON.parse(Q);if(B.name!=="@sourcegraph/amp")return T.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var Ti5=3600000,Si5=5000;function v81(A,Q,B={}){let $=new HA,J=$.pipe(sA({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??Ti5,F=!1,X=()=>{F=!0};return setImmediate(async()=>{let D=new UD().scoped("update");if(Y>0){if(await vU(Y),F)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!F){let U=await ki5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await vU(Si5),F)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!F){let W=Math.min(K,E);await vU(W),E-=W}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:X}}async function ki5(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 oU0(),F=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:F});let X;if(F)X=await tU0(A);else{let V=await HP();X=await sU0(A,V)}if(!(X.latestVersion&&X.hasUpdate))return B.debug("no update available"),J;let D=(V)=>{$.next(V),J.emittedVisibleState=!0};if(Z){let V=await gs4(Z);if(V&&Ye(V,X.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:X.latestVersion}),J.updatedTo=V,Ye(A,V)<0){let U=await yH(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(X.currentVersionAge!==void 0&&X.latestVersionAge!==void 0){let V=X.currentVersionAge-X.latestVersionAge,U=0.5;if(Math.abs(V)<0.5)return B.debug("versions too close together, suppressing update warning",{currentVersionAge:X.currentVersionAge,latestVersionAge:X.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!==Qe()){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 Je(X.latestVersion,Z),J.updatedTo=X.latestVersion;let V=await yH(X.latestVersion),U={from:X.currentVersion,to:X.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}}KI();import{stderr as TG}from"node:process";function ps4(A){let Q=new bI().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 N81($.force||!1,$.verbose||!1,"0.0.1777185893-gae6d40"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new bI("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 yi5($.targetVersion)});A.addCommand(B)}function vi5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
4644
4655
  `),$=!1,B=0}function Y(Z){if(!Q)return;let F=Z.padEnd(B," ");A.write(`\r${F}`),$=!0,B=F.length}return{flushProgressLine:J,renderProgress:Y}}async function yi5(A){let B=process.platform==="win32"&&WP()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:$,renderProgress:J}=vi5(TG);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")TG.write(n0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4645
4656
 
4646
4657
  `));try{if(!A){TG.write(n0.blue(`Checking for updates...
4647
- `));let F=!1,X;if(WP()){let D=await tU0("0.0.1777184774-g5a2bb8");F=D.hasUpdate,X=D.latestVersion}else{let D=await HP(),G=await sU0("0.0.1777184774-g5a2bb8",D);F=G.hasUpdate,X=G.latestVersion}if(!F){let D=S81("0.0.1777184774-g5a2bb8"),G=D?.age?`released ${D.age} ago`:`built ${yU(new Date("2026-04-26T06:29:46.840Z"))} ago`;TG.write(n0.green(`✓ Amp is already up to date on version ${"0.0.1777184774-g5a2bb8"} (${G})
4648
- `));let V=await yH("0.0.1777184774-g5a2bb8",B);if(V.warning)TG.write(`
4658
+ `));let F=!1,X;if(WP()){let D=await tU0("0.0.1777185893-gae6d40");F=D.hasUpdate,X=D.latestVersion}else{let D=await HP(),G=await sU0("0.0.1777185893-gae6d40",D);F=G.hasUpdate,X=G.latestVersion}if(!F){let D=S81("0.0.1777185893-gae6d40"),G=D?.age?`released ${D.age} ago`:`built ${yU(new Date("2026-04-26T06:48:40.597Z"))} ago`;TG.write(n0.green(`✓ Amp is already up to date on version ${"0.0.1777185893-gae6d40"} (${G})
4659
+ `));let V=await yH("0.0.1777185893-gae6d40",B);if(V.warning)TG.write(`
4649
4660
  `+n0.yellow(V.warning)+`
4650
4661
  `);process.exit(0)}if(!X)TG.write(n0.yellow("[WARN] could not find latest version")),process.exit(0);A=X}TG.write(n0.blue(`Updating to version ${A}...
4651
4662
  `)),await Je(A,void 0,(F)=>{$(),TG.write(n0.dim(`Running: ${F}
@@ -5156,7 +5167,7 @@ Ctrl-X, Y, Z to unlock`;if(U){let x=D.text.replace(/`([^`]+)`/g,"$1")+`
5156
5167
 
5157
5168
  `,new h({color:$.toolSuccess,bold:!0})),new O(`This thread has been shared with Amp support for debugging and bug prioritization.
5158
5169
  `,new h({color:B.foreground})),new O(`This is not a support request.
5159
- `,new h({color:B.foreground,dim:!0})),new O("If you need a reply, post on X @AmpCode or email amp-devs@ampcode.com.",new h({color:B.foreground,dim:!0}))]),textAlign:"center"})})}}function L9A(A){return new V3({header:A.title,minWidth:80,maxWidth:80,chromePadding:M0.symmetric(1,0),footer:"none",onDismiss:A.onDismiss,child:A.child})}function c78(A,Q,B){return new p1({child:new u0({constraints:new W1(80,80,0,12),child:new tH({commandName:"Share with Support",title:"Share Thread with Support",placeholder:"What went wrong? (Need a reply? Email amp-devs@ampcode.com.)",isRequiredArg:!1,onSubmit:async($)=>{try{await A.shareThreadWithSupport(Q,$||void 0),B.pushResultPane(L9A({title:"Shared with Support",onDismiss:B.dismissFlow,child:new $10}))}catch(J){T.error("Failed to share thread with support",{error:J,threadID:Q}),B.pushResultPane(L9A({title:"Share with Support failed",onDismiss:B.dismissFlow,child:new t({text:new O(`Failed to share thread with support: ${J instanceof Error?J.message:String(J)}`)})}))}},onDismiss:B.dismissFlow})})})}function O9A(A,Q){return{noun:"thread",verb:"share with support",description:"Share with Amp support for debugging",get status(){return Q()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(B,$,J)=>{let Y=Q()?.client.getThreadId();if(!Y)return;B.push(c78(A,Y,{dismissFlow:J,pushResultPane:(Z)=>B.push(Z)}))}}}class J10 extends y0{props;constructor(A){super();this.props=A}createState(){return new j9A}}class j9A extends v0{result=void 0;isLoading=!1;build(A){let Q=[];if(this.isLoading)Q.push(new fQ({message:"Updating visibility..."}));else if(this.result!==void 0)Q.push(new i7({message:this.result,onDismiss:()=>{this.widget.props.onDismiss()}}));else{let B=["private","workspace","unlisted","public"],$=this.widget.props.workspace?.groups&&this.widget.props.workspace.groups.length>0?["private","workspace","group","unlisted","public"]:B;Q.push(new k5({items:$,getLabel:(J)=>{switch(J){case"private":return"Private - Only you can see this thread";case"workspace":return"Workspace - Visible to workspace members";case"group":return"Group - Visible to group members";case"unlisted":return"Unlisted - Anyone with the link can view";case"public":return"Public - Searchable and on your public profile"}},title:"Select Thread Visibility",onAccept:async(J)=>{this.setState(()=>{this.isLoading=!0});let Y=await this.widget.props.execute(J);this.setState(()=>{this.isLoading=!1,this.result=Y})},onDismiss:this.widget.props.onDismiss}))}return new CA({children:Q,fit:"expand"})}}function l78(A,Q,B){return new p1({child:new u0({constraints:new W1(80,80,0,16),child:new J10({workspace:null,threadID:Q,execute:($)=>A.setVisibility(Q,$),onDismiss:B})})})}function R9A(A,Q){return{noun:"thread",verb:"set visibility",description:"Set thread visibility",keywords:["share","private","workspace","public","unlisted","team","group"],get status(){return Q()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(B,$,J)=>{let Y=Q()?.client?.getThreadId();if(!Y)return;B.push(l78(A,Y,J))}}}class JB1 extends y0{initialAgentMode;analyzeContextForThread;listSkillsForThread;threadContext;draftThreadSettings;editorController;history;updateDraftThreadSettings;onNewThread;shareThreadWithSupport;setThreadVisibility;archiveThread;addThreadLabel;removeThreadLabel;configService;connectionErrorMessage;hints;ideStatus;constructor(A){super();this.initialAgentMode=A.initialAgentMode,this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.threadContext=A.threadContext,this.draftThreadSettings=A.draftThreadSettings,this.editorController=A.editorController,this.history=A.history,this.updateDraftThreadSettings=A.updateDraftThreadSettings,this.onNewThread=A.onNewThread,this.shareThreadWithSupport=A.shareThreadWithSupport,this.setThreadVisibility=A.setThreadVisibility,this.archiveThread=A.archiveThread,this.addThreadLabel=A.addThreadLabel,this.removeThreadLabel=A.removeThreadLabel,this.configService=A.configService,this.connectionErrorMessage=A.connectionErrorMessage,this.hints=A.hints,this.ideStatus=A.ideStatus}createState(){return new P9A}}class P9A extends v0{historyIndex=-1;historyDraft=null;promptHistoryPicker=new pe(this);agentMode;expansion=new UQ1;previousThreadIDForReference=null;unregisterCommands=null;initState(){this.agentMode=this.widget.initialAgentMode,this.unregisterCommands=this.registerCommands()}didUpdateWidget(A){if(A.threadContext?.client!==this.widget.threadContext?.client)if(this.historyIndex=-1,this.historyDraft=null,!this.widget.threadContext)this.previousThreadIDForReference=A.threadContext?.client.getThreadId()??null;else this.previousThreadIDForReference=null}dispose(){this.unregisterCommands?.(),this.unregisterCommands=null}registerCommands(){let A=jX.of(this.context),Q=l7.of(this.context),B=this,$=()=>{return B.widget.threadContext??null},J=()=>{let X=B.widget.threadContext?.client.getThreadId();if(!X)return null;return TY(new URL(Q.ampURL),X).toString()},F=[...t$(void 0,{isInternalUser:Q.isInternalUser}).map(({mode:X})=>({noun:"mode",verb:`use ${X}`,description:`Enable ${X} mode`,get status(){if(B.widget.threadContext)return{type:"disabled",reason:"Mode can only be changed on a new thread"};if(X===B.agentMode)return{type:"disabled",reason:`Already using ${X} mode`};return{type:"enabled"}},run:(D,G,V)=>{B.setAgentMode(X),V()}})),{noun:"speed",verb:"toggle speed",description:"Toggle speed (fast/standard) for this thread",keywords:["anthropic","openai","fast","standard","smart","deep"],get status(){let X=B.currentCommandAgentMode();return X==="smart"||y2(X)?{type:"enabled"}:{type:"hidden"}},run:(X,D,G)=>{B.toggleSpeed(),G()}},{noun:"thread",verb:"toggle thinking blocks",description:"Expand or collapse all thinking blocks",keywords:["thinking","expand","collapse","reasoning"],shortcut:a1.alt("t"),status:{type:"enabled"},run:(X,D,G)=>{B.toggleGlobalThinking(),G()}},{noun:"mode",verb:"toggle reasoning effort",description:"Cycle reasoning effort for the active model",keywords:["deep","thinking","reasoning","effort","depth","anthropic","openai","smart","frontier"],shortcut:a1.alt("d"),get status(){return Ic(B.currentCommandAgentMode())?{type:"enabled"}:{type:"hidden"}},run:(X,D,G)=>{B.toggleReasoningEffort(),G()}},{noun:"prompt",verb:"history",description:"Restore a previous prompt",keywords:["recent","reuse","search"],shortcut:a1.ctrl("r"),status:{type:"enabled"},run:(X,D,G)=>{X.pushWithDismiss((V)=>new lW0({entries:this.widget.history.getAll(),currentCwd:$B1.cwd(),onAccept:(U)=>{this.restorePromptHistory(U),G()},onDismiss:V}))}},{noun:"thread",verb:"copy ID",description:"Copy thread ID to clipboard",keywords:["identifier","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=$()?.client.getThreadId();if(!V)return;A6.maybeInvoke(D,new gG(V,"Thread ID copied to clipboard","Failed to copy thread ID")),G()}},{noun:"thread",verb:"copy URL",description:"Copy thread URL to clipboard",keywords:["link","share","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=J();if(!V)return;A6.maybeInvoke(D,new gG(V,"Thread URL copied to clipboard","Failed to copy thread URL")),G()}},{noun:"thread",verb:"copy markdown",description:"Copy thread as Markdown",keywords:["markdown","export","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=$()?.client.getThreadId();if(!V)return;(async()=>{try{let U=await Q.getThreadMarkdown(V);if(!U){fK.error(D,"Failed to copy thread markdown");return}A6.maybeInvoke(D,new gG(U,"Thread markdown copied to clipboard","Failed to copy thread markdown"))}catch(U){T.error("Failed to render thread markdown from Neo command palette",{error:U,threadID:V}),fK.error(D,"Failed to copy thread markdown")}finally{G()}})()}},{noun:"thread",verb:"analyze context",description:"Analyze context token usage",keywords:["tokens","usage","window","size","cost"],get status(){let X=B.widget.threadContext;if(!X)return{type:"disabled",reason:"No active thread"};let D=e$(X.observer.agentMode);if(!T3A.includes(D))return{type:"disabled",reason:"Context analysis requires Claude Opus 4.7 (smart) or GPT-5.4 (deep)"};return{type:"enabled"}},run:(X)=>{let D=$()?.client.getThreadId();if(!D)return;X.pushWithDismiss((G)=>{return new V3({header:"Context Usage Analysis",minWidth:60,maxWidth:60,chromePadding:M0.symmetric(1,0),footer:[{keys:["Esc"],label:"close"}],onDismiss:G,child:new i00({embedded:!0,contentWidth:58,thread:null,dtwAnalyze:(K)=>{return B.widget.analyzeContextForThread(D,K)},onDismiss:G})})})}},{noun:"skills",verb:"list",description:"List available skills for this thread",keywords:["agent","show"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X)=>{let D=$()?.client.getThreadId();if(!D)return;X.pushWithDismiss((G)=>new BB1({listSkills:(V)=>B.widget.listSkillsForThread(D,V),onDismiss:G,cwd:Q.workspaceRoot}))}},{noun:"thread",verb:"new",description:"Start new thread",keywords:["create","start","reset","clear"],sortBoost:101,get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"Already on a new thread"}},run:(X,D)=>{A6.maybeInvoke(D,new h00)}},{noun:"thread",verb:"open in browser",description:"Open thread in browser",keywords:["web","view","launch"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(X,D,G)=>{let V=J();if(!V)return;try{await V5(D,V)}finally{G()}}},O9A({shareThreadWithSupport:(X,D)=>{return this.widget.shareThreadWithSupport(X,D)}},$),R9A({setVisibility:(X,D)=>this.widget.setThreadVisibility(X,D)},$),d2A({archiveThread:(X)=>this.widget.archiveThread(X)},$),M9A($),G9A({configService:this.widget.configService,addLabel:(X,D)=>this.widget.addThreadLabel(X,D)},$),K9A({configService:this.widget.configService,removeLabel:(X,D)=>this.widget.removeThreadLabel(X,D)},$)].map((X)=>A.register(X));return()=>{for(let X of F)X()}}currentCommandAgentMode(){return this.widget.threadContext?.observer.agentMode??this.agentMode}updateThreadSettings(A){let Q=this.widget.threadContext;if(Q){let B=Q.observer.threadSettings().getValue()??{},$=A(B);return Q.client.sendClientUpdateThreadSettings($),this.widget.updateDraftThreadSettings(()=>$),"handled"}return this.widget.updateDraftThreadSettings(A),"handled"}toggleSpeed(){let A=this.currentCommandAgentMode();if(A==="smart")return this.updateThreadSettings((Q)=>{let B={...Q};if(B["anthropic.speed"]==="fast")delete B["anthropic.speed"];else B["anthropic.speed"]="fast";return B});if(y2(A))return this.updateThreadSettings((Q)=>{let B={...Q};if(B["openai.speed"]==="fast")B["openai.speed"]="standard";else B["openai.speed"]="fast";return B});return"ignored"}toggleGlobalThinking(){return this.expansion.toggle(),"handled"}toggleReasoningEffort(){let A=this.currentCommandAgentMode(),Q=Ic(A);if(!Q)return"ignored";return this.updateThreadSettings((B)=>{let $=R90(A,B);if(!$)return B;let J=B[$]??J3(A)?.reasoningEffort,Y=j90(Q,J);return{...B,[$]:Y}})}onPromptSubmitted=(A)=>{this.widget.history.add(A,$B1.cwd()),this.resetHistory()};restorePromptHistory(A){this.resetHistory(),this.widget.editorController.text=A,this.widget.editorController.moveCursorToEnd()}handlePromptHistorySelection=(A)=>{this.promptHistoryPicker.disable(),this.restorePromptHistory(A)};navigateHistoryPrevious=()=>{let A=this.widget.history.previous();if(A!==null){if(this.historyIndex===-1)this.historyDraft=this.widget.editorController.text;this.historyIndex++,this.widget.editorController.text=A,this.widget.editorController.moveCursorToStart()}return"handled"};navigateHistoryNext=()=>{let A=this.widget.history.next();if(A!==null)this.historyIndex--,this.widget.editorController.text=A,this.widget.editorController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.widget.editorController.text=this.historyDraft||"",this.widget.editorController.moveCursorToEnd(),this.historyDraft=null;return"handled"};resetHistory(){this.widget.history.reset(),this.historyIndex=-1,this.historyDraft=null}setAgentMode(A){if(this.widget.threadContext)return;this.setState(()=>{this.agentMode=A}),qZ((Q)=>({...Q,agentMode:A}))}buildActions(){let A=new S4(()=>{return this.promptHistoryPicker.enable(),"handled"}),Q=new S4(()=>{return this.navigateHistoryPrevious()}),B=new S4(()=>{return this.navigateHistoryNext()}),$=new S4((Z)=>{return this.setAgentMode(Z.mode),"handled"}),J=new S4(()=>{return this.toggleReasoningEffort()}),Y=new S4(()=>{return this.toggleGlobalThinking()});return new Map([[hH,A],[jW0,B],[OW0,Q],[d00,$],[RW0,J],[MW0,Y]])}build(A){let Q=this.widget.threadContext,$=[Q?new rQ1({editorController:this.widget.editorController,observingClient:{client:Q.client,observer:Q.observer},hints:this.widget.hints,ideStatus:this.widget.ideStatus,onPromptSubmitted:this.onPromptSubmitted}):new AB1({agentMode:this.agentMode,threadSettings:this.widget.draftThreadSettings,editorController:this.widget.editorController,onNewThread:this.widget.onNewThread,previousThreadIDForReference:this.previousThreadIDForReference,connectionErrorMessage:this.widget.connectionErrorMessage,hints:this.widget.hints,ideStatus:this.widget.ideStatus})];if(this.promptHistoryPicker.isEnabled())$.push(new lW0({entries:this.widget.history.getAll(),currentCwd:$B1.cwd(),onAccept:this.handlePromptHistorySelection,onDismiss:this.promptHistoryPicker.disable}));let J=new Map([[a1.ctrl("r"),new hH],[a1.alt("d"),new RW0],[a1.alt("t"),new MW0]]);if(this.promptHistoryPicker.isEnabled())J.set(a1.ctrl("o"),new hH);else J.set(a1.ctrl("n"),new jW0),J.set(a1.ctrl("p"),new OW0);return new A6({actions:this.buildActions(),child:new G3({debugLabel:"NeoThreadShortcuts",shortcuts:J,child:new RX({controller:this.expansion,child:new CA({children:$})})})})}}class YB1 extends y0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;isFirstOpen;notificationService;onThreadArchived;initialUserInput;openThreadPickerOnStart;neoContext;constructor(A){super();this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.initialThreadID=A.initialThreadID,this.isFirstOpen=A.isFirstOpen??!1,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.initialUserInput=A.initialUserInput,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new _9A}}class _9A extends v0{editorController=new I2;commandPalette=new pe(this);commandRegistry=new QQ1;toastController=new a31;exitHintTimer=new me(this,1000);connectionErrorMessage=new r3(this,null);ideStatus=new r3(this,{});draftThreadSettings={};draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;ideErrorSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;firstOpenDialogVisible=!1;focusDebugVisible=!1;unregisterCommands=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.clearConnectionError(),this.connectToExistingThread(A)};shareThreadWithSupport=async(A,Q)=>{let B;if(this.activeThreadContext&&this.activeThreadContext.client.getThreadId()===A){let $=this.activeThreadContext.observer.activeError().getValue();if($)B={message:$.message,type:$.code,stack:$.stack,retryAfterSeconds:$.retryAt!==void 0?Math.max(0,Math.ceil(($.retryAt-Date.now())/1000)):void 0}}await o8A({configService:this.widget.configService},A,Q,B)};setThreadVisibility=(A,Q)=>{return r8A({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await V1A({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await U1A({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 K1A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(H$.getInstance().interceptConsole(),this.widget.isFirstOpen)this.firstOpenDialogVisible=!0;if(this.connectionErrorMessage.subscribe(this.widget.clientPool.connectionErrors$.pipe(aE(({threadID:Q,error:B})=>{T.error("Neo failed to connect to thread",{threadID:Q,error:B})}),N5(({threadID:Q})=>this.isConnectionErrorRelevant(Q)),aE(()=>this.clearActiveClientForConnectionError()),w1(({threadID:Q,error:B})=>{return Q?`Connection failed for ${Q}: ${B.message}`:`Connection failed: ${B.message}`}))),this.ideStatus.subscribe(this.widget.ideManager.status),this.ideErrorSubscription=this.widget.ideManager.errors$.subscribe((Q)=>{if(Q)this.setState(()=>{this.connectionErrorMessage.setValue(Q)})}),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID)this.connectToExistingThread(this.widget.initialThreadID,A);else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=i4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let Q=[{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(B,$,J)=>{B.pushWithDismiss((Y)=>lQ1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:Y,onThreadSelected:J}))}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(B)=>{B.pushWithDismiss(($)=>new VQ1({mcpServers:this.widget.neoContext.mcpServers,onDismiss:$}))}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{pJ(this.widget.neoContext.settingsFilePath).catch((B)=>{T.error("Failed to open settings file in editor",{error:B})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(B,$,J)=>{B.pushWithDismiss((Y)=>new DQ1({onCancel:Y,onSelect:(Z)=>{this.handleIdeSelection(Z),J()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(B,$)=>{B.pushWithDismiss((J)=>new ZQ1({commands:jX.of($).commands,onDismiss:J}))}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(B)=>{B.pushWithDismiss(($)=>new V3({header:"Amp Version",maxWidth:72,onDismiss:$,child:new t({text:new O(p31({version:"0.0.1777184774-g5a2bb8",buildTimestamp:"2026-04-26T06:29:46.840Z",buildType:"'release'"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:a1.ctrl("c"),status:{type:"enabled"},run:(B,$)=>{A6.maybeInvoke($,new cu)}},...a8A(this.widget.neoContext.logFilePath)].map((B)=>this.commandRegistry.register(B));return()=>{for(let B of Q)B()}}build(A){let Q=this.buildHints(),B=this.connectionErrorMessage.getValue(),$=this.ideStatus.getValue(),J=new JB1({initialAgentMode:this.widget.neoContext.sessionAgentMode,analyzeContextForThread:this.widget.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,shareThreadWithSupport:this.shareThreadWithSupport,setThreadVisibility:this.setThreadVisibility,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,connectionErrorMessage:B,hints:Q,ideStatus:$}),Y=F4.of(A),F=[new u0({constraints:W1.tight(Y.size.width,Y.size.height),child:J})];if(this.commandPalette.isEnabled())F.push(new BQ1({onDismiss:this.commandPalette.disable}));if(this.switchThreadPickerVisible)F.push(lQ1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.firstOpenDialogVisible)F.push(new FQ1({onDismiss:this.dismissFirstOpenDialog}));if(this.focusDebugVisible)F.push(new XQ1);return new l7({neoContext:this.widget.neoContext,child:new jX({commandRegistry:this.commandRegistry,child:new eC({completionBuilder:this.widget.completionBuilder,child:new fK({controller:this.toastController,child:new A6({actions:this.buildActions(),child:new G3({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[a1.ctrl("c"),new CW0],[a1.ctrl("o"),new wW0],[a1.ctrl("t"),new LW0]]),child:new e4({debugLabel:"AppShellFocus",child:new o31({controller:this.toastController,child:new CA({children:F})})})})})})})})})}buildActions(){let A=new S4(()=>{return this.onExitPressed(),"handled"}),Q=new S4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new S4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new S4(()=>{return this.commandPalette.disable(),this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.writeTerminalTitle(void 0),this.activeThreadContext=null,this.connectingToThreadID=null,this.connectionErrorMessage.setValue(null)}),"handled"}),J=new S4(()=>{return i4.instance.stop(),"handled"}),Y=new S4((F)=>{if(!F.text)return"ignored";return i4.instance.tuiInstance.clipboard.writeText(F.text).then(()=>{this.toastController.show(F.successMessage,"success",2000)}).catch((X)=>{T.error("Failed to copy Neo text to clipboard",{error:X}),this.toastController.show(F.failureMessage,"error",2000)}),"handled"}),Z=new S4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[CW0,A],[h00,$],[cu,J],[gG,Y],[p00,B],[wW0,Q],[LW0,Z]])}ensureDraftThreadSettingsInitialized(){if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=await _K0(this.widget.configService);if(!this.mounted)return;this.setState(()=>{this.draftThreadSettings=A})}catch(A){T.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(mu);if(this.exitHintTimer.isActive())A.add(v00);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),i4.instance.stop();else this.exitHintTimer.activate()};dismissFirstOpenDialog=()=>{if(!this.firstOpenDialogVisible)return;this.setState(()=>{this.firstOpenDialogVisible=!1})};closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q)=>{await this.ensureDraftThreadSettingsInitialized();let B=A.find((J)=>J.type==="text");if(B&&B.type==="text")this.widget.history.add(B.text,iW0.cwd()),this.widget.history.reset();let $=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings);this.clearConnectionError(),this.sendUserMessage($,A,Q),this.setActiveClient($)};sendUserMessage(A,Q,B){A.observer.markMessageSent();let $=hX0(this.ideStatus.getValue());A.client.sendUserMessage(Q,B,{userState:$})}async connectToExistingThread(A,Q){this.setState(()=>{this.connectingToThreadID=A});try{let B=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly});if(this.setActiveClient(B),Q)this.sendUserMessage(B,[{type:"text",text:Q}])}catch(B){T.error("Failed to load thread",{error:B,threadID:A}),this.connectionErrorMessage.setValue(`Failed to load ${A}: ${B instanceof Error?B.message:String(B)}`)}finally{this.setState(()=>{this.connectingToThreadID=null})}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q},this.connectionErrorMessage.setValue(null),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=iW0.cwd().replace(iW0.env.HOME||"","~"),B=A?`amp - ${A} - ${Q}`:"";iW0.stdout.write(RC(B))}handleIdeSelection=async(A)=>{await this.widget.ideManager.connect(A)};dispose(){this.unregisterCommands?.(),this.unregisterCommands=null,this.titleSubscription?.unsubscribe(),this.ideErrorSubscription?.unsubscribe(),this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}isConnectionErrorRelevant(A){if(!this.activeThreadContext)return!0;if(!A)return!0;return this.activeThreadContext.client.getThreadId()===A}clearConnectionError(){if(!this.connectionErrorMessage.getValue())return;this.setState(()=>{this.connectionErrorMessage.setValue(null)})}clearActiveClientForConnectionError(){if(!this.activeThreadContext)return;this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.widget.notificationService.detach(),this.writeTerminalTitle(void 0),this.activeThreadContext=null})}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.firstOpenDialogVisible}}t4();function T9A(A,Q,B,$){let J=pk(A),Y="\x1B[0m",Z="\x1B[34m",F="\x1B[90m",X="\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 WZ(G,V),K=new mJ(42),E=new SC(G,V,G,V,G,V,0,A.agentMode??"smart","intensity",void 0,void 0,C0.default(),K);E.layout(W1.tight(G,V)),E.paint(U,0,0);let W=U.getBuffer().getCells(),H=0;for(let j=0;j<V;j++)if(W[j].some((P)=>P.char!==" ")){H=j;break}let z=V-1;for(let j=V-1;j>=0;j--)if(W[j].some((P)=>P.char!==" ")){z=j;break}function q(j,P){if(!j)return"";if(j.type==="rgb"){let{r:R,g:b,b:g}=j.value;if(B.getColorDepth()>=24)return`\x1B[${P?38:48};2;${R};${b};${g}m`;let f=IP(R,b,g);return`\x1B[${P?38:48};5;${f}m`}return""}let N=[];if(z>=H)for(let j=H;j<=z;j++){let P="";for(let R=0;R<G;R++){let b=W[j][R],g=b.char,f=q(b.style.fg,!0);P+=f+g+"\x1B[0m"}N.push(P)}let I=N.length,C=Math.max(I,D.length),w=Math.floor((C-I)/2),M=Math.floor((C-D.length)/2);for(let j=0;j<C;j++){let P=" ".repeat(G);if(j>=w&&j<w+I)P=N[j-w];let R=" ",b="";if(j>=M&&j<M+D.length)b=D[j-M];B.write(P+R+b+`
5170
+ `,new h({color:B.foreground,dim:!0})),new O("If you need a reply, post on X @AmpCode or email amp-devs@ampcode.com.",new h({color:B.foreground,dim:!0}))]),textAlign:"center"})})}}function L9A(A){return new V3({header:A.title,minWidth:80,maxWidth:80,chromePadding:M0.symmetric(1,0),footer:"none",onDismiss:A.onDismiss,child:A.child})}function c78(A,Q,B){return new p1({child:new u0({constraints:new W1(80,80,0,12),child:new tH({commandName:"Share with Support",title:"Share Thread with Support",placeholder:"What went wrong? (Need a reply? Email amp-devs@ampcode.com.)",isRequiredArg:!1,onSubmit:async($)=>{try{await A.shareThreadWithSupport(Q,$||void 0),B.pushResultPane(L9A({title:"Shared with Support",onDismiss:B.dismissFlow,child:new $10}))}catch(J){T.error("Failed to share thread with support",{error:J,threadID:Q}),B.pushResultPane(L9A({title:"Share with Support failed",onDismiss:B.dismissFlow,child:new t({text:new O(`Failed to share thread with support: ${J instanceof Error?J.message:String(J)}`)})}))}},onDismiss:B.dismissFlow})})})}function O9A(A,Q){return{noun:"thread",verb:"share with support",description:"Share with Amp support for debugging",get status(){return Q()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(B,$,J)=>{let Y=Q()?.client.getThreadId();if(!Y)return;B.push(c78(A,Y,{dismissFlow:J,pushResultPane:(Z)=>B.push(Z)}))}}}class J10 extends y0{props;constructor(A){super();this.props=A}createState(){return new j9A}}class j9A extends v0{result=void 0;isLoading=!1;build(A){let Q=[];if(this.isLoading)Q.push(new fQ({message:"Updating visibility..."}));else if(this.result!==void 0)Q.push(new i7({message:this.result,onDismiss:()=>{this.widget.props.onDismiss()}}));else{let B=["private","workspace","unlisted","public"],$=this.widget.props.workspace?.groups&&this.widget.props.workspace.groups.length>0?["private","workspace","group","unlisted","public"]:B;Q.push(new k5({items:$,getLabel:(J)=>{switch(J){case"private":return"Private - Only you can see this thread";case"workspace":return"Workspace - Visible to workspace members";case"group":return"Group - Visible to group members";case"unlisted":return"Unlisted - Anyone with the link can view";case"public":return"Public - Searchable and on your public profile"}},title:"Select Thread Visibility",onAccept:async(J)=>{this.setState(()=>{this.isLoading=!0});let Y=await this.widget.props.execute(J);this.setState(()=>{this.isLoading=!1,this.result=Y})},onDismiss:this.widget.props.onDismiss}))}return new CA({children:Q,fit:"expand"})}}function l78(A,Q,B){return new p1({child:new u0({constraints:new W1(80,80,0,16),child:new J10({workspace:null,threadID:Q,execute:($)=>A.setVisibility(Q,$),onDismiss:B})})})}function R9A(A,Q){return{noun:"thread",verb:"set visibility",description:"Set thread visibility",keywords:["share","private","workspace","public","unlisted","team","group"],get status(){return Q()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(B,$,J)=>{let Y=Q()?.client?.getThreadId();if(!Y)return;B.push(l78(A,Y,J))}}}class JB1 extends y0{initialAgentMode;analyzeContextForThread;listSkillsForThread;threadContext;draftThreadSettings;editorController;history;updateDraftThreadSettings;onNewThread;shareThreadWithSupport;setThreadVisibility;archiveThread;addThreadLabel;removeThreadLabel;configService;connectionErrorMessage;hints;ideStatus;constructor(A){super();this.initialAgentMode=A.initialAgentMode,this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.threadContext=A.threadContext,this.draftThreadSettings=A.draftThreadSettings,this.editorController=A.editorController,this.history=A.history,this.updateDraftThreadSettings=A.updateDraftThreadSettings,this.onNewThread=A.onNewThread,this.shareThreadWithSupport=A.shareThreadWithSupport,this.setThreadVisibility=A.setThreadVisibility,this.archiveThread=A.archiveThread,this.addThreadLabel=A.addThreadLabel,this.removeThreadLabel=A.removeThreadLabel,this.configService=A.configService,this.connectionErrorMessage=A.connectionErrorMessage,this.hints=A.hints,this.ideStatus=A.ideStatus}createState(){return new P9A}}class P9A extends v0{historyIndex=-1;historyDraft=null;promptHistoryPicker=new pe(this);agentMode;expansion=new UQ1;previousThreadIDForReference=null;unregisterCommands=null;initState(){this.agentMode=this.widget.initialAgentMode,this.unregisterCommands=this.registerCommands()}didUpdateWidget(A){if(A.threadContext?.client!==this.widget.threadContext?.client)if(this.historyIndex=-1,this.historyDraft=null,!this.widget.threadContext)this.previousThreadIDForReference=A.threadContext?.client.getThreadId()??null;else this.previousThreadIDForReference=null}dispose(){this.unregisterCommands?.(),this.unregisterCommands=null}registerCommands(){let A=jX.of(this.context),Q=l7.of(this.context),B=this,$=()=>{return B.widget.threadContext??null},J=()=>{let X=B.widget.threadContext?.client.getThreadId();if(!X)return null;return TY(new URL(Q.ampURL),X).toString()},F=[...t$(void 0,{isInternalUser:Q.isInternalUser}).map(({mode:X})=>({noun:"mode",verb:`use ${X}`,description:`Enable ${X} mode`,get status(){if(B.widget.threadContext)return{type:"disabled",reason:"Mode can only be changed on a new thread"};if(X===B.agentMode)return{type:"disabled",reason:`Already using ${X} mode`};return{type:"enabled"}},run:(D,G,V)=>{B.setAgentMode(X),V()}})),{noun:"speed",verb:"toggle speed",description:"Toggle speed (fast/standard) for this thread",keywords:["anthropic","openai","fast","standard","smart","deep"],get status(){let X=B.currentCommandAgentMode();return X==="smart"||y2(X)?{type:"enabled"}:{type:"hidden"}},run:(X,D,G)=>{B.toggleSpeed(),G()}},{noun:"thread",verb:"toggle thinking blocks",description:"Expand or collapse all thinking blocks",keywords:["thinking","expand","collapse","reasoning"],shortcut:a1.alt("t"),status:{type:"enabled"},run:(X,D,G)=>{B.toggleGlobalThinking(),G()}},{noun:"mode",verb:"toggle reasoning effort",description:"Cycle reasoning effort for the active model",keywords:["deep","thinking","reasoning","effort","depth","anthropic","openai","smart","frontier"],shortcut:a1.alt("d"),get status(){return Ic(B.currentCommandAgentMode())?{type:"enabled"}:{type:"hidden"}},run:(X,D,G)=>{B.toggleReasoningEffort(),G()}},{noun:"prompt",verb:"history",description:"Restore a previous prompt",keywords:["recent","reuse","search"],shortcut:a1.ctrl("r"),status:{type:"enabled"},run:(X,D,G)=>{X.pushWithDismiss((V)=>new lW0({entries:this.widget.history.getAll(),currentCwd:$B1.cwd(),onAccept:(U)=>{this.restorePromptHistory(U),G()},onDismiss:V}))}},{noun:"thread",verb:"copy ID",description:"Copy thread ID to clipboard",keywords:["identifier","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=$()?.client.getThreadId();if(!V)return;A6.maybeInvoke(D,new gG(V,"Thread ID copied to clipboard","Failed to copy thread ID")),G()}},{noun:"thread",verb:"copy URL",description:"Copy thread URL to clipboard",keywords:["link","share","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=J();if(!V)return;A6.maybeInvoke(D,new gG(V,"Thread URL copied to clipboard","Failed to copy thread URL")),G()}},{noun:"thread",verb:"copy markdown",description:"Copy thread as Markdown",keywords:["markdown","export","clipboard"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X,D,G)=>{let V=$()?.client.getThreadId();if(!V)return;(async()=>{try{let U=await Q.getThreadMarkdown(V);if(!U){fK.error(D,"Failed to copy thread markdown");return}A6.maybeInvoke(D,new gG(U,"Thread markdown copied to clipboard","Failed to copy thread markdown"))}catch(U){T.error("Failed to render thread markdown from Neo command palette",{error:U,threadID:V}),fK.error(D,"Failed to copy thread markdown")}finally{G()}})()}},{noun:"thread",verb:"analyze context",description:"Analyze context token usage",keywords:["tokens","usage","window","size","cost"],get status(){let X=B.widget.threadContext;if(!X)return{type:"disabled",reason:"No active thread"};let D=e$(X.observer.agentMode);if(!T3A.includes(D))return{type:"disabled",reason:"Context analysis requires Claude Opus 4.7 (smart) or GPT-5.4 (deep)"};return{type:"enabled"}},run:(X)=>{let D=$()?.client.getThreadId();if(!D)return;X.pushWithDismiss((G)=>{return new V3({header:"Context Usage Analysis",minWidth:60,maxWidth:60,chromePadding:M0.symmetric(1,0),footer:[{keys:["Esc"],label:"close"}],onDismiss:G,child:new i00({embedded:!0,contentWidth:58,thread:null,dtwAnalyze:(K)=>{return B.widget.analyzeContextForThread(D,K)},onDismiss:G})})})}},{noun:"skills",verb:"list",description:"List available skills for this thread",keywords:["agent","show"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:(X)=>{let D=$()?.client.getThreadId();if(!D)return;X.pushWithDismiss((G)=>new BB1({listSkills:(V)=>B.widget.listSkillsForThread(D,V),onDismiss:G,cwd:Q.workspaceRoot}))}},{noun:"thread",verb:"new",description:"Start new thread",keywords:["create","start","reset","clear"],sortBoost:101,get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"Already on a new thread"}},run:(X,D)=>{A6.maybeInvoke(D,new h00)}},{noun:"thread",verb:"open in browser",description:"Open thread in browser",keywords:["web","view","launch"],get status(){return B.widget.threadContext?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(X,D,G)=>{let V=J();if(!V)return;try{await V5(D,V)}finally{G()}}},O9A({shareThreadWithSupport:(X,D)=>{return this.widget.shareThreadWithSupport(X,D)}},$),R9A({setVisibility:(X,D)=>this.widget.setThreadVisibility(X,D)},$),d2A({archiveThread:(X)=>this.widget.archiveThread(X)},$),M9A($),G9A({configService:this.widget.configService,addLabel:(X,D)=>this.widget.addThreadLabel(X,D)},$),K9A({configService:this.widget.configService,removeLabel:(X,D)=>this.widget.removeThreadLabel(X,D)},$)].map((X)=>A.register(X));return()=>{for(let X of F)X()}}currentCommandAgentMode(){return this.widget.threadContext?.observer.agentMode??this.agentMode}updateThreadSettings(A){let Q=this.widget.threadContext;if(Q){let B=Q.observer.threadSettings().getValue()??{},$=A(B);return Q.client.sendClientUpdateThreadSettings($),this.widget.updateDraftThreadSettings(()=>$),"handled"}return this.widget.updateDraftThreadSettings(A),"handled"}toggleSpeed(){let A=this.currentCommandAgentMode();if(A==="smart")return this.updateThreadSettings((Q)=>{let B={...Q};if(B["anthropic.speed"]==="fast")delete B["anthropic.speed"];else B["anthropic.speed"]="fast";return B});if(y2(A))return this.updateThreadSettings((Q)=>{let B={...Q};if(B["openai.speed"]==="fast")B["openai.speed"]="standard";else B["openai.speed"]="fast";return B});return"ignored"}toggleGlobalThinking(){return this.expansion.toggle(),"handled"}toggleReasoningEffort(){let A=this.currentCommandAgentMode(),Q=Ic(A);if(!Q)return"ignored";return this.updateThreadSettings((B)=>{let $=R90(A,B);if(!$)return B;let J=B[$]??J3(A)?.reasoningEffort,Y=j90(Q,J);return{...B,[$]:Y}})}onPromptSubmitted=(A)=>{this.widget.history.add(A,$B1.cwd()),this.resetHistory()};restorePromptHistory(A){this.resetHistory(),this.widget.editorController.text=A,this.widget.editorController.moveCursorToEnd()}handlePromptHistorySelection=(A)=>{this.promptHistoryPicker.disable(),this.restorePromptHistory(A)};navigateHistoryPrevious=()=>{let A=this.widget.history.previous();if(A!==null){if(this.historyIndex===-1)this.historyDraft=this.widget.editorController.text;this.historyIndex++,this.widget.editorController.text=A,this.widget.editorController.moveCursorToStart()}return"handled"};navigateHistoryNext=()=>{let A=this.widget.history.next();if(A!==null)this.historyIndex--,this.widget.editorController.text=A,this.widget.editorController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.widget.editorController.text=this.historyDraft||"",this.widget.editorController.moveCursorToEnd(),this.historyDraft=null;return"handled"};resetHistory(){this.widget.history.reset(),this.historyIndex=-1,this.historyDraft=null}setAgentMode(A){if(this.widget.threadContext)return;this.setState(()=>{this.agentMode=A}),qZ((Q)=>({...Q,agentMode:A}))}buildActions(){let A=new S4(()=>{return this.promptHistoryPicker.enable(),"handled"}),Q=new S4(()=>{return this.navigateHistoryPrevious()}),B=new S4(()=>{return this.navigateHistoryNext()}),$=new S4((Z)=>{return this.setAgentMode(Z.mode),"handled"}),J=new S4(()=>{return this.toggleReasoningEffort()}),Y=new S4(()=>{return this.toggleGlobalThinking()});return new Map([[hH,A],[jW0,B],[OW0,Q],[d00,$],[RW0,J],[MW0,Y]])}build(A){let Q=this.widget.threadContext,$=[Q?new rQ1({editorController:this.widget.editorController,observingClient:{client:Q.client,observer:Q.observer},hints:this.widget.hints,ideStatus:this.widget.ideStatus,onPromptSubmitted:this.onPromptSubmitted}):new AB1({agentMode:this.agentMode,threadSettings:this.widget.draftThreadSettings,editorController:this.widget.editorController,onNewThread:this.widget.onNewThread,previousThreadIDForReference:this.previousThreadIDForReference,connectionErrorMessage:this.widget.connectionErrorMessage,hints:this.widget.hints,ideStatus:this.widget.ideStatus})];if(this.promptHistoryPicker.isEnabled())$.push(new lW0({entries:this.widget.history.getAll(),currentCwd:$B1.cwd(),onAccept:this.handlePromptHistorySelection,onDismiss:this.promptHistoryPicker.disable}));let J=new Map([[a1.ctrl("r"),new hH],[a1.alt("d"),new RW0],[a1.alt("t"),new MW0]]);if(this.promptHistoryPicker.isEnabled())J.set(a1.ctrl("o"),new hH);else J.set(a1.ctrl("n"),new jW0),J.set(a1.ctrl("p"),new OW0);return new A6({actions:this.buildActions(),child:new G3({debugLabel:"NeoThreadShortcuts",shortcuts:J,child:new RX({controller:this.expansion,child:new CA({children:$})})})})}}class YB1 extends y0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;isFirstOpen;notificationService;onThreadArchived;initialUserInput;openThreadPickerOnStart;neoContext;constructor(A){super();this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.initialThreadID=A.initialThreadID,this.isFirstOpen=A.isFirstOpen??!1,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.initialUserInput=A.initialUserInput,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new _9A}}class _9A extends v0{editorController=new I2;commandPalette=new pe(this);commandRegistry=new QQ1;toastController=new a31;exitHintTimer=new me(this,1000);connectionErrorMessage=new r3(this,null);ideStatus=new r3(this,{});draftThreadSettings={};draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;ideErrorSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;firstOpenDialogVisible=!1;focusDebugVisible=!1;unregisterCommands=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.clearConnectionError(),this.connectToExistingThread(A)};shareThreadWithSupport=async(A,Q)=>{let B;if(this.activeThreadContext&&this.activeThreadContext.client.getThreadId()===A){let $=this.activeThreadContext.observer.activeError().getValue();if($)B={message:$.message,type:$.code,stack:$.stack,retryAfterSeconds:$.retryAt!==void 0?Math.max(0,Math.ceil(($.retryAt-Date.now())/1000)):void 0}}await o8A({configService:this.widget.configService},A,Q,B)};setThreadVisibility=(A,Q)=>{return r8A({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await V1A({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await U1A({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 K1A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(H$.getInstance().interceptConsole(),this.widget.isFirstOpen)this.firstOpenDialogVisible=!0;if(this.connectionErrorMessage.subscribe(this.widget.clientPool.connectionErrors$.pipe(aE(({threadID:Q,error:B})=>{T.error("Neo failed to connect to thread",{threadID:Q,error:B})}),N5(({threadID:Q})=>this.isConnectionErrorRelevant(Q)),aE(()=>this.clearActiveClientForConnectionError()),w1(({threadID:Q,error:B})=>{return Q?`Connection failed for ${Q}: ${B.message}`:`Connection failed: ${B.message}`}))),this.ideStatus.subscribe(this.widget.ideManager.status),this.ideErrorSubscription=this.widget.ideManager.errors$.subscribe((Q)=>{if(Q)this.setState(()=>{this.connectionErrorMessage.setValue(Q)})}),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID)this.connectToExistingThread(this.widget.initialThreadID,A);else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=i4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let Q=[{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(B,$,J)=>{B.pushWithDismiss((Y)=>lQ1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:Y,onThreadSelected:J}))}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(B)=>{B.pushWithDismiss(($)=>new VQ1({mcpServers:this.widget.neoContext.mcpServers,onDismiss:$}))}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{pJ(this.widget.neoContext.settingsFilePath).catch((B)=>{T.error("Failed to open settings file in editor",{error:B})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(B,$,J)=>{B.pushWithDismiss((Y)=>new DQ1({onCancel:Y,onSelect:(Z)=>{this.handleIdeSelection(Z),J()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(B,$)=>{B.pushWithDismiss((J)=>new ZQ1({commands:jX.of($).commands,onDismiss:J}))}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(B)=>{B.pushWithDismiss(($)=>new V3({header:"Amp Version",maxWidth:72,onDismiss:$,child:new t({text:new O(p31({version:"0.0.1777185893-gae6d40",buildTimestamp:"2026-04-26T06:48:40.597Z",buildType:"'release'"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:a1.ctrl("c"),status:{type:"enabled"},run:(B,$)=>{A6.maybeInvoke($,new cu)}},...a8A(this.widget.neoContext.logFilePath)].map((B)=>this.commandRegistry.register(B));return()=>{for(let B of Q)B()}}build(A){let Q=this.buildHints(),B=this.connectionErrorMessage.getValue(),$=this.ideStatus.getValue(),J=new JB1({initialAgentMode:this.widget.neoContext.sessionAgentMode,analyzeContextForThread:this.widget.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,shareThreadWithSupport:this.shareThreadWithSupport,setThreadVisibility:this.setThreadVisibility,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,connectionErrorMessage:B,hints:Q,ideStatus:$}),Y=F4.of(A),F=[new u0({constraints:W1.tight(Y.size.width,Y.size.height),child:J})];if(this.commandPalette.isEnabled())F.push(new BQ1({onDismiss:this.commandPalette.disable}));if(this.switchThreadPickerVisible)F.push(lQ1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.firstOpenDialogVisible)F.push(new FQ1({onDismiss:this.dismissFirstOpenDialog}));if(this.focusDebugVisible)F.push(new XQ1);return new l7({neoContext:this.widget.neoContext,child:new jX({commandRegistry:this.commandRegistry,child:new eC({completionBuilder:this.widget.completionBuilder,child:new fK({controller:this.toastController,child:new A6({actions:this.buildActions(),child:new G3({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[a1.ctrl("c"),new CW0],[a1.ctrl("o"),new wW0],[a1.ctrl("t"),new LW0]]),child:new e4({debugLabel:"AppShellFocus",child:new o31({controller:this.toastController,child:new CA({children:F})})})})})})})})})}buildActions(){let A=new S4(()=>{return this.onExitPressed(),"handled"}),Q=new S4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new S4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new S4(()=>{return this.commandPalette.disable(),this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.writeTerminalTitle(void 0),this.activeThreadContext=null,this.connectingToThreadID=null,this.connectionErrorMessage.setValue(null)}),"handled"}),J=new S4(()=>{return i4.instance.stop(),"handled"}),Y=new S4((F)=>{if(!F.text)return"ignored";return i4.instance.tuiInstance.clipboard.writeText(F.text).then(()=>{this.toastController.show(F.successMessage,"success",2000)}).catch((X)=>{T.error("Failed to copy Neo text to clipboard",{error:X}),this.toastController.show(F.failureMessage,"error",2000)}),"handled"}),Z=new S4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[CW0,A],[h00,$],[cu,J],[gG,Y],[p00,B],[wW0,Q],[LW0,Z]])}ensureDraftThreadSettingsInitialized(){if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=await _K0(this.widget.configService);if(!this.mounted)return;this.setState(()=>{this.draftThreadSettings=A})}catch(A){T.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(mu);if(this.exitHintTimer.isActive())A.add(v00);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),i4.instance.stop();else this.exitHintTimer.activate()};dismissFirstOpenDialog=()=>{if(!this.firstOpenDialogVisible)return;this.setState(()=>{this.firstOpenDialogVisible=!1})};closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q)=>{await this.ensureDraftThreadSettingsInitialized();let B=A.find((J)=>J.type==="text");if(B&&B.type==="text")this.widget.history.add(B.text,iW0.cwd()),this.widget.history.reset();let $=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings);this.clearConnectionError(),this.sendUserMessage($,A,Q),this.setActiveClient($)};sendUserMessage(A,Q,B){A.observer.markMessageSent();let $=hX0(this.ideStatus.getValue());A.client.sendUserMessage(Q,B,{userState:$})}async connectToExistingThread(A,Q){this.setState(()=>{this.connectingToThreadID=A});try{let B=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly});if(this.setActiveClient(B),Q)this.sendUserMessage(B,[{type:"text",text:Q}])}catch(B){T.error("Failed to load thread",{error:B,threadID:A}),this.connectionErrorMessage.setValue(`Failed to load ${A}: ${B instanceof Error?B.message:String(B)}`)}finally{this.setState(()=>{this.connectingToThreadID=null})}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q},this.connectionErrorMessage.setValue(null),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=iW0.cwd().replace(iW0.env.HOME||"","~"),B=A?`amp - ${A} - ${Q}`:"";iW0.stdout.write(RC(B))}handleIdeSelection=async(A)=>{await this.widget.ideManager.connect(A)};dispose(){this.unregisterCommands?.(),this.unregisterCommands=null,this.titleSubscription?.unsubscribe(),this.ideErrorSubscription?.unsubscribe(),this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}isConnectionErrorRelevant(A){if(!this.activeThreadContext)return!0;if(!A)return!0;return this.activeThreadContext.client.getThreadId()===A}clearConnectionError(){if(!this.connectionErrorMessage.getValue())return;this.setState(()=>{this.connectionErrorMessage.setValue(null)})}clearActiveClientForConnectionError(){if(!this.activeThreadContext)return;this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.widget.notificationService.detach(),this.writeTerminalTitle(void 0),this.activeThreadContext=null})}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.firstOpenDialogVisible}}t4();function T9A(A,Q,B,$){let J=pk(A),Y="\x1B[0m",Z="\x1B[34m",F="\x1B[90m",X="\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 WZ(G,V),K=new mJ(42),E=new SC(G,V,G,V,G,V,0,A.agentMode??"smart","intensity",void 0,void 0,C0.default(),K);E.layout(W1.tight(G,V)),E.paint(U,0,0);let W=U.getBuffer().getCells(),H=0;for(let j=0;j<V;j++)if(W[j].some((P)=>P.char!==" ")){H=j;break}let z=V-1;for(let j=V-1;j>=0;j--)if(W[j].some((P)=>P.char!==" ")){z=j;break}function q(j,P){if(!j)return"";if(j.type==="rgb"){let{r:R,g:b,b:g}=j.value;if(B.getColorDepth()>=24)return`\x1B[${P?38:48};2;${R};${b};${g}m`;let f=IP(R,b,g);return`\x1B[${P?38:48};5;${f}m`}return""}let N=[];if(z>=H)for(let j=H;j<=z;j++){let P="";for(let R=0;R<G;R++){let b=W[j][R],g=b.char,f=q(b.style.fg,!0);P+=f+g+"\x1B[0m"}N.push(P)}let I=N.length,C=Math.max(I,D.length),w=Math.floor((C-I)/2),M=Math.floor((C-D.length)/2);for(let j=0;j<C;j++){let P=" ".repeat(G);if(j>=w&&j<w+I)P=N[j-w];let R=" ",b="";if(j>=M&&j<M+D.length)b=D[j-M];B.write(P+R+b+`
5160
5171
  `)}if($)B.write(`
5161
5172
  \x1B[90m${$}\x1B[0m
5162
5173
  `)}l0();cK0();var i78=2000;function S9A(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<i78)return;if(J=U,_P())return;if(hU0())gU0();else lr(V)},Z=(V)=>{if(!Q||!B)return;if(_P()&&!ye()&&!XK0())return;process.stdout.write(kG(`\x1B]777;notify;Amp;${V}\x1B\\`))},F=null,X=null,D=()=>{F?.unsubscribe(),F=null,X=null};return{attach:(V)=>{D(),F=V.subscribe({next:(U)=>{try{let K=X!==null&&qC(X),E=X==="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){T.debug("Neo notification handling failed",{error:K})}finally{X=U}},error:(U)=>{T.debug("Neo notification agent state stream errored",{error:U})}})},detach:D,unsubscribe(){D(),$.unsubscribe()}}}l0();$W();z4();O1();function k9A(A,Q){if(!Q)return A;let B=Q.toLowerCase(),$=[];for(let J of A){let Y=n78(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 n78(A,Q){let B=a78(A,Q),$=o78(A.message.toLowerCase(),Q);return Math.max(B,$)}function a78(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 o78(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 $=r78(A,Q);if($>0)return $;return 0}function r78(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 v9A=":";function U_(A,Q){if(!UP())return;T.debug("[file mention completions]",{event:A,...Q})}function tu(A){return A.length<=80?A:`${A.slice(0,77)}...`}class K_{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(v9A)){let Z=Q.slice(v9A.length);return U_("commit_query_detected",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:Z.length,queryPreview:tu(Z)}),this.buildCommitOptions(Z)}let $=Q.length===0?18:20,J=await this.buildFileOptions(Q,$),Y=this.appendHintOptions(Q,J);return U_("build_options_completed",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:Q.length,queryPreview:tu(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)=>K2A(Z));return U_("file_options_built",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:tu(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 U_("file_options_failed",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:tu(A),maxResults:Q,error:B instanceof Error?B.message:String(B)}),[]}}async getOpenFiles(){let A=await k1(i8.status);if(!A.connected)return;let Q=[];if(A.openFile)Q.push(Z1.parse(A.openFile).fsPath);if(A.visibleFiles)for(let B of A.visibleFiles){let $=Z1.parse(B).fsPath;if(!Q.includes($))Q.push($)}if(Q.length===0)return;return Q}refreshDirtyFilesInBackground(){if(this.refreshPromise!==void 0)return;this.refreshPromise=Pk4(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 U_("commit_options_empty_cache",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:tu(A)}),[];let B=k9A(Q,A).slice(0,20);return U_("commit_options_built",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:tu(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=_k4(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 U_("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 t78=[{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:""}],Ih2=g0A({name:"amp neo",description:"Start the Neo TUI",options:t78,positionals:[],action:async({options:A})=>{let Q=y9A(A);if(A.observe){let B=C3(A.observe)??EB(A.observe);await nW0(Q,{initialThreadID:B,observerOnly:!0});return}await nW0(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 $=y9A(A);if(!Q["thread-id"]){await nW0($,{openThreadPickerOnStart:!0});return}let J=C3(Q["thread-id"]);if(!J)throw"invalid thread ID";await nW0($,{initialThreadID:J})}}]}]});function e78(A){if(A)return A;if(process.env.AMP_URL)return process.env.AMP_URL;return k9}function AQ8(A){if(process.env.RIVET_PUBLIC_ENDPOINT)return process.env.RIVET_PUBLIC_ENDPOINT;return fJ(A)}var x9A=Z1.file(s78.homedir()),QQ8=process.env.XDG_CONFIG_HOME?Z1.file(process.env.XDG_CONFIG_HOME):G1.joinPath(x9A,".config");async function BQ8(A){await qZ((Q)=>xK0(Q,A,"interactive"))}function y9A(A){return{url:A.url,dangerouslyAllowAll:A["dangerously-allow-all"]}}async function nW0(A,Q={}){let{initialThreadID:B,openThreadPickerOnStart:$=!1,observerOnly:J=!1}=Q,Y=e78(A.url),Z={dataDir:void 0,getHook:(I,C)=>{if(I==="url")return Promise.resolve(Y);return C()}},F=await lU0(Z),X=yK0(await at(Z,F)),D=AQ8(Y);if(A.dangerouslyAllowAll)S9("dangerouslyAllowAll",!0);let G=await X.get("apiKey",Y);if(!G)throw new K4("API key required. Please run `amp login` first.",1);let V=uk({storage:F,secretStorage:X,workspaceRoot:g0.of(Z1.file(process.cwd())),defaultAmpURL:Y,homeDir:x9A,userConfigDir:QQ8}),U=lO(V),K=CD0({configService:V}),E=t$0({configService:V,filesystem:k8}),W={registerToolsWithToolService:()=>({dispose:()=>{}}),getClient:()=>{return},servers:g0.of([]),getPrompt:async()=>null,searchResources:async()=>[],searchPrompts:()=>g0.of([]),getToolsForServer:async()=>{return}},H=process.cwd(),z=async({uri:I})=>{return NC({fileSystem:k8,workspaceRoot:H},I)},q=new ob(H,{},!0),N=new K_(q);await ZB1({ampURL:Y,apiKey:G,rivetEndpoint:D,configService:V,toolService:K.toolService,skillService:E,mcpService:W,readFileSystemDirectory:z,completionBuilder:N,workspaceRoot:H,listThreads:()=>U.listThreads(),getThreadFromServer:(I)=>U.getThread(I),isInternalUser:!1,settingsFilePath:F.getSettingsFilePath(),dispose:()=>{q.dispose(),K.dispose()}},{initialThreadID:B,openThreadPickerOnStart:$,observerOnly:J})}async function ZB1(A,Q={}){let{initialThreadID:B,initialUserInput:$,openThreadPickerOnStart:J=!1,observerOnly:Y=!1,initialAgentMode:Z}=Q,F=async(z)=>{let q=await A.getThreadFromServer(z);if(!q)return null;return MU0(q)},X=new N31(A.rivetEndpoint,A.apiKey,A.configService,{clientID:WC.parse(`neo-${crypto.randomUUID()}`),toolService:A.toolService,skillService:A.skillService,invokeTool:async(z,q)=>{let N=typeof q.args==="object"&&q.args!==null?q.args:{},I=await PK({toolName:q.toolName,configService:A.configService,toolService:A.toolService,mcpService:A.mcpService,skillService:A.skillService,toolUseID:q.toolCallId,threadID:z});return A.toolService.invokeTool(q.toolName,{args:N},I)},persistLastThreadID:BQ8,readFileSystemDirectory:A.readFileSystemDirectory},F),D=await Zu(),G={ampURL:A.ampURL,configService:A.configService,getThreadMarkdown:async(z)=>{let q=await A.getThreadFromServer(z);return q?UU(q):null},isInternalUser:A.isInternalUser,listThreads:A.listThreads,logFilePath:_t,mcpServers:A.mcpService.servers,observerOnly:Y,sessionAgentMode:Z??D.agentMode,settingsFilePath:A.settingsFilePath,workspaceRoot:A.workspaceRoot},V=(z,q)=>{return Lb({ampURL:A.ampURL,configService:A.configService,threadID:z,signal:q})},U=(z,q)=>{return ie4({ampURL:A.ampURL,configService:A.configService,threadID:z,signal:q})},K=new m31,E=se4(D);qZ(te4);let W=S9A({configService:A.configService}),H=new Set;try{await xe(new YB1({clientPool:X,analyzeContextForThread:V,listSkillsForThread:U,completionBuilder:A.completionBuilder,history:new ht,ideManager:K,configService:A.configService,initialThreadID:B,notificationService:W,initialUserInput:$,openThreadPickerOnStart:J,neoContext:G,isFirstOpen:E,onThreadArchived:(q)=>{H.add(q)}}));let z=X.lastActiveObservingClient;if(z){let{client:q,observer:N}=z,I=q.getThreadId();if(I){let C={id:I,title:N.title().getValue(),agentMode:N.agentMode,archived:H.has(I)},w=`${A.ampURL.replace(/\/$/,"")}/threads/${I}`;T9A(C,w,process.stdout)}}}finally{process.stdout.write(RC("")),W.unsubscribe(),X.dispose(),await A.dispose?.()}process.exit(0)}Wl();gL();async function $Q8(A,Q,B){let $=x70(A);if(!$.success)throw Error(`Invalid permission format: ${$.error.message}`);if($.data.length===0)throw Error("No permission entry provided");let J=xq($.data);if(!J.success){let X=J.error.issues.map((D)=>D.message).join(", ");throw Error(`Invalid permission entry: ${X}`)}let Y=await Q.get("permissions",B)??[],F=[$.data[0],...Y];await Q.set("permissions",F,B)}async function f9A(A){try{let Q=A.args.map((B)=>{if(/[\s/\\*?[\]{}()"]/.test(B))return`"${B}"`;return B}).join(" ");await $Q8(Q,A.settings,A.scope),A.exit(0)}catch(Q){let B=Q instanceof Error?Q.message:"Unknown error";A.stderr.write(`Error: ${B}
@@ -5941,7 +5952,7 @@ ${J}`,Q);this.line=B,this.column=$,this.codeblock=J}}/*!
5941
5952
  `),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 O(G.slice(1,-1),new h({color:$.app.keybind,bold:!0})));else Y.push(new O(G,new h({color:B.colorScheme.foreground})));if(Z<J.length-1)Y.push(new O(`
5942
5953
  `))}return new u0({decoration:{color:B.colorScheme.background,border:Q4.all(new e1($.app.keybind,1,"rounded"))},child:new x0({padding:M0.symmetric(0,1),child:new t({text:new O(void 0,void 0,Y)})})})}}class C$1 extends a2{chartData;highlightIndex;showAxes;colors;constructor({key:A,chartData:Q,highlightIndex:B=null,showAxes:$=!0,colors:J=zz0}){super(A?{key:A}:{});this.chartData=Q,this.highlightIndex=B,this.showAxes=$,this.colors=J}createRenderObject(){return new N$1({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 G$A(A,Q,B,$,J,Y,Z){if(Y<=0)return null;switch(A){case"horizontal-bar":{let F=B;return F>=0&&F<Y?F:null}case"bar":case"stacked-bar":{let F=Z?A2:0,X=$-F;if(X<=0)return null;let D=Q-F;if(D<0||D>=X)return null;let G=Math.max(1,Math.floor(X/Y)),V=Math.floor(D/G);return V>=0&&V<Y?V:null}case"line":case"sparkline":case"stacked-area":{let F=Z?A2:0,X=$-F;if(X<=0)return null;let D=Math.max(0,Math.min(X-1,Q-F));if(Y===1)return 0;let G=X/(Y-1),V=Math.round(D/G);return Math.max(0,Math.min(Y-1,V))}default:return null}}function DX8(A,Q,B,$,J,Y,Z,F){if(J<=0||Q<0||Q>=J)return null;let X=2;switch(A){case"horizontal-bar":return{x:Math.floor(B/2),y:Q};case"bar":case"stacked-bar":{let D=Y?A2:0,G=B-D,V=$-(Y?X: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=F>0?Z/F:0,W=Math.round((1-E)*(V-1));return{x:K,y:W}}case"line":case"sparkline":case"stacked-area":{let D=Y?A2:0,G=B-D,V=$-(Y?X: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=F>0?Z/F:0,E=Math.round((1-K)*(V-1));return{x:U,y:E}}default:return null}}function GX8(A){let Q=0;for(let B of A)for(let $ of B.points)if($.value>Q)Q=$.value;return Q||1}function VX8(A,Q,B,$,J){if(B.length<=1){let F=$(A.value),X=A.meta?` (${A.meta})`:"";return A.label.length+2+F.length+X.length}let Y=A.label.length,Z=0;for(let F of B){let X=F.points[Q];if(!X)continue;Z+=X.value;let D=2+F.name.length+2+$(X.value).length;Y=Math.max(Y,D)}if(J){let F=9+$(Z).length;Y=Math.max(Y,F)}return Y}function UX8(A,Q,B,$,J,Y,Z){let F;try{let E=S1.of(A),W=S0.of(A);F={foreground:E.colorScheme.foreground,background:E.colorScheme.background,border:W.app.keybind}}catch{F={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let X=new h({color:F.foreground,bold:!0}),D=new h({color:F.foreground}),G=new h({color:F.foreground,dim:!0}),V=[],U=new h({color:F.foreground,underline:!0}),K=(E,W)=>new O(W,U,void 0,YK0(E),()=>{V5(A,E)});if($.length<=1){if(V.push(new O(`${Q.label}: `,X)),Q.link)V.push(K(Q.link,Y(Q.value)));else V.push(new O(Y(Q.value),D));if(Q.meta)V.push(new O(` (${Q.meta})`,G))}else{let E=Z==="stacked-bar"||Z==="stacked-area";V.push(new O(`${Q.label}
5943
5954
  `,X));let W=0;for(let H=0;H<$.length;H++){let z=$[H],q=z.points[B];if(!q)continue;W+=q.value;let N=z.color??J[H%J.length]??F.foreground;if(V.push(new O("● ",new h({color:N}))),V.push(new O(`${z.name}: `,G)),q.link)V.push(K(q.link,Y(q.value)));else V.push(new O(Y(q.value),D));if(H<$.length-1||E)V.push(new O(`
5944
- `))}if(E)V.push(new O(" ",G)),V.push(new O("Total: ",G)),V.push(new O(Y(W),D))}return new u0({decoration:{color:F.background,border:Q4.all(new e1(F.border,1,"rounded"))},child:new t({text:new O(void 0,void 0,V)})})}l0();c8();lL();v9();C8();W7();fo();EF();EQ();WQ();oB();GR();t4();wy();zk();O1();l0();EQ();class w$1{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.1777184774-g5a2bb8"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await S70(Q,this.configService)}catch(Q){T.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 Cw extends y0{props;constructor(A){super();this.props=A}createState(){return new V$A}}class V$A extends v0{_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)}}oB();class U$A extends v0{controller=new I2;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new E6({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>=SY)return!1;let Q=await PX(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(A){let Q=S0.of(A),{colors:B,app:$}=Q,Y=F4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),F=new pG({controller:this.controller,triggers:[new nJ],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:i4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),X=new e4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:F}),D=new u0({constraints:new W1({maxHeight:Z}),padding:M0.symmetric(1,0),child:X}),G=new u0({padding:M0.symmetric(1,0),child:new t({text:new O("",void 0,[new O("Command: ",new h({color:B.foreground})),new O(this.widget.props.commandName,new h({color:$.command,bold:!0}))])})}),V=new u0({padding:M0.symmetric(1,0),child:new t({text:this.isConfirmingClearInput?new O("",void 0,[new O("Esc",new h({color:$.keybind})),new O(" again to clear input",new h({color:B.foreground,dim:!0}))]):new O("",void 0,[new O("Press ",new h({color:B.foreground,dim:!0})),new O("Enter",new h({color:$.keybind})),new O(" to submit, ",new h({color:B.foreground,dim:!0})),new O("Esc",new h({color:$.keybind})),new O(" to clear",new h({color:B.foreground,dim:!0}))])})}),U=[G,new j0({height:1}),new y1({child:D}),new j0({height:1}),V];return new u0({decoration:{border:Q4.all(new e1(B.foreground,1,"solid")),color:B.background},padding:M0.all(1),child:new m0({children:U})})}}class M$1 extends y0{props;constructor(A){super();this.props=A}createState(){return new U$A}}function K$A(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 L$1 extends T1{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)=>K$A(J.pubDate).length));return new k5({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,F)=>{let X=S0.of(F),{colors:D}=X,G=X.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(W,H)=>new j0({width:H,child:F1.end([new t({text:new O(W,new h({color:K}))})])});return new u0({decoration:V?{color:V}:void 0,padding:M0.symmetric(2,0),child:new F1({children:[new y1({child:new t({text:new O(J.title,new h({color:U})),overflow:"ellipsis",maxLines:1})}),new j0({width:2}),E(K$A(J.pubDate),B)]})})}})}}class SB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!SB._instance)SB._instance=new SB;return SB._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()}}c8();class E$A extends y0{props;constructor(A){super();this.props=A}createState(){return new W$A}}class W$A extends v0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=A.startsWith("file://")?A.slice(7):A,B=this.widget.props.cwd;if(Q.startsWith(B))return Q.slice(B.length+1);return Q}statusIcon(A){let Q=s3.default(),{colors:B,app:$}=Q;switch(A){case"loading":return{icon:"◌",color:B.warning};case"active":return{icon:"✓",color:$.toolSuccess};case"error":return{icon:"✗",color:$.toolError}}}build(A){let Q=S0.of(A),{app:B}=Q;if(this.plugins.length===0)return new t({text:new O("No plugins found.",new h({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((X)=>X.status==="active").length,Z=this.plugins.reduce((X,D)=>X+D.registeredCommands.length,0),F=this.plugins.reduce((X,D)=>X+D.registeredTools.length,0);if($.push(new O(`${Y}/${J} ${w4(J,"plugin")} active`,new h({bold:!0}))),Z>0||F>0)$.push(new O(` (${Z} ${w4(Z,"command")}, ${F} ${w4(F,"tool")})`,new h({dim:!0})));$.push(new O(`
5955
+ `))}if(E)V.push(new O(" ",G)),V.push(new O("Total: ",G)),V.push(new O(Y(W),D))}return new u0({decoration:{color:F.background,border:Q4.all(new e1(F.border,1,"rounded"))},child:new t({text:new O(void 0,void 0,V)})})}l0();c8();lL();v9();C8();W7();fo();EF();EQ();WQ();oB();GR();t4();wy();zk();O1();l0();EQ();class w$1{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.1777185893-gae6d40"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await S70(Q,this.configService)}catch(Q){T.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 Cw extends y0{props;constructor(A){super();this.props=A}createState(){return new V$A}}class V$A extends v0{_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)}}oB();class U$A extends v0{controller=new I2;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new E6({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>=SY)return!1;let Q=await PX(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(A){let Q=S0.of(A),{colors:B,app:$}=Q,Y=F4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),F=new pG({controller:this.controller,triggers:[new nJ],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:i4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),X=new e4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:F}),D=new u0({constraints:new W1({maxHeight:Z}),padding:M0.symmetric(1,0),child:X}),G=new u0({padding:M0.symmetric(1,0),child:new t({text:new O("",void 0,[new O("Command: ",new h({color:B.foreground})),new O(this.widget.props.commandName,new h({color:$.command,bold:!0}))])})}),V=new u0({padding:M0.symmetric(1,0),child:new t({text:this.isConfirmingClearInput?new O("",void 0,[new O("Esc",new h({color:$.keybind})),new O(" again to clear input",new h({color:B.foreground,dim:!0}))]):new O("",void 0,[new O("Press ",new h({color:B.foreground,dim:!0})),new O("Enter",new h({color:$.keybind})),new O(" to submit, ",new h({color:B.foreground,dim:!0})),new O("Esc",new h({color:$.keybind})),new O(" to clear",new h({color:B.foreground,dim:!0}))])})}),U=[G,new j0({height:1}),new y1({child:D}),new j0({height:1}),V];return new u0({decoration:{border:Q4.all(new e1(B.foreground,1,"solid")),color:B.background},padding:M0.all(1),child:new m0({children:U})})}}class M$1 extends y0{props;constructor(A){super();this.props=A}createState(){return new U$A}}function K$A(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 L$1 extends T1{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)=>K$A(J.pubDate).length));return new k5({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,F)=>{let X=S0.of(F),{colors:D}=X,G=X.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(W,H)=>new j0({width:H,child:F1.end([new t({text:new O(W,new h({color:K}))})])});return new u0({decoration:V?{color:V}:void 0,padding:M0.symmetric(2,0),child:new F1({children:[new y1({child:new t({text:new O(J.title,new h({color:U})),overflow:"ellipsis",maxLines:1})}),new j0({width:2}),E(K$A(J.pubDate),B)]})})}})}}class SB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!SB._instance)SB._instance=new SB;return SB._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()}}c8();class E$A extends y0{props;constructor(A){super();this.props=A}createState(){return new W$A}}class W$A extends v0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=A.startsWith("file://")?A.slice(7):A,B=this.widget.props.cwd;if(Q.startsWith(B))return Q.slice(B.length+1);return Q}statusIcon(A){let Q=s3.default(),{colors:B,app:$}=Q;switch(A){case"loading":return{icon:"◌",color:B.warning};case"active":return{icon:"✓",color:$.toolSuccess};case"error":return{icon:"✗",color:$.toolError}}}build(A){let Q=S0.of(A),{app:B}=Q;if(this.plugins.length===0)return new t({text:new O("No plugins found.",new h({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((X)=>X.status==="active").length,Z=this.plugins.reduce((X,D)=>X+D.registeredCommands.length,0),F=this.plugins.reduce((X,D)=>X+D.registeredTools.length,0);if($.push(new O(`${Y}/${J} ${w4(J,"plugin")} active`,new h({bold:!0}))),Z>0||F>0)$.push(new O(` (${Z} ${w4(Z,"command")}, ${F} ${w4(F,"tool")})`,new h({dim:!0})));$.push(new O(`
5945
5956
 
5946
5957
  `));for(let X of this.plugins){let{icon:D,color:G}=this.statusIcon(X.status),V=this.getRelativePath(X.uri.toString());if($.push(new O(`${D} `,new h({color:G}))),$.push(new O(V,new h({bold:!0}))),$.push(new O(` ${X.status}`,new h({dim:!0}))),$.push(new O(`
5947
5958
  `)),X.status==="active"&&X.registeredEvents.length>0)$.push(new O(" Events: ",new h({dim:!0}))),$.push(new O(X.registeredEvents.join(", "),new h({color:B.link}))),$.push(new O(`
@@ -6123,7 +6134,7 @@ ${o.content||""}`:o.content||"",P0=[],b0=o.baseDir.startsWith("file://")?rz0(o.b
6123
6134
  `)}function KZA(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"),F=K54({settings:{url:Y.ampURL,proxy:Z},secrets:{getToken:(D,G)=>Y.secrets.get(D,G)}}),X=await lA.userDisplayBalanceInfo({},{config:F});if(!X.ok){if(X.error.code==="auth-required")process.stderr.write(n0.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(n0.red("Error: ")+X.error.message+`
6124
6135
  `),process.exit(1)}process.stdout.write(await mU8(X.result.displayText)+`
6125
6136
  `),process.exit(0)})}var Xz8=U40.join(KF,"logs","headless.log"),kZ1=U40.join(sb,"device-id.json"),Dz8=`cli-tui-${mDA(16).toString("hex")}`;async function Gz8(){for(let A of aL)try{if((await A.listConfigs()).length>0)return A}catch(Q){T.debug("Failed to detect query-based IDE integration",{ideName:A.ideName,error:Q})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => H4(oh(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){_$.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
6126
- `)}function Vz8(A){process.emitWarning=(Q,B,$,J)=>{let Y=typeof Q==="string"?Q:Q.message||String(Q),Z=B||"Warning",F=!1;A.warn(Y,{name:Z,code:$})}}function Y7(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")S9("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")S9("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)S9("internal.model",Uz8(Q.model))}function yDA(A){let Q=A.indexOf(":");if(Q===-1)throw new K4(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let B=A.slice(0,Q).trim(),$=A.slice(Q+1).trim();if(!B||!$)throw new K4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function Uz8(A){if(!A.includes("="))return yDA(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new K4(`Invalid mode-specific model entry "${$}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let Y=$.slice(0,J).trim(),Z=$.slice(J+1).trim();if(!Y)throw new K4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new K4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);yDA(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new K4("No valid model overrides found in --model flag value.",1);return Q}function Kz8(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 Ez8(A){try{return await pDA(A,"utf-8")}catch{return A}}async function xDA(A,Q,B){let $=Kz8(A,Q);if(!$)return;let J=gA(B)?B.features:[],Y=gA(B)?B.user.email:void 0;if(!rh(J,Y9.HARNESS_SYSTEM_PROMPT)&&!(Y&&K7(Y)))throw new K4("You are not allowed to do this.",1);S9("systemPrompt",await Ez8($))}function rh(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function Wz8(A){return A!=="pending"}function th(A){if(!gA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function Hz8(A){let Q=th(A);if(Q)return Q.id;if(VW(A))throw Error(A.error.message);throw Error("unreachable")}function zz8(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 qz8(A){let $=zz8(A)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new K4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function yZ1(A,Q){let B=H51(Error(A.error.message));if(B.message===h7.networkOffline||B.message===h7.networkTimeout)return qz8(Q);if(B.message!==h7.internalBug)return new K4(B.message,1,B.suggestion);return new K4(A.error.message.replace(/^Error: /,""),1)}var fDA=[{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(T).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${_t})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","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:M9(),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:dL.SMART.key,description:`Set the agent mode (${t$({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(t$().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neo",long:"neo",type:"switch",description:"Use the Neo TUI",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}],bDA=(A)=>("deprecated"in A)&&A.deprecated===!0,Nz8=(A)=>("hidden"in A)&&A.hidden===!0,Iz8=(A)=>("default"in A),Cz8=(A)=>("default"in A)?A.default:void 0,dDA=[{name:"toggle-skills-count",entryPoint:FB1}];function wz8(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((F)=>B.includes(F)||F.includes(B)),Z="Run amp --help for a list of available commands.";if(Y.length>0)Z=`Did you mean: ${Y.join(", ")}? Or run amp --help for all commands.`;throw new K4(h7.unknownCommand(B),1,Z)}}async function mq0(A){return{...A,getThreadEnvironment:WH,osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new mO(A.fileSystem),generateThreadTitle:OK4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>ZJ(A.configService),pluginService:A.pluginService}}function cDA(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:WH,filesystem:A.fileSystem,threadService:A.threadService}}var lDA="code-tour";function vZ1(A){return A.filter((Q)=>Q.name!==lDA)}function Mz8(A){return{...A,skills:A.skills.pipe(w1(vZ1)),getSkills:async()=>vZ1(await A.getSkills()),getSkill:async(Q)=>Q===lDA?void 0:A.getSkill(Q),getSkillsList:async()=>{let Q=vZ1(await A.getSkills());return qy(Q)}}}var hq0=Z1.file(Fz8.homedir()),xZ1=process.env.XDG_CONFIG_HOME?Z1.file(process.env.XDG_CONFIG_HOME):G1.joinPath(hq0,".config");function Lz8(A){return iy4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(hU0())gU0();else if(process.platform==="darwin"&&Q==="idle"&&A.isTUIVoiceNotifEnabled())ly4();else lr(Q);let B=_P(),$=ye();if((!B||$||XK0())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(kG("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(kG("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(_P()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function A9(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;o54("0.0.1777184774-g5a2bb8");let Y=uk({storage:A.settings,secretStorage:A.secrets,workspaceRoot:g0.of(Z1.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:hq0,userConfigDir:xZ1});$7A(Y);let Z=await Y.getLatest();T.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let F=!1;{let m=await A.secrets.get("apiKey",A.ampURL);if(F=Boolean(m),T.info("API key lookup before login",{found:Boolean(m),ampURL:A.ampURL,deferAuth:$}),!m)if($)T.info("No API key found, continuing startup with deferred auth");else{E5.write(`No API key found. Starting login flow...
6137
+ `)}function Vz8(A){process.emitWarning=(Q,B,$,J)=>{let Y=typeof Q==="string"?Q:Q.message||String(Q),Z=B||"Warning",F=!1;A.warn(Y,{name:Z,code:$})}}function Y7(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")S9("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")S9("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)S9("internal.model",Uz8(Q.model))}function yDA(A){let Q=A.indexOf(":");if(Q===-1)throw new K4(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let B=A.slice(0,Q).trim(),$=A.slice(Q+1).trim();if(!B||!$)throw new K4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function Uz8(A){if(!A.includes("="))return yDA(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new K4(`Invalid mode-specific model entry "${$}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let Y=$.slice(0,J).trim(),Z=$.slice(J+1).trim();if(!Y)throw new K4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new K4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);yDA(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new K4("No valid model overrides found in --model flag value.",1);return Q}function Kz8(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 Ez8(A){try{return await pDA(A,"utf-8")}catch{return A}}async function xDA(A,Q,B){let $=Kz8(A,Q);if(!$)return;let J=gA(B)?B.features:[],Y=gA(B)?B.user.email:void 0;if(!rh(J,Y9.HARNESS_SYSTEM_PROMPT)&&!(Y&&K7(Y)))throw new K4("You are not allowed to do this.",1);S9("systemPrompt",await Ez8($))}function rh(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function Wz8(A){return A!=="pending"}function th(A){if(!gA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function Hz8(A){let Q=th(A);if(Q)return Q.id;if(VW(A))throw Error(A.error.message);throw Error("unreachable")}function zz8(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 qz8(A){let $=zz8(A)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new K4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function yZ1(A,Q){let B=H51(Error(A.error.message));if(B.message===h7.networkOffline||B.message===h7.networkTimeout)return qz8(Q);if(B.message!==h7.internalBug)return new K4(B.message,1,B.suggestion);return new K4(A.error.message.replace(/^Error: /,""),1)}var fDA=[{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(T).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${_t})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","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:M9(),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:dL.SMART.key,description:`Set the agent mode (${t$({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(t$().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neo",long:"neo",type:"switch",description:"Use the Neo TUI",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}],bDA=(A)=>("deprecated"in A)&&A.deprecated===!0,Nz8=(A)=>("hidden"in A)&&A.hidden===!0,Iz8=(A)=>("default"in A),Cz8=(A)=>("default"in A)?A.default:void 0,dDA=[{name:"toggle-skills-count",entryPoint:FB1}];function wz8(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((F)=>B.includes(F)||F.includes(B)),Z="Run amp --help for a list of available commands.";if(Y.length>0)Z=`Did you mean: ${Y.join(", ")}? Or run amp --help for all commands.`;throw new K4(h7.unknownCommand(B),1,Z)}}async function mq0(A){return{...A,getThreadEnvironment:WH,osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new mO(A.fileSystem),generateThreadTitle:OK4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>ZJ(A.configService),pluginService:A.pluginService}}function cDA(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:WH,filesystem:A.fileSystem,threadService:A.threadService}}var lDA="code-tour";function vZ1(A){return A.filter((Q)=>Q.name!==lDA)}function Mz8(A){return{...A,skills:A.skills.pipe(w1(vZ1)),getSkills:async()=>vZ1(await A.getSkills()),getSkill:async(Q)=>Q===lDA?void 0:A.getSkill(Q),getSkillsList:async()=>{let Q=vZ1(await A.getSkills());return qy(Q)}}}var hq0=Z1.file(Fz8.homedir()),xZ1=process.env.XDG_CONFIG_HOME?Z1.file(process.env.XDG_CONFIG_HOME):G1.joinPath(hq0,".config");function Lz8(A){return iy4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(hU0())gU0();else if(process.platform==="darwin"&&Q==="idle"&&A.isTUIVoiceNotifEnabled())ly4();else lr(Q);let B=_P(),$=ye();if((!B||$||XK0())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(kG("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(kG("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(_P()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function A9(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;o54("0.0.1777185893-gae6d40");let Y=uk({storage:A.settings,secretStorage:A.secrets,workspaceRoot:g0.of(Z1.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:hq0,userConfigDir:xZ1});$7A(Y);let Z=await Y.getLatest();T.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let F=!1;{let m=await A.secrets.get("apiKey",A.ampURL);if(F=Boolean(m),T.info("API key lookup before login",{found:Boolean(m),ampURL:A.ampURL,deferAuth:$}),!m)if($)T.info("No API key found, continuing startup with deferred auth");else{E5.write(`No API key found. Starting login flow...
6127
6138
  `);let p=await Oz8(A),u=await A.secrets.get("apiKey",A.ampURL);if(T.info("Login flow completed",{success:p,storedKeyPresent:Boolean(u),ampURL:A.ampURL}),!p)await LK(),process.exit(1);F=!0}}{let m=await Y.getLatest(),p=m.settings.url,u=m.secrets.isSet?.[p];T.info("Config secrets state after login",{configURL:p,apiKeySet:u?.apiKey??!1})}let X=k1(ZJ(Y).pipe(N5(Wz8))),D=$?"pending":await X;if(!$)T.info("Server status resolved",{status:"ready",isAuthenticated:gA(D),isError:VW(D),errorMessage:VW(D)?D.error.message:void 0});let G=X.then((m)=>Hz8(m));G.catch(()=>{return});let{toolService:V,dispose:U}=CD0({configService:Y}),K=new Map,E=()=>K.clear(),W=new Mm0(Y,A.settings.getWorkspaceRootPath()),H=t$0({configService:Y,filesystem:k8}),z=xF4({configService:Y,trustStore:W,skillMCPServers:H.skillMCPServers,createOAuthProvider:async(m,p,u)=>{let a=`${m}:${p}`,d=K.get(a);if(d)return T.debug("Reusing existing OAuth provider for server",{serverName:m,serverUrl:p}),d;T.debug("Creating OAuth provider for server",{serverName:m,serverUrl:p});let s=(async()=>{let W0=new AO(A.secrets),n=await W0.getClientInfo(m,p),A0=u?.scopes??n?.scopes,D0=Rr4();T.info("OAuth headless mode check",{useHeadless:D0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:E5.isTTY});let z0;if(D0)z0=A.executeMode?jr4():Or4(m);let B0=new Yb0({storage:W0,serverName:m,serverUrl:p,clientId:u?.clientId??n?.clientId,clientSecret:u?.clientSecret??n?.clientSecret,authUrl:u?.authUrl??n?.authUrl,tokenUrl:u?.tokenUrl??n?.tokenUrl,scopes:A0,headlessAuthHandler:z0});return T.debug("OAuth provider created",{serverName:m,serverUrl:p,hasManualClientId:!!(u?.clientId??n?.clientId),willUseDCR:!(u?.clientId??n?.clientId),scopes:A0,headlessMode:D0,executeMode:A.executeMode}),B0})();return K.set(a,s),s}}),q=wt0({configService:Y,filesystem:k8,spawn:cX0}),N;if(J)N=new Map;else if(A.executeMode){let m=await Xk4({toolService:V,providers:[z,q],initialTimeout:15000});N=m.registrations;for(let[p,u]of m.initErrors)T.warn(`${p} provider initialization slow or failed:`,u)}else N=Mt0({toolService:V,providers:[z,q]});if(Q.jetbrains)iL("JetBrains");else if(Q.ide&&Gs4())iL("VS Code");else if(Q.ide&&Vs4())iL("Neovim");else if(Q.ide){let m=await Gz8();if(m){let p=n90(m.ideName);if(p)iL(p)}}if(A.executeMode)r54(!0);let I,C=i8.status.pipe(w1((m)=>Boolean(m.connected&&m.authenticated&&m.ideName&&O84(m.ideName))),c4()).subscribe((m)=>{if(m){if(!I)I=V.registerTool(Fk4)}else I?.dispose(),I=void 0}),w;if(!A.executeMode){let m=await A.settings.get("fuzzy.alwaysIncludePaths")??[];w=new ob(process.cwd(),{alwaysIncludePaths:m},!0)}else w=new class extends ob{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let M=new Rd0(lO(Y),{maxThreads:200});T.info("Starting Amp background services");let j=new KB1,P=process.env.PLUGINS??"off",R=Q.headless?m9A():void 0,b=R??new aW0({configService:Y}),g=b instanceof aW0?b:void 0;if(g)g.pluginExecutorKind="local";let f=gm0({configService:Y,fileSystem:k8,platform:b,internalPlugins:dDA,pluginFilter:P}),k=_X4({pluginService:f,toolService:V}),x={configService:Y,toolService:V,mcpService:z,skillService:H,toolboxService:q,trustStore:W,threadService:M,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:w,fileSystem:k8,terminal:j,pluginService:f,pluginPlatform:g,headlessPluginPlatform:R,serverStatus:D,serverStatusPromise:X,viewerUserIDPromise:G,hasAPIKeyAtStartup:F};return{...x,async asyncDispose(){if(x.mcpService.hasAuthenticatingClients())T.info("Waiting for OAuth authentication to complete before exit..."),await x.mcpService.waitForAuthentication();for(let m of N.values())m.dispose();await x.mcpService.dispose(),E(),await x.threadService.asyncDispose(),x.configService.unsubscribe(),U(),x.fuzzyServer.dispose(),x.settingsStorage[Symbol.dispose](),C.unsubscribe(),I?.dispose(),k.dispose(),await x.pluginService.dispose()}}}async function Oz8(A){if(!A.executeMode){if(!await PK0("Would you like to log in to Amp? [(y)es, (n)o]: "))return E5.write(`Login cancelled. Run the command again to retry.
6128
6139
  `),!1}return await iDA(A)}async function iDA(A){let Q=mDA(32).toString("hex"),B=await Yu(A.ampURL,Q),$=new AbortController;try{await KD(B,$.signal)}catch(Y){T.error("Error opening browser",{error:Y})}let J=await Yu(A.ampURL,Q,!1);E5.write(`If your browser does not open automatically, visit:
6129
6140
 
@@ -6131,7 +6142,7 @@ ${n0.blue.bold(J)}
6131
6142
 
6132
6143
  `);try{return await Le4(A.ampURL,Q,A.secrets,$),E5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(Y){return T.error("Login failed",{error:Y}),_$.write(`
6133
6144
  Login failed: ${Y instanceof Error?Y.message:String(Y)}
6134
- `),!1}}function jz8(A){let Q=new bI().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((E)=>{if(E.code==="commander.help"||E.code==="commander.version"||E.exitCode===0)ZP(),process.exit(0);let W=E.originalError??E;Ya4(W)}),p0A(Q,{version:"0.0.1777184774-g5a2bb8",buildTimestamp:"2026-04-26T06:29:46.840Z",buildType:"'release'"}),Q.addHelpText("after",Fs4()),Q.configureHelp({formatHelp:Xs4}),Q.command("logout").description("Log out by removing stored API key").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await vz8(z)}),Q.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await kz8(z,await at(H,z.settings))}),Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(E,W,H)=>{let z=H.optsWithGlobals(),q=await K8(z);await zr4(E??"get",q.ampURL,q.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await qr4(z.ampURL,z.secrets),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(E)=>{await jt4({raw:E.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(`
6145
+ `),!1}}function jz8(A){let Q=new bI().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((E)=>{if(E.code==="commander.help"||E.code==="commander.version"||E.exitCode===0)ZP(),process.exit(0);let W=E.originalError??E;Ya4(W)}),p0A(Q,{version:"0.0.1777185893-gae6d40",buildTimestamp:"2026-04-26T06:48:40.597Z",buildType:"'release'"}),Q.addHelpText("after",Fs4()),Q.configureHelp({formatHelp:Xs4}),Q.command("logout").description("Log out by removing stored API key").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await vz8(z)}),Q.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await kz8(z,await at(H,z.settings))}),Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(E,W,H)=>{let z=H.optsWithGlobals(),q=await K8(z);await zr4(E??"get",q.ampURL,q.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await qr4(z.ampURL,z.secrets),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(E)=>{await jt4({raw:E.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(`
6135
6146
  `)).option("--apply <threadIDOrURL>","Apply the current DTW thread snapshot once and exit").option("--checkout","Automatically check out the thread commit when it differs").option("--skip-checkout","Skip the startup checkout prompt when commits differ").action(async(E,W,H)=>{if(E&&W.apply)throw new K4("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let z=W.apply??E;if(!z||z.trim().length===0)E5.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.
6136
6147
 
6137
6148
  `),H.outputHelp(),process.exit(0);let q=C3(z)??EB(z),N=H.optsWithGlobals(),I=await K8(N);Y7(H,N);let C=await A9(I,N),w=!1;try{if(W.checkout&&W.skipCheckout)throw new K4("Choose either --checkout or --skip-checkout, not both.",1);if(VW(C.serverStatus))throw yZ1(C.serverStatus,I.ampURL);let M=gA(C.serverStatus)?C.serverStatus.features:void 0;if(!rh(M,Y9.V2))throw new K4("live-sync is not enabled for your user",1);await Ke4({ampURL:I.ampURL,threadId:q,configService:C.configService,threadService:C.threadService,apiKey:process.env.AMP_API_KEY,applyOnce:typeof W.apply==="string",checkoutMode:W.checkout?"always":W.skipCheckout?"never":"prompt",promptForYesNo:PK0}),w=!0}finally{if(await C.asyncDispose(),w)process.exit(0)}});let B=async(E,W,H)=>{uk({storage:W.settings,secretStorage:W.secrets,workspaceRoot:g0.of(Z1.file(process.cwd())),defaultAmpURL:W.ampURL,homeDir:hq0,userConfigDir:xZ1});let z={...W,executeMode:!1};await gq0(z,{...E,openThreadSwitcher:!0},H,A)},$=Q.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").option("--include-archived","Include archived threads in the list").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await gDA(H,z,W)});$.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(E,W)=>{let H=W.optsWithGlobals(),z=await K8(H);await cz8(H,z,W)}),$.command("continue [threadIDOrURL]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, interactive mode shows a picker. Use --last to continue the last thread for the current mode directly.").option("--last","Continue the last thread for the current mode directly").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(E,W,H)=>{let z=H.optsWithGlobals(),q=await K8(z);if(W.pick)_$.write(`${n0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
@@ -6165,8 +6176,8 @@ ${I}
6165
6176
 
6166
6177
  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 Rz8(A){if(A.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof A.execute==="string"){let Q=(await sW0()).trimEnd();return{userInput:A.execute,stdinInput:Q||null}}return{userInput:(await sW0()).trimEnd(),stdinInput:null}}function Pz8(A,Q,B){if(A.streamJson&&!Q)throw new K4("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new K4("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new K4("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new K4("The --stats and --stream-json flags are mutually exclusive output formats",1,'Use one or the other: amp --execute "your message" --stats OR amp --execute "your message" --stream-json');if(A.stats&&!Q)throw new K4("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archive&&!Q)throw new K4("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(A.streamJsonInput&&typeof A.execute==="string"&&A.execute.trim()!=="")throw new K4("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Q&&B===""&&!A.streamJsonInput&&!A.headless)throw new K4("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
6167
6178
  Or pipe via stdin: echo "your message" | amp --execute`)}async function gq0(A,Q,B,$){let J=process.hrtime.bigint(),Y=(i,o)=>{let e=Number(process.hrtime.bigint()-o)/1e6,Y0=md4();T.info("Startup phase",{phase:i,phaseMs:Math.round(e),sinceMainMs:Y0===null?void 0:Math.round(Y0)})},{userInput:Z,stdinInput:F}=await Rz8(Q),X=!!Q.streamJson||!!Q.streamJsonThinking;Pz8({...Q,streamJson:X},A.executeMode,Z),Y7(B,Q);let D=process.hrtime.bigint(),G=Boolean(await A.secrets.get("apiKey",A.ampURL)),V=!A.executeMode&&!Q.headless&&G;T.info("Interactive auth startup mode",{deferInteractiveAuth:V,hasAPIKeyAtStartup:G,executeMode:A.executeMode,headless:Boolean(Q.headless)});let U=await A9(A,Q,{deferAuth:V});Y("runMainThread:createThreadDependencies",D);let{serverStatus:K}=U;if(!V&&VW(K))throw yZ1(K,A.ampURL);let E=gA(K)?K:null,W=E?.user.email,H=!!(W&&K7(W));if(!V)await xDA(B,Q,K);let z=th(K),q=z?.features??[],N=z?.team??null,I=PW0(Q,z);if(I instanceof Error)o5(I.message);if(E&&!zc(Q.mode,W))throw new K4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(Q.headless){if(process.env.AMP_EXECUTOR!=="1"&&(!W||!K7(W)))throw new K4("Headless executor mode is only available for Amp employees",1);let o=await U.secretStorage.get("apiKey",A.ampURL);if(!o)throw new K4("API key required for headless mode. Please run `amp login` first.",1);let e=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(e&&!AJ(e))throw new K4(`Invalid thread ID: ${e}`,1);let Y0=e?void 0:await pz8({dependencies:U,apiKey:o,visibility:I??void 0}),$0=e??Y0?.threadId;if(!$0)throw new K4("Failed to resolve headless thread ID",1);let K0=await Sr4($0);if(K0.status==="already-running")await U.asyncDispose(),await LK(),process.exit(0);try{await wr4({ampURL:A.ampURL,apiKey:o,workspaceRoot:process.cwd(),threadId:$0,ownerUserId:Y0?.ownerUserId,threadVersion:Y0?.threadVersion,agentMode:Y0?.agentMode,initialToolDiscovery:Promise.all([U.mcpService.initialized,U.toolboxService.initialized]).then(()=>{return}),configService:U.configService,mcpService:U.mcpService,toolService:U.toolService,skillService:U.skillService,fileSystem:U.fileSystem,pluginService:U.pluginService,pluginPlatform:U.headlessPluginPlatform})}finally{await K0.release(),await U.asyncDispose()}await LK(),process.exit(0)}let C=Q.threadId&&AJ(Q.threadId)?Q.threadId:void 0,w=Q.observe?C3(Q.observe)??EB(Q.observe):void 0,M=V?await U.serverStatusPromise:K,j=gA(M)&&rh(M.features,Y9.NEO_TUI);if((j||Q.neo||!!w||!1)&&!A.executeMode&&!Q.takeMeBack){if((Q.neo||w)&&!j&&(!gA(M)||!K7(M.user.email)))throw new K4(Q.observe?"--observe is only available for Amp employees":"--neo is only available for Amp employees",1);let i=await U.secretStorage.get("apiKey",A.ampURL);if(!i)throw new K4("API key required. Please run `amp login` first.",1);let o=lO(U.configService),e=new K_(U.fuzzyServer),Y0=process.cwd();await ZB1({ampURL:A.ampURL,apiKey:i,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??fJ(A.ampURL),configService:U.configService,toolService:U.toolService,skillService:U.skillService,mcpService:U.mcpService,readFileSystemDirectory:({uri:$0})=>NC({fileSystem:U.fileSystem,workspaceRoot:Y0},$0),completionBuilder:e,workspaceRoot:Y0,listThreads:()=>o.listThreads(),getThreadFromServer:($0)=>o.getThread($0),isInternalUser:gA(M)&&K7(M.user.email),settingsFilePath:U.settingsStorage.getSettingsFilePath()},{initialThreadID:w??C,initialUserInput:Z||void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!w,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0});return}let R=gA(M)&&rh(M.features,Y9.THREAD_ACTORS_TUI);if(A.executeMode&&!Q.takeMeBack&&R){let i=await U.secretStorage.get("apiKey",A.ampURL);if(!i)throw new K4("API key required. Please run `amp login` first.",1);K31(U.mcpService,A.settings);try{let o=await go4({apiKey:i,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:U,userInput:Z,stdinInput:F,stats:!!Q.stats,streamJson:X,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,labels:Q.label,initialThreadID:C});if(await sh(o,"execute"),Q.archive)await U.threadService.archive(o,!0)}finally{await U.asyncDispose()}await LK(),process.exit(0)}if(!A.executeMode&&!Q.headless)U.skillService=Mz8(U.skillService);D=process.hrtime.bigint();let g=await mq0(U);Y("runMainThread:createWorkerDeps",D);let f=A.executeMode?void 0:async(i)=>sh(i,"interactive"),k={threadService:U.threadService,workerDeps:g,createThread:async(i)=>{let o=V?await U.serverStatusPromise:K,e=await GU0(A.settings,process.cwd(),th(o),I);if(e instanceof Error)o5(e.message);return YY1(g,{threadMeta:e?mG(e):void 0,agentMode:i??Q.mode,onFirstAssistantMessage:f})},validateThreadOwnership:async(i,o)=>{if(o?.nonBlockingOwnershipCheck){uDA(i,U.configService,U.viewerUserIDPromise).catch((e)=>{if(e instanceof K4){if(o.onOwnershipError){o.onOwnershipError(e,i);return}SH(e,i);return}T.warn("Failed to validate thread ownership in CLI, allowing to open",{error:e})});return}try{await uDA(i,U.configService,U.viewerUserIDPromise)}catch(e){if(e instanceof K4)throw e;T.warn("Failed to validate thread ownership in CLI, allowing to open",{error:e})}},switchThreadVisibility:I,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:f,handleError:SH},x=async()=>{try{return DZA(k,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(i){if(i instanceof K4)throw i;throw await SH(i,Q.threadId),Error("handleError should have called process.exit()")}};if(Q.format==="jsonl")_$.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
6168
- `),await LK(),process.exit(1);let m=(async()=>{if(V){T.info("Skipping initial free tier status fetch until auth is complete");return}try{let i=await U.configService.getLatest(),o=Yc(i),e=await lA.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(o)});if(e.ok)return T.info("User free tier status:",e),e.result;return}catch(i){T.error("Failed to fetch free tier status:",i);return}})(),u=!A.executeMode?new MB1:null,a,d=null;if(u)a=u,d=(async()=>{let i=V?await U.serverStatusPromise:U.serverStatus;if(VW(i))throw yZ1(i,A.ampURL);await xDA(B,Q,i);let o=process.hrtime.bigint(),e=await x();if(Y("runMainThread:createThreadPool",o),u.attach(e),Z){let Y0=await k1(e.threadHandles$);if(!Y0)throw new K4("No active thread is available yet.",1);await Y0.sendMessage({content:[{type:"text",text:Z}]})}})(),d.catch(async(i)=>{let o=i instanceof Error?i:Error(String(i));u.setInitError(o),await SH(i,Q.threadId)});else D=process.hrtime.bigint(),a=await x(),Y("runMainThread:createThreadPool",D);let s=Q.notifications!==void 0?Q.notifications:!A.executeMode,W0=E!==null&&rh(E.features,Y9.TUI_VOICE_NOTIF);if(V)U.serverStatusPromise.then((i)=>{W0=gA(i)&&rh(i.features,Y9.TUI_VOICE_NOTIF)}).catch((i)=>{T.debug("Failed to resolve TUI voice notification feature flag",{error:i})});D=process.hrtime.bigint();let n=await U.configService.getLatest();if(Y("runMainThread:configService.getLatest",D),D=process.hrtime.bigint(),Lz8({configService:U.configService,threadService:U.threadService,config:n,useNotificationsForService:s,isTUIVoiceNotifEnabled:()=>W0,threadViewStates$:()=>a.threadHandles$.pipe(l4((i)=>{if(!i)return g0.of({});return u6(i.thread$,i.threadViewState$).pipe(w1(([o,e])=>({[o.id]:e})))}))}),Y("runMainThread:createCliNotificationService",D),A.executeMode){K31(U.mcpService,A.settings);let i={userInput:Z,stdinInput:F,dependencies:U,streamJson:X,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:H,agentMode:Q.mode,labels:Q.label},o=await ja4({threadPool:a,...i});if(await sh(o,"execute"),Q.archive)await U.threadService.archive(o,!0);await U.asyncDispose(),process.exit(0)}let A0=!1,D0=!1;if(Q.jetbrains||Q.ide){await a90();let i=await CD({jetbrainsOnly:Q.jetbrains});if(i.length===0){if(Q.jetbrains)A0=!await U.configService.get("jetbrains.skipInstall")}else if(i.length===1){let o=i[0];if(o)i8.selectConfig(o)}else D0=!0}D=process.hrtime.bigint();let z0=v81("0.0.1777184774-g5a2bb8",U.settingsStorage,{startDelayMs:3000});Y("runMainThread:createUpdateService",D),D=process.hrtime.bigint();let B0=new E31(U.mcpService,A.settings.getWorkspaceRootPath());if(Y("runMainThread:createMcpTrustHandler",D),Z&&A.executeMode){let i=await k1(a.threadHandles$);if(!i)throw new K4("No active thread is available yet.",1);await i.sendMessage({content:[{type:"text",text:Z}]})}D=process.hrtime.bigint();let Z0=await Zu();Y("runMainThread:loadSessionState",D),T.info("Loaded session state:",Z0);let c={...Z0,launchCount:Z0.launchCount+1};qZ((i)=>({...i,launchCount:i.launchCount+1}));try{if(D=process.hrtime.bigint(),await ZQA({history:new ht,fuzzyServer:U.fuzzyServer,settingsStorage:U.settingsStorage,threadService:U.threadService,skillService:U.skillService,configService:U.configService,secretStorage:U.secretStorage,internalAPIClient:lA,threadPool:a,createSystemPromptDeps:async()=>cDA(U),ideClient:i8,mcpService:U.mcpService,toolboxService:U.toolboxService,mcpTrustHandler:B0,updateService:z0,pluginPlatform:U.pluginPlatform,pluginService:U.pluginService},{initialServerStatus:U.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:U.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:C,showJetBrainsInstaller:A0,showIdePickerHint:D0,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:Dz8,logFile:{path:$},sessionState:c,freeTierStatusPromise:m,workspace:N??null,features:q,isInternalUser:H,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,buildTimestamp:"2026-04-26T06:29:46.840Z"},(i)=>new TB1({...i,threadPool:i.threadPool},(o)=>new $Y1({...o,threadState:o.threadState}))),Y("runMainThread:mountApp-returned",D),d)await d}finally{await a.dispose().catch((i)=>{T.error("Failed to dispose thread pool during shutdown",i)})}await U.asyncDispose(),Y("runMainThread:dependencies.asyncDispose",J),process.exit(0)}async function K8(A){if(T.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)_$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6169
- `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;T.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await gF4({get:async(F)=>{if(F!==Gi)return;try{let X=await pDA(kZ1,"utf-8");return JSON.parse(X).installationID}catch{return}},set:async(F,X)=>{if(F!==Gi)return;await Yz8(U40.dirname(kZ1),{recursive:!0}),await Zz8(kZ1,JSON.stringify({installationID:X},null,2),{mode:384})}},{clientType:"cli",platform:xB0()});s54($);let J=await lU0({...A,workspaceTrust:{current:!0,changes:kx0},getHook:process.env.AMP_URL?(F,X)=>{if(F==="url")return Promise.resolve(process.env.AMP_URL);return X()}:void 0});if(A.mcpConfig){let F=await ye4(A.mcpConfig);J=xe4(J,F)}let Y=U40.dirname(J.getSettingsFilePath());cy4(sb,Y),J=S64(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=k9;if(T.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!yq(Z))T.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:yK0(await at(A,J))}}function _z8(A){let Q={};for(let B=0;B<A.length;B++){let $=A[B];if($?.startsWith("--")){let Y=$.slice(2).replace(/-([a-z])/g,(F,X)=>X.toUpperCase()),Z=A[B+1];if(Z&&!Z.startsWith("--"))Q[Y]=Z,B++}}return Q}function Tz8(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=U40.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?Xz8:_t));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function Sz8(){gd4();let A=_z8(process.argv),Q=Tz8(process.argv,A),B=rn4(Q),$=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)n0.level=0;if(Vz8(T),T.info("Starting Amp CLI.",{version:"0.0.1777184774-g5a2bb8",buildTimestamp:"2026-04-26T06:29:46.840Z"}),process.platform==="win32"&&WP())_s4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new K4(h7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await jz8(B).parseAsync(process.argv)}py4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await Sz8().catch(SH)});async function kz8(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"),E5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6179
+ `),await LK(),process.exit(1);let m=(async()=>{if(V){T.info("Skipping initial free tier status fetch until auth is complete");return}try{let i=await U.configService.getLatest(),o=Yc(i),e=await lA.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(o)});if(e.ok)return T.info("User free tier status:",e),e.result;return}catch(i){T.error("Failed to fetch free tier status:",i);return}})(),u=!A.executeMode?new MB1:null,a,d=null;if(u)a=u,d=(async()=>{let i=V?await U.serverStatusPromise:U.serverStatus;if(VW(i))throw yZ1(i,A.ampURL);await xDA(B,Q,i);let o=process.hrtime.bigint(),e=await x();if(Y("runMainThread:createThreadPool",o),u.attach(e),Z){let Y0=await k1(e.threadHandles$);if(!Y0)throw new K4("No active thread is available yet.",1);await Y0.sendMessage({content:[{type:"text",text:Z}]})}})(),d.catch(async(i)=>{let o=i instanceof Error?i:Error(String(i));u.setInitError(o),await SH(i,Q.threadId)});else D=process.hrtime.bigint(),a=await x(),Y("runMainThread:createThreadPool",D);let s=Q.notifications!==void 0?Q.notifications:!A.executeMode,W0=E!==null&&rh(E.features,Y9.TUI_VOICE_NOTIF);if(V)U.serverStatusPromise.then((i)=>{W0=gA(i)&&rh(i.features,Y9.TUI_VOICE_NOTIF)}).catch((i)=>{T.debug("Failed to resolve TUI voice notification feature flag",{error:i})});D=process.hrtime.bigint();let n=await U.configService.getLatest();if(Y("runMainThread:configService.getLatest",D),D=process.hrtime.bigint(),Lz8({configService:U.configService,threadService:U.threadService,config:n,useNotificationsForService:s,isTUIVoiceNotifEnabled:()=>W0,threadViewStates$:()=>a.threadHandles$.pipe(l4((i)=>{if(!i)return g0.of({});return u6(i.thread$,i.threadViewState$).pipe(w1(([o,e])=>({[o.id]:e})))}))}),Y("runMainThread:createCliNotificationService",D),A.executeMode){K31(U.mcpService,A.settings);let i={userInput:Z,stdinInput:F,dependencies:U,streamJson:X,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:H,agentMode:Q.mode,labels:Q.label},o=await ja4({threadPool:a,...i});if(await sh(o,"execute"),Q.archive)await U.threadService.archive(o,!0);await U.asyncDispose(),process.exit(0)}let A0=!1,D0=!1;if(Q.jetbrains||Q.ide){await a90();let i=await CD({jetbrainsOnly:Q.jetbrains});if(i.length===0){if(Q.jetbrains)A0=!await U.configService.get("jetbrains.skipInstall")}else if(i.length===1){let o=i[0];if(o)i8.selectConfig(o)}else D0=!0}D=process.hrtime.bigint();let z0=v81("0.0.1777185893-gae6d40",U.settingsStorage,{startDelayMs:3000});Y("runMainThread:createUpdateService",D),D=process.hrtime.bigint();let B0=new E31(U.mcpService,A.settings.getWorkspaceRootPath());if(Y("runMainThread:createMcpTrustHandler",D),Z&&A.executeMode){let i=await k1(a.threadHandles$);if(!i)throw new K4("No active thread is available yet.",1);await i.sendMessage({content:[{type:"text",text:Z}]})}D=process.hrtime.bigint();let Z0=await Zu();Y("runMainThread:loadSessionState",D),T.info("Loaded session state:",Z0);let c={...Z0,launchCount:Z0.launchCount+1};qZ((i)=>({...i,launchCount:i.launchCount+1}));try{if(D=process.hrtime.bigint(),await ZQA({history:new ht,fuzzyServer:U.fuzzyServer,settingsStorage:U.settingsStorage,threadService:U.threadService,skillService:U.skillService,configService:U.configService,secretStorage:U.secretStorage,internalAPIClient:lA,threadPool:a,createSystemPromptDeps:async()=>cDA(U),ideClient:i8,mcpService:U.mcpService,toolboxService:U.toolboxService,mcpTrustHandler:B0,updateService:z0,pluginPlatform:U.pluginPlatform,pluginService:U.pluginService},{initialServerStatus:U.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:U.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:C,showJetBrainsInstaller:A0,showIdePickerHint:D0,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:Dz8,logFile:{path:$},sessionState:c,freeTierStatusPromise:m,workspace:N??null,features:q,isInternalUser:H,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,buildTimestamp:"2026-04-26T06:48:40.597Z"},(i)=>new TB1({...i,threadPool:i.threadPool},(o)=>new $Y1({...o,threadState:o.threadState}))),Y("runMainThread:mountApp-returned",D),d)await d}finally{await a.dispose().catch((i)=>{T.error("Failed to dispose thread pool during shutdown",i)})}await U.asyncDispose(),Y("runMainThread:dependencies.asyncDispose",J),process.exit(0)}async function K8(A){if(T.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)_$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6180
+ `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;T.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await gF4({get:async(F)=>{if(F!==Gi)return;try{let X=await pDA(kZ1,"utf-8");return JSON.parse(X).installationID}catch{return}},set:async(F,X)=>{if(F!==Gi)return;await Yz8(U40.dirname(kZ1),{recursive:!0}),await Zz8(kZ1,JSON.stringify({installationID:X},null,2),{mode:384})}},{clientType:"cli",platform:xB0()});s54($);let J=await lU0({...A,workspaceTrust:{current:!0,changes:kx0},getHook:process.env.AMP_URL?(F,X)=>{if(F==="url")return Promise.resolve(process.env.AMP_URL);return X()}:void 0});if(A.mcpConfig){let F=await ye4(A.mcpConfig);J=xe4(J,F)}let Y=U40.dirname(J.getSettingsFilePath());cy4(sb,Y),J=S64(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=k9;if(T.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!yq(Z))T.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:yK0(await at(A,J))}}function _z8(A){let Q={};for(let B=0;B<A.length;B++){let $=A[B];if($?.startsWith("--")){let Y=$.slice(2).replace(/-([a-z])/g,(F,X)=>X.toUpperCase()),Z=A[B+1];if(Z&&!Z.startsWith("--"))Q[Y]=Z,B++}}return Q}function Tz8(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=U40.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?Xz8:_t));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function Sz8(){gd4();let A=_z8(process.argv),Q=Tz8(process.argv,A),B=rn4(Q),$=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)n0.level=0;if(Vz8(T),T.info("Starting Amp CLI.",{version:"0.0.1777185893-gae6d40",buildTimestamp:"2026-04-26T06:48:40.597Z"}),process.platform==="win32"&&WP())_s4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new K4(h7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await jz8(B).parseAsync(process.argv)}py4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await Sz8().catch(SH)});async function kz8(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"),E5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6170
6181
  `);else if(!yq(A.ampURL))E5.write(`Logging in to ${new URL(A.ampURL).hostname}
6171
6182
  `);let $=process.env.AMP_API_KEY;if($)E5.write(`API key found in environment variable, storing...
6172
6183
  `),await Q.set("apiKey",$,A.ampURL),E5.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1777184774-g5a2bb8",
3
+ "version": "0.0.1777185893-gae6d40",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {