@sourcegraph/amp 0.0.1780677932-g159ed8 → 0.0.1780694019-g120cbb

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 +13 -11
  2. package/package.json +2 -2
package/dist/main.js CHANGED
@@ -1524,7 +1524,7 @@ Stacked area chart with groupColumn (auto-pivots rows by credit_type):
1524
1524
  - ISO-date xColumn values (YYYY-MM-DD…) are automatically sorted ascending; categorical labels preserve source order.
1525
1525
  - Include a \`link\` key in JSON rows to make tooltip values clickable hyperlinks.
1526
1526
  - Use \`hoverColumns\` to surface extra context (IDs, descriptions) in tooltips without adding chart clutter.
1527
- - Choose \`horizontal: true\` for bar charts when labels are long (e.g. file paths, URLs).`,c04={spec:{name:jyA,description:vFQ,inputSchema:{type:"object",properties:{cmd:{type:"string",description:"A shell command to execute that produces JSON output (a JSON array of objects)."},chartType:{type:"string",enum:["bar","line","area"],description:"The type of chart to render."},xColumn:{type:"string",description:"Column name to use for the X axis (labels)."},yColumns:{type:"array",items:{type:"string"},description:"Column name(s) for the Y axis. Multiple columns create multiple series."},title:{type:"string",description:"Chart title."},subtitle:{type:"string",description:"Optional subtitle shown below the title."},xAxisLabel:{type:"string",description:"Label for the X axis. Defaults to the xColumn name."},yAxisLabel:{type:"string",description:"Label for the Y axis. Defaults to the first yColumn name."},stacked:{type:"boolean",description:"Stack multiple series instead of overlaying. Works with bar and area charts."},horizontal:{type:"boolean",description:"Render bars horizontally. Only applies to bar chartType."},hoverColumns:{type:"array",items:{type:"string"},description:"Extra columns to display in hover tooltips but not plotted on the Y axis."},groupColumn:{type:"string",description:'Column whose unique values become separate series. Pivots unpivoted data — e.g., a "type" column creates one series per type. Use with a single yColumn.'}},required:["cmd","chartType","xColumn","yColumns"]},source:"builtin"},fn:({args:A},Q)=>j1(async()=>{let $=await _FQ(A.cmd,Q);if($.error)return{status:"error",error:{message:$.error}};let E=$.output.replace(/\n/g,"");try{let D=JSON.parse(E);if(!Array.isArray(D)){if(typeof D!=="object"||D===null)return{status:"error",error:{message:"Data is not a JSON array or object. Expected a JSON array of objects."}}}}catch(D){return{status:"error",error:{message:`Invalid JSON data: ${D instanceof Error?D.message:String(D)}. The command output was not valid JSON. Try piping the command output through \`jq -c .\` to produce compact single-line JSON.`}}}return{status:"done",result:{success:!0,data:E}}})};async function _FQ(A,Q){let $=await LG(Q.toolService.invokeTool(U$,{args:{cmd:A}},Q));if($.status==="error")return{error:`Command failed: ${$.error?.message??"Bash command failed"}`};if($.status!=="done")return{error:`Command did not complete (status: ${$.status})`};let B=$.result;if(!B)return{error:"Command produced no output"};if(B.exitCode!==void 0&&B.exitCode!==0)return{error:`Command exited with code ${B.exitCode}: ${B.output??"(no output)"}`};let E=B.output;if(!E||E.trim().length===0)return{error:"Command produced no output"};return{output:E}}bA();$3();bA();R8();ID();function p04(A){return A.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&").replace(/&quot;/g,'"').replace(/&apos;/g,"'")}function $B(A,Q){let $=`<${Q}>`,B=`</${Q}>`,E=A.indexOf($);if(E===-1)return null;let D=E+$.length,J=A.indexOf(B,D);if(J===-1)return null;return p04(A.slice(D,J).trim())}function wV(A,Q){let $=[],B=`<${Q}>`,E=`</${Q}>`,D=0;while(!0){let J=A.indexOf(B,D);if(J===-1)break;let U=J+B.length,Y=A.indexOf(E,U);if(Y===-1)break;$.push(p04(A.slice(U,Y))),D=Y+E.length}return $}bA();n0();Pj();function Tj(A,Q){if(Zg(A))return{title:"Model Stream Timed Out",description:"The model stopped sending data before finishing. Try again in a few seconds.",actions:["retry"]};if(Bj0(A))return{title:"Network Error",description:"Cannot reach Amp servers. Check your internet connection and try again.",actions:["retry"]};if(zQ0(A))return{title:"Unauthorized",description:"Check your access token.",actions:["retry"]};if(KQ0(A)||n04(A)){let D=Q.userEmail?` Signed in as ${Q.userEmail}.`:"";if(Q.freeTierEnabled)return{title:"Out of Credits",description:`Add credits to keep using Amp right now, or wait until the next hour starts for more free usage.${D}`,actions:["add-credits","retry"]};return{title:"Out of Credits",description:`Add credits to keep using Amp.${D}`,actions:["add-credits","retry"]}}if(Yg(A))return{title:"Model Provider Overloaded",description:"Try again in a few seconds.",actions:["retry"]};if(o04(A))return{title:"Image Too Large",description:"The attached image is too large. Please compress or resize your image and try again.",actions:[]};if(r04(A))return{title:"Turn Limit Reached",description:"This Gemini request exceeded the maximum allowed turn count for Gemini.",actions:["dismiss"]};if(A.error?.type==="rate_limit_error")return{title:"Rate Limit Hit",description:A.error.message??"Rate limit exceeded. Try again shortly.",actions:["retry"]};if(Rj(A))return{title:"Context Limit Reached",description:"This conversation has reached the context window limit. Start a new thread to continue.",actions:["new-thread"]};if(a04(A))return{title:"Usage Quota Exceeded",description:MV(A),actions:["retry"]};if(t04(A))return{title:"Agent Mode Disabled",description:MV(A),actions:["dismiss"]};let $=200,B=MV(A);return{title:"Error",description:B.length>$?`${B.substring(0,$)}...`:B,actions:["retry"]}}function bFQ(A){return A.replace(/^https?:\/\//,"")}function Ej0(A,Q){switch(A){case"retry":if(Q?.retryCountdown!==void 0&&Q.retryCountdown!==null)return`Retry (auto-retry in ${Q.retryCountdown}s)`;return"Retry";case"add-credits":{let $="Add Credits";if(Q?.ampURL){let B=bFQ(new URL("/pay",Q.ampURL).toString());$+=` (${B})`}return $}case"new-thread":return"New Thread";case"dismiss":return"Dismiss";default:throw Error(`Unhandled error action: ${String(A)}`)}}Pj();n8();n0();lH();var A74=j.object({summary:j.string().describe("A concise summary of the work completed by the subagent before it encountered an error. Focus on what was accomplished, files modified, and any important findings.")}),QMQ=F$`
1527
+ - Choose \`horizontal: true\` for bar charts when labels are long (e.g. file paths, URLs).`,c04={spec:{name:jyA,description:vFQ,inputSchema:{type:"object",properties:{cmd:{type:"string",description:"A shell command to execute that produces JSON output (a JSON array of objects)."},chartType:{type:"string",enum:["bar","line","area"],description:"The type of chart to render."},xColumn:{type:"string",description:"Column name to use for the X axis (labels)."},yColumns:{type:"array",items:{type:"string"},description:"Column name(s) for the Y axis. Multiple columns create multiple series."},title:{type:"string",description:"Chart title."},subtitle:{type:"string",description:"Optional subtitle shown below the title."},xAxisLabel:{type:"string",description:"Label for the X axis. Defaults to the xColumn name."},yAxisLabel:{type:"string",description:"Label for the Y axis. Defaults to the first yColumn name."},stacked:{type:"boolean",description:"Stack multiple series instead of overlaying. Works with bar and area charts."},horizontal:{type:"boolean",description:"Render bars horizontally. Only applies to bar chartType."},hoverColumns:{type:"array",items:{type:"string"},description:"Extra columns to display in hover tooltips but not plotted on the Y axis."},groupColumn:{type:"string",description:'Column whose unique values become separate series. Pivots unpivoted data — e.g., a "type" column creates one series per type. Use with a single yColumn.'}},required:["cmd","chartType","xColumn","yColumns"]},source:"builtin"},fn:({args:A},Q)=>j1(async()=>{let $=await _FQ(A.cmd,Q);if($.error)return{status:"error",error:{message:$.error}};let E=$.output.replace(/\n/g,"");try{let D=JSON.parse(E);if(!Array.isArray(D)){if(typeof D!=="object"||D===null)return{status:"error",error:{message:"Data is not a JSON array or object. Expected a JSON array of objects."}}}}catch(D){return{status:"error",error:{message:`Invalid JSON data: ${D instanceof Error?D.message:String(D)}. The command output was not valid JSON. Try piping the command output through \`jq -c .\` to produce compact single-line JSON.`}}}return{status:"done",result:{success:!0,data:E}}})};async function _FQ(A,Q){let $=await LG(Q.toolService.invokeTool(U$,{args:{cmd:A}},Q));if($.status==="error")return{error:`Command failed: ${$.error?.message??"Bash command failed"}`};if($.status!=="done")return{error:`Command did not complete (status: ${$.status})`};let B=$.result;if(!B)return{error:"Command produced no output"};if(B.exitCode!==void 0&&B.exitCode!==0)return{error:`Command exited with code ${B.exitCode}: ${B.output??"(no output)"}`};let E=B.output;if(!E||E.trim().length===0)return{error:"Command produced no output"};return{output:E}}bA();$3();bA();R8();ID();function p04(A){return A.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&").replace(/&quot;/g,'"').replace(/&apos;/g,"'")}function $B(A,Q){let $=`<${Q}>`,B=`</${Q}>`,E=A.indexOf($);if(E===-1)return null;let D=E+$.length,J=A.indexOf(B,D);if(J===-1)return null;return p04(A.slice(D,J).trim())}function wV(A,Q){let $=[],B=`<${Q}>`,E=`</${Q}>`,D=0;while(!0){let J=A.indexOf(B,D);if(J===-1)break;let U=J+B.length,Y=A.indexOf(E,U);if(Y===-1)break;$.push(p04(A.slice(U,Y))),D=Y+E.length}return $}bA();n0();Pj();function Tj(A,Q){if(Zg(A))return{title:"Model Stream Timed Out",description:"The model stopped sending data before finishing. Try again in a few seconds.",actions:["retry"]};if(Bj0(A))return{title:"Network Error",description:"Cannot reach Amp servers. Check your internet connection and try again.",actions:["retry"]};if(zQ0(A))return{title:"Unauthorized",description:"Check your access token.",actions:["retry"]};if(KQ0(A)||n04(A)){let D=Q.userEmail?` Signed in as ${Q.userEmail}.`:"";if(Q.freeTierEnabled)return{title:"Out of Credits",description:`Add credits to keep using Amp right now, or wait until the next hour starts for more free usage.${D}`,actions:["add-credits","retry"]};return{title:"Out of Credits",description:`Add credits to keep using Amp.${D}`,actions:["add-credits","retry"]}}if(Yg(A))return{title:"Model Provider Overloaded",description:"Try again in a few seconds.",actions:["retry"]};if(o04(A))return{title:"Image Too Large",description:"The attached image is too large. Please compress or resize your image and try again.",actions:[]};if(r04(A))return{title:"Turn Limit Reached",description:"This Gemini request exceeded the maximum allowed turn count for Gemini.",actions:["dismiss"]};if(A.error?.type==="rate_limit_error")return{title:"Rate Limit Hit",description:A.error.message??"Rate limit exceeded. Try again shortly.",actions:["retry"]};if(Rj(A))return{title:"Context Limit Reached",description:"This conversation has reached the context window limit. Start a new thread to continue.",actions:["new-thread"]};if(a04(A))return{title:"Usage Quota Exceeded",description:MV(A),actions:["retry"]};if(t04(A))return{title:"Agent Mode Disabled",description:MV(A),actions:["dismiss"]};let $=500,B=MV(A);return{title:"Error",description:B.length>$?`${B.substring(0,$)}...`:B,actions:["retry"]}}function bFQ(A){return A.replace(/^https?:\/\//,"")}function Ej0(A,Q){switch(A){case"retry":if(Q?.retryCountdown!==void 0&&Q.retryCountdown!==null)return`Retry (auto-retry in ${Q.retryCountdown}s)`;return"Retry";case"add-credits":{let $="Add Credits";if(Q?.ampURL){let B=bFQ(new URL("/pay",Q.ampURL).toString());$+=` (${B})`}return $}case"new-thread":return"New Thread";case"dismiss":return"Dismiss";default:throw Error(`Unhandled error action: ${String(A)}`)}}Pj();n8();n0();lH();var A74=j.object({summary:j.string().describe("A concise summary of the work completed by the subagent before it encountered an error. Focus on what was accomplished, files modified, and any important findings.")}),QMQ=F$`
1528
1528
  You are helping summarize work done by an AI coding agent (subagent) before it encountered an error.
1529
1529
 
1530
1530
  ## Task
@@ -2817,13 +2817,13 @@ ${K}`))}},error:(V)=>{if(!G)G=!0,Z(Error(`Failed to spawn brew: ${V.message}`))}
2817
2817
  ${K}`;if(J==="pnpm"&&K.includes("Unable to find the global bin directory"))z+=`
2818
2818
 
2819
2819
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
2820
- npm install -g ${D}`;Z(Error(z))}},error:(V)=>{if(!I)I=!0,Z(Error(`Failed to spawn ${J}: ${V.message}`))},complete:()=>{if(!I)I=!0,Y()}})})}n0();n0();Ug();var mtQ="@ampcode/cli";async function K50(A,Q,$=mtQ){let E=`${Q||"https://registry.npmjs.org"}/${$}/latest`,D=new AbortController,J=setTimeout(()=>D.abort(),5000);try{let U=await fetch(E,{signal:D.signal});if(!U.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let Y=await U.json(),Z=Y.version??Y["dist-tags"]?.latest;if(!Z)return{hasUpdate:!1,currentVersion:A,source:"npm"};let F=ec(A,Z),X=F<0,I,G;if(Y.time){let V=Y.time[A],K=Y.time[Z],z=Date.now();if(V)I=Math.floor((z-new Date(V).getTime())/3600000);if(K)G=Math.floor((z-new Date(K).getTime())/3600000)}return S.info("NPM version comparison",{currentVersion:A,latestVersion:Z,compareResult:F,hasUpdate:X,currentVersionAge:I,latestVersionAge:G}),{hasUpdate:X,latestVersion:Z,currentVersion:A,currentVersionAge:I,latestVersionAge:G,source:"npm"}}catch(U){return S.debug("Error checking npm version",{error:U}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(J)}}var dtQ="https://static.ampcode.com/cli/cli-version.txt";async function z50(A){let Q=new AbortController,$=setTimeout(()=>Q.abort(),5000);try{let B=await fetch(`${dtQ}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!B.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let E=(await B.text()).trim();if(!E||!/^\d+\.\d+\.\d+/.test(E))return{hasUpdate:!1,currentVersion:A,source:"bin"};let D=ec(A,E),J=D<0;return S.info("Bin version comparison",{currentVersion:A,latestVersion:E,compareResult:D,hasUpdate:J}),{hasUpdate:J,latestVersion:E,currentVersion:A,source:"bin"}}catch(B){return S.debug("Error checking bin version",{error:B}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout($)}}function ec(A,Q){let $=(J)=>{let[U,Y]=J.split("-");return{parts:U?.split(".").map(Number)||[],label:Y}},B=$(A),E=$(Q),D=Math.max(B.parts.length,E.parts.length);for(let J=0;J<D;J++){let U=B.parts[J]||0,Y=E.parts[J]||0;if(U<Y)return-1;if(U>Y)return 1}if(B.label===E.label)return 0;if(!B.label&&E.label)return 1;if(B.label&&!E.label)return-1;if(B.label&&E.label)return B.label<E.label?-1:1;return 0}function Ap(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-(.+))?/);if(!Q)return null;let $=parseInt(Q[1],10),B=$!==0?$*1000:void 0,D=Q[2]?.match(/^g?([a-f0-9]+)$/)?.[1],J=B!==void 0?uV(B):void 0;return{sha:D,timestamp:B,age:J}}catch{return null}}bA();n0();import{readFile as ctQ,realpath as ptQ}from"node:fs/promises";import{dirname as JV4,join as ltQ}from"node:path";async function UV4(A){switch(A){case"binary":case"brew":return itQ(sc());case"npm":case"pnpm":case"yarn":case"bun":return ntQ()}}async function itQ(A){let Q=await uK(A,["--version"],5000);if(Q.reason!=="success")return S.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function ntQ(){try{let A=process.argv[1];if(!A)return null;let Q=await ptQ(A),$=JV4(JV4(Q));return await atQ(ltQ($,"package.json"))}catch(A){return S.debug("failed to read installed version from package.json",{error:A}),null}}async function atQ(A){let Q=await ctQ(A,"utf8"),$=JSON.parse(Q);if(!$.name||!qy0($.name))return S.debug("package.json name mismatch",{pkgJsonPath:A,name:$.name}),null;return $.version||null}n0();import{spawn as otQ}from"node:child_process";function Ry0(A){if(A=A.replace(/\/$/,""),!A.startsWith("http://")&&!A.startsWith("https://"))A=`https://${A}`;try{return new URL(A),A}catch{return S.warn(`Invalid registry URL: ${A}, falling back to npmjs.org`),"https://registry.npmjs.org"}}var W50=null,Qp=null;function YV4(A){return new Promise((Q)=>{let $=otQ("npm",["config","get",A],{stdio:["ignore","pipe","ignore"],timeout:5000,shell:process.platform==="win32"}),B="";$.stdout.on("data",(E)=>{B+=E.toString()}),$.on("close",(E,D)=>{if(E!==0||D==="SIGTERM"){Q(null);return}let J=B.trim();Q(J&&J!=="undefined"?J:null)}),$.on("error",()=>{Q(null)})})}async function C50(){if(W50)return W50;if(Qp)return Qp;Qp=(async()=>{let A=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(A)return Ry0(A);let Q=await YV4("@sourcegraph:registry");if(Q)return Ry0(Q);let $=await YV4("registry");if($)return Ry0($);return"https://registry.npmjs.org"})();try{return W50=await Qp,W50}finally{Qp=null}}var rtQ=3600000,stQ=5000;function Py0(A,Q,$={}){let B=new M4,E=B.pipe(_$({shouldCountRefs:!1})),D=$.startDelayMs??0,J=$.checkIntervalMs??rtQ,U=!1,Y=()=>{U=!0};return setImmediate(async()=>{let Z=S.getChild("update");if(D>0){if(await OV(D),U)return}let F=E.subscribe({next:(I)=>{Z.debug("emit new state",I)}}),X=A;try{while(!U){let I=await ttQ(X,Q,Z,B);if(I.stop)return;if(I.updatedTo)X=I.updatedTo;if(I.emittedVisibleState){if(await OV(stQ),U)return;B.next("hidden")}if(J<=0)return;let G=1000,V=J;while(V>0&&!U){let K=Math.min(G,V);await OV(K),V-=K}}}finally{F.unsubscribe(),B.complete()}}),{state:E,dispose:Y}}async function ttQ(A,Q,$,B){let E={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return $.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),E.stop=!0,E;let D=await Q.get("updates.mode");if(D==="disabled")return $.debug("checking disabled"),E.stop=!0,E;let J=await aY(),U=J==="binary"||J==="brew",Y=U?void 0:await MK();$.debug("checking",{currentVersion:A,mode:D,packageManager:J,isBinaryDistribution:U,npmPackageName:Y});let Z;if(U)Z=await z50(A);else{let I=await C50();Z=await K50(A,I,Y)}if(!(Z.latestVersion&&Z.hasUpdate))return $.debug("no update available"),E;let F=(I)=>{B.next(I),E.emittedVisibleState=!0};if(J){let I=await UV4(J);if(I&&ec(I,Z.latestVersion)>=0){if($.debug("on-disk version already up to date",{currentVersion:A,installedVersion:I,latestVersion:Z.latestVersion}),E.updatedTo=I,ec(A,I)<0){let G=await OX(I),V={from:A,to:I,externallyUpdated:!0,...G};if(G.status==="same")$.info("on-disk already updated by another instance",V),F("updated");else $.warn("on-disk already updated by another instance, with PATH warning",V),F("updated-with-warning")}return E}}let X=()=>{if(Z.currentVersionAge!==void 0&&Z.latestVersionAge!==void 0){let I=Z.currentVersionAge-Z.latestVersionAge,G=0.5;if(Math.abs(I)<0.5)return $.debug("versions too close together, suppressing update warning",{currentVersionAge:Z.currentVersionAge,latestVersionAge:Z.latestVersionAge,ageDifferenceHours:I}),!0}return!1};if(!D)D=J==="pnpm"?"warn":"auto",$.debug("no configured update mode; selected default based on package manager",{packageManager:J,mode:D});if(J==="brew"){if(!X())F("update-available-brew");return E}if(J==="binary"&&process.execPath!==sc()){if($.debug("non-standard binary path, showing warning"),!X())F("update-available-unrecognized-path");return E}if(D==="warn"){if(!X())F("update-available");return E}if(!J){if($.debug("auto-update not supported, falling back to warn mode"),!X())F("update-available");return E}try{await tc(Z.latestVersion,J),E.updatedTo=Z.latestVersion;let I=await OX(Z.latestVersion),G={from:Z.currentVersion,to:Z.latestVersion,...I};if(I.status==="same")$.info("success",G),F("updated");else $.warn("success with warning",G),F("updated-with-warning")}catch(I){F("update-error")}return E}catch(D){return $.debug("check failed",{error:D}),E}}Ug();import{stderr as tD}from"node:process";function ZV4(A){let Q=new NX().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(B)=>{await Hy0(B.force||!1,B.verbose||!1,"0.0.1780677932-g159ed8"),process.exit()});A.addCommand(Q,{hidden:!0});let $=new NX("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(B)=>{await QeQ(B.targetVersion)});A.addCommand($)}function etQ(A){let Q=Boolean(A.isTTY),$=0,B=!1;function E(){if(!Q||!B)return;A.write(`
2820
+ npm install -g ${D}`;Z(Error(z))}},error:(V)=>{if(!I)I=!0,Z(Error(`Failed to spawn ${J}: ${V.message}`))},complete:()=>{if(!I)I=!0,Y()}})})}n0();n0();Ug();var mtQ="@ampcode/cli";async function K50(A,Q,$=mtQ){let E=`${Q||"https://registry.npmjs.org"}/${$}/latest`,D=new AbortController,J=setTimeout(()=>D.abort(),5000);try{let U=await fetch(E,{signal:D.signal});if(!U.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let Y=await U.json(),Z=Y.version??Y["dist-tags"]?.latest;if(!Z)return{hasUpdate:!1,currentVersion:A,source:"npm"};let F=ec(A,Z),X=F<0,I,G;if(Y.time){let V=Y.time[A],K=Y.time[Z],z=Date.now();if(V)I=Math.floor((z-new Date(V).getTime())/3600000);if(K)G=Math.floor((z-new Date(K).getTime())/3600000)}return S.info("NPM version comparison",{currentVersion:A,latestVersion:Z,compareResult:F,hasUpdate:X,currentVersionAge:I,latestVersionAge:G}),{hasUpdate:X,latestVersion:Z,currentVersion:A,currentVersionAge:I,latestVersionAge:G,source:"npm"}}catch(U){return S.debug("Error checking npm version",{error:U}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(J)}}var dtQ="https://static.ampcode.com/cli/cli-version.txt";async function z50(A){let Q=new AbortController,$=setTimeout(()=>Q.abort(),5000);try{let B=await fetch(`${dtQ}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!B.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let E=(await B.text()).trim();if(!E||!/^\d+\.\d+\.\d+/.test(E))return{hasUpdate:!1,currentVersion:A,source:"bin"};let D=ec(A,E),J=D<0;return S.info("Bin version comparison",{currentVersion:A,latestVersion:E,compareResult:D,hasUpdate:J}),{hasUpdate:J,latestVersion:E,currentVersion:A,source:"bin"}}catch(B){return S.debug("Error checking bin version",{error:B}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout($)}}function ec(A,Q){let $=(J)=>{let[U,Y]=J.split("-");return{parts:U?.split(".").map(Number)||[],label:Y}},B=$(A),E=$(Q),D=Math.max(B.parts.length,E.parts.length);for(let J=0;J<D;J++){let U=B.parts[J]||0,Y=E.parts[J]||0;if(U<Y)return-1;if(U>Y)return 1}if(B.label===E.label)return 0;if(!B.label&&E.label)return 1;if(B.label&&!E.label)return-1;if(B.label&&E.label)return B.label<E.label?-1:1;return 0}function Ap(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-(.+))?/);if(!Q)return null;let $=parseInt(Q[1],10),B=$!==0?$*1000:void 0,D=Q[2]?.match(/^g?([a-f0-9]+)$/)?.[1],J=B!==void 0?uV(B):void 0;return{sha:D,timestamp:B,age:J}}catch{return null}}bA();n0();import{readFile as ctQ,realpath as ptQ}from"node:fs/promises";import{dirname as JV4,join as ltQ}from"node:path";async function UV4(A){switch(A){case"binary":case"brew":return itQ(sc());case"npm":case"pnpm":case"yarn":case"bun":return ntQ()}}async function itQ(A){let Q=await uK(A,["--version"],5000);if(Q.reason!=="success")return S.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function ntQ(){try{let A=process.argv[1];if(!A)return null;let Q=await ptQ(A),$=JV4(JV4(Q));return await atQ(ltQ($,"package.json"))}catch(A){return S.debug("failed to read installed version from package.json",{error:A}),null}}async function atQ(A){let Q=await ctQ(A,"utf8"),$=JSON.parse(Q);if(!$.name||!qy0($.name))return S.debug("package.json name mismatch",{pkgJsonPath:A,name:$.name}),null;return $.version||null}n0();import{spawn as otQ}from"node:child_process";function Ry0(A){if(A=A.replace(/\/$/,""),!A.startsWith("http://")&&!A.startsWith("https://"))A=`https://${A}`;try{return new URL(A),A}catch{return S.warn(`Invalid registry URL: ${A}, falling back to npmjs.org`),"https://registry.npmjs.org"}}var W50=null,Qp=null;function YV4(A){return new Promise((Q)=>{let $=otQ("npm",["config","get",A],{stdio:["ignore","pipe","ignore"],timeout:5000,shell:process.platform==="win32"}),B="";$.stdout.on("data",(E)=>{B+=E.toString()}),$.on("close",(E,D)=>{if(E!==0||D==="SIGTERM"){Q(null);return}let J=B.trim();Q(J&&J!=="undefined"?J:null)}),$.on("error",()=>{Q(null)})})}async function C50(){if(W50)return W50;if(Qp)return Qp;Qp=(async()=>{let A=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(A)return Ry0(A);let Q=await YV4("@sourcegraph:registry");if(Q)return Ry0(Q);let $=await YV4("registry");if($)return Ry0($);return"https://registry.npmjs.org"})();try{return W50=await Qp,W50}finally{Qp=null}}var rtQ=3600000,stQ=5000;function Py0(A,Q,$={}){let B=new M4,E=B.pipe(_$({shouldCountRefs:!1})),D=$.startDelayMs??0,J=$.checkIntervalMs??rtQ,U=!1,Y=()=>{U=!0};return setImmediate(async()=>{let Z=S.getChild("update");if(D>0){if(await OV(D),U)return}let F=E.subscribe({next:(I)=>{Z.debug("emit new state",I)}}),X=A;try{while(!U){let I=await ttQ(X,Q,Z,B);if(I.stop)return;if(I.updatedTo)X=I.updatedTo;if(I.emittedVisibleState){if(await OV(stQ),U)return;B.next("hidden")}if(J<=0)return;let G=1000,V=J;while(V>0&&!U){let K=Math.min(G,V);await OV(K),V-=K}}}finally{F.unsubscribe(),B.complete()}}),{state:E,dispose:Y}}async function ttQ(A,Q,$,B){let E={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return $.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),E.stop=!0,E;let D=await Q.get("updates.mode");if(D==="disabled")return $.debug("checking disabled"),E.stop=!0,E;let J=await aY(),U=J==="binary"||J==="brew",Y=U?void 0:await MK();$.debug("checking",{currentVersion:A,mode:D,packageManager:J,isBinaryDistribution:U,npmPackageName:Y});let Z;if(U)Z=await z50(A);else{let I=await C50();Z=await K50(A,I,Y)}if(!(Z.latestVersion&&Z.hasUpdate))return $.debug("no update available"),E;let F=(I)=>{B.next(I),E.emittedVisibleState=!0};if(J){let I=await UV4(J);if(I&&ec(I,Z.latestVersion)>=0){if($.debug("on-disk version already up to date",{currentVersion:A,installedVersion:I,latestVersion:Z.latestVersion}),E.updatedTo=I,ec(A,I)<0){let G=await OX(I),V={from:A,to:I,externallyUpdated:!0,...G};if(G.status==="same")$.info("on-disk already updated by another instance",V),F("updated");else $.warn("on-disk already updated by another instance, with PATH warning",V),F("updated-with-warning")}return E}}let X=()=>{if(Z.currentVersionAge!==void 0&&Z.latestVersionAge!==void 0){let I=Z.currentVersionAge-Z.latestVersionAge,G=0.5;if(Math.abs(I)<0.5)return $.debug("versions too close together, suppressing update warning",{currentVersionAge:Z.currentVersionAge,latestVersionAge:Z.latestVersionAge,ageDifferenceHours:I}),!0}return!1};if(!D)D=J==="pnpm"?"warn":"auto",$.debug("no configured update mode; selected default based on package manager",{packageManager:J,mode:D});if(J==="brew"){if(!X())F("update-available-brew");return E}if(J==="binary"&&process.execPath!==sc()){if($.debug("non-standard binary path, showing warning"),!X())F("update-available-unrecognized-path");return E}if(D==="warn"){if(!X())F("update-available");return E}if(!J){if($.debug("auto-update not supported, falling back to warn mode"),!X())F("update-available");return E}try{await tc(Z.latestVersion,J),E.updatedTo=Z.latestVersion;let I=await OX(Z.latestVersion),G={from:Z.currentVersion,to:Z.latestVersion,...I};if(I.status==="same")$.info("success",G),F("updated");else $.warn("success with warning",G),F("updated-with-warning")}catch(I){F("update-error")}return E}catch(D){return $.debug("check failed",{error:D}),E}}Ug();import{stderr as tD}from"node:process";function ZV4(A){let Q=new NX().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(B)=>{await Hy0(B.force||!1,B.verbose||!1,"0.0.1780694019-g120cbb"),process.exit()});A.addCommand(Q,{hidden:!0});let $=new NX("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(B)=>{await QeQ(B.targetVersion)});A.addCommand($)}function etQ(A){let Q=Boolean(A.isTTY),$=0,B=!1;function E(){if(!Q||!B)return;A.write(`
2821
2821
  `),B=!1,$=0}function D(J){if(!Q)return;let U=J.padEnd($," ");A.write(`\r${U}`),B=!0,$=U.length}return{flushProgressLine:E,renderProgress:D}}function AeQ(A){if(A.source==="npm"&&A.latestVersionAge!==void 0&&A.latestVersionAge>36)tD.write(_0.yellow(`The latest Amp CLI version reported by npm is older than expected. Be aware that you may be using an npm proxy with a corporate policy to delay package updates.
2822
2822
  `))}async function QeQ(A){let $=process.platform==="win32"&&Qq()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:B,renderProgress:E}=etQ(tD);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")tD.write(_0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
2823
2823
 
2824
2824
  `));try{if(!A){tD.write(_0.blue(`Checking for updates...
2825
- `));let U=!1,Y;if(Qq()){let Z=await z50("0.0.1780677932-g159ed8");U=Z.hasUpdate,Y=Z.latestVersion}else{let Z=await C50(),F=await MK(),X=await K50("0.0.1780677932-g159ed8",Z,F);AeQ(X),U=X.hasUpdate,Y=X.latestVersion}if(!U){let Z=Ap("0.0.1780677932-g159ed8"),F=Z?.age?`released ${Z.age} ago`:`built ${uV(new Date("2026-06-05T16:49:58.070Z"))} ago`;tD.write(_0.green(`✓ Amp is already up to date on version ${"0.0.1780677932-g159ed8"} (${F})
2826
- `));let X=await OX("0.0.1780677932-g159ed8",$);if(X.warning)tD.write(`
2825
+ `));let U=!1,Y;if(Qq()){let Z=await z50("0.0.1780694019-g120cbb");U=Z.hasUpdate,Y=Z.latestVersion}else{let Z=await C50(),F=await MK(),X=await K50("0.0.1780694019-g120cbb",Z,F);AeQ(X),U=X.hasUpdate,Y=X.latestVersion}if(!U){let Z=Ap("0.0.1780694019-g120cbb"),F=Z?.age?`released ${Z.age} ago`:`built ${uV(new Date("2026-06-05T21:18:30.332Z"))} ago`;tD.write(_0.green(`✓ Amp is already up to date on version ${"0.0.1780694019-g120cbb"} (${F})
2826
+ `));let X=await OX("0.0.1780694019-g120cbb",$);if(X.warning)tD.write(`
2827
2827
  `+_0.yellow(X.warning)+`
2828
2828
  `);process.exit(0)}if(!Y)tD.write(_0.yellow("[WARN] could not find latest version")),process.exit(0);A=Y}tD.write(_0.blue(`Updating to version ${A}...
2829
2829
  `)),await tc(A,void 0,(U)=>{B(),tD.write(_0.dim(`Running: ${U}
@@ -2991,7 +2991,7 @@ ${B}`}async function j$6(A,Q){if(!Q?.forceExternal&&Q?.onShowImagePreview&&MH4(A
2991
2991
  `).length,E=new D0({text:new g(A,new $0({color:$}))});if(B<=k80)return E;return new y0({width:1/0,height:k80,child:new TB({autofocus:!1,controller:Q,child:E})})}function g86(){return new Map([[CA.key("PageUp"),new f80],[CA.key("PageDown"),new Jm0],[CA.ctrl("u"),new f80],[CA.shift("Home"),new Um0],[CA.shift("End"),new Ym0]])}function m86(A,Q,$){return Math.max(Q,Math.min(A,$))}var Zm0=8,rw4=1,sw4=Zm0-1;class Fm0 extends V4{}class Xm0 extends V4{}class x80 extends V4{}class y80 extends V4{}class Im0 extends V4{}class Gm0 extends V4{}class Vm0 extends d0{props;constructor(A){super(A.key===void 0?{}:{key:A.key});this.props=A}createState(){return new tw4}}class tw4 extends m0{messageScroll=new K$;initState(){super.initState(),this.messageScroll.followMode=!1,this.messageScroll.jumpTo(0)}dispose(){this.messageScroll.dispose(),super.dispose()}build(A){let Q=this.widget.props,$=d86(Q,this.messageScroll),B=c86(Q.options.message),E=B?new w4({actions:this.buildScrollActions(),child:new aQ({debugLabel:"SelectDialogScrollShortcuts",shortcuts:l86(),child:$})}):$,D=[{keys:["↑/↓","j/k"],label:"move"},{keys:["Enter"],label:"select"}];if(B)D.push({keys:["Ctrl+E","Ctrl+Y"],label:"scroll"});return D.push({keys:["Esc"],label:"cancel"}),new E1({header:Q.options.title,minWidth:64,maxWidth:80,footer:D,autofocus:!1,onDismiss:Q.onCancel,child:E})}buildScrollActions(){let A=(Q)=>{let $=i86(this.messageScroll.offset+Q,0,this.messageScroll.maxScrollExtent);this.messageScroll.jumpTo($)};return new Map([[Fm0,new cA(()=>A(-rw4))],[Xm0,new cA(()=>A(rw4))],[x80,new cA(()=>A(-sw4))],[y80,new cA(()=>A(sw4))],[Im0,new cA(()=>this.messageScroll.jumpTo(0))],[Gm0,new cA(()=>this.messageScroll.jumpTo(this.messageScroll.maxScrollExtent))]])}}function d86(A,Q){let $=A.options.options.map((E)=>({value:E,label:E})),B=Math.max(0,$.findIndex((E)=>E.value===A.options.initialValue));return new SX({options:$,selectedIndex:B,body:p86(A.options.message,Q),onSelect:(E)=>{if(E===null){A.onCancel();return}A.onSelect(E)},padding:p0.all(0),showBorder:!1,showDismissalMessage:!1,enableMouseInteraction:!0,wrapOptions:!0})}function c86(A){if(A===void 0)return!1;return A.split(`
2992
2992
  `).length>Zm0}function p86(A,Q){if(A===void 0)return;let $=A.split(`
2993
2993
  `).length,B=Math.min($,Zm0);return new y0({width:1/0,height:B,child:new TB({autofocus:!1,controller:Q,child:new D0({text:new g(A)})})})}function l86(){return new Map([[CA.key("PageUp"),new x80],[CA.key("PageDown"),new y80],[CA.ctrl("u"),new x80],[CA.ctrl("d"),new y80],[CA.ctrl("y"),new Fm0],[CA.ctrl("e"),new Xm0],[CA.shift("Home"),new Im0],[CA.shift("End"),new Gm0]])}function i86(A,Q,$){return Math.max(Q,Math.min(A,$))}var n86=3,a86=2097152,o86=new UB("PluginDialogOverlay");function b80(A,Q,$){if($!==void 0)return{type:"response",id:A,error:$};if(Q===void 0)return{type:"response",id:A};return{type:"response",id:A,result:Q}}function r86(A){let Q=new TextEncoder().encode(JSON.stringify(A)).byteLength;if(Q<=a86)return;throw Error(`thread.messages response is too large (${Q} bytes). Request fewer messages.`)}class Km0{options;unregisterPluginCommands=null;pluginCommandSubscriptions=[];pluginErrorToastKeys=new Set;activeDialog=null;queuedDialogs=[];resolvingDialog=null;pendingOwnerUIRequests=new Map;pendingActorUIRequests=new Map;stateBackedRequestIDs=new Set;pluginUIRespondRequestCounter=0;statusItems=new Map;blockingConfirmDialog=!1;disposed=!1;constructor(A){this.options=A}init(){this.disposed=!1,this.configurePluginPlatform(),this.subscribePluginCommands()}dispose(){this.disposed=!0,this.unregisterPluginCommands?.(),this.unregisterPluginCommands=null;for(let A of this.pluginCommandSubscriptions)A.unsubscribe();this.pluginCommandSubscriptions=[],this.cancelOwnerUIRequests(),this.cancelPendingDialogs(),this.statusItems.clear(),this.clearPluginPlatformStatusHandlers()}handlePluginMessage(A,Q){let $=A.message;if($.type==="response"){this.cancelOwnerUIRequest($.id),this.cancelActorUIRequest($.id);return}if($.type==="event"){if(this.handlePluginUIStateEvent($,Q))return;this.handlePluginEvent($);return}if(this.stateBackedRequestIDs.has($.id))return;if(!J30($.method)){if($.method==="thread.messages")this.handleThreadMessagesRequest($,Q);return}this.handleOwnerUIRequest($,Q)}cancelOwnerUIRequests(){let A=[...this.pendingOwnerUIRequests.values(),...this.pendingActorUIRequests.values()];this.pendingOwnerUIRequests.clear(),this.pendingActorUIRequests.clear(),this.stateBackedRequestIDs.clear();for(let Q of A)Q.abort()}hasBlockingDialog(){return this.activeDialog!==null}hasBlockingConfirmDialog(){return this.activeDialog?.kind==="confirm"}buildDialogLayers(){let A=this.activeDialog;if(!A)return[];return[new C6({key:o86,debugLabel:"PluginDialogOverlay",autofocus:!1,canRequestFocus:!0,child:this.buildActiveDialog(A)})]}buildActiveDialog(A){switch(A.kind){case"input":return new vl({key:new RK(A),header:A.options.title??"Input",helpText:A.options.helpText,initialValue:A.options.initialValue,isRequired:!1,onSubmit:(Q)=>this.resolveInputDialog(A,Q),onDismiss:()=>this.resolveInputDialog(A,void 0)});case"confirm":return new Dm0({key:new RK(A),options:A.options,onConfirm:()=>this.resolveConfirmDialog(A,!0),onCancel:()=>this.resolveConfirmDialog(A,!1)});case"select":return new Vm0({key:new RK(A),options:A.options,onSelect:(Q)=>this.resolveSelectDialog(A,Q),onCancel:()=>this.resolveSelectDialog(A,void 0)})}}getStatusItems(){return[...this.statusItems.values()].flatMap((A)=>A.value===void 0?[]:[{pluginURI:A.pluginURI,id:A.id,value:A.value}])}configurePluginPlatform(){let A=this.options.context.pluginPlatform;if(!A)return;if(A.showToast=(Q)=>this.options.toastController.show(Q,"success"),A.showOpenedURLToast=(Q)=>{this.options.toastController.show(`Opened URL: ${Q}`,"success",8000)},A.appendToThreadHandler=this.options.context.observerOnly?async()=>{throw Error("thread.append is only available from an executor-owned plugin runtime")}:this.options.appendToThread,this.options.readThreadMessages)A.readThreadMessagesHandler=this.readThreadMessages;if(this.options.readThreadTitle)A.readThreadTitleHandler=this.readThreadTitle;if(this.options.subscribeThreadTitle)A.subscribeThreadTitleHandler=this.subscribeThreadTitle;A.runAgentHandler=this.options.context.observerOnly?async()=>{throw Error("agent.run is only available from an executor-owned plugin runtime")}:this.options.runAgent??(async()=>{throw Error("agent.run is not available in this context")}),A.showInputDialog=this.showInputDialog,A.showConfirmDialog=this.showConfirmDialog,A.showSelectDialog=this.showSelectDialog,A.createStatusItemHandler=this.createStatusItem,A.updateStatusItemHandler=this.updateStatusItem,A.removeStatusItemHandler=this.removeStatusItem}handlePluginEvent(A){if(A.event!=="ui.notify")return;let Q=A.data;if(typeof Q.message==="string")this.options.toastController.show(Q.message,"success")}async handleThreadMessagesRequest(A,Q){try{let{options:$,threadID:B}=this.parseThreadMessagesRequestParams(A.params),E=await this.readThreadMessages($,B);r86(E),Q(b80(A.id,E))}catch($){Q(b80(A.id,void 0,$ instanceof Error?$.message:String($)))}}parseThreadMessagesRequestParams(A){if(!A||typeof A!=="object")return{options:void 0,threadID:void 0};let Q=A;return{options:Q.options,threadID:typeof Q.threadID==="string"?Q.threadID:void 0}}async handleOwnerUIRequest(A,Q){let $=new AbortController;this.pendingOwnerUIRequests.set(A.id,$);try{let B=await this.dispatchOwnerUIRequest(A,$.signal);if(this.pendingOwnerUIRequests.get(A.id)!==$)return;this.pendingOwnerUIRequests.delete(A.id),Q(b80(A.id,B))}catch(B){if(this.pendingOwnerUIRequests.get(A.id)!==$)return;this.pendingOwnerUIRequests.delete(A.id),Q(b80(A.id,void 0,B instanceof Error?B.message:String(B)))}}dispatchOwnerUIRequest(A,Q){switch(A.method){case"ui.input":return this.showInputDialog(A.params.options,Q);case"ui.confirm":return this.showConfirmDialog(A.params.options,Q);case"ui.select":return this.showSelectDialog(A.params.options,Q);default:throw Error(`Unknown owner UI request method: ${A.method}`)}}cancelOwnerUIRequest(A){let Q=this.pendingOwnerUIRequests.get(A);if(!Q)return;this.pendingOwnerUIRequests.delete(A),Q.abort()}cancelActorUIRequest(A){let Q=this.pendingActorUIRequests.get(A);if(!Q)return;this.pendingActorUIRequests.delete(A),Q.abort()}buildPluginUIRespondRequest(A,Q,$){this.pluginUIRespondRequestCounter+=1;let B={requestId:A};if($!==void 0)B.error=$;else if(Q!==void 0)B.result=Q;return{type:"request",id:`plugin-ui-respond-${A}-${this.pluginUIRespondRequestCounter}`,method:"plugin.ui.respond",params:B}}async handleActorUIRequest(A,Q){let $=new AbortController;this.pendingActorUIRequests.set(A.requestId,$);let B={type:"request",id:A.requestId,method:A.method,params:A.params};try{let E=await this.dispatchOwnerUIRequest(B,$.signal);if(this.pendingActorUIRequests.get(A.requestId)!==$)return;this.pendingActorUIRequests.delete(A.requestId),Q(this.buildPluginUIRespondRequest(A.requestId,E))}catch(E){if(this.pendingActorUIRequests.get(A.requestId)!==$)return;this.pendingActorUIRequests.delete(A.requestId),Q(this.buildPluginUIRespondRequest(A.requestId,void 0,E instanceof Error?E.message:String(E)))}}upsertActorUIState(A,Q){if(this.stateBackedRequestIDs.add(A.requestId),A.status!=="pending"){this.cancelActorUIRequest(A.requestId);return}if(this.pendingActorUIRequests.has(A.requestId))return;this.handleActorUIRequest(A,Q)}handlePluginUISnapshot(A,Q){let $=new Set(A.requests.map((B)=>B.requestId));for(let B of this.pendingActorUIRequests.keys())if(!$.has(B))this.cancelActorUIRequest(B);for(let B of this.stateBackedRequestIDs)if(!$.has(B))this.stateBackedRequestIDs.delete(B);for(let B of A.requests)this.upsertActorUIState(B,Q)}handlePluginUIRequestAdded(A,Q){this.upsertActorUIState(A.request,Q)}handlePluginUIRequestSettled(A,Q){this.upsertActorUIState(A.request,Q)}handlePluginUIRequestRemoved(A){this.cancelActorUIRequest(A.requestId),this.stateBackedRequestIDs.delete(A.requestId)}handlePluginUIStateEvent(A,Q){if(A.event==="plugin.ui.snapshot"){let $=kZ4.safeParse(A.data);if($.success)this.handlePluginUISnapshot($.data,Q);return!0}if(A.event==="plugin.ui.request_added"){let $=fZ4.safeParse(A.data);if($.success)this.handlePluginUIRequestAdded($.data,Q);return!0}if(A.event==="plugin.ui.request_settled"){let $=xZ4.safeParse(A.data);if($.success)this.handlePluginUIRequestSettled($.data,Q);return!0}if(A.event==="plugin.ui.request_removed"){let $=yZ4.safeParse(A.data);if($.success)this.handlePluginUIRequestRemoved($.data);return!0}return!1}clearPluginPlatformStatusHandlers(){let A=this.options.context.pluginPlatform;if(!A)return;if(A.readThreadMessagesHandler===this.readThreadMessages)A.readThreadMessagesHandler=null;if(A.readThreadTitleHandler===this.readThreadTitle)A.readThreadTitleHandler=null;if(A.subscribeThreadTitleHandler===this.subscribeThreadTitle)A.subscribeThreadTitleHandler=null;if(A.createStatusItemHandler===this.createStatusItem)A.createStatusItemHandler=null;if(A.updateStatusItemHandler===this.updateStatusItem)A.updateStatusItemHandler=null;if(A.removeStatusItemHandler===this.removeStatusItem)A.removeStatusItemHandler=null;if(A.runAgentHandler===this.options.runAgent)A.runAgentHandler=null}subscribePluginCommands(){let A=this.options.context.pluginService;if(!A)return;this.refreshPluginCommands(A.commands.list()),this.pluginCommandSubscriptions=[A.plugins.subscribe((Q)=>{this.removeInactivePluginStatusItems(Q),this.showNewPluginErrorToasts(Q),this.refreshPluginCommands(A.commands.list())}),A.commands.changed.subscribe(()=>{this.refreshPluginCommands(A.commands.list())})]}refreshPluginCommands(A){this.unregisterPluginCommands?.();let $=A.map((B)=>this.createPluginCommand(B)).map((B)=>this.options.commandRegistry.register(B));this.unregisterPluginCommands=()=>{for(let B of $)B()}}showNewPluginErrorToasts(A){let Q=new Set;for(let $ of A){if($.status!=="error")continue;if(Hh($.errorMessage))continue;let B=`${$.uri.toString()}
2994
- ${$.errorMessage??""}`;if(Q.add(B),this.pluginErrorToastKeys.has(B))continue;this.options.toastController.show(this.formatPluginErrorToast($),"error",8000)}this.pluginErrorToastKeys=Q}removeInactivePluginStatusItems(A){let Q=new Set(A.filter((B)=>B.status==="active").map((B)=>B.uri.toString())),$=[];for(let[B,E]of this.statusItems){if(Q.has(E.pluginURI))continue;$.push(B)}if($.length===0)return;this.updateStatusItemState(()=>{for(let B of $)this.statusItems.delete(B)})}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.context.logFilePath}`}createPluginCommand(A){return{id:A.id,noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,status:A.availability,run:async(Q,$,B)=>{B();try{await this.options.context.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(E){S.error("Neo plugin command failed",{error:E,command:A}),this.options.toastController.show(E instanceof Error?E.message:String(E),"error",5000)}}}}showInputDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"input",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=lG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showConfirmDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(!1);return}let B={kind:"confirm",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=lG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showSelectDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"select",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=lG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};createStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let B=this.statusItemKey(A,Q),E={pluginURI:A,id:Q};if($!==void 0)E.value=$;this.statusItems.set(B,E)})};updateStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.set(this.statusItemKey(A,Q),{pluginURI:A,id:Q,value:$})})};removeStatusItem=(A,Q)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.delete(this.statusItemKey(A,Q))})};readThreadMessages=(A,Q)=>{let $=this.options.readThreadMessages;if(!$)return Promise.reject(Error("thread.messages is not available - no active thread"));return $(A,Q)};readThreadTitle=(A)=>{let Q=this.options.readThreadTitle;if(!Q)return Promise.reject(Error("thread.title is not available - no active thread"));return Q(A)};subscribeThreadTitle=(A,Q)=>{let $=this.options.subscribeThreadTitle;if(!$)throw Error("thread.title.subscribe is not available - no active thread");return $(A,Q)};updateStatusItemState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}statusItemKey(A,Q){return`${A}\x00${Q}`}cancelPendingDialogs(){let A=[];if(this.activeDialog)A.push(this.activeDialog);A.push(...this.queuedDialogs),this.activeDialog=null,this.queuedDialogs=[],this.resolvingDialog=null,this.emitBlockingConfirmDialogChange();for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.abortUnsubscribe(),A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}abortDialog(A){if(this.activeDialog===A){this.advanceDialog(),this.cancelDialog(A);return}let Q=this.queuedDialogs.indexOf(A);if(Q===-1)return;this.updateDialogState(()=>{this.queuedDialogs.splice(Q,1)}),this.cancelDialog(A)}enqueueDialog(A){if(this.activeDialog){if(this.queuedDialogs.push(A),this.resolvingDialog===this.activeDialog)this.advanceResolvingDialog(this.activeDialog);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A}),this.emitBlockingConfirmDialogChange()}resolveInputDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveConfirmDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveSelectDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveDialog(A,Q){if(this.activeDialog!==A||this.resolvingDialog===A)return;this.resolvingDialog=A,A.abortUnsubscribe(),Q(),this.scheduleResolvingDialogAdvance(A,n86)}scheduleResolvingDialogAdvance(A,Q){W6.instance.addPostFrameCallback(()=>{if(this.activeDialog!==A)return;if(this.queuedDialogs.length>0||Q<=1){this.advanceResolvingDialog(A);return}this.scheduleResolvingDialogAdvance(A,Q-1)},"PluginIntegration.advanceDialog")}advanceResolvingDialog(A){if(this.resolvingDialog===A)this.resolvingDialog=null;if(this.activeDialog!==A)return;this.advanceDialog()}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A();this.emitBlockingConfirmDialogChange()}emitBlockingConfirmDialogChange(){let A=this.hasBlockingConfirmDialog();if(A===this.blockingConfirmDialog)return;this.blockingConfirmDialog=A,this.options.onBlockingConfirmDialogChange?.(A)}}n0();import{spawnSync as s86}from"node:child_process";import X9 from"node:process";var ew4={options:new Set(["settings-file","log-level","log-file","mcp-config"]),booleans:new Set(["color","dangerously-allow-all","ide","jetbrains","neo-orb","notifications"])};function _l(A){let Q=A.getRelaunchThreadIDs();if(A.onRelaunchRequested?.(Q),A.stop)A.stop();else V1.instance.stop()}function Au4(A){return{noun:"amp",verb:"Relaunch (Quit & Reopen)",description:"Quit, reopen Amp, and resume active threads",keywords:["restart","update"],shortcut:X9.env.NODE_ENV==="development"&&X9.platform==="darwin"?CA.meta("r"):void 0,status:{type:"enabled"},sortBoost:90,run:(Q,$,B)=>{B(),_l(A)}}}function t86(A,Q){let{command:$,args:B}=e86(A),E=X9.execve,D=X9.platform==="win32"||!E,J=D?"spawnSync":"execve";if(S.info("Relaunching Amp; threads will be resumed",{threadIDs:A,relaunchMethod:J}),D){let U=s86($,B,{cwd:Q,env:X9.env,stdio:"inherit"});if(U.error)return S.error("Failed to relaunch Amp",{error:U.error}),1;return U.status??1}try{if(X9.chdir(Q),$.includes("/"))return E($,[$,...B],X9.env);return E("/usr/bin/env",["env",$,...B],X9.env)}catch(U){return S.error("Failed to relaunch Amp",{error:U}),1}}class zm0{relaunchRequested=!1;requestedThreadIDs=[];request=(A)=>{S.info("Relaunch requested; threads will be resumed",{threadIDs:A}),this.relaunchRequested=!0,this.requestedThreadIDs=A};get shouldShowExitSummary(){return!this.relaunchRequested}relaunchIfRequested(A){if(!this.relaunchRequested)return;return t86(this.requestedThreadIDs,A)}}function e86(A){let Q=A.length>0?["threads","continue",...A]:[],$=A96(X9.argv),B=$96();if(B)return{command:B.command,args:[...B.args,...$,...Q]};let E=X9.argv[1],D=E&&Q96(E)?[E]:[];return{command:X9.execPath,args:[...D,...$,...Q]}}function A96(A){let Q=[],$=A.slice(2);for(let B=0;B<$.length;B+=1){let E=$[B];if(!E?.startsWith("--"))continue;let[D,J]=E.split("=",2);if(!D)continue;let U=D.slice(2),Y=U.startsWith("no-")?U.slice(3):U;if(ew4.booleans.has(Y)){Q.push(E);continue}if(!ew4.options.has(U))continue;if(J!==void 0){Q.push(E);continue}let Z=$[B+1];if(Z===void 0||Z.startsWith("--"))continue;Q.push(E,Z),B+=1}return Q}function Q96(A){return A!==X9.execPath&&!A.startsWith("/$bunfs/")}function $96(){if(X9.env.NODE_ENV!=="development")return null;let A=X9.env.AMP_DEV_RELAUNCH_COMMAND?.trim();if(!A)return null;let Q=B96(A),$=Q[0];if(!$)return null;return{command:$,args:Q.slice(1)}}function B96(A){if(A.startsWith("["))try{let Q=JSON.parse(A);if(Array.isArray(Q)&&Q.every(($)=>typeof $==="string"))return Q}catch{return[]}return A.split(/\s+/).filter(Boolean)}var E96=48;class Wm0{visible=!1;onClick=void 0;listeners=new Set;show(A){this.visible=!0,this.onClick=A,this.notifyListeners()}activate(){this.onClick?.()}get isVisible(){return this.visible}dismiss(){this.visible=!1,this.onClick=void 0,this.notifyListeners()}addListener(A){this.listeners.add(A)}removeListener(A){this.listeners.delete(A)}buildComplexToast(){if(!this.visible||!this.onClick)return null;return new Rl({width:E96,title:"Relaunch to Update Amp",message:"Your threads will resume.",variant:"success",mouseBehavior:"click-anywhere",action:{keyboardShortcut:"Ctrl+O",command:"amp: relaunch",confirmShortcut:"Enter",label:"relaunch",onAction:()=>this.activate()}})}notifyListeners(){for(let A of this.listeners)A()}}import{readFile as Y96}from"node:fs/promises";import Hm0 from"node:os";var D96=["command","args","url","transport","_target"];function Cm0(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}function J96(A){if(typeof A!=="string")return A;let Q=A.indexOf("?");return Q===-1?A:A.slice(0,Q)}function U96(A){if(!Cm0(A))return A;let Q={};for(let[$,B]of Object.entries(A)){if(!Cm0(B)){Q[$]=B;continue}let E={};for(let D of D96){if(!(D in B))continue;E[D]=D==="url"?J96(B[D]):B[D]}Q[$]=E}return Q}function Qu4(A){let Q=wO(A,[],{allowTrailingComma:!0});if(!Cm0(Q))return zP(A);let $={...Q};for(let B of Object.keys($))if(B==="mcpServers"||B==="amp.mcpServers")$[B]=U96($[B]);return zP(JSON.stringify($,null,2))}Y$();function Z96(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function $u4(A,Q,$=zP){try{return{path:Q,contents:$(await Y96(A,"utf8"))}}catch{return null}}async function h80(A,Q){let $=[],B=Z96(),E=await O4.getThread({thread:Q},{config:A.configService}),D=E.ok?E.result.thread.data:null;$.push({path:`${B}/thread.json`,contents:JSON.stringify(lD(D),null,2)});let J=await $u4(RP(Q),`${B}/logs/${Q}.log`);if(J)$.push(J);let U=await $u4(A.settingsFilePath,`${B}/settings/global.json`,Qu4);if(U)$.push(U);let Y=await aY()??"unknown",Z=await O4.sendReport({threadID:Q,files:$,metadata:{clientVersion:"0.0.1780677932-g159ed8",clientOS:`${Hm0.platform()} ${Hm0.release()} ${Hm0.arch()}`,installMethod:Y}},{config:A.configService});if(!Z.ok)throw Error(`Failed to submit report: ${Z.error.message}`);return Z.result.reportID}class Nm0{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.backStack.pop();this.forwardStack.push(Q)}}}}var F96=86400000;class qm0{options;subscription=null;relaunchNotificationShown=!1;relaunchNotificationPending=!1;relaunchNotificationTimer=null;openedAt=Date.now();constructor(A){this.options=A}init(){if(this.subscription=this.options.updateService?.state.subscribe((A)=>{this.handleUpdateState(A)})??null,process.env.DEV_SHOW_RELAUNCH_NOTIF_ON_STARTUP==="1")this.showUpdateRelaunchNotification(!0)}dispose(){if(this.subscription?.unsubscribe(),this.subscription=null,this.relaunchNotificationTimer)clearTimeout(this.relaunchNotificationTimer),this.relaunchNotificationTimer=null}handleUpdateState(A){if(A!=="updated")return;this.showUpdateRelaunchNotification()}showUpdateRelaunchNotification(A=!1){if(this.relaunchNotificationShown)return;let $=(this.options.minimumOpenDurationMs??F96)-(Date.now()-this.openedAt);if($>0&&!A){if(this.relaunchNotificationPending=!0,!this.relaunchNotificationTimer)this.relaunchNotificationTimer=setTimeout(()=>{if(this.relaunchNotificationTimer=null,!this.relaunchNotificationPending)return;this.relaunchNotificationPending=!1,this.showUpdateRelaunchNotification()},$),this.relaunchNotificationTimer.unref();return}this.relaunchNotificationPending=!1,this.relaunchNotificationShown=!0,this.options.relaunchNotificationController.show(()=>_l(this.options))}}class g80 extends v6{offstage;constructor({key:A,offstage:Q=!0,child:$}){super({key:A,child:$});this.offstage=Q}createRenderObject(){return new wm0(this.offstage)}updateRenderObject(A){if(A instanceof wm0)A.offstage=this.offstage}}class wm0 extends gA{_offstage;constructor(A){super();this._offstage=A}get offstage(){return this._offstage}set offstage(A){if(A===this._offstage)return;this._offstage=A,this.markNeedsLayout()}getMinIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicWidth(A)??0}getMaxIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicWidth(A)??0}getMinIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicHeight(A)??0}getMaxIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicHeight(A)??0}performLayout(){let A=this._lastConstraints;nA(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let $=A.constrain(Q.size.width,Q.size.height);this.setSize($.width,$.height),Q.setOffset(0,0)}else{let $=A.smallest;this.setSize($.width,$.height)}super.performLayout()}paint(A,Q,$){if(this._offstage)return;super.paint(A,Q,$)}hitTest(A,Q,$,B){if(this._offstage)return!1;return super.hitTest(A,Q,$,B)}}class Sl{_state=null;_attach(A){this._state=A}_detach(){this._state=null}push(A){this._state?.push(A)}pushWithDismiss(A){this._state?.pushWithDismiss(A)}pop(){return this._state?.pop()??!1}get canPop(){return this._state?.canPop??!1}}class um0 extends d0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new Bu4}}class Bu4 extends m0{entries=[];initState(){this.widget.controller._attach(this)}didUpdateWidget(A){if(A.controller!==this.widget.controller)A.controller._detach(),this.widget.controller._attach(this)}dispose(){this.widget.controller._detach(),super.dispose()}push(A){let Q=new iP,$=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:$})})}pushWithDismiss(A){let Q=new iP,$=this.makeScopedDismiss(Q),B=A($);this.setState(()=>{this.entries.push({key:Q,widget:B,dismiss:$})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new g80({offstage:this.entries.length>0,child:this.widget.root}));for(let $=0;$<this.entries.length;$++){let B=this.entries[$],E=$===this.entries.length-1,D=E?new C6({autofocus:!0,debugLabel:`ModalStackEntry[${$}]`,onKey:(J)=>{if(J.key!=="Escape")return"ignored";return B.dismiss(),"handled"},child:B.widget}):B.widget;Q.push(new g80({key:B.key,offstage:!E,child:D}))}return new EQ({fit:"expand",children:Q})}}class Om0 extends U4{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter((E)=>E.status.type!=="hidden"),$=I96(Q),B="";return new E1({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:p0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new L5({items:Q,showBorder:!1,getLabel:(E)=>{let D=Mm0(E);return E.keywords&&E.keywords.length>0?`${D} ${E.keywords.join(" ").toLowerCase()}`:D},onQueryChange:(E)=>{B=E},sortItems:(E,D,J)=>{B=J;let U=J.trim().toLowerCase();if(U===""){let V=E.item.status.type==="disabled"?1:0,K=D.item.status.type==="disabled"?1:0;if(V!==K)return V-K;let z=E.item.sortBoost??0,W=D.item.sortBoost??0;if(z!==W)return W-z;let C=E.item.noun?.toLowerCase()??"",H=D.item.noun?.toLowerCase()??"";if(C!==H)return C<H?-1:1;return 0}let Y=Eu4(E.item,U),Z=Eu4(D.item,U);if(Y!==Z)return Y?-1:1;let F=Mq(E.item.verb.toLowerCase(),J),X=Mq(D.item.verb.toLowerCase(),J);if(F!==X)return X-F;let I=Mq(Mm0(E.item),J),G=Mq(Mm0(D.item),J);if(I!==G)return G-I;return D.score-E.score},isItemDisabled:(E)=>E.status.type==="disabled",buildDisabledReasonWidget:(E,D)=>{if(E.status.type!=="disabled")return;let{colors:J}=QA.of(D);return new D0({text:new g(E.status.reason,new $0({color:J.mutedForeground,dim:!0})),textAlign:"center",maxLines:1,overflow:"ellipsis"})},renderItem:(E,D,J,U)=>new Du4({command:E,isSelected:D,isDisabled:J,categoryWidth:$,query:B,buildContext:U}),onAccept:(E)=>{this.props.onAccept(E)},onDismiss:this.props.onDismiss})})}}class Du4 extends U4{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:$,isDisabled:B,categoryWidth:E,query:D,buildContext:J}=this.props,U=QA.of(J),{colors:Y,app:Z}=U,F=$?Z.selectionBackground:void 0,X=$?Z.selectionForeground:Y.foreground,I=$?X:Y.mutedForeground,G=new D0({text:new g(Q.noun?.toLowerCase()??"",new $0({color:I,dim:B||!$})),textAlign:"right",maxLines:1,overflow:"ellipsis"}),V=Q.verb.toLowerCase();if(B)V+=" (unavailable)";let K=X96(Q,D);if(K)V+=` (alias: ${K})`;let z=new D0({text:new g(V,new $0({color:X,bold:!0,dim:B})),maxLines:1,overflow:"ellipsis"}),W=[{child:G,fixedWidth:E},{child:z,expanded:!0}];if(Q.shortcut)W.push({child:G96(Q.shortcut,U,B)});return new Ju4({columns:W,padding:p0.horizontal(1),backgroundColor:F})}}function Mm0(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function Eu4(A,Q){return A.keywords?.some(($)=>$.trim().toLowerCase()===Q)??!1}function X96(A,Q){let $=Q.trim().toLowerCase();if($==="")return;return A.keywords?.find((B)=>B.trim().toLowerCase()===$)}function I96(A){return A.reduce((Q,$)=>{return $.noun?Math.max(Q,fA($.noun)):Q},0)}function G96(A,Q,$){let{app:B}=Q,E=new $0({color:B.keybind,bold:!0,dim:$}),D=[],J=jX(A.toString()).split("+");for(let U=0;U<J.length;U++){if(U>0)D.push(new g("+",E));D.push(new g(J[U],E))}return D0.spans(D)}class Ju4 extends U4{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:$=2,padding:B,backgroundColor:E}=this.props,D=[];for(let U=0;U<Q.length;U++){let Y=Q[U];if(U>0&&$>0)D.push(new y0({width:$}));if(Y.fixedWidth!==void 0)D.push(new y0({width:Y.fixedWidth,child:Y.child}));else if(Y.expanded)D.push(new j4({child:Y.child}));else D.push(Y.child)}let J=new OA({crossAxisAlignment:"start",children:D});if(!B&&!E)return J;return new KA({decoration:E?{color:E}:void 0,padding:B,child:J})}}class Lm0{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#$(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#$()}}findByID(A){return this.#A.find((Q)=>Q.id===A)}runByID(A,Q){let $=this.findByID(A);if(!$||$.status.type!=="enabled")return!1;return $.run(new Sl,Q,()=>{}),!0}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#$(){for(let A of this.#Q)A()}}class aB extends oQ{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=aB.maybeOf(A);if(!Q)throw Error("No CommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(aB)?.commandRegistry??null}}class jm0 extends d0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new Uu4}}class Uu4 extends m0{modalStack=new Sl;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=aB.of(this.context);this.commandRegistry=A,A.addListener(this.onCommandsChanged)})}dispose(){this.commandRegistry?.removeListener(this.onCommandsChanged),this.commandRegistry=null,super.dispose()}onCommandsChanged=()=>{this.setState()};build(A){let Q=aB.of(A).commands,$=new Om0({commands:Q,onAccept:(B)=>{B.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new um0({root:$,controller:this.modalStack})}}var Yu4=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Move cursor left/right",methods:[{keys:["←"]},{keys:["→"]},{input:"B",keys:["Ctrl"]},{input:"F",keys:["Ctrl"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!0},{description:"Insert newline",methods:[{keys:["Enter"]},{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!1},{description:"Submit message",methods:[{keys:["Enter"]}],submitOnEnterOnly:!0},{description:"Submit message",methods:[{keys:["Ctrl/Cmd","Enter"]}],submitOnEnterOnly:!1},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]},{keys:["Ctrl","←"]},{input:"B",keys:["Alt"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]},{keys:["Ctrl","→"]},{input:"F",keys:["Alt"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]},{input:"H",keys:["Ctrl"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]},{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]}]},{description:"Toggle reasoning effort",methods:[{input:"D",keys:["Alt"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]},{description:"Mention threads",methods:[{keys:["@@"]}]},{description:"Show prompt history",methods:[{input:"R",keys:["Ctrl"]}]},{description:"Toggle inline shortcuts help",methods:[{keys:["?"]}]},{description:"Toggle thinking/dense view",methods:[{input:"T",keys:["Alt"]}]}],Zu4=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Half-page scroll",methods:[{input:"K",keys:["Alt"]},{input:"J",keys:["Alt"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class m80 extends U4{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let $=W4.of(A).size.width<50,B=[];for(let E of this.items){let[D,J]=this.renderRow(E),U;if($)U=new FA({crossAxisAlignment:"start",mainAxisSize:"min",children:[D,new mA({padding:p0.only({left:4}),child:J})]});else U=new OA({crossAxisAlignment:"start",children:[new j4({flex:1,child:D}),new y0({width:1}),new j4({flex:1,child:J})]});B.push(new mA({padding:p0.horizontal(6),child:U}))}return new FA({crossAxisAlignment:"start",mainAxisSize:"min",children:B})}}function V96(A){let Q=[...A.keys];if(A.input)Q.push(A.input);return jX(Q.join("+"))}class Rm0 extends U4{commands;onDismiss;constructor(A){super();this.commands=A.commands,this.onDismiss=A.onDismiss}build(A){let Q=QA.of(A),{colors:$,app:B}=Q,E=W4.of(A),D=new $0({color:$.secondary,bold:!0}),J=new $0({color:B.keybind}),U=new $0({color:B.command}),Y=new $0({color:$.foreground}),Z=Math.max(40,Math.min(80,E.size.width-4)),X=[...this.commands.filter((V)=>{let K=V.noun?.toLowerCase();return K!=="dev"&&K!=="debug"&&V.status.type!=="hidden"})].sort((V,K)=>{let z=(V.noun??"").toLowerCase(),W=(K.noun??"").toLowerCase(),C=z.localeCompare(W);if(C!==0)return C;return V.verb.toLowerCase().localeCompare(K.verb.toLowerCase())}),I=(V)=>{let K=V.methods.map((z)=>V96(z)).join(", ");return[new D0({text:new g(K,J)}),new D0({text:new g(V.description,Y)})]},G=new TB({autofocus:!0,child:new KA({constraints:new Z4(Z,Z,0,Number.POSITIVE_INFINITY),child:new FA({crossAxisAlignment:"start",mainAxisSize:"min",children:[new mA({padding:p0.horizontal(2),child:new D0({text:new g(`Editor Shortcuts
2994
+ ${$.errorMessage??""}`;if(Q.add(B),this.pluginErrorToastKeys.has(B))continue;this.options.toastController.show(this.formatPluginErrorToast($),"error",8000)}this.pluginErrorToastKeys=Q}removeInactivePluginStatusItems(A){let Q=new Set(A.filter((B)=>B.status==="active").map((B)=>B.uri.toString())),$=[];for(let[B,E]of this.statusItems){if(Q.has(E.pluginURI))continue;$.push(B)}if($.length===0)return;this.updateStatusItemState(()=>{for(let B of $)this.statusItems.delete(B)})}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.context.logFilePath}`}createPluginCommand(A){return{id:A.id,noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,status:A.availability,run:async(Q,$,B)=>{B();try{await this.options.context.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(E){S.error("Neo plugin command failed",{error:E,command:A}),this.options.toastController.show(E instanceof Error?E.message:String(E),"error",5000)}}}}showInputDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"input",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=lG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showConfirmDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(!1);return}let B={kind:"confirm",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=lG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showSelectDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"select",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=lG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};createStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let B=this.statusItemKey(A,Q),E={pluginURI:A,id:Q};if($!==void 0)E.value=$;this.statusItems.set(B,E)})};updateStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.set(this.statusItemKey(A,Q),{pluginURI:A,id:Q,value:$})})};removeStatusItem=(A,Q)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.delete(this.statusItemKey(A,Q))})};readThreadMessages=(A,Q)=>{let $=this.options.readThreadMessages;if(!$)return Promise.reject(Error("thread.messages is not available - no active thread"));return $(A,Q)};readThreadTitle=(A)=>{let Q=this.options.readThreadTitle;if(!Q)return Promise.reject(Error("thread.title is not available - no active thread"));return Q(A)};subscribeThreadTitle=(A,Q)=>{let $=this.options.subscribeThreadTitle;if(!$)throw Error("thread.title.subscribe is not available - no active thread");return $(A,Q)};updateStatusItemState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}statusItemKey(A,Q){return`${A}\x00${Q}`}cancelPendingDialogs(){let A=[];if(this.activeDialog)A.push(this.activeDialog);A.push(...this.queuedDialogs),this.activeDialog=null,this.queuedDialogs=[],this.resolvingDialog=null,this.emitBlockingConfirmDialogChange();for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.abortUnsubscribe(),A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}abortDialog(A){if(this.activeDialog===A){this.advanceDialog(),this.cancelDialog(A);return}let Q=this.queuedDialogs.indexOf(A);if(Q===-1)return;this.updateDialogState(()=>{this.queuedDialogs.splice(Q,1)}),this.cancelDialog(A)}enqueueDialog(A){if(this.activeDialog){if(this.queuedDialogs.push(A),this.resolvingDialog===this.activeDialog)this.advanceResolvingDialog(this.activeDialog);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A}),this.emitBlockingConfirmDialogChange()}resolveInputDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveConfirmDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveSelectDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveDialog(A,Q){if(this.activeDialog!==A||this.resolvingDialog===A)return;this.resolvingDialog=A,A.abortUnsubscribe(),Q(),this.scheduleResolvingDialogAdvance(A,n86)}scheduleResolvingDialogAdvance(A,Q){W6.instance.addPostFrameCallback(()=>{if(this.activeDialog!==A)return;if(this.queuedDialogs.length>0||Q<=1){this.advanceResolvingDialog(A);return}this.scheduleResolvingDialogAdvance(A,Q-1)},"PluginIntegration.advanceDialog")}advanceResolvingDialog(A){if(this.resolvingDialog===A)this.resolvingDialog=null;if(this.activeDialog!==A)return;this.advanceDialog()}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A();this.emitBlockingConfirmDialogChange()}emitBlockingConfirmDialogChange(){let A=this.hasBlockingConfirmDialog();if(A===this.blockingConfirmDialog)return;this.blockingConfirmDialog=A,this.options.onBlockingConfirmDialogChange?.(A)}}n0();import{spawnSync as s86}from"node:child_process";import X9 from"node:process";var ew4={options:new Set(["settings-file","log-level","log-file","mcp-config"]),booleans:new Set(["color","dangerously-allow-all","ide","jetbrains","neo-orb","notifications"])};function _l(A){let Q=A.getRelaunchThreadIDs();if(A.onRelaunchRequested?.(Q),A.stop)A.stop();else V1.instance.stop()}function Au4(A){return{noun:"amp",verb:"Relaunch (Quit & Reopen)",description:"Quit, reopen Amp, and resume active threads",keywords:["restart","update"],shortcut:X9.env.NODE_ENV==="development"&&X9.platform==="darwin"?CA.meta("r"):void 0,status:{type:"enabled"},sortBoost:90,run:(Q,$,B)=>{B(),_l(A)}}}function t86(A,Q){let{command:$,args:B}=e86(A),E=X9.execve,D=X9.platform==="win32"||!E,J=D?"spawnSync":"execve";if(S.info("Relaunching Amp; threads will be resumed",{threadIDs:A,relaunchMethod:J}),D){let U=s86($,B,{cwd:Q,env:X9.env,stdio:"inherit"});if(U.error)return S.error("Failed to relaunch Amp",{error:U.error}),1;return U.status??1}try{if(X9.chdir(Q),$.includes("/"))return E($,[$,...B],X9.env);return E("/usr/bin/env",["env",$,...B],X9.env)}catch(U){return S.error("Failed to relaunch Amp",{error:U}),1}}class zm0{relaunchRequested=!1;requestedThreadIDs=[];request=(A)=>{S.info("Relaunch requested; threads will be resumed",{threadIDs:A}),this.relaunchRequested=!0,this.requestedThreadIDs=A};get shouldShowExitSummary(){return!this.relaunchRequested}relaunchIfRequested(A){if(!this.relaunchRequested)return;return t86(this.requestedThreadIDs,A)}}function e86(A){let Q=A.length>0?["threads","continue",...A]:[],$=A96(X9.argv),B=$96();if(B)return{command:B.command,args:[...B.args,...$,...Q]};let E=X9.argv[1],D=E&&Q96(E)?[E]:[];return{command:X9.execPath,args:[...D,...$,...Q]}}function A96(A){let Q=[],$=A.slice(2);for(let B=0;B<$.length;B+=1){let E=$[B];if(!E?.startsWith("--"))continue;let[D,J]=E.split("=",2);if(!D)continue;let U=D.slice(2),Y=U.startsWith("no-")?U.slice(3):U;if(ew4.booleans.has(Y)){Q.push(E);continue}if(!ew4.options.has(U))continue;if(J!==void 0){Q.push(E);continue}let Z=$[B+1];if(Z===void 0||Z.startsWith("--"))continue;Q.push(E,Z),B+=1}return Q}function Q96(A){return A!==X9.execPath&&!A.startsWith("/$bunfs/")}function $96(){if(X9.env.NODE_ENV!=="development")return null;let A=X9.env.AMP_DEV_RELAUNCH_COMMAND?.trim();if(!A)return null;let Q=B96(A),$=Q[0];if(!$)return null;return{command:$,args:Q.slice(1)}}function B96(A){if(A.startsWith("["))try{let Q=JSON.parse(A);if(Array.isArray(Q)&&Q.every(($)=>typeof $==="string"))return Q}catch{return[]}return A.split(/\s+/).filter(Boolean)}var E96=48;class Wm0{visible=!1;onClick=void 0;listeners=new Set;show(A){this.visible=!0,this.onClick=A,this.notifyListeners()}activate(){this.onClick?.()}get isVisible(){return this.visible}dismiss(){this.visible=!1,this.onClick=void 0,this.notifyListeners()}addListener(A){this.listeners.add(A)}removeListener(A){this.listeners.delete(A)}buildComplexToast(){if(!this.visible||!this.onClick)return null;return new Rl({width:E96,title:"Relaunch to Update Amp",message:"Your threads will resume.",variant:"success",mouseBehavior:"click-anywhere",action:{keyboardShortcut:"Ctrl+O",command:"amp: relaunch",confirmShortcut:"Enter",label:"relaunch",onAction:()=>this.activate()}})}notifyListeners(){for(let A of this.listeners)A()}}import{readFile as Y96}from"node:fs/promises";import Hm0 from"node:os";var D96=["command","args","url","transport","_target"];function Cm0(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}function J96(A){if(typeof A!=="string")return A;let Q=A.indexOf("?");return Q===-1?A:A.slice(0,Q)}function U96(A){if(!Cm0(A))return A;let Q={};for(let[$,B]of Object.entries(A)){if(!Cm0(B)){Q[$]=B;continue}let E={};for(let D of D96){if(!(D in B))continue;E[D]=D==="url"?J96(B[D]):B[D]}Q[$]=E}return Q}function Qu4(A){let Q=wO(A,[],{allowTrailingComma:!0});if(!Cm0(Q))return zP(A);let $={...Q};for(let B of Object.keys($))if(B==="mcpServers"||B==="amp.mcpServers")$[B]=U96($[B]);return zP(JSON.stringify($,null,2))}Y$();function Z96(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function $u4(A,Q,$=zP){try{return{path:Q,contents:$(await Y96(A,"utf8"))}}catch{return null}}async function h80(A,Q){let $=[],B=Z96(),E=await O4.getThread({thread:Q},{config:A.configService}),D=E.ok?E.result.thread.data:null;$.push({path:`${B}/thread.json`,contents:JSON.stringify(lD(D),null,2)});let J=await $u4(RP(Q),`${B}/logs/${Q}.log`);if(J)$.push(J);let U=await $u4(A.settingsFilePath,`${B}/settings/global.json`,Qu4);if(U)$.push(U);let Y=await aY()??"unknown",Z=await O4.sendReport({threadID:Q,files:$,metadata:{clientVersion:"0.0.1780694019-g120cbb",clientOS:`${Hm0.platform()} ${Hm0.release()} ${Hm0.arch()}`,installMethod:Y}},{config:A.configService});if(!Z.ok)throw Error(`Failed to submit report: ${Z.error.message}`);return Z.result.reportID}class Nm0{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.backStack.pop();this.forwardStack.push(Q)}}}}var F96=86400000;class qm0{options;subscription=null;relaunchNotificationShown=!1;relaunchNotificationPending=!1;relaunchNotificationTimer=null;openedAt=Date.now();constructor(A){this.options=A}init(){if(this.subscription=this.options.updateService?.state.subscribe((A)=>{this.handleUpdateState(A)})??null,process.env.DEV_SHOW_RELAUNCH_NOTIF_ON_STARTUP==="1")this.showUpdateRelaunchNotification(!0)}dispose(){if(this.subscription?.unsubscribe(),this.subscription=null,this.relaunchNotificationTimer)clearTimeout(this.relaunchNotificationTimer),this.relaunchNotificationTimer=null}handleUpdateState(A){if(A!=="updated")return;this.showUpdateRelaunchNotification()}showUpdateRelaunchNotification(A=!1){if(this.relaunchNotificationShown)return;let $=(this.options.minimumOpenDurationMs??F96)-(Date.now()-this.openedAt);if($>0&&!A){if(this.relaunchNotificationPending=!0,!this.relaunchNotificationTimer)this.relaunchNotificationTimer=setTimeout(()=>{if(this.relaunchNotificationTimer=null,!this.relaunchNotificationPending)return;this.relaunchNotificationPending=!1,this.showUpdateRelaunchNotification()},$),this.relaunchNotificationTimer.unref();return}this.relaunchNotificationPending=!1,this.relaunchNotificationShown=!0,this.options.relaunchNotificationController.show(()=>_l(this.options))}}class g80 extends v6{offstage;constructor({key:A,offstage:Q=!0,child:$}){super({key:A,child:$});this.offstage=Q}createRenderObject(){return new wm0(this.offstage)}updateRenderObject(A){if(A instanceof wm0)A.offstage=this.offstage}}class wm0 extends gA{_offstage;constructor(A){super();this._offstage=A}get offstage(){return this._offstage}set offstage(A){if(A===this._offstage)return;this._offstage=A,this.markNeedsLayout()}getMinIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicWidth(A)??0}getMaxIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicWidth(A)??0}getMinIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicHeight(A)??0}getMaxIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicHeight(A)??0}performLayout(){let A=this._lastConstraints;nA(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let $=A.constrain(Q.size.width,Q.size.height);this.setSize($.width,$.height),Q.setOffset(0,0)}else{let $=A.smallest;this.setSize($.width,$.height)}super.performLayout()}paint(A,Q,$){if(this._offstage)return;super.paint(A,Q,$)}hitTest(A,Q,$,B){if(this._offstage)return!1;return super.hitTest(A,Q,$,B)}}class Sl{_state=null;_attach(A){this._state=A}_detach(){this._state=null}push(A){this._state?.push(A)}pushWithDismiss(A){this._state?.pushWithDismiss(A)}pop(){return this._state?.pop()??!1}get canPop(){return this._state?.canPop??!1}}class um0 extends d0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new Bu4}}class Bu4 extends m0{entries=[];initState(){this.widget.controller._attach(this)}didUpdateWidget(A){if(A.controller!==this.widget.controller)A.controller._detach(),this.widget.controller._attach(this)}dispose(){this.widget.controller._detach(),super.dispose()}push(A){let Q=new iP,$=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:$})})}pushWithDismiss(A){let Q=new iP,$=this.makeScopedDismiss(Q),B=A($);this.setState(()=>{this.entries.push({key:Q,widget:B,dismiss:$})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new g80({offstage:this.entries.length>0,child:this.widget.root}));for(let $=0;$<this.entries.length;$++){let B=this.entries[$],E=$===this.entries.length-1,D=E?new C6({autofocus:!0,debugLabel:`ModalStackEntry[${$}]`,onKey:(J)=>{if(J.key!=="Escape")return"ignored";return B.dismiss(),"handled"},child:B.widget}):B.widget;Q.push(new g80({key:B.key,offstage:!E,child:D}))}return new EQ({fit:"expand",children:Q})}}class Om0 extends U4{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter((E)=>E.status.type!=="hidden"),$=I96(Q),B="";return new E1({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:p0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new L5({items:Q,showBorder:!1,getLabel:(E)=>{let D=Mm0(E);return E.keywords&&E.keywords.length>0?`${D} ${E.keywords.join(" ").toLowerCase()}`:D},onQueryChange:(E)=>{B=E},sortItems:(E,D,J)=>{B=J;let U=J.trim().toLowerCase();if(U===""){let V=E.item.status.type==="disabled"?1:0,K=D.item.status.type==="disabled"?1:0;if(V!==K)return V-K;let z=E.item.sortBoost??0,W=D.item.sortBoost??0;if(z!==W)return W-z;let C=E.item.noun?.toLowerCase()??"",H=D.item.noun?.toLowerCase()??"";if(C!==H)return C<H?-1:1;return 0}let Y=Eu4(E.item,U),Z=Eu4(D.item,U);if(Y!==Z)return Y?-1:1;let F=Mq(E.item.verb.toLowerCase(),J),X=Mq(D.item.verb.toLowerCase(),J);if(F!==X)return X-F;let I=Mq(Mm0(E.item),J),G=Mq(Mm0(D.item),J);if(I!==G)return G-I;return D.score-E.score},isItemDisabled:(E)=>E.status.type==="disabled",buildDisabledReasonWidget:(E,D)=>{if(E.status.type!=="disabled")return;let{colors:J}=QA.of(D);return new D0({text:new g(E.status.reason,new $0({color:J.mutedForeground,dim:!0})),textAlign:"center",maxLines:1,overflow:"ellipsis"})},renderItem:(E,D,J,U)=>new Du4({command:E,isSelected:D,isDisabled:J,categoryWidth:$,query:B,buildContext:U}),onAccept:(E)=>{this.props.onAccept(E)},onDismiss:this.props.onDismiss})})}}class Du4 extends U4{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:$,isDisabled:B,categoryWidth:E,query:D,buildContext:J}=this.props,U=QA.of(J),{colors:Y,app:Z}=U,F=$?Z.selectionBackground:void 0,X=$?Z.selectionForeground:Y.foreground,I=$?X:Y.mutedForeground,G=new D0({text:new g(Q.noun?.toLowerCase()??"",new $0({color:I,dim:B||!$})),textAlign:"right",maxLines:1,overflow:"ellipsis"}),V=Q.verb.toLowerCase();if(B)V+=" (unavailable)";let K=X96(Q,D);if(K)V+=` (alias: ${K})`;let z=new D0({text:new g(V,new $0({color:X,bold:!0,dim:B})),maxLines:1,overflow:"ellipsis"}),W=[{child:G,fixedWidth:E},{child:z,expanded:!0}];if(Q.shortcut)W.push({child:G96(Q.shortcut,U,B)});return new Ju4({columns:W,padding:p0.horizontal(1),backgroundColor:F})}}function Mm0(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function Eu4(A,Q){return A.keywords?.some(($)=>$.trim().toLowerCase()===Q)??!1}function X96(A,Q){let $=Q.trim().toLowerCase();if($==="")return;return A.keywords?.find((B)=>B.trim().toLowerCase()===$)}function I96(A){return A.reduce((Q,$)=>{return $.noun?Math.max(Q,fA($.noun)):Q},0)}function G96(A,Q,$){let{app:B}=Q,E=new $0({color:B.keybind,bold:!0,dim:$}),D=[],J=jX(A.toString()).split("+");for(let U=0;U<J.length;U++){if(U>0)D.push(new g("+",E));D.push(new g(J[U],E))}return D0.spans(D)}class Ju4 extends U4{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:$=2,padding:B,backgroundColor:E}=this.props,D=[];for(let U=0;U<Q.length;U++){let Y=Q[U];if(U>0&&$>0)D.push(new y0({width:$}));if(Y.fixedWidth!==void 0)D.push(new y0({width:Y.fixedWidth,child:Y.child}));else if(Y.expanded)D.push(new j4({child:Y.child}));else D.push(Y.child)}let J=new OA({crossAxisAlignment:"start",children:D});if(!B&&!E)return J;return new KA({decoration:E?{color:E}:void 0,padding:B,child:J})}}class Lm0{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#$(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#$()}}findByID(A){return this.#A.find((Q)=>Q.id===A)}runByID(A,Q){let $=this.findByID(A);if(!$||$.status.type!=="enabled")return!1;return $.run(new Sl,Q,()=>{}),!0}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#$(){for(let A of this.#Q)A()}}class aB extends oQ{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=aB.maybeOf(A);if(!Q)throw Error("No CommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(aB)?.commandRegistry??null}}class jm0 extends d0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new Uu4}}class Uu4 extends m0{modalStack=new Sl;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=aB.of(this.context);this.commandRegistry=A,A.addListener(this.onCommandsChanged)})}dispose(){this.commandRegistry?.removeListener(this.onCommandsChanged),this.commandRegistry=null,super.dispose()}onCommandsChanged=()=>{this.setState()};build(A){let Q=aB.of(A).commands,$=new Om0({commands:Q,onAccept:(B)=>{B.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new um0({root:$,controller:this.modalStack})}}var Yu4=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Move cursor left/right",methods:[{keys:["←"]},{keys:["→"]},{input:"B",keys:["Ctrl"]},{input:"F",keys:["Ctrl"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!0},{description:"Insert newline",methods:[{keys:["Enter"]},{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!1},{description:"Submit message",methods:[{keys:["Enter"]}],submitOnEnterOnly:!0},{description:"Submit message",methods:[{keys:["Ctrl/Cmd","Enter"]}],submitOnEnterOnly:!1},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]},{keys:["Ctrl","←"]},{input:"B",keys:["Alt"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]},{keys:["Ctrl","→"]},{input:"F",keys:["Alt"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]},{input:"H",keys:["Ctrl"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]},{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]}]},{description:"Toggle reasoning effort",methods:[{input:"D",keys:["Alt"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]},{description:"Mention threads",methods:[{keys:["@@"]}]},{description:"Show prompt history",methods:[{input:"R",keys:["Ctrl"]}]},{description:"Toggle inline shortcuts help",methods:[{keys:["?"]}]},{description:"Toggle thinking/dense view",methods:[{input:"T",keys:["Alt"]}]}],Zu4=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Half-page scroll",methods:[{input:"K",keys:["Alt"]},{input:"J",keys:["Alt"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class m80 extends U4{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let $=W4.of(A).size.width<50,B=[];for(let E of this.items){let[D,J]=this.renderRow(E),U;if($)U=new FA({crossAxisAlignment:"start",mainAxisSize:"min",children:[D,new mA({padding:p0.only({left:4}),child:J})]});else U=new OA({crossAxisAlignment:"start",children:[new j4({flex:1,child:D}),new y0({width:1}),new j4({flex:1,child:J})]});B.push(new mA({padding:p0.horizontal(6),child:U}))}return new FA({crossAxisAlignment:"start",mainAxisSize:"min",children:B})}}function V96(A){let Q=[...A.keys];if(A.input)Q.push(A.input);return jX(Q.join("+"))}class Rm0 extends U4{commands;onDismiss;constructor(A){super();this.commands=A.commands,this.onDismiss=A.onDismiss}build(A){let Q=QA.of(A),{colors:$,app:B}=Q,E=W4.of(A),D=new $0({color:$.secondary,bold:!0}),J=new $0({color:B.keybind}),U=new $0({color:B.command}),Y=new $0({color:$.foreground}),Z=Math.max(40,Math.min(80,E.size.width-4)),X=[...this.commands.filter((V)=>{let K=V.noun?.toLowerCase();return K!=="dev"&&K!=="debug"&&V.status.type!=="hidden"})].sort((V,K)=>{let z=(V.noun??"").toLowerCase(),W=(K.noun??"").toLowerCase(),C=z.localeCompare(W);if(C!==0)return C;return V.verb.toLowerCase().localeCompare(K.verb.toLowerCase())}),I=(V)=>{let K=V.methods.map((z)=>V96(z)).join(", ");return[new D0({text:new g(K,J)}),new D0({text:new g(V.description,Y)})]},G=new TB({autofocus:!0,child:new KA({constraints:new Z4(Z,Z,0,Number.POSITIVE_INFINITY),child:new FA({crossAxisAlignment:"start",mainAxisSize:"min",children:[new mA({padding:p0.horizontal(2),child:new D0({text:new g(`Editor Shortcuts
2995
2995
  `,D)})}),new m80({items:Yu4.filter((V)=>V.submitOnEnterOnly===void 0||V.submitOnEnterOnly===!0),renderRow:I}),new y0({height:1}),new mA({padding:p0.horizontal(2),child:new D0({text:new g(`Scrolling & Navigation
2996
2996
  `,D)})}),new m80({items:Zu4,renderRow:I}),new y0({height:1}),new mA({padding:p0.horizontal(2),child:new D0({text:new g(`Command Palette Commands
2997
2997
  `,D)})}),new m80({items:X,renderRow:(V)=>{let K=V.noun?`${V.noun}: ${V.verb}`:V.verb;return[new D0({text:new g(K,U)}),new D0({text:new g(V.description,Y)})]}}),new y0({height:1})]})})});return new E1({header:"Amp CLI — Help & Keyboard Shortcuts",minWidth:Z,maxWidth:Z,maxHeight:E.size.height,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["↑↓","j/k"],label:"scroll"}],onDismiss:this.onDismiss,child:G})}}class qT extends oQ{completionBuilder;constructor({completionBuilder:A,child:Q}){super({child:Q});this.completionBuilder=A}updateShouldNotify(A){return!1}static of(A){let Q=A.dependOnInheritedWidgetOfExactType(qT);if(!Q)throw Error("No CompletionBuilderProvider found in widget tree");return Q.completionBuilder}}var K96=250,z96=2000;class Pm0 extends d0{configReloadEvents;toastController;child;constructor(A){super();this.configReloadEvents=A.configReloadEvents,this.toastController=A.toastController,this.child=A.child}createState(){return new Fu4}}class Fu4 extends m0{subscription=null;toastTimer=null;pendingToastType=null;lastToast=null;initState(){this.subscribeToConfigReloadEvents()}didUpdateWidget(A){if(A.configReloadEvents===this.widget.configReloadEvents)return;this.clearPendingToast(),this.subscribeToConfigReloadEvents()}dispose(){this.subscription?.unsubscribe(),this.subscription=null,this.clearPendingToast(),super.dispose()}build(A){return this.widget.child}subscribeToConfigReloadEvents(){this.subscription?.unsubscribe(),this.subscription=this.widget.configReloadEvents.subscribe((A)=>{this.scheduleToast(A)})}scheduleToast(A){if(this.pendingToastType=W96(this.pendingToastType,A),this.toastTimer)clearTimeout(this.toastTimer);this.toastTimer=setTimeout(()=>{if(!this.mounted)return;this.flushToast()},K96),this.toastTimer.unref()}flushToast(){let A=this.pendingToastType;if(this.clearPendingToast(),!A)return;let Q=Date.now();if(C96(this.lastToast,A,Q))return;this.lastToast={type:A,shownAt:Q},H96(this.widget.toastController,A)}clearPendingToast(){if(this.toastTimer)clearTimeout(this.toastTimer),this.toastTimer=null;this.pendingToastType=null}}function W96(A,Q){return A==="failed"||Q.type==="failed"?"failed":"succeeded"}function C96(A,Q,$){return A?.type===Q&&$-A.shownAt<z96}function H96(A,Q){switch(Q){case"succeeded":A.show("Config reloaded","success",1500);break;case"failed":A.show("Config reload failed","error",5000);break}}class SQ extends oQ{context;constructor({context:A,child:Q}){super({child:Q});this.context=A}updateShouldNotify(A){return!1}static of(A){let Q=A.dependOnInheritedWidgetOfExactType(SQ);if(!Q)throw Error("No ContextProvider found in widget tree");return Q.context}}n0();S8();var c80=80,N96=15,q96=1,Xu4=-c80,w96=16,u96=xb0(c80,c80);function Iu4({ampURL:A,threadID:Q,logPath:$}){return[`Debug thread ${xG(new URL(A),Q).toString()} (cli log: ${$}). Start with the CLI log, actor logs, and Rivet DB/inspector as sources of truth. Read thread-actors/docs/debugging-actors.md and thread-actors/scripts/README.md. For dev, actor logs are in .amp/in/thread-actors.json.log; for staging/prod, logs are in gcloud.`,"","Problem: "].join(`
@@ -3059,7 +3059,9 @@ ${$}`,this.imageAttachmentsController.setImages(A.queuedMessage.content.filter(E
3059
3059
 
3060
3060
  `,E));let J=Q.sections.flatMap((F)=>[F.name,...F.children?.map((X)=>` ${X.name}`)??[]]),U=Math.max(10,...J.map((F)=>fA(F))),Y=Math.min(U,42);for(let F of Q.sections){D.push(...this.formatSectionRow(F.name,F.tokens,F.percentage,{nameWidth:Y,nameStyle:$,valueStyle:B,percentStyle:E}));for(let X of F.children??[])D.push(...this.formatSectionRow(` ${X.name}`,X.tokens,X.percentage,{nameWidth:Y,nameStyle:E,valueStyle:E,percentStyle:E}))}let Z=(Q.totalTokens/Q.maxContextTokens*100).toFixed(1);return D.push(new g(`
3061
3061
  Used: `,$)),D.push(new g(`${g90(Q.totalTokens)} tokens`,B)),D.push(new g(` (${Z}% used)
3062
- `,E)),D.push(new g("Free: ",$)),D.push(new g(`${g90(Q.freeSpace)} tokens`,B)),D}formatSectionRow(A,Q,$,B){let E=n7(A,B.nameWidth),D=I50(E,B.nameWidth+2),J=I50(g90(Q),8,void 0,"right"),U=I50(`(${$.toFixed(1)}%)`,8,void 0,"right");return[new g(D,B.nameStyle),new g(J,B.valueStyle),new g(` ${U}
3062
+ `,E)),D.push(new g("Free: ",$)),D.push(new g(`${g90(Q.freeSpace)} tokens`,B)),D.push(new g(`
3063
+ ────────────────────────────────────────────────────────────────────
3064
+ `,E)),D.push(new g("Token counts are for the last inference request made in this thread.",E)),D}formatSectionRow(A,Q,$,B){let E=n7(A,B.nameWidth),D=I50(E,B.nameWidth+2),J=I50(g90(Q),8,void 0,"right"),U=I50(`(${$.toFixed(1)}%)`,8,void 0,"right");return[new g(D,B.nameStyle),new g(J,B.valueStyle),new g(` ${U}
3063
3065
  `,B.percentStyle)]}}_7();function tY6(A){return new Date(A).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}class jc0 extends U4{message;onDestruct;constructor({key:A,message:Q,onDestruct:$}){super(A?{key:A}:{});this.message=Q,this.onDestruct=$}build(A){let $=QA.of(A).colors,B=W4.of(A),E=new $0({color:$.foreground,dim:!0}),D=new $0({color:$.foreground}),J=Math.max(50,Math.min(80,B.size.width-4)),U=[{keys:["Esc"],label:"destroy message"}];return new E1({header:this.message.title,footer:U,visualStyle:{borderShape:"classic",borderAnimation:"mysterious-message",titleAnimation:"scramble"},chromePadding:p0.symmetric(2,2),minWidth:J,maxWidth:J,maxHeight:B.size.height,autofocus:!1,onDismiss:this.onDestruct,child:new M5({child:new TB({autofocus:!0,child:new FA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new $6({child:new D0({text:new g(tY6(this.message.visibleFrom),E)})}),new y0({height:1}),new D0({text:new g(this.message.body,D),selectable:!0})]})})})})}}var Rc0=[" ",".","·","·",":",":","•","•","●","●"],kT=0.5,Bz=64,eY6=30,Ui=0.9,Nj4=1.4,Pc0=Ui+Nj4,Tc0=6,Hj4=0.5,AZ6=1.6,QZ6=28;class vc0 extends d0{originX;originY;agentMode;primaryColor;secondaryColor;elapsed;fps;onComplete;constructor({originX:A,originY:Q,agentMode:$,primaryColor:B,secondaryColor:E,elapsed:D,fps:J=eY6,onComplete:U,key:Y}){super(Y?{key:Y}:{});this.originX=A,this.originY=Q,this.agentMode=$,this.primaryColor=B,this.secondaryColor=E,this.elapsed=D,this.fps=J,this.onComplete=U}createState(){return new qj4}}class qj4 extends m0{elapsed=0;timer=null;startMs=0;completed=!1;glow=new R5;initState(){if(super.initState(),this.widget.elapsed!==void 0){this.elapsed=this.widget.elapsed;return}if(this.startMs=performance.now(),this.widget.fps<=0){this.elapsed=Pc0,this.complete();return}let A=Math.max(16,Math.floor(1000/this.widget.fps));this.timer=setInterval(()=>{if(!this.mounted)return;if(this.elapsed=(performance.now()-this.startMs)/1000,this.elapsed>=Pc0){this.elapsed=Pc0,this.setState(()=>{}),this.complete();return}this.setState(()=>{})},A)}didUpdateWidget(A){if(super.didUpdateWidget(A),this.widget.elapsed!==void 0&&this.widget.elapsed!==A.elapsed)this.elapsed=this.widget.elapsed,this.setState(()=>{})}dispose(){if(this.timer)clearInterval(this.timer),this.timer=null;super.dispose()}complete(){if(this.completed)return;if(this.completed=!0,this.timer)clearInterval(this.timer),this.timer=null;this.widget.onComplete?.()}build(A){let Q=p4.of(A);return new wj4({originX:this.widget.originX,originY:this.widget.originY,elapsed:this.elapsed,agentMode:this.widget.agentMode,primaryColor:this.widget.primaryColor,secondaryColor:this.widget.secondaryColor,backgroundColor:Q.colorScheme.background,glow:this.glow})}}class wj4 extends YB{props;constructor(A,Q){super(Q?{key:Q}:{});this.props=A}createElement(){return new BJ(this)}createRenderObject(){return new uj4(this.props)}updateRenderObject(A){A.update(this.props)}}function $Z6(A){let Q=A>>>0;return()=>{Q=Q+1831565813>>>0;let $=Q;return $=Math.imul($^$>>>15,$|1),$^=$+Math.imul($^$>>>7,$|61),(($^$>>>14)>>>0)/4294967296}}class uj4 extends gA{_props;_palette=[];_paletteSignature="";_fragments=null;_fragmentRadius=0;constructor(A){super();this._props=A,this.rebuildPalette()}update(A){let Q=A.agentMode!==this._props.agentMode||A.primaryColor!==this._props.primaryColor||A.secondaryColor!==this._props.secondaryColor;if(this._props=A,Q)this.rebuildPalette();this.markNeedsPaint()}rebuildPalette(){let A=this._props.primaryColor&&this._props.secondaryColor?{primary:this._props.primaryColor,secondary:this._props.secondaryColor}:void 0;this._palette=Array.from({length:Bz},(Q,$)=>{let B=$/(Bz-1);return Y7(B,this._props.agentMode,A)}),this._paletteSignature=`${this._props.agentMode??"smart"}|${this._props.primaryColor?`${this._props.primaryColor.r},${this._props.primaryColor.g},${this._props.primaryColor.b}`:""}|${this._props.secondaryColor?`${this._props.secondaryColor.r},${this._props.secondaryColor.g},${this._props.secondaryColor.b}`:""}`}performLayout(){let A=this._lastConstraints,Q=A.constrain(A.biggest.width,A.biggest.height);this.setSize(Q.width,Q.height),super.performLayout()}getMaxRadius(A,Q){let $=A*Hj4,B=Q*Hj4*(1/kT);return Math.max(Tc0+1,Math.min($,B))}buildFragments(A){let Q=$Z6(2654435761),$=[],B=Rc0,E=Math.min(600,Math.max(120,Math.floor(A*A*0.45)));for(let D=0;D<E;D++){let J=Math.sqrt(Q()),U=Q()*Math.PI*2,Y=Math.cos(U)*J*A,Z=Math.sin(U)*J*A*kT,F=(0.5+J*0.9)*AZ6*A,X=0.7+Q()*0.6,I=Math.cos(U)*F*X,G=Math.sin(U)*F*X*kT-Q()*A*0.6,V=0.4+Q()*0.6,K=Math.min(B.length-1,Math.floor(V*B.length));$.push({x:Y,y:Z,vx:I,vy:G,glyph:B[K]||"*",intensity:V})}return $}paint(A,Q=0,$=0){let{elapsed:B,originX:E,originY:D,backgroundColor:J,glow:U}=this._props,Y=Q+this.offset.x,Z=$+this.offset.y,F=Math.floor(this.size.width),X=Math.floor(this.size.height),I=A.getSize(),G=I.width,V=I.height,K=this._palette;this._paletteSignature;let z=this.getMaxRadius(F,X),W=E-Y,C=D-Z;if(B<Ui){let L=1-(1-B/Ui)**3,R=Tc0+(z-Tc0)*L;this.paintOrb(A,Y,Z,W,C,R,1,B,U,K,J,G,V);return}if(!this._fragments||this._fragmentRadius!==z)this._fragments=this.buildFragments(z),this._fragmentRadius=z;let H=Math.min(1,(B-Ui)/Nj4);if(H<0.2){let u=1-H/0.2;this.paintOrb(A,Y,Z,W,C,z,u,B,U,K,J,G,V)}let N=B-Ui,w=1-H;for(let u of this._fragments){let L=u.x+u.vx*N,R=u.y+u.vy*N+0.5*QZ6*N*N,_=Math.round(Y+W+L),P=Math.round(Z+C+R);if(_<0||_>=G||P<0||P>=V)continue;let f=Math.max(0.05,u.intensity*w),h=Rc0,x=Math.min(h.length-1,Math.floor(f*h.length)),v=H>0.7?".":h[x]||u.glyph,k=Math.min(Bz-1,Math.floor(f*Bz)),c=K[k]||K[Bz-1];if(!c)continue;A.setCell(_,P,{char:v,width:1,style:{fg:c,bg:J,dim:H>0.55,bold:H<0.15}})}}paintOrb(A,Q,$,B,E,D,J,U,Y,Z,F,X,I){let G=Math.max(1,D),V=G*G,K=1/V,z=1/kT,W=Math.max(0,Math.floor(E-G*kT)),C=Math.min(I-$-1,Math.ceil(E+G*kT));for(let H=W;H<=C;H++){let N=$+H;if(N<0||N>=I)continue;let w=(H-E)*z,u=w*w;if(u>=V)continue;let L=Math.sqrt(V-u),R=Math.max(0,Math.floor(B-L)),_=Math.min(X-Q-1,Math.ceil(B+L));for(let P=R;P<=_;P++){let f=P-B,h=f*f+u;if(h>=V)continue;let x=1-h*K,v=Y.sample(P,H,U,1),k=v*x*J,c=Math.sqrt(h*K),d=f/G,b=w/G,p=Math.sqrt(Math.max(0,1-c*c)),n=Math.max(0,d*-0.45+b*-0.35+p*0.88),a=Math.max(0,1-p)**1.8,X0=Math.exp(-((d+0.28)*(d+0.28)*54+(b+0.32)*(b+0.32)*115));k=(0.12+x*0.16+n*0.6+a*0.34+X0*0.75+v*0.16)*J;let t=Rc0;if(k<0.08)continue;if(k<=0)continue;let Y0=Math.max(1,Math.min(t.length-1,Math.floor(k*t.length))),K0=t[Y0]||" ",R0=Math.min(Bz-1,Math.floor(k*Bz*1.2)),B0=Z[R0]||Z[Bz-1];if(!B0)continue;let W0=Q+P;if(W0<0||W0>=X)continue;A.setCell(W0,N,{char:K0,width:1,style:{fg:B0,bg:F,bold:k>0.65}})}}}}var _c0=5;class Sc0 extends YB{text;baseColor;backgroundColor;glow;time;agentMode;orbWidth;orbHeight;glowIntensity;shockwaves;constructor({key:A,text:Q,baseColor:$,backgroundColor:B,glow:E,time:D,agentMode:J,orbWidth:U=40,orbHeight:Y=40,glowIntensity:Z=0.4,shockwaves:F=[]}){super(A?{key:A}:{});this.text=Q,this.baseColor=$,this.backgroundColor=B,this.glow=E,this.time=D,this.agentMode=J,this.orbWidth=U,this.orbHeight=Y,this.glowIntensity=Z,this.shockwaves=F}createElement(){return new BJ(this)}createRenderObject(){return new Mj4(this.text,this.baseColor,this.backgroundColor,this.glow,this.time,this.agentMode,this.orbWidth,this.orbHeight,this.glowIntensity,this.shockwaves)}updateRenderObject(A){A.update(this.text,this.baseColor,this.backgroundColor,this.glow,this.time,this.agentMode,this.orbWidth,this.orbHeight,this.glowIntensity,this.shockwaves)}}var BZ6=0.5;class Mj4 extends gA{_text;_baseColor;_backgroundColor;_glow;_time;_agentMode;_orbWidth;_orbHeight;_glowIntensity;_shockwaves;constructor(A,Q,$,B,E,D,J,U,Y,Z){super();this._text=A;this._baseColor=Q;this._backgroundColor=$;this._glow=B;this._time=E;this._agentMode=D;this._orbWidth=J;this._orbHeight=U;this._glowIntensity=Y;this._shockwaves=Z}update(A,Q,$,B,E,D,J,U,Y,Z){let F=A!==this._text;if(this._text=A,this._baseColor=Q,this._backgroundColor=$,this._glow=B,this._time=E,this._agentMode=D,this._orbWidth=J,this._orbHeight=U,this._glowIntensity=Y,this._shockwaves=Z,F)this.markNeedsLayout();this.markNeedsPaint()}getMinIntrinsicWidth(A){return fA(this._text,!1)}getMaxIntrinsicWidth(A){return fA(this._text,!1)}getMinIntrinsicHeight(A){return 1}getMaxIntrinsicHeight(A){return 1}performLayout(){let A=this._lastConstraints;nA(!!A,"performLayout called without constraints");let Q=fA(this._text,!1),$=A.constrain(Q,1);this.setSize($.width,$.height),super.performLayout()}paint(A,Q=0,$=0){let B=Q+this.offset.x,E=$+this.offset.y,D=tA(this._text),J=this._agentMode==="rush"?2.5:1,{primary:U,secondary:Y}=dh0(this._agentMode),Z=B;for(let F=0;F<D.length;F++){let X=D[F],I=JQ(X,!1),V=(1-F/Math.max(D.length-1,1)*0.7)**1.2,K=this._glow.sample(this._orbWidth-2+F*0.5,this._orbHeight/2,this._time,J),z=0;for(let N of this._shockwaves){let w=this._time-N.startTime;if(w<0||w>l2)continue;let u=this._orbWidth*0.7+F,L=this._orbHeight/2,R=u-N.x,_=(L-N.y)/BZ6,P=Math.sqrt(R*R+_*_),f=w*_m0,h=Math.abs(P-f);if(h<kl){let x=1-w/l2,v=(1-h/kl)*x;z=Math.max(z,v*0.6)}}let W=K**0.7,C=Math.min(1,W*V+z),H=this.blendWithGlow(this._baseColor,C,U,Y);A.setCell(Z,E,{char:X,width:I,style:{fg:H,bg:this._backgroundColor}}),Z+=I}}blendWithGlow(A,Q,$,B){let E=Oq($,B,Q),D=Q*this._glowIntensity;if(A.type==="rgb"){let J=A.value,U=Math.round(J.r*(1-D)+E.r*D),Y=Math.round(J.g*(1-D)+E.g*D),Z=Math.round(J.b*(1-D)+E.b*D);return{type:"rgb",value:{r:U,g:Y,b:Z}}}if(D>0.15)return{type:"rgb",value:{r:E.r,g:E.g,b:E.b}};return A}}var Oj4=["ctrl+x","y","z"],Lj4=1.5,EZ6=2000,m90="!@#$%^&*()_+-=[]{}|;:,.<>?/~`0123456789",bc0="Welcome to ",Yi=2,fc0=1,jj4=Yi+fc0,Rj4=3.2,DZ6=0.18,JZ6=1.5,Pj4=1.4,Tj4=30,kc0=0.16,fj4=[{suffix:"the Orb",palettePosition:0.62},{suffix:"the Future",palettePosition:0.72},{suffix:"the Frontier",palettePosition:0.82},{suffix:"the Jungle",palettePosition:0.54},{suffix:"your Agent",palettePosition:0.68}],hc0={suffix:"Amp",palettePosition:0.98,final:!0},UZ6=[...fj4,hc0],YZ6=Math.max(...UZ6.map((A)=>fA(A.suffix,!1))),ZZ6=tA(bc0).length,FZ6=tA(`${bc0}${hc0.suffix}`).length;function XZ6(){let A=[...fj4];for(let Q=A.length-1;Q>0;Q--){let $=Math.floor(Math.random()*(Q+1)),B=A[Q];A[Q]=A[$],A[$]=B}return A.push(hc0),A}function IZ6(A,Q){let $=Q.length-1;if(A>=Yi)return Q[$];let B=Yi/$,E=Math.min($,Math.floor(A/B));return Q[E]}function vj4(A,Q){let $={color:A};if(Q)$.bold=!0;return new $0($)}function GZ6(A,Q){let B=Math.max(0,A-Yi)%Rj4/Rj4*1.6-0.3,E=Q/Math.max(1,FZ6-1),D=Math.abs(E-B);return Math.max(0,1-D/DZ6)**2}function _j4(A,Q,$,B,E,D){if(!D.bold)return new g(A,vj4(Y7(Q,B,E),!1));return new g("",void 0,tA(A).map((J,U)=>{let Y=GZ6($,D.characterOffset+U),Z=Y7(Math.min(1,Q+Y*0.14),B,E);return new g(J,vj4(Z,!0))}))}function VZ6(A,Q,$,B){let E=IZ6(A,Q),D="final"in E,J=Math.max(0,A-Yi),U=D&&J<fc0?Math.sin(J/fc0*Math.PI):0,Y=D?0.74+U*0.22:Math.max(0.34,E.palettePosition-0.24),Z=D?0.88+U*0.12:E.palettePosition,F=_j4(bc0,Y,A,$,B,{bold:D,characterOffset:0}),X=_j4(E.suffix,Z,A,$,B,{bold:D,characterOffset:ZZ6});return new OA({mainAxisSize:"min",children:[new D0({text:F}),new y0({width:YZ6,child:new _X({contentKey:E.suffix,durationMs:280,child:new D0({text:X})})})]})}function KZ6(A,Q,$){let B=Math.max(A.length,Q.length),E=[];for(let D=0;D<B;D++){let J=A[D]??" ",U=Q[D]??" ",Y=J===" "||J===`
3064
3066
  `||J==="\t",Z=U===" "||U===`
3065
3067
  `||U==="\t";if(Y&&Z){E.push($<0.5?J:U);continue}let F=D/B*0.4,X=Math.max(0,Math.min(1,($-F)/(1-F)));if(X===0)E.push(J);else if(X>=1)E.push(U);else if(Y)E.push(X<0.7?" ":U);else if(Z)E.push(X<0.3?J:" ");else if(X<0.5){let I=X*2;if(Math.random()<I)E.push(m90[Math.floor(Math.random()*m90.length)]);else E.push(J)}else{let I=(X-0.5)*2;if(Math.random()<I)E.push(U);else E.push(m90[Math.floor(Math.random()*m90.length)])}}return E.join("").trimEnd()}var zZ6="https://ampcode.com/news/neo",WZ6={type:"quote",text:'"Wait, a completely rebuilt Amp? Called Neo?"',url:zZ6,linkText:"Neo"},xc0=44,yc0=36,CZ6=26,HZ6=8,NZ6=8,gc0=50,d90=2,c90=4,qZ6=4,wZ6=20,uZ6={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},MZ6={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}};function OZ6(A){return A==="rush"?3.4:A==="deep"?0.9:1.45}function Sj4(A,Q,$){let B=(A-Q)/$;return Math.exp(-(B*B))}function LZ6(A){return 1-(1-Math.max(0,Math.min(1,A)))**3}function jZ6(A,Q){let $=OZ6(Q),B=0.35,E=4.5,D=72,J=A+1.4,U=Number.NEGATIVE_INFINITY;for(let Y=0;Y<72;Y++){let Z=Y/Math.max(1,71),F=A+0.35+4.15*Z,X=F*$,I=X*1.35,V=(Math.sin(I)+1)*0.5,K=1-Math.abs(Math.cos(I)),z=Math.cos(X*1.55)*0.38-0.18,W=Math.sin(X*1.15)*0.25-0.26,C=Sj4(z,-0.14,0.2)*0.45+Sj4(W,-0.29,0.12)*0.55,H=(1-Math.abs(Math.sin(X*1.55)))*0.5+(1-Math.abs(Math.cos(X*1.15)))*0.5,N=X*0.45,w=(1-Math.abs(Math.cos(N)))*0.6+(1-Math.abs(Math.sin(N*0.7)))*0.4,u=1-Z,L=V*0.34+K*0.24+C*0.22+H*0.12+w*0.04+u*0.04;if(L>U)U=L,J=F}return J}function kj4(A,Q){if(Q&&A==="smart")return{colorMode:"vertical",colors:uZ6};if(Q&&A==="deep")return{colorMode:"vertical",colors:MZ6};return{colorMode:"intensity"}}function RZ6(A,Q,$,B){if(A.type==="hint")return A.text.split(/(`[^`]+`)/g).map((D)=>{if(D.startsWith("`")&&D.endsWith("`"))return new g(D.slice(1,-1),$);return new g(D,Q)});if(A.url&&A.linkText){let E=A.text.indexOf(A.linkText);if(E>=0){let D=A.url,J=A.text.slice(0,E),U=A.text.slice(E+A.linkText.length);return[new g(J,Q),new g(A.linkText,Q.copyWith({underline:!0}),void 0,uX(D),()=>B(D)),new g(U,Q)]}}return[new g(A.text,Q)]}function xj4(A){return A.width<gc0+d90+wZ6+c90}function PZ6(A){let Q=xj4(A),$=Math.max(HZ6,Q?A.width-c90:A.width-gc0-d90-c90),B=Math.max(NZ6,A.height-qZ6),E=Math.min(xc0,$),D=Math.ceil(E/xc0*yc0),U=Math.min(Q?CZ6:yc0,B,D);return{width:E,height:U}}function TZ6(A,Q){return Y7(0.9,A,Q)}class mc0 extends d0{agentMode;primaryColor;secondaryColor;mysteriousMessage;mysterySequenceProgress;onOrbExplode;settleAnimation;interactive;useColors;centerContent;constructor(A={}){super(A.key?{key:A.key}:{});this.agentMode=A.agentMode,this.primaryColor=A.primaryColor,this.secondaryColor=A.secondaryColor,this.mysteriousMessage=A.mysteriousMessage,this.mysterySequenceProgress=A.mysterySequenceProgress,this.onOrbExplode=A.onOrbExplode,this.settleAnimation=A.settleAnimation??!1,this.interactive=A.interactive??!0,this.useColors=A.useColors??!1,this.centerContent=A.centerContent}createState(){return new yj4}}class yj4 extends m0{_glow;_WelcomeVariants;_t=0;_effectTime=0;_WelcomeTime=0;_timer=null;_fps=0;_animateWelcome=!1;_lastTickTimeMs=null;_settleStartTimeMs=null;_settleStartAnimationTime=null;_settleTargetAnimationTime=null;_shockwaves=[];_OrbClickComboCount=0;_OrbLastClickTime=null;_OrbChargeStartTime=null;_OrbRegrowStartTime=null;_suggestion;_morphStartTime=null;_previousHasMystery=!1;initState(){if(super.initState(),this._glow=new R5,this._WelcomeVariants=XZ6(),this._suggestion=WZ6,this._previousHasMystery=!!this.widget.mysteriousMessage,this.widget.settleAnimation)this.startSettlingAnimation()}didUpdateWidget(A){if(super.didUpdateWidget(A),!A.settleAnimation&&this.widget.settleAnimation)this.startSettlingAnimation()}getMorphProgress(A){if(this._morphStartTime===null)return null;let Q=A-this._morphStartTime;if(Q>=Lj4)return null;return Q/Lj4}handleShockwave=(A)=>{if(this._shockwaves.push(A),this._timer===null&&this._fps>0)this.startAnimation(this._fps,this._animateWelcome);this.setState(()=>{})};handleOrbClick=(A)=>{if(this.getOrbRegrowthScale(A.time)<1){this._OrbClickComboCount=0,this._OrbLastClickTime=null,this._OrbChargeStartTime=null;return}let Q=this._OrbLastClickTime===null?Number.POSITIVE_INFINITY:A.time-this._OrbLastClickTime,$=Q>=0&&Q<=JZ6;if(this._OrbClickComboCount=$?this._OrbClickComboCount+1:1,this._OrbLastClickTime=A.time,this._OrbChargeStartTime=A.time,this._timer===null&&this._fps>0)this.startAnimation(this._fps,this._animateWelcome);if(this._OrbClickComboCount>=_c0){this._OrbClickComboCount=0,this._OrbLastClickTime=null,this._OrbChargeStartTime=null,this._OrbRegrowStartTime=A.time;let B=kj4(this.widget.agentMode,this.widget.useColors).colors,E=this.widget.primaryColor&&this.widget.secondaryColor?{primary:this.widget.primaryColor,secondary:this.widget.secondaryColor}:B,D={x:A.x,y:A.y};if(E)D.primaryColor=E.primary,D.secondaryColor=E.secondary;this.widget.onOrbExplode?.(D)}this.setState(()=>{})};dispose(){if(this._timer)clearInterval(this._timer),this._timer=null;this._lastTickTimeMs=null,super.dispose()}startSettlingAnimation(){if(this._settleStartTimeMs!==null)return;this._settleStartTimeMs=Date.now(),this._settleStartAnimationTime=this._t,this._settleTargetAnimationTime=jZ6(this._t,this.widget.agentMode)}getSettleProgress(A){if(this._settleStartTimeMs===null)return null;return Math.min(1,Math.max(0,(A-this._settleStartTimeMs)/EZ6))}getCurrentEffectTime(){if(this._timer===null&&this._lastTickTimeMs!==null)return this._effectTime+(Date.now()-this._lastTickTimeMs)/1000;return this._effectTime}getOrbClickCharge(A=this.getCurrentEffectTime()){if(this._OrbChargeStartTime===null)return 0;let Q=A-this._OrbChargeStartTime;if(Q<0||Q>Pj4)return 0;let $=Math.min(1,this._OrbClickComboCount/Math.max(1,_c0-1)),B=1-Q/Pj4,E=Math.exp(-Q*4)*0.12;return Math.max(0,Math.min(1,$*(0.3+B*0.7)+E))}getOrbRegrowthScale(A=this.getCurrentEffectTime()){if(this._OrbRegrowStartTime===null)return 1;let Q=A-this._OrbRegrowStartTime;if(Q<=0)return kc0;if(Q>=Tj4)return 1;let $=Q/Tj4;return kc0+(1-kc0)*$}getAnimationSpeed(A){let Q=this.getSettleProgress(A);if(Q===null)return 1;return(1-Q)*(1-Q)}getSettledOrbTime(A){let Q=this.getSettleProgress(A);if(Q===null||this._settleStartAnimationTime===null||this._settleTargetAnimationTime===null)return null;return this._settleStartAnimationTime+(this._settleTargetAnimationTime-this._settleStartAnimationTime)*LZ6(Q)}isWelcomeAnimationPending(){return this._animateWelcome&&this._WelcomeTime<jj4}isClickEffectPending(){let A=this.getCurrentEffectTime();return this._shockwaves.some((Q)=>A-Q.startTime<l2)||this.getOrbClickCharge(A)>0||this.getOrbRegrowthScale(A)<1}stopAnimationTimer(){if(this._timer)clearInterval(this._timer),this._timer=null;this._lastTickTimeMs=null}startAnimation(A,Q){if(this.stopAnimationTimer(),this._fps=A,this._animateWelcome=Q,A>0&&(this.getAnimationSpeed(Date.now())>0||this.isWelcomeAnimationPending()||this.isClickEffectPending()))this._lastTickTimeMs=Date.now(),this._timer=setInterval(()=>{let $=Date.now(),B=this.getAnimationSpeed($);if(B<=0&&!this.isWelcomeAnimationPending()&&!this.isClickEffectPending()){let D=this.getSettledOrbTime($);if(D!==null)this._t=D;this.stopAnimationTimer(),this.setState(()=>{});return}let E=this._lastTickTimeMs===null?1/A:($-this._lastTickTimeMs)/1000;if(this._lastTickTimeMs=$,this._effectTime+=E,this._animateWelcome)this._WelcomeTime+=E;if(B>0){let D=this.getSettledOrbTime($);this._t=D??this._t+E*B}this._shockwaves=this._shockwaves.filter((D)=>this._effectTime-D.startTime<l2),this.setState(()=>{})},1000/A)}build(A){let $=p4.of(A).colorScheme,B=W4.of(A),E=B.capabilities.animationSupport,D=E==="fast"?30:E==="slow"?15:0,J=E==="fast";if(D!==this._fps||J!==this._animateWelcome)this.startAnimation(D,J);let U=!!this.widget.mysteriousMessage,Y=this._suggestion,Z=E==="disabled"?3:this._t,F=E==="disabled"?jj4:this._WelcomeTime;if(U&&!this._previousHasMystery&&E!=="disabled")this._morphStartTime=Z;this._previousHasMystery=U;let X=this.getMorphProgress(Z),I=X!==null,G=kj4(this.widget.agentMode,this.widget.useColors),V=this.widget.primaryColor&&this.widget.secondaryColor?{primary:this.widget.primaryColor,secondary:this.widget.secondaryColor}:G.colors,K=TZ6(this.widget.agentMode,V),z=new $0({color:$.foreground,dim:!0}),W=new $0({color:$.foreground,bold:!0}),C=new $0({color:K}),H=new $0({color:$.foreground,dim:!0}),N=RZ6(Y,z,C,(p)=>{i6(A,p)}),w=E==="fast",u;if(J)u=VZ6(F,this._WelcomeVariants,this.widget.agentMode,V);else u=new D0({text:new g("Welcome to Amp",new $0({color:$.foreground}))});let L=null;if(U){let n=0.3+(Math.sin(Z*0.5)*0.5+0.5)*0.4,a=new $0({color:$.primary,italic:!0,dim:n<0.5}),t=this.widget.mysterySequenceProgress?.matched.length??0,Y0=t>0?"Keep going...":"A message awaits...",K0=[];for(let R0=0;R0<Oj4.length;R0++){let B0=Oj4[R0],W0=B0==="ctrl+x"?"Ctrl-X":B0.toUpperCase(),i=R0<t?new $0({color:$.primary,bold:!0}):W;if(R0>0)K0.push(new g(", ",H));K0.push(new g(W0,i))}L=new FA({crossAxisAlignment:"start",mainAxisSize:"min",children:[w?new Sc0({text:Y0,baseColor:$.primary,glow:this._glow,time:Z,agentMode:this.widget.agentMode,orbWidth:xc0,orbHeight:yc0,glowIntensity:0.6,shockwaves:this._shockwaves}):new D0({text:new g(Y0,a)}),new D0({text:new g("",void 0,[...K0,new g(" to unlock",H)])})]})}let R,_=`A message awaits...
@@ -3084,7 +3086,7 @@ Ctrl-X, Y, Z to unlock`;if(this.widget.centerContent)R=this.widget.centerContent
3084
3086
  `));if(U.tools.length===0)J.push(new g(` └─ No tools available
3085
3087
  `,E));else for(let F of U.tools)CF6(J,F,$);J.push(new g(`
3086
3088
  `))}return J}function CF6(A,Q,$){let{colors:B,app:E}=$,D=HF6(Q.status,$);if(A.push(new g(` ${D.icon} `,new $0({color:D.color}))),A.push(new g(Q.name,new $0({color:Q.status==="pending"?B.warning:E.command}))),Q.status==="pending")A.push(new g(" discovering...",new $0({color:B.foreground,dim:!0})));else if(Q.description)A.push(new g(` ${XR4(Q.description,50)}`,new $0({color:B.foreground,dim:!0})));if(Q.error)A.push(new g(` ${XR4(Q.error,40)}`,new $0({color:E.toolError})));A.push(new g(`
3087
- `))}function HF6(A,Q){let{colors:$,app:B}=Q;switch(A){case"pending":return{icon:"◌",color:$.warning};case"registered":return{icon:"•",color:$.mutedForeground};case"failed":return{icon:"✗",color:B.toolError};case"duplicate":return{icon:"◇",color:$.warning};default:return{icon:"?",color:$.foreground}}}function XR4(A,Q){let $=A.replace(/\s+/g," ").trim();if(fA($)<=Q)return $;let B="...",E=fA(B);if(Q<=E)return n7(B,Q);return`${n7($,Q-E,!0,"")}${B}`}var Bp0="https://ampcode.com/news/neo",Ep0=[{title:"Meet the new Amp CLI",body:[]},{title:"Rebuilt From The Ground Up",body:["Same close-up terminal workflow. Completely different underneath."]},{title:"Just Keep Typing",body:["Context is summarized automatically at ~90%.","No handoff flow. No context percentage to babysit."]},{title:"Queueing and Steering",body:["Sending a message now queues by default instead of cancelling tools.","Use steering when you want the agent to see something sooner."]},{title:"Remote Control",body:["Start a thread in the CLI, then keep going from ampcode.com.","Watch live updates and queue follow-ups from any device."]},{title:"Customize Amp with Amp",body:[{text:"Amp now has a ",linkText:"complete plugin API",href:"https://ampcode.com/manual/plugin-api",textAfter:"."},"Add tools, commands, control UI, and hook into events."]},{title:"Permissions",body:[{text:"By default (when no ",highlightText:"amp.permissions",textAfterHighlight:" setting is present), Amp no longer asks for confirmation before running any tools and commands. And you can now implement your own custom permission logic with ",linkText:"plugins",href:"https://ampcode.com/manual/plugin-api",textAfter:"."}]},{title:null,body:["Check out the full news post for more:",{text:Bp0,href:Bp0}]}];function NF6(A){return[{title:"Upgrade your Amp CLI",body:[{text:"This npm-based distribution of Amp CLI has been deprecated. To use the ",linkText:"new Amp CLI",href:Bp0,textAfter:" you'll need to switch to the binary install:",linkWidget:!0},"",{codeBlock:["npm uninstall -g @sourcegraph/amp",A]}]}]}function qF6(){if(process.platform==="win32")return'powershell -c "irm https://ampcode.com/install.ps1 | iex"';return"curl -fsSL https://ampcode.com/install.sh | bash"}var fT=50,nq=40,Qp0=1000,wF6=420,uF6=760,MF6=-250,OF6=1100,a90=33,KR4=0.999,LF6=2.1,jF6=720,RF6=420,uR4="Meet the new",MR4="Amp",OR4="CLI",Dp0=tA(uR4).length,PF6=tA(MR4).length,TF6=tA(OR4).length,o90={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}},zR4={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},WR4={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}},CR4=[o90,zR4,WR4,o90,zR4,WR4,o90],vF6=o90;class Jp0 extends d0{onDismiss;onQuit;animationProgress;animationsEnabled;variant;binaryInstallCommand;introStages;dismissible;constructor(A){super();this.onDismiss=A.onDismiss,this.onQuit=A.onQuit,this.animationProgress=A.animationProgress,this.animationsEnabled=A.animationsEnabled??!0,this.variant=A.variant??"intro",this.binaryInstallCommand=A.binaryInstallCommand??qF6(),this.introStages=this.variant==="npm-migration"?NF6(this.binaryInstallCommand):Ep0,this.dismissible=this.variant!=="npm-migration"}createState(){return new LR4}}class LR4 extends m0{startedAt=performance.now();animationTimer=null;stageTransitionTimer=null;firstStageTitleTimer=null;firstStageHintTimer=null;firstStageRevealTimer=null;firstStageTitleRevealStartedAt=null;firstStageHintRevealStartedAt=null;stageTransitionStartedAt=performance.now();animationStartProgress=0;animationTargetProgress=1;animationDurationMs=Qp0;onAnimationComplete=null;animationProgress=0;introStage=0;previousIntroStage=null;stageTransitionProgress=1;stageTransitionDirection=1;firstStageTitleVisible=!1;firstStageHintVisible=!1;firstStageTitleRevealProgress=0;firstStageHintRevealProgress=0;dismissTimer=null;dismissStartedAt=performance.now();dismissProgress=0;isDismissing=!1;splashOrbGlow=new R5(42);initState(){super.initState(),this.startAnimationIfNeeded()}didUpdateWidget(A){if(super.didUpdateWidget(A),A.animationProgress!==this.widget.animationProgress||A.animationsEnabled!==this.widget.animationsEnabled)this.startAnimationIfNeeded()}dispose(){this.stopAnimation(),this.stopStageTransitionTimer(),this.stopFirstStageRevealTimers(),this.stopDismissAnimation(),super.dispose()}startAnimationIfNeeded(){if(this.stopAnimation(),this.stopFirstStageRevealTimers(),this.widget.animationProgress!==void 0){this.animationProgress=ME(this.widget.animationProgress),this.firstStageTitleVisible=this.animationProgress>=KR4,this.firstStageHintVisible=this.animationProgress>=KR4,this.firstStageTitleRevealProgress=this.firstStageTitleVisible?1:0,this.firstStageHintRevealProgress=this.firstStageHintVisible?1:0;return}if(!this.widget.animationsEnabled){this.stopStageTransitionTimer(),this.stopDismissAnimation(),this.animationProgress=1,this.isDismissing=!1,this.dismissProgress=0,this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1,this.previousIntroStage=null,this.stageTransitionProgress=1;return}if(this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0,this.startProgressAnimation({from:0,to:1,durationMs:Qp0,onComplete:()=>{if(!this.widget.dismissible)this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1})}}),this.widget.dismissible)this.startFirstStageRevealSequence()}startDismissAnimation(){if(this.isDismissing)return;if(!this.widget.animationsEnabled){this.widget.onDismiss();return}this.stopFirstStageRevealTimers(),this.stopStageTransitionTimer(),this.dismissStartedAt=performance.now(),this.setState(()=>{this.isDismissing=!0,this.dismissProgress=0}),this.dismissTimer=setInterval(()=>{let A=performance.now()-this.dismissStartedAt,Q=ME(A/uF6);if(this.setState(()=>{this.dismissProgress=Q}),Q>=1)this.stopDismissAnimation(),this.widget.onDismiss()},a90)}canNavigateIntroStage(){if(this.isDismissing)return!1;if(!this.firstStageHintVisible)return!1;if(this.introStage===0&&this.firstStageHintRevealProgress<1)return!1;return!0}advanceIntroStage(){if(!this.canNavigateIntroStage())return;if(this.isFinalIntroStage()){if(this.widget.dismissible)this.startDismissAnimation();return}this.moveIntroStage(1)}dismissFromFinalIntroStage(){if(!this.widget.dismissible||!this.canNavigateIntroStage()||!this.isFinalIntroStage())return!1;return this.startDismissAnimation(),!0}nextIntroStage(){if(!this.canNavigateIntroStage()||this.isFinalIntroStage())return;this.moveIntroStage(1)}goToPreviousIntroStage(){if(!this.canNavigateIntroStage()||this.introStage<=0)return;this.moveIntroStage(-1)}isFinalIntroStage(){return this.introStage>=this.widget.introStages.length-1}moveIntroStage(A){let Q=this.introStage+A;if(this.stopStageTransitionTimer(),this.stageTransitionStartedAt=performance.now(),this.setState(()=>{this.previousIntroStage=this.introStage,this.introStage=Q,this.stageTransitionDirection=A}),this.widget.animationProgress!==void 0||!this.widget.animationsEnabled){this.setState(()=>{this.previousIntroStage=null,this.stageTransitionProgress=1});return}this.setState(()=>{this.stageTransitionProgress=0}),this.stageTransitionTimer=setInterval(()=>{let $=performance.now()-this.stageTransitionStartedAt,B=ME($/wF6);if(this.setState(()=>{if(this.stageTransitionProgress=B,B>=1)this.previousIntroStage=null}),B>=1)this.stopStageTransitionTimer()},a90)}startProgressAnimation({from:A,to:Q,durationMs:$,onComplete:B}){this.stopAnimation(),this.startedAt=performance.now(),this.animationStartProgress=A,this.animationTargetProgress=Q,this.animationDurationMs=$,this.onAnimationComplete=B,this.animationProgress=A,this.animationTimer=setInterval(()=>{let E=performance.now()-this.startedAt,D=ME(E/this.animationDurationMs),J=this.animationStartProgress+(this.animationTargetProgress-this.animationStartProgress)*xT(D);if(this.setState(()=>{this.animationProgress=J}),D>=1)this.stopAnimation(),this.onAnimationComplete?.(),this.onAnimationComplete=null},a90)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null}stopStageTransitionTimer(){if(this.stageTransitionTimer)clearInterval(this.stageTransitionTimer),this.stageTransitionTimer=null}startFirstStageRevealSequence(){if(this.stopFirstStageRevealTimers(),!this.widget.animationsEnabled){this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1});return}this.setState(()=>{this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0});let A=Math.max(0,Qp0+MF6),Q=A+OF6;this.firstStageTitleTimer=setTimeout(()=>{this.firstStageTitleRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageTitleRevealProgress=0}),this.startFirstStageRevealTimer()},A),this.firstStageHintTimer=setTimeout(()=>{this.firstStageHintRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageHintVisible=!0,this.firstStageHintRevealProgress=0}),this.startFirstStageRevealTimer()},Q)}startFirstStageRevealTimer(){if(this.firstStageRevealTimer)return;this.firstStageRevealTimer=setInterval(()=>{let A=performance.now(),Q=this.firstStageTitleRevealStartedAt?ME((A-this.firstStageTitleRevealStartedAt)/jF6):this.firstStageTitleRevealProgress,$=this.firstStageHintRevealStartedAt?ME((A-this.firstStageHintRevealStartedAt)/RF6):this.firstStageHintRevealProgress;if(this.setState(()=>{this.firstStageTitleRevealProgress=Q,this.firstStageHintRevealProgress=$}),Q>=1&&$>=1)this.stopFirstStageRevealTimer()},a90)}stopFirstStageRevealTimers(){if(this.stopFirstStageRevealTimer(),this.firstStageTitleRevealStartedAt=null,this.firstStageHintRevealStartedAt=null,this.firstStageTitleTimer)clearTimeout(this.firstStageTitleTimer),this.firstStageTitleTimer=null;if(this.firstStageHintTimer)clearTimeout(this.firstStageHintTimer),this.firstStageHintTimer=null}stopFirstStageRevealTimer(){if(this.firstStageRevealTimer)clearInterval(this.firstStageRevealTimer),this.firstStageRevealTimer=null}stopDismissAnimation(){if(this.dismissTimer)clearInterval(this.dismissTimer),this.dismissTimer=null}currentOrbPalette(){let A=HR4(this.introStage),Q=this.previousIntroStage===null||this.stageTransitionProgress>=1?A:NR4(HR4(this.previousIntroStage),A,xT(this.stageTransitionProgress));return this.dismissProgress>0?NR4(Q,vF6,xT(this.dismissProgress)):Q}build(A){let Q=p4.of(A).colorScheme,$=QA.of(A),B=this.currentOrbPalette(),E=Y7(1,"deep",B),D=W4.of(A).size,U=this.widget.animationProgress??this.animationProgress,Y=Math.max(D.width/fT,D.height/nq)*LF6,Z=Y+(1-Y)*U,F=xT(this.dismissProgress),X=Math.max(fT,Math.round(fT*Z)),I=Math.max(nq,Math.round(nq*Z)),G=Math.round((D.width-X)/2),V=Math.round((D.height-I)/2),K=Math.max(0,Math.floor((D.width-fT)/2)),z=-Math.floor(nq/2),W=Math.round(G+(K-G)*U),C=Math.round(V+(z-V)*U),H=W+X/2,N=C+I/2,w=_F6({dismissProgress:this.dismissProgress,easedDismissProgress:F,introOrbScale:Z,normalOrbCenterX:H,normalOrbCenterY:N,size:D}),u=Math.max(fT,Math.round(fT*w.orbScale)),L=Math.max(nq,Math.round(nq*w.orbScale)),R=w.orbCenterX,_=w.orbCenterY,P=Math.round(R-u/2),f=Math.round(_-L/2),h=Math.max(3,Math.min(D.height-5,Math.floor(nq/2)+2)),x=Math.max(h+3,D.height-3),v=w.textDissolveProgress,k=this.isFinalIntroStage()?w.backdropDissolveProgress:0,c=this.firstStageTitleVisible&&v<1,d=c&&this.firstStageHintVisible,b=d&&this.widget.dismissible&&this.introStage>0&&!this.isFinalIntroStage(),p=this.introStage===0?this.firstStageTitleRevealProgress:1,n=this.introStage===0?this.firstStageHintRevealProgress:1,a=Math.max(24,Math.min(74,D.width-4)),X0=Math.min(12,Math.max(8,D.height-h-6)),t=Math.max(0,Math.floor((D.width-a)/2)),Y0=Math.max(0,Math.min(D.height-X0,Math.floor(D.height*0.55-X0/2))),R0=this.widget.animationProgress!==void 0||!this.widget.animationsEnabled?new iK({width:u,height:L,agentMode:"deep",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,seed:42,fps:0,onClick:()=>{}}):new iK({width:u,height:L,agentMode:"deep",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,onClick:()=>{}});return new C6({autofocus:!0,canRequestFocus:!0,debugLabel:"WelcomeTakeover",onKey:(B0)=>{if(B0.key==="Enter")return this.advanceIntroStage(),"handled";if(!this.widget.dismissible&&B0.key==="c"&&B0.ctrlKey)return this.widget.onQuit?.(),"handled";if(!this.widget.dismissible&&B0.key==="q")return this.widget.onQuit?.(),"handled";if((B0.key===" "||B0.key==="Space")&&!this.isFinalIntroStage())return this.advanceIntroStage(),"handled";if(B0.key==="Escape"||B0.key==="Esc"){if(!this.widget.dismissible)return this.widget.onQuit?.(),"handled";return this.dismissFromFinalIntroStage()?"handled":"ignored"}if(B0.key==="ArrowRight")return this.nextIntroStage(),"handled";if(B0.key==="ArrowLeft")return this.goToPreviousIntroStage(),"handled";return"ignored"},child:new EQ({fit:"expand",children:[new jR4({color:Q.background,dissolveProgress:k}),new EQ({fit:"expand",children:[new aA({onClick:()=>{},child:y0.expand()}),new e1({left:P,top:f,width:u,height:L,child:R0}),...c?[new e1({left:t,top:Y0,width:a,height:X0,child:kF6({introStages:this.widget.introStages,stage:this.introStage,previousStage:this.previousIntroStage,progress:this.stageTransitionProgress,direction:this.stageTransitionDirection,width:a,height:X0,foreground:Q.foreground,mutedForeground:Q.mutedForeground,accent:E,link:$.app.link,keybind:$.app.keybind,titleRevealProgress:p,dissolveProgress:v,context:A})})]:[],...d?[...b?[new e1({left:t,top:Math.max(0,x-1),width:a,height:1,child:new D0({text:gF6({stage:this.introStage,featureStageCount:Math.max(0,this.widget.introStages.length-2),foreground:Q.mutedForeground,dissolveProgress:v}),textAlign:"center"})})]:[],new e1({left:t,top:x,width:a,height:1,child:dF6({finalStage:this.isFinalIntroStage(),dismissible:this.widget.dismissible,foreground:Q.mutedForeground,keybind:$.app.keybind,revealProgress:n,dissolveProgress:v,context:A})})]:[]]})]})})}}class jR4 extends YB{color;dissolveProgress;constructor({color:A,dissolveProgress:Q}){super();this.color=A,this.dissolveProgress=Q}createRenderObject(){return new RR4(this.color,this.dissolveProgress)}updateRenderObject(A){A.update(this.color,this.dissolveProgress)}}class RR4 extends gA{color;dissolveProgress;constructor(A,Q){super();this.color=A,this.dissolveProgress=Q}update(A,Q){this.color=A,this.dissolveProgress=Q,this.markNeedsPaint()}performLayout(){let A=this._lastConstraints;nA(!!A,"performLayout called without constraints");let Q=A.constrain(A.biggest.width,A.biggest.height);this.setSize(Q.width,Q.height),super.performLayout()}paint(A,Q=0,$=0){let B=Math.floor(Q+this.offset.x),E=Math.floor($+this.offset.y),D=Math.floor(this.size.width),J=Math.floor(this.size.height),U={bg:this.color},Y=ME(this.dissolveProgress);if(Y<=0){A.fill(B,E,D,J," ",U);return}if(Y>=1)return;for(let Z=0;Z<J;Z++)for(let F=0;F<D;F++)if(!SF6(F,Z,D,J,Y))A.fill(B+F,E+Z,1,1," ",U)}}function ME(A){return Math.min(1,Math.max(0,A))}function xT(A){return 1-(1-A)**3}function HR4(A){return CR4[A]??CR4[0]}function NR4(A,Q,$){return{primary:Oq(A.primary,Q.primary,$),secondary:Oq(A.secondary,Q.secondary,$)}}function _F6({dismissProgress:A,easedDismissProgress:Q,introOrbScale:$,normalOrbCenterX:B,normalOrbCenterY:E,size:D}){return{orbScale:$+($*0.86-$)*Q,orbCenterX:B+(D.width*0.54-B)*Q,orbCenterY:E-D.height*0.44*Q,textDissolveProgress:ME(A/0.52),backdropDissolveProgress:xT(ME((A-0.12)/0.88))}}function SF6(A,Q,$,B,E){let D=B<=1?0:Q/(B-1),J=PR4(A+Q*Math.max(1,$));return(1-D)*0.72+J*0.28<E}function kF6({introStages:A,stage:Q,previousStage:$,progress:B,direction:E,width:D,height:J,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V}){if($===null||B>=1)return $p0({introStages:A,stage:Q,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V});let K=xT(B),z=E*Math.round((1-K)*D),W=-E*Math.round(K*D);return new Fq(new EQ({fit:"expand",children:[new e1({left:W,top:0,width:D,height:J,child:$p0({introStages:A,stage:$,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:$===0?1:I,dissolveProgress:G,context:V})}),new e1({left:z,top:0,width:D,height:J,child:$p0({introStages:A,stage:Q,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V})})]}))}function $p0({introStages:A,stage:Q,foreground:$,mutedForeground:B,accent:E,link:D,keybind:J,titleRevealProgress:U,dissolveProgress:Y,context:Z}){let F=A[Q]??A[0]??Ep0[0],X=new $0({color:E,bold:!0}),I=new $0({color:$}),G=A===Ep0&&Q===0,V=[...F.title===null?[]:[new D0({text:G?r90(yF6({progress:U,foreground:E,pulseColor:E}),Y):new g(A8(F.title,Y),X),textAlign:"center"})],...F.body.length>0?[fF6()]:[],...F.body.map((K)=>xF6(K,I,B,D,J,Y,Z))];return new $6({child:new mA({padding:p0.horizontal(1),child:new FA({crossAxisAlignment:"stretch",mainAxisAlignment:"center",mainAxisSize:"min",children:V})})})}function fF6(){return y0.height(1)}function xF6(A,Q,$,B,E,D,J){if(typeof A==="string")return new D0({text:new g(A8(A,D),Q),textAlign:"center"});if("codeBlock"in A)return new M5({onCopy:(U,Y)=>{if(Y)UQ.success(J,"Copied to clipboard",2000)},child:new FA({mainAxisSize:"min",children:A.codeBlock.map((U)=>new D0({text:new g(A8(U,D),new $0({color:E})),textAlign:"center",selectable:!0}))})});if("keybind"in A){let U=new D0({text:new g("",void 0,[new g(A8(A.text,D),new $0({color:$,dim:!0})),new g(A8(A.keybind,D,tA(A.text).length),new $0({color:E}))]),textAlign:"center",selectable:"selectable"in A?A.selectable:!1});if("selectable"in A)return new $6({child:new M5({child:U})});return U}if("highlightText"in A){let U=j$.createSpan(A.href,A.linkText,new $0({color:B,underline:!0})),Y=dX.of(J),Z=new g("",void 0,[new g(A.text,Q),new g(A.highlightText,new $0({color:E})),new g(A.textAfterHighlight,Q),new g(U.text,U.style,U.children,U.hyperlink,()=>{i6(J,A.href,{forceExternal:!1,onShowImagePreview:Y})}),new g(A.textAfter,Q)]);return new D0({text:r90(Z,D),textAlign:"center"})}if("linkText"in A){if(A.linkWidget)return new FA({mainAxisSize:"min",children:[new D0({text:new g(A8(A.text,D),Q),textAlign:"center"}),new $6({child:new OA({mainAxisSize:"min",children:[j$.createWidget(J,A.href,A8(A.linkText,D),new $0({color:B,underline:!0})),new D0({text:new g(A8(A.textAfter,D),Q)})]})})]});let U=j$.createSpan(A.href,A.linkText,new $0({color:B,underline:!0})),Y=dX.of(J),Z=new g("",void 0,[new g(A.text,Q),new g(U.text,U.style,U.children,U.hyperlink,()=>{i6(J,A.href,{forceExternal:!1,onShowImagePreview:Y})}),new g(A.textAfter,Q)]);return new D0({text:r90(Z,D),textAlign:"center"})}if(D>0)return new D0({text:new g(A8(A.text,D),new $0({color:B,underline:!0})),textAlign:"center"});return new $6({child:j$.createWidget(J,A.href,A.text,new $0({color:B,underline:!0}))})}function yF6({progress:A,foreground:Q,pulseColor:$}){let B=new $0({color:Q,bold:!0}),E=new $0({color:hF6({progress:A,foreground:Q,pulseColor:$}),bold:!0});return new g("",void 0,[new g(bF6(A).padEnd(Dp0," "),B),new g(" ",B),new g(qR4(MR4,PF6,A,0.72),B),new g(" ",B),new g(qR4(OR4,TF6,A,0.88),E)])}function bF6(A){let Q=tA(uR4),$=Math.min(Dp0,Math.ceil(ME(A/0.62)*Dp0));return Q.slice(0,$).join("")}function qR4(A,Q,$,B){return $>=B?A:"".padEnd(Q," ")}function hF6({progress:A,foreground:Q,pulseColor:$}){if(A<0.88||A>=1)return Q;let B=ME((A-0.88)/0.12);return Math.cos(B*Math.PI*4)*(1-B)>0.12?$:Q}function gF6({stage:A,featureStageCount:Q,foreground:$,dissolveProgress:B}){return new g(A8(`${A}/${Q}`,B),new $0({color:$,dim:!0}))}function mF6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D}){let J=new $0({color:B}),U=new $0({color:$,dim:!0}),Y=Q?A?"Enter":"Space":"Esc",Z=Q?A?" to get started":" to continue":" to quit",F="",X="",I=`${Z}`;if(!Q)return new g("",void 0,[new g(Y,J),new g(Z,U),new g("",J),new g("",U)]);let G=wR4(Y,E),V=wR4(I,ME((E*(tA(Y).length+tA(I).length)-tA(Y).length)/tA(I).length));return new g("",void 0,[new g(A8(G,D),J),new g(A8(V.slice(0,Z.length),D),U),new g(A8(V.slice(Z.length,Z.length+0),D),J),new g(A8(V.slice(Z.length+0),D),U)])}function dF6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D,context:J}){if(Q)return new D0({text:mF6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D}),textAlign:"center"});let U=new $0({color:B}),Y=new $0({color:$,dim:!0});return new M5({onCopy:(Z,F)=>{if(F)UQ.success(J,"Copied to clipboard",2000)},child:new D0({text:new g("",void 0,[new g("q",U),new g(" to quit",Y)]),textAlign:"center",selectable:!0})})}function wR4(A,Q){let $=tA(A),B=Math.min($.length,Math.ceil(ME(Q)*$.length));return $.slice(0,B).join("").padEnd($.length," ")}function r90(A,Q,$=0){if(Q<=0)return A;let B=$+tA(A.text??"").length,E=A.children?.map((D)=>{let J=r90(D,Q,B);return B+=tA(D.toPlainText()).length,J});return new g(A.text?A8(A.text,Q,$):A.text,A.style,E,A.hyperlink,A.onClick)}function A8(A,Q,$=0){if(Q<=0)return A;return tA(A).map((E,D)=>{if(E.trim()==="")return E;return PR4($+D)<Q?" ":E}).join("")}function PR4(A){let Q=Math.sin((A+1)*12.9898)*43758.5453;return Q-Math.floor(Q)}function pF6(A){let $=A.observer.protocolMessages().filter((B)=>B.role==="assistant").at(-1);if(!$)return null;return $.content.filter((B)=>B.type==="text").map((B)=>B.text).join("")}function TR4(A){A.client.cancelAgentLoop().catch((Q)=>{S.warn("Failed to cancel plugin agent run",{error:Q})})}function lF6(A,Q={}){return new Promise(($,B)=>{if(Q.signal?.aborted){TR4(A),B(Error("Agent run cancelled"));return}let E=!1,D=null,J=setTimeout(()=>{D?.(),Y.unsubscribe(),B(Error("Timed out waiting for agent response"))},Q.timeoutMs??600000),U=()=>{clearTimeout(J),Y.unsubscribe(),TR4(A),B(Error("Agent run cancelled"))};if(Q.signal!==void 0)Q.signal.addEventListener("abort",U,{once:!0}),D=()=>Q.signal?.removeEventListener("abort",U);let Y=A.observer.agentState().subscribe((Z)=>{if(h3(Z)){E=!0;return}if(!E)return;let F=pF6(A);if(F===null)return;clearTimeout(J),D?.(),Y.unsubscribe(),$(F)})})}class Up0 extends d0{listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;updateService;initialThreadIDs;showWelcome;welcomeVariant;onWelcomeDismissed;notificationService;mcpTrustHandler;onThreadArchived;onActiveThreadChange;onRelaunchRequested;onFirstFrame;initialUserInput;getDefaultNewThreadVisibility;observeThreadSummaries;openThreadPickerOnStart;workspaceSettingsFilePath;context;constructor(A){super();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.updateService=A.updateService,this.initialThreadIDs=A.initialThreadIDs??[],this.showWelcome=A.showWelcome??!1,this.welcomeVariant=A.welcomeVariant??"intro",this.onWelcomeDismissed=A.onWelcomeDismissed,this.notificationService=A.notificationService,this.mcpTrustHandler=A.mcpTrustHandler,this.onThreadArchived=A.onThreadArchived,this.onActiveThreadChange=A.onActiveThreadChange,this.onRelaunchRequested=A.onRelaunchRequested,this.onFirstFrame=A.onFirstFrame,this.initialUserInput=A.initialUserInput,this.getDefaultNewThreadVisibility=A.getDefaultNewThreadVisibility,this.observeThreadSummaries=A.observeThreadSummaries,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.workspaceSettingsFilePath=A.workspaceSettingsFilePath,this.context=A.context}createState(){return new _R4}}class _R4 extends m0{editorController=new $Z;commandPalette=new vb0(this);commandRegistry=new Lm0;toastController=new kb0;relaunchNotificationController=new Wm0;exitHintTimer=new Op(this,1000);ideStatus=new c3(this,{});threadNavigationHistory=new Nm0;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;activeThreadIDSubscription=null;activePluginMessageSubscription=null;activePluginUIRequestsSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;executorAlreadyConnectedDialog=null;switchThreadPickerVisible=!1;welcomeVisible=!1;endCreditsVisible=!1;invadersHighScore=0;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;emptyThreadTerminalTitleController=new dl;pluginIntegration=null;mcpTrustIntegration=null;updateRelaunchIntegration=null;noticesPollingTimeout=null;notices;editorFocusNode=new a7({debugLabel:"EditorPanel"});loadThreads=async()=>{return this.widget.context.listThreads()};focusEditor=()=>{this.editorFocusNode.requestFocus()};focusEditorAfterNextFrame(){W6.instance.addPostFrameCallback(()=>{if(!this.mounted)return;this.focusEditor()},"Neo focus editor")}analyzeContextForThread=async(A,Q)=>{return Nz4({ampURL:this.widget.context.ampURL,configService:this.widget.configService,threadID:A,signal:Q})};onSwitchThread=(A)=>{return this.connectToExistingThread(A,{recordNavigation:!0,rethrowError:!0})};onSelectSidebarThread=async(A)=>{this.focusEditor(),await this.onSwitchThread(A)};threadListSidebar=new ec0({state:this,isBlocked:()=>this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal(),getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,getWorkspaceRoot:()=>this.widget.context.workspaceRoot,loadThreads:this.loadThreads,observeThreadSummaries:()=>this.widget.observeThreadSummaries(),archiveThread:(A)=>this.archiveThread(A),onSelectThread:this.onSelectSidebarThread,focusMainContent:this.focusEditor,getInitialVisible:()=>this.widget.context.threadListSidebarVisible});sendFeedbackReport=async(A)=>h80({configService:this.widget.configService,settingsFilePath:this.widget.context.settingsFilePath},A);archiveThread=async(A)=>{let Q=await TH4({configService:this.widget.configService},A);if(Q===null){let $=this.activeThreadContext?.client.getThreadId()??null;if(this.widget.clientPool.disconnectThread(A),this.widget.onThreadArchived?.(A),$===A)this.startNewDraftThread()}return Q};addThreadLabel=async(A,Q)=>{let $=await ON4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};removeThreadLabel=async(A,Q)=>{let $=await LN4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};initState(){if(LX.getInstance().interceptConsole(),this.invadersHighScore=this.widget.context.invadersHighScore??0,this.notices=new Am0(this.widget.configService,($)=>this.setState($)),W6.instance.addPostFrameCallback(()=>{setTimeout(()=>this.widget.onFirstFrame?.(),0),this.noticesPollingTimeout=setTimeout(()=>{this.noticesPollingTimeout=null,this.notices.startPolling()},500)},"Neo notices polling"),this.widget.showWelcome)this.welcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:$,error:B})=>{if(S.error("Neo failed to connect to thread",{threadID:$,error:B}),!$)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configSubscription=this.widget.configService.config.subscribe(($)=>{this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(I00($.settings)))}),this.updateRelaunchIntegration=new qm0({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested,relaunchNotificationController:this.relaunchNotificationController,updateService:this.widget.updateService}),this.updateRelaunchIntegration.init(),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput,Q=this.widget.initialThreadIDs[0];if(Q){let $={};if(A)$.initialUserInput=A;this.connectToInitialThreads(Q,$)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.context.sessionAgentMode);this.pluginIntegration=new Km0({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,context:this.widget.context,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread,readThreadMessages:this.readPluginThreadMessages,readThreadTitle:this.readPluginThreadTitle,subscribeThreadTitle:this.subscribePluginThreadTitle,runAgent:this.runPluginAgent,onBlockingConfirmDialogChange:this.syncEmptyThreadPluginConfirmationTitle}),this.pluginIntegration.init(),this.mcpTrustIntegration=new sh0({state:this,mcpTrustHandler:this.widget.mcpTrustHandler,toastController:this.toastController,workspaceSettingsFilePath:this.widget.workspaceSettingsFilePath}),this.mcpTrustIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=V1.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this,Q=this.widget.context.pluginService?iw4({pluginService:this.widget.context.pluginService,workspaceRoot:this.widget.context.workspaceRoot,logFilePath:this.widget.context.logFilePath,toastController:this.toastController}):[],B=[Au4({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["resume"],status:{type:"enabled"},sortBoost:100,run:(E,D,J)=>{E.pushWithDismiss((U)=>td0({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,loadThreadTail:this.widget.context.loadThreadTail,onSelectThread:this.onSwitchThread,onDismiss:U,onThreadSelected:J}))}},...this.threadListSidebar.commands(),{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(E,D,J)=>{A.navigateBack(),J()}},aM4({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(E,D,J)=>{A.navigateForward(),J()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",status:{type:"enabled"},run:(E,D,J)=>{E.push(new Yd0({mcpServers:this.widget.context.mcpServers,onDismiss:J}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",status:{type:"enabled"},run:(E)=>{E.pushWithDismiss((D)=>new Ap0({toolboxes:this.widget.context.toolboxes,onDismiss:D}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","blog","announcements"],status:{type:"enabled"},run:async(E,D,J)=>{try{await i6(D,"https://ampcode.com/chronicle")}finally{J()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config"],status:{type:"enabled"},run:()=>{TK(this.widget.context.settingsFilePath).catch((E)=>{S.error("Failed to open settings file in editor",{error:E})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains"],status:{type:"enabled"},run:(E,D,J)=>{E.pushWithDismiss((U)=>new Ud0({onCancel:U,onSelect:(Y)=>{this.handleIdeSelection(Y),J()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["manual","?"],status:{type:"enabled"},run:(E,D,J)=>{E.push(new Rm0({commands:aB.of(D).commands,onDismiss:J}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",status:{type:"enabled"},run:(E,D,J)=>{J(),A.showWelcome()}},{noun:"amp",verb:"end credits",description:"Roll the full-screen Amp credits",status:{type:"enabled"},run:(E,D,J)=>{J(),A.showEndCredits()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["v"],status:{type:"enabled"},run:(E,D,J)=>{E.push(new E1({header:"Amp Version",maxWidth:72,onDismiss:J,child:new D0({text:new g(r50({version:"0.0.1780677932-g159ed8",buildTimestamp:"2026-06-05T16:49:58.070Z",buildType:"release"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","bye"],shortcut:CA.ctrl("c"),status:{type:"enabled"},run:(E,D)=>{w4.maybeInvoke(D,new hK)}},...Q,...MN4(this.widget.context.logFilePath)].map((E)=>this.commandRegistry.register(E));return()=>{for(let E of B)E()}}build(A){let Q=this.buildHints(),$=this.ideStatus.getValue(),B=this.notices.current,E=new nc0({initialAgentMode:this.widget.context.sessionAgentMode,initialPluginAgentModeKey:this.widget.context.initialPluginAgentModeKey,analyzeContextForThread:this.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,editorFocusNode:this.editorFocusNode,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,sendFeedbackReport:this.sendFeedbackReport,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:$,statusItems:this.pluginIntegration?.getStatusItems()??[],pluginConfirmationBlocked:this.pluginIntegration?.hasBlockingConfirmDialog()??!1,notificationService:this.widget.notificationService,notice:this.activeThreadContext||this.welcomeVisible?null:B,onDismissNotice:(I)=>this.notices.dismiss(I)}),D=W4.of(A),J=D.capabilities.animationSupport!=="disabled",U=this.threadListSidebar.visibleWidth(),Y=Math.max(0,D.size.width-U),F=[new KA({constraints:Z4.tight(D.size.width,D.size.height),child:this.threadListSidebar.buildBody(E)})];if(this.commandPalette.isEnabled())F.push(new C6({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new jm0({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.welcomeVisible)F.push(td0({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,loadThreadTail:this.widget.context.loadThreadTail,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.welcomeVisible)F.push(new C6({debugLabel:"WelcomeDialogOverlay",child:new Jp0({onDismiss:this.dismissWelcome,onQuit:()=>V1.instance.stop(),animationsEnabled:J,variant:this.widget.welcomeVariant})}));let X=this.executorAlreadyConnectedDialog;if(X)F.push(new C6({debugLabel:"ExecutorAlreadyConnectedDialogOverlay",child:new Ed0({existingExecutorPid:X.existingExecutorPid,onChoice:this.handleExecutorAlreadyConnectedChoice})}));if(F.push(...this.mcpTrustIntegration?.buildDialogLayers()??[]),F.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.context.isInternalUser)F.push(new Tm0({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:s90.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,observerSnapshot$:this.activeThreadContext?.observer.observerSnapshot()??null}));if(this.focusDebugVisible)F.push(new Dd0);if(this.endCreditsVisible)F.push(new tm0({onComplete:this.completeEndCredits,highScore:this.invadersHighScore,onHighScoreChange:this.updateInvadersHighScore}));return new SQ({context:this.widget.context,child:new aB({commandRegistry:this.commandRegistry,child:new qT({completionBuilder:this.widget.completionBuilder,child:new UQ({controller:this.toastController,child:new w4({actions:this.buildActions(),child:new aQ({debugLabel:"AppShortcuts",shortcuts:this.buildShortcuts(),child:new TQ({debugLabel:"AppShellFocus",canRequestFocus:!1,skipTraversal:!0,child:new fb0({controller:this.toastController,complexToastControllers:[this.relaunchNotificationController,...B&&this.activeThreadContext&&!this.welcomeVisible?[this.notices]:[]],child:new Pm0({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new ap({left:U,width:Y,child:new EQ({children:F})})})})})})})})})})})}buildShortcuts(){let A=new Map([[CA.ctrl("c"),new g70],[CA.ctrl("o"),new d70],[CA.alt("i"),new p70],[CA.alt("p"),new Up],[CA.ctrl("."),new n70],[CA.ctrl("t"),new r70],...this.threadListSidebar.shortcutEntries()]);if(s90.env.NODE_ENV==="development"&&s90.platform==="darwin")A.set(CA.meta("r"),new m70);return A}buildActions(){let A=new cA(()=>{if(y2.hasAnyCopyableSelection())return y2.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new cA(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),$=new cA(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),B=new cA(()=>{return this.startNewDraftThread(),"handled"}),E=new cA(()=>{return V1.instance.stop(),"handled"}),D=new cA(()=>{return _l({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),"handled"}),J=new cA((I)=>{if(!I.text)return"ignored";return V1.instance.tuiInstance.clipboard.writeText(I.text).then((G)=>{if(G.ok)this.toastController.show(I.successMessage,"success",2000);else this.toastController.show(`${I.failureMessage}: ${G.userFacingErrorMessage}`,"error",4000)}).catch((G)=>{S.error("Failed to copy Neo text to clipboard",{error:G}),this.toastController.show(I.failureMessage,"error",2000)}),"handled"}),U=new cA(()=>{return V1.instance.toggleFrameStatsOverlay(),"handled"}),Y=new cA(()=>this.notices.dismissCurrent()?"handled":"ignored"),Z=new cA(()=>{if(!this.widget.context.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),F=Gu4({getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,context:this.widget.context,toastController:this.toastController,startNewDraftThread:this.startNewDraftThread,sendFeedbackReport:this.sendFeedbackReport}),X=new cA(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[g70,A],[Lq,B],[hK,E],[m70,D],[FB,J],[Dl,$],[d70,Q],[p70,Z],...this.threadListSidebar.actionEntries(),[n70,Y],...F,[Up,U],[r70,X]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.cancelOwnerUIRequests(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),this.widget.onActiveThreadChange?.(null),this.syncEmptyThreadPluginConfirmationTitle(),A.prompt!==void 0)this.editorController.text=A.prompt;this.focusEditorAfterNextFrame()}syncEmptyThreadPluginConfirmationTitle=()=>{this.emptyThreadTerminalTitleController.setPluginConfirmationBlocked(this.activeThreadContext===null&&(this.pluginIntegration?.hasBlockingConfirmDialog()??!1))};closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=this.applySessionDefaultsToThreadSettings(await gP(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){S.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.context.sessionAgentMode,$=A,B=$q(Q),E=q50(this.widget.context,Q);if(B!==void 0&&E!==void 0)$={...$,[B]:E};return H50($,{agentMode:Q,explicitEffort:this.widget.context.explicitReasoningEffort,sessionState:this.widget.context})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=vR4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(aU(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=vR4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(bK);if(this.exitHintTimer.isActive())A.add(ZT);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),V1.instance.stop();else this.exitHintTimer.activate()};dismissWelcome=()=>{if(!this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!1}),this.widget.onWelcomeDismissed?.()};updateInvadersHighScore=(A)=>{if(A<=this.invadersHighScore)return;this.setState(()=>{this.invadersHighScore=A}),AJ((Q)=>({...Q,neoInvadersHighScore:Math.max(Q.neoInvadersHighScore,A)})).catch((Q)=>{S.warn("Failed to save Neo Invaders high score",{error:Q instanceof Error?Q.message:String(Q)})})};showWelcome=()=>{if(this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!0})};showEndCredits=()=>{if(this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!0})};completeEndCredits=()=>{if(!this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!1})};promptExecutorAlreadyConnected(A){return new Promise((Q)=>{this.setState(()=>{this.executorAlreadyConnectedDialog={existingExecutorPid:A.existingExecutorPid,resolve:($)=>{Q($==="watch"?"observe":"disconnect")}}})})}handleExecutorAlreadyConnectedChoice=(A)=>{if(this.resolveExecutorAlreadyConnectedDialog(A),A==="exit")V1.instance.stop()};resolveExecutorAlreadyConnectedDialog(A){let Q=this.executorAlreadyConnectedDialog;if(!Q)return;this.setState(()=>{this.executorAlreadyConnectedDialog=null}),Q.resolve(A)}closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1}),this.focusEditorAfterNextFrame()};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,$=null,B,E,D)=>{await this.ensureDraftThreadSettingsInitialized();let J=this.activeThreadContext?.client.getThreadId(),U=A.find(D00);if(U)this.widget.history.add(U.text,s90.cwd()),this.widget.history.reset();let Y=$?void 0:await this.widget.getDefaultNewThreadVisibility?.(),Z=$??Y??null,F=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,Z??void 0,E,D);if(this.sendUserMessage(F,A,E?void 0:Q,E?void 0:B),!E)this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings);this.threadNavigationHistory.recordNavigation(J),this.setActiveClient(F)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.context.sessionAgentMode=A;let $=Q["reasoning.effort"];if($!==void 0)this.widget.context.lastReasoningEffortByMode={...this.widget.context.lastReasoningEffortByMode??{},[A]:$};let B=$q(A),E=B?Q[B]:void 0;if(E!==void 0)this.widget.context.lastSpeedByMode={...this.widget.context.lastSpeedByMode??{},[A]:E};AJ((D)=>{let J={...D,agentMode:A};if($!==void 0)J={...J,lastReasoningEffortByMode:{...J.lastReasoningEffortByMode??{},[A]:$}};if(E!==void 0)J={...J,lastSpeedByMode:{...J.lastSpeedByMode??{},[A]:E}};return J}).catch((D)=>{S.warn("Failed to persist Neo session defaults for new message",{error:D instanceof Error?D.message:String(D)})})}sendUserMessage(A,Q,$,B,E){let D=o50(this.ideStatus.getValue());if(B===void 0){A.client.sendUserMessage(Q,$,{steer:E?.steer,userState:D}).catch((J)=>{S.warn("Failed to send user message",{error:J})});return}A.client.sendUserMessage(Q,$,{reasoningEffort:B,steer:E?.steer,userState:D}).catch((J)=>{S.warn("Failed to send user message",{error:J})})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};getRelaunchThreadIDs=()=>{let A=new Set,Q=this.getActiveThreadID();if(Q)A.add(Q);for(let $ of this.widget.clientPool.activeThreadIDs)A.add($);return[...A]};appendPluginMessagesToThread=async(A,Q,$)=>{let B=this.activeThreadContext;if(!B){if(Q){for(let D of A)await this.widget.clientPool.appendUserMessageToThread(Q,D.content,$);return}throw Error("appendToThread is not available - no active thread")}let E=B.client.getThreadId();if(Q&&E!==Q){for(let D of A)await this.widget.clientPool.appendUserMessageToThread(Q,D.content,$);return}for(let D of A)this.sendUserMessage(B,[{type:"text",text:D.content}],void 0,void 0,$)};readPluginThreadMessages=async(A,Q)=>{let $=this.activeThreadContext;if(!$)throw Error("thread.messages is not available - no active thread");let B=$.client.getThreadId();if(Q&&B!==Q)throw Error("thread.messages is only available for the active thread");return QoA($oA($.observer.protocolMessages()),A)};readPluginThreadTitle=async(A)=>{let Q=this.activeThreadContext;if(!Q)throw Error("thread.title is not available - no active thread");let $=Q.client.getThreadId();if(A&&$!==A)throw Error("thread.title is only available for the active thread");return Q.observer.title().getValue()??null};subscribePluginThreadTitle=(A,Q)=>{let $=this.activeThreadContext;if(!$)throw Error("thread.title.subscribe is not available - no active thread");let B=$.client.getThreadId();if(A&&B!==A)throw Error("thread.title.subscribe is only available for the active thread");return $.observer.title().subscribe((E)=>{Q.next(E??null)})};runPluginAgent=async(A,Q,$)=>{await this.ensureDraftThreadSettingsInitialized();let B=this.widget.clientPool.createNewThread(this.widget.context.sessionAgentMode,this.draftThreadSettings,void 0,A,Q.agentModeDisplay,Q.parentThreadID,{trackAsLastActive:!1,executorClientID:cY.parse(`neo-subagent-${cF6()}`)});this.sendUserMessage(B,[{type:"text",text:Q.message}]);try{let E=await lF6(B,{timeoutMs:Q.timeoutMs,signal:$}),D=B.client.getThreadId();return D?{threadID:D,text:E}:{text:E}}finally{this.widget.clientPool.disconnect(B)}};async connectToExistingThread(A,Q={}){let $=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let B=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:(E)=>this.promptExecutorAlreadyConnected(E)});if(this.setActiveClient(B),Q.recordNavigation&&$!==A)this.threadNavigationHistory.recordNavigation($);if(Q.initialUserInput)this.sendUserMessage(B,[{type:"text",text:Q.initialUserInput}])}catch(B){if(S.error("Failed to load thread",{error:B,threadID:A}),this.toastController.show(`Failed to load ${A}: ${B instanceof Error?B.message:String(B)}`,"error",4000),Q.rethrowError)throw B}finally{this.setState(()=>{this.connectingToThreadID=null})}}async connectToInitialThreads(A,Q={}){await this.connectToExistingThread(A,Q);let $=this.widget.initialThreadIDs.filter((B)=>B!==A);await Promise.all($.map((B)=>this.resumeBackgroundThread(B)))}async resumeBackgroundThread(A){try{await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:async()=>"observe"})}catch(Q){S.error("Failed to resume background thread",{error:Q,threadID:A}),this.toastController.show(`Failed to resume ${A}: ${Q instanceof Error?Q.message:String(Q)}`,"error",4000)}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}setActiveClient({client:A,observer:Q,agentModeDisplay:$}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q,agentModeDisplay:$}}),this.syncEmptyThreadPluginConfirmationTitle(),this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe((B)=>{this.widget.onActiveThreadChange?.(B)}),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription?.unsubscribe(),this.pluginIntegration?.cancelOwnerUIRequests(),this.activePluginMessageSubscription=Q.pluginMessages().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage(B,(E)=>{A.sendPluginMessage(E)})}),this.activePluginUIRequestsSubscription=Q.pluginUIRequests().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage({type:"plugin_message",message:{type:"event",event:"plugin.ui.snapshot",data:{requests:[...B]}}},(E)=>{A.sendPluginMessage(E)})})}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){S.error("Failed to connect to IDE",{error:Q});let $=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${$}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.threadListSidebar.dispose(),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.emptyThreadTerminalTitleController.dispose(),this.mcpTrustIntegration?.dispose(),this.mcpTrustIntegration=null,this.updateRelaunchIntegration?.dispose(),this.updateRelaunchIntegration=null,this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.noticesPollingTimeout)clearTimeout(this.noticesPollingTimeout),this.noticesPollingTimeout=null;this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.notices.dispose(),this.widget.notificationService.detach(),this.toastController.dispose(),this.editorFocusNode.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.executorAlreadyConnectedDialog!==null||this.welcomeVisible||(this.mcpTrustIntegration?.hasBlockingDialog()??!1)||this.endCreditsVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function vR4(A,Q,$){let B={...A};for(let E of iF6(Q,$)){if(!aU(A[E],Q[E]))continue;let D=$[E];if(D===void 0)delete B[E];else B[E]=D}return B}function iF6(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}E3();function SR4(A,Q,$,B){let E=UbA(A),D="\x1B[0m",J="\x1B[34m",U="\x1B[90m",Y="\x1B[2m",Z=[];if(A.archived)Z.push("\x1B[90m\x1B[2mArchived\x1B[0m");Z.push(`${E}`),Z.push(`\x1B[34m${Q}\x1B[0m`),Z.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let F=14,X=7,I=new f2(F,X),G=new R5(42),V=new wT(F,X,F,X,F,X,0,A.agentMode??"smart","intensity","ascii",void 0,void 0,g0.default(),G);V.layout(Z4.tight(F,X)),V.paint(I,0,0);let K=I.getBuffer().getCells(),z=0;for(let R=0;R<X;R++)if(K[R].some((_)=>_.char!==" ")){z=R;break}let W=X-1;for(let R=X-1;R>=0;R--)if(K[R].some((_)=>_.char!==" ")){W=R;break}function C(R,_){if(!R)return"";if(R.type==="rgb"){let{r:P,g:f,b:h}=R.value;if($.getColorDepth()>=24)return`\x1B[${_?38:48};2;${P};${f};${h}m`;let x=Kp(P,f,h);return`\x1B[${_?38:48};5;${x}m`}return""}let H=[];if(W>=z)for(let R=z;R<=W;R++){let _="";for(let P=0;P<F;P++){let f=K[R][P],h=f.char,x=C(f.style.fg,!0);_+=x+h+"\x1B[0m"}H.push(_)}let N=H.length,w=Math.max(N,Z.length),u=Math.floor((w-N)/2),L=Math.floor((w-Z.length)/2);for(let R=0;R<w;R++){let _=" ".repeat(F);if(R>=u&&R<u+N)_=H[R-u];let P=" ",f="";if(R>=L&&R<L+Z.length)f=Z[R-L];$.write(_+P+f+`
3089
+ `))}function HF6(A,Q){let{colors:$,app:B}=Q;switch(A){case"pending":return{icon:"◌",color:$.warning};case"registered":return{icon:"•",color:$.mutedForeground};case"failed":return{icon:"✗",color:B.toolError};case"duplicate":return{icon:"◇",color:$.warning};default:return{icon:"?",color:$.foreground}}}function XR4(A,Q){let $=A.replace(/\s+/g," ").trim();if(fA($)<=Q)return $;let B="...",E=fA(B);if(Q<=E)return n7(B,Q);return`${n7($,Q-E,!0,"")}${B}`}var Bp0="https://ampcode.com/news/neo",Ep0=[{title:"Meet the new Amp CLI",body:[]},{title:"Rebuilt From The Ground Up",body:["Same close-up terminal workflow. Completely different underneath."]},{title:"Just Keep Typing",body:["Context is summarized automatically at ~90%.","No handoff flow. No context percentage to babysit."]},{title:"Queueing and Steering",body:["Sending a message now queues by default instead of cancelling tools.","Use steering when you want the agent to see something sooner."]},{title:"Remote Control",body:["Start a thread in the CLI, then keep going from ampcode.com.","Watch live updates and queue follow-ups from any device."]},{title:"Customize Amp with Amp",body:[{text:"Amp now has a ",linkText:"complete plugin API",href:"https://ampcode.com/manual/plugin-api",textAfter:"."},"Add tools, commands, control UI, and hook into events."]},{title:"Permissions",body:[{text:"By default (when no ",highlightText:"amp.permissions",textAfterHighlight:" setting is present), Amp no longer asks for confirmation before running any tools and commands. And you can now implement your own custom permission logic with ",linkText:"plugins",href:"https://ampcode.com/manual/plugin-api",textAfter:"."}]},{title:null,body:["Check out the full news post for more:",{text:Bp0,href:Bp0}]}];function NF6(A){return[{title:"Upgrade your Amp CLI",body:[{text:"This npm-based distribution of Amp CLI has been deprecated. To use the ",linkText:"new Amp CLI",href:Bp0,textAfter:" you'll need to switch to the binary install:",linkWidget:!0},"",{codeBlock:["npm uninstall -g @sourcegraph/amp",A]}]}]}function qF6(){if(process.platform==="win32")return'powershell -c "irm https://ampcode.com/install.ps1 | iex"';return"curl -fsSL https://ampcode.com/install.sh | bash"}var fT=50,nq=40,Qp0=1000,wF6=420,uF6=760,MF6=-250,OF6=1100,a90=33,KR4=0.999,LF6=2.1,jF6=720,RF6=420,uR4="Meet the new",MR4="Amp",OR4="CLI",Dp0=tA(uR4).length,PF6=tA(MR4).length,TF6=tA(OR4).length,o90={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}},zR4={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},WR4={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}},CR4=[o90,zR4,WR4,o90,zR4,WR4,o90],vF6=o90;class Jp0 extends d0{onDismiss;onQuit;animationProgress;animationsEnabled;variant;binaryInstallCommand;introStages;dismissible;constructor(A){super();this.onDismiss=A.onDismiss,this.onQuit=A.onQuit,this.animationProgress=A.animationProgress,this.animationsEnabled=A.animationsEnabled??!0,this.variant=A.variant??"intro",this.binaryInstallCommand=A.binaryInstallCommand??qF6(),this.introStages=this.variant==="npm-migration"?NF6(this.binaryInstallCommand):Ep0,this.dismissible=this.variant!=="npm-migration"}createState(){return new LR4}}class LR4 extends m0{startedAt=performance.now();animationTimer=null;stageTransitionTimer=null;firstStageTitleTimer=null;firstStageHintTimer=null;firstStageRevealTimer=null;firstStageTitleRevealStartedAt=null;firstStageHintRevealStartedAt=null;stageTransitionStartedAt=performance.now();animationStartProgress=0;animationTargetProgress=1;animationDurationMs=Qp0;onAnimationComplete=null;animationProgress=0;introStage=0;previousIntroStage=null;stageTransitionProgress=1;stageTransitionDirection=1;firstStageTitleVisible=!1;firstStageHintVisible=!1;firstStageTitleRevealProgress=0;firstStageHintRevealProgress=0;dismissTimer=null;dismissStartedAt=performance.now();dismissProgress=0;isDismissing=!1;splashOrbGlow=new R5(42);initState(){super.initState(),this.startAnimationIfNeeded()}didUpdateWidget(A){if(super.didUpdateWidget(A),A.animationProgress!==this.widget.animationProgress||A.animationsEnabled!==this.widget.animationsEnabled)this.startAnimationIfNeeded()}dispose(){this.stopAnimation(),this.stopStageTransitionTimer(),this.stopFirstStageRevealTimers(),this.stopDismissAnimation(),super.dispose()}startAnimationIfNeeded(){if(this.stopAnimation(),this.stopFirstStageRevealTimers(),this.widget.animationProgress!==void 0){this.animationProgress=ME(this.widget.animationProgress),this.firstStageTitleVisible=this.animationProgress>=KR4,this.firstStageHintVisible=this.animationProgress>=KR4,this.firstStageTitleRevealProgress=this.firstStageTitleVisible?1:0,this.firstStageHintRevealProgress=this.firstStageHintVisible?1:0;return}if(!this.widget.animationsEnabled){this.stopStageTransitionTimer(),this.stopDismissAnimation(),this.animationProgress=1,this.isDismissing=!1,this.dismissProgress=0,this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1,this.previousIntroStage=null,this.stageTransitionProgress=1;return}if(this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0,this.startProgressAnimation({from:0,to:1,durationMs:Qp0,onComplete:()=>{if(!this.widget.dismissible)this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1})}}),this.widget.dismissible)this.startFirstStageRevealSequence()}startDismissAnimation(){if(this.isDismissing)return;if(!this.widget.animationsEnabled){this.widget.onDismiss();return}this.stopFirstStageRevealTimers(),this.stopStageTransitionTimer(),this.dismissStartedAt=performance.now(),this.setState(()=>{this.isDismissing=!0,this.dismissProgress=0}),this.dismissTimer=setInterval(()=>{let A=performance.now()-this.dismissStartedAt,Q=ME(A/uF6);if(this.setState(()=>{this.dismissProgress=Q}),Q>=1)this.stopDismissAnimation(),this.widget.onDismiss()},a90)}canNavigateIntroStage(){if(this.isDismissing)return!1;if(!this.firstStageHintVisible)return!1;if(this.introStage===0&&this.firstStageHintRevealProgress<1)return!1;return!0}advanceIntroStage(){if(!this.canNavigateIntroStage())return;if(this.isFinalIntroStage()){if(this.widget.dismissible)this.startDismissAnimation();return}this.moveIntroStage(1)}dismissFromFinalIntroStage(){if(!this.widget.dismissible||!this.canNavigateIntroStage()||!this.isFinalIntroStage())return!1;return this.startDismissAnimation(),!0}nextIntroStage(){if(!this.canNavigateIntroStage()||this.isFinalIntroStage())return;this.moveIntroStage(1)}goToPreviousIntroStage(){if(!this.canNavigateIntroStage()||this.introStage<=0)return;this.moveIntroStage(-1)}isFinalIntroStage(){return this.introStage>=this.widget.introStages.length-1}moveIntroStage(A){let Q=this.introStage+A;if(this.stopStageTransitionTimer(),this.stageTransitionStartedAt=performance.now(),this.setState(()=>{this.previousIntroStage=this.introStage,this.introStage=Q,this.stageTransitionDirection=A}),this.widget.animationProgress!==void 0||!this.widget.animationsEnabled){this.setState(()=>{this.previousIntroStage=null,this.stageTransitionProgress=1});return}this.setState(()=>{this.stageTransitionProgress=0}),this.stageTransitionTimer=setInterval(()=>{let $=performance.now()-this.stageTransitionStartedAt,B=ME($/wF6);if(this.setState(()=>{if(this.stageTransitionProgress=B,B>=1)this.previousIntroStage=null}),B>=1)this.stopStageTransitionTimer()},a90)}startProgressAnimation({from:A,to:Q,durationMs:$,onComplete:B}){this.stopAnimation(),this.startedAt=performance.now(),this.animationStartProgress=A,this.animationTargetProgress=Q,this.animationDurationMs=$,this.onAnimationComplete=B,this.animationProgress=A,this.animationTimer=setInterval(()=>{let E=performance.now()-this.startedAt,D=ME(E/this.animationDurationMs),J=this.animationStartProgress+(this.animationTargetProgress-this.animationStartProgress)*xT(D);if(this.setState(()=>{this.animationProgress=J}),D>=1)this.stopAnimation(),this.onAnimationComplete?.(),this.onAnimationComplete=null},a90)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null}stopStageTransitionTimer(){if(this.stageTransitionTimer)clearInterval(this.stageTransitionTimer),this.stageTransitionTimer=null}startFirstStageRevealSequence(){if(this.stopFirstStageRevealTimers(),!this.widget.animationsEnabled){this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1});return}this.setState(()=>{this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0});let A=Math.max(0,Qp0+MF6),Q=A+OF6;this.firstStageTitleTimer=setTimeout(()=>{this.firstStageTitleRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageTitleRevealProgress=0}),this.startFirstStageRevealTimer()},A),this.firstStageHintTimer=setTimeout(()=>{this.firstStageHintRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageHintVisible=!0,this.firstStageHintRevealProgress=0}),this.startFirstStageRevealTimer()},Q)}startFirstStageRevealTimer(){if(this.firstStageRevealTimer)return;this.firstStageRevealTimer=setInterval(()=>{let A=performance.now(),Q=this.firstStageTitleRevealStartedAt?ME((A-this.firstStageTitleRevealStartedAt)/jF6):this.firstStageTitleRevealProgress,$=this.firstStageHintRevealStartedAt?ME((A-this.firstStageHintRevealStartedAt)/RF6):this.firstStageHintRevealProgress;if(this.setState(()=>{this.firstStageTitleRevealProgress=Q,this.firstStageHintRevealProgress=$}),Q>=1&&$>=1)this.stopFirstStageRevealTimer()},a90)}stopFirstStageRevealTimers(){if(this.stopFirstStageRevealTimer(),this.firstStageTitleRevealStartedAt=null,this.firstStageHintRevealStartedAt=null,this.firstStageTitleTimer)clearTimeout(this.firstStageTitleTimer),this.firstStageTitleTimer=null;if(this.firstStageHintTimer)clearTimeout(this.firstStageHintTimer),this.firstStageHintTimer=null}stopFirstStageRevealTimer(){if(this.firstStageRevealTimer)clearInterval(this.firstStageRevealTimer),this.firstStageRevealTimer=null}stopDismissAnimation(){if(this.dismissTimer)clearInterval(this.dismissTimer),this.dismissTimer=null}currentOrbPalette(){let A=HR4(this.introStage),Q=this.previousIntroStage===null||this.stageTransitionProgress>=1?A:NR4(HR4(this.previousIntroStage),A,xT(this.stageTransitionProgress));return this.dismissProgress>0?NR4(Q,vF6,xT(this.dismissProgress)):Q}build(A){let Q=p4.of(A).colorScheme,$=QA.of(A),B=this.currentOrbPalette(),E=Y7(1,"deep",B),D=W4.of(A).size,U=this.widget.animationProgress??this.animationProgress,Y=Math.max(D.width/fT,D.height/nq)*LF6,Z=Y+(1-Y)*U,F=xT(this.dismissProgress),X=Math.max(fT,Math.round(fT*Z)),I=Math.max(nq,Math.round(nq*Z)),G=Math.round((D.width-X)/2),V=Math.round((D.height-I)/2),K=Math.max(0,Math.floor((D.width-fT)/2)),z=-Math.floor(nq/2),W=Math.round(G+(K-G)*U),C=Math.round(V+(z-V)*U),H=W+X/2,N=C+I/2,w=_F6({dismissProgress:this.dismissProgress,easedDismissProgress:F,introOrbScale:Z,normalOrbCenterX:H,normalOrbCenterY:N,size:D}),u=Math.max(fT,Math.round(fT*w.orbScale)),L=Math.max(nq,Math.round(nq*w.orbScale)),R=w.orbCenterX,_=w.orbCenterY,P=Math.round(R-u/2),f=Math.round(_-L/2),h=Math.max(3,Math.min(D.height-5,Math.floor(nq/2)+2)),x=Math.max(h+3,D.height-3),v=w.textDissolveProgress,k=this.isFinalIntroStage()?w.backdropDissolveProgress:0,c=this.firstStageTitleVisible&&v<1,d=c&&this.firstStageHintVisible,b=d&&this.widget.dismissible&&this.introStage>0&&!this.isFinalIntroStage(),p=this.introStage===0?this.firstStageTitleRevealProgress:1,n=this.introStage===0?this.firstStageHintRevealProgress:1,a=Math.max(24,Math.min(74,D.width-4)),X0=Math.min(12,Math.max(8,D.height-h-6)),t=Math.max(0,Math.floor((D.width-a)/2)),Y0=Math.max(0,Math.min(D.height-X0,Math.floor(D.height*0.55-X0/2))),R0=this.widget.animationProgress!==void 0||!this.widget.animationsEnabled?new iK({width:u,height:L,agentMode:"deep",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,seed:42,fps:0,onClick:()=>{}}):new iK({width:u,height:L,agentMode:"deep",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,onClick:()=>{}});return new C6({autofocus:!0,canRequestFocus:!0,debugLabel:"WelcomeTakeover",onKey:(B0)=>{if(B0.key==="Enter")return this.advanceIntroStage(),"handled";if(!this.widget.dismissible&&B0.key==="c"&&B0.ctrlKey)return this.widget.onQuit?.(),"handled";if(!this.widget.dismissible&&B0.key==="q")return this.widget.onQuit?.(),"handled";if((B0.key===" "||B0.key==="Space")&&!this.isFinalIntroStage())return this.advanceIntroStage(),"handled";if(B0.key==="Escape"||B0.key==="Esc"){if(!this.widget.dismissible)return this.widget.onQuit?.(),"handled";return this.dismissFromFinalIntroStage()?"handled":"ignored"}if(B0.key==="ArrowRight")return this.nextIntroStage(),"handled";if(B0.key==="ArrowLeft")return this.goToPreviousIntroStage(),"handled";return"ignored"},child:new EQ({fit:"expand",children:[new jR4({color:Q.background,dissolveProgress:k}),new EQ({fit:"expand",children:[new aA({onClick:()=>{},child:y0.expand()}),new e1({left:P,top:f,width:u,height:L,child:R0}),...c?[new e1({left:t,top:Y0,width:a,height:X0,child:kF6({introStages:this.widget.introStages,stage:this.introStage,previousStage:this.previousIntroStage,progress:this.stageTransitionProgress,direction:this.stageTransitionDirection,width:a,height:X0,foreground:Q.foreground,mutedForeground:Q.mutedForeground,accent:E,link:$.app.link,keybind:$.app.keybind,titleRevealProgress:p,dissolveProgress:v,context:A})})]:[],...d?[...b?[new e1({left:t,top:Math.max(0,x-1),width:a,height:1,child:new D0({text:gF6({stage:this.introStage,featureStageCount:Math.max(0,this.widget.introStages.length-2),foreground:Q.mutedForeground,dissolveProgress:v}),textAlign:"center"})})]:[],new e1({left:t,top:x,width:a,height:1,child:dF6({finalStage:this.isFinalIntroStage(),dismissible:this.widget.dismissible,foreground:Q.mutedForeground,keybind:$.app.keybind,revealProgress:n,dissolveProgress:v,context:A})})]:[]]})]})})}}class jR4 extends YB{color;dissolveProgress;constructor({color:A,dissolveProgress:Q}){super();this.color=A,this.dissolveProgress=Q}createRenderObject(){return new RR4(this.color,this.dissolveProgress)}updateRenderObject(A){A.update(this.color,this.dissolveProgress)}}class RR4 extends gA{color;dissolveProgress;constructor(A,Q){super();this.color=A,this.dissolveProgress=Q}update(A,Q){this.color=A,this.dissolveProgress=Q,this.markNeedsPaint()}performLayout(){let A=this._lastConstraints;nA(!!A,"performLayout called without constraints");let Q=A.constrain(A.biggest.width,A.biggest.height);this.setSize(Q.width,Q.height),super.performLayout()}paint(A,Q=0,$=0){let B=Math.floor(Q+this.offset.x),E=Math.floor($+this.offset.y),D=Math.floor(this.size.width),J=Math.floor(this.size.height),U={bg:this.color},Y=ME(this.dissolveProgress);if(Y<=0){A.fill(B,E,D,J," ",U);return}if(Y>=1)return;for(let Z=0;Z<J;Z++)for(let F=0;F<D;F++)if(!SF6(F,Z,D,J,Y))A.fill(B+F,E+Z,1,1," ",U)}}function ME(A){return Math.min(1,Math.max(0,A))}function xT(A){return 1-(1-A)**3}function HR4(A){return CR4[A]??CR4[0]}function NR4(A,Q,$){return{primary:Oq(A.primary,Q.primary,$),secondary:Oq(A.secondary,Q.secondary,$)}}function _F6({dismissProgress:A,easedDismissProgress:Q,introOrbScale:$,normalOrbCenterX:B,normalOrbCenterY:E,size:D}){return{orbScale:$+($*0.86-$)*Q,orbCenterX:B+(D.width*0.54-B)*Q,orbCenterY:E-D.height*0.44*Q,textDissolveProgress:ME(A/0.52),backdropDissolveProgress:xT(ME((A-0.12)/0.88))}}function SF6(A,Q,$,B,E){let D=B<=1?0:Q/(B-1),J=PR4(A+Q*Math.max(1,$));return(1-D)*0.72+J*0.28<E}function kF6({introStages:A,stage:Q,previousStage:$,progress:B,direction:E,width:D,height:J,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V}){if($===null||B>=1)return $p0({introStages:A,stage:Q,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V});let K=xT(B),z=E*Math.round((1-K)*D),W=-E*Math.round(K*D);return new Fq(new EQ({fit:"expand",children:[new e1({left:W,top:0,width:D,height:J,child:$p0({introStages:A,stage:$,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:$===0?1:I,dissolveProgress:G,context:V})}),new e1({left:z,top:0,width:D,height:J,child:$p0({introStages:A,stage:Q,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V})})]}))}function $p0({introStages:A,stage:Q,foreground:$,mutedForeground:B,accent:E,link:D,keybind:J,titleRevealProgress:U,dissolveProgress:Y,context:Z}){let F=A[Q]??A[0]??Ep0[0],X=new $0({color:E,bold:!0}),I=new $0({color:$}),G=A===Ep0&&Q===0,V=[...F.title===null?[]:[new D0({text:G?r90(yF6({progress:U,foreground:E,pulseColor:E}),Y):new g(A8(F.title,Y),X),textAlign:"center"})],...F.body.length>0?[fF6()]:[],...F.body.map((K)=>xF6(K,I,B,D,J,Y,Z))];return new $6({child:new mA({padding:p0.horizontal(1),child:new FA({crossAxisAlignment:"stretch",mainAxisAlignment:"center",mainAxisSize:"min",children:V})})})}function fF6(){return y0.height(1)}function xF6(A,Q,$,B,E,D,J){if(typeof A==="string")return new D0({text:new g(A8(A,D),Q),textAlign:"center"});if("codeBlock"in A)return new M5({onCopy:(U,Y)=>{if(Y)UQ.success(J,"Copied to clipboard",2000)},child:new FA({mainAxisSize:"min",children:A.codeBlock.map((U)=>new D0({text:new g(A8(U,D),new $0({color:E})),textAlign:"center",selectable:!0}))})});if("keybind"in A){let U=new D0({text:new g("",void 0,[new g(A8(A.text,D),new $0({color:$,dim:!0})),new g(A8(A.keybind,D,tA(A.text).length),new $0({color:E}))]),textAlign:"center",selectable:"selectable"in A?A.selectable:!1});if("selectable"in A)return new $6({child:new M5({child:U})});return U}if("highlightText"in A){let U=j$.createSpan(A.href,A.linkText,new $0({color:B,underline:!0})),Y=dX.of(J),Z=new g("",void 0,[new g(A.text,Q),new g(A.highlightText,new $0({color:E})),new g(A.textAfterHighlight,Q),new g(U.text,U.style,U.children,U.hyperlink,()=>{i6(J,A.href,{forceExternal:!1,onShowImagePreview:Y})}),new g(A.textAfter,Q)]);return new D0({text:r90(Z,D),textAlign:"center"})}if("linkText"in A){if(A.linkWidget)return new FA({mainAxisSize:"min",children:[new D0({text:new g(A8(A.text,D),Q),textAlign:"center"}),new $6({child:new OA({mainAxisSize:"min",children:[j$.createWidget(J,A.href,A8(A.linkText,D),new $0({color:B,underline:!0})),new D0({text:new g(A8(A.textAfter,D),Q)})]})})]});let U=j$.createSpan(A.href,A.linkText,new $0({color:B,underline:!0})),Y=dX.of(J),Z=new g("",void 0,[new g(A.text,Q),new g(U.text,U.style,U.children,U.hyperlink,()=>{i6(J,A.href,{forceExternal:!1,onShowImagePreview:Y})}),new g(A.textAfter,Q)]);return new D0({text:r90(Z,D),textAlign:"center"})}if(D>0)return new D0({text:new g(A8(A.text,D),new $0({color:B,underline:!0})),textAlign:"center"});return new $6({child:j$.createWidget(J,A.href,A.text,new $0({color:B,underline:!0}))})}function yF6({progress:A,foreground:Q,pulseColor:$}){let B=new $0({color:Q,bold:!0}),E=new $0({color:hF6({progress:A,foreground:Q,pulseColor:$}),bold:!0});return new g("",void 0,[new g(bF6(A).padEnd(Dp0," "),B),new g(" ",B),new g(qR4(MR4,PF6,A,0.72),B),new g(" ",B),new g(qR4(OR4,TF6,A,0.88),E)])}function bF6(A){let Q=tA(uR4),$=Math.min(Dp0,Math.ceil(ME(A/0.62)*Dp0));return Q.slice(0,$).join("")}function qR4(A,Q,$,B){return $>=B?A:"".padEnd(Q," ")}function hF6({progress:A,foreground:Q,pulseColor:$}){if(A<0.88||A>=1)return Q;let B=ME((A-0.88)/0.12);return Math.cos(B*Math.PI*4)*(1-B)>0.12?$:Q}function gF6({stage:A,featureStageCount:Q,foreground:$,dissolveProgress:B}){return new g(A8(`${A}/${Q}`,B),new $0({color:$,dim:!0}))}function mF6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D}){let J=new $0({color:B}),U=new $0({color:$,dim:!0}),Y=Q?A?"Enter":"Space":"Esc",Z=Q?A?" to get started":" to continue":" to quit",F="",X="",I=`${Z}`;if(!Q)return new g("",void 0,[new g(Y,J),new g(Z,U),new g("",J),new g("",U)]);let G=wR4(Y,E),V=wR4(I,ME((E*(tA(Y).length+tA(I).length)-tA(Y).length)/tA(I).length));return new g("",void 0,[new g(A8(G,D),J),new g(A8(V.slice(0,Z.length),D),U),new g(A8(V.slice(Z.length,Z.length+0),D),J),new g(A8(V.slice(Z.length+0),D),U)])}function dF6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D,context:J}){if(Q)return new D0({text:mF6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D}),textAlign:"center"});let U=new $0({color:B}),Y=new $0({color:$,dim:!0});return new M5({onCopy:(Z,F)=>{if(F)UQ.success(J,"Copied to clipboard",2000)},child:new D0({text:new g("",void 0,[new g("q",U),new g(" to quit",Y)]),textAlign:"center",selectable:!0})})}function wR4(A,Q){let $=tA(A),B=Math.min($.length,Math.ceil(ME(Q)*$.length));return $.slice(0,B).join("").padEnd($.length," ")}function r90(A,Q,$=0){if(Q<=0)return A;let B=$+tA(A.text??"").length,E=A.children?.map((D)=>{let J=r90(D,Q,B);return B+=tA(D.toPlainText()).length,J});return new g(A.text?A8(A.text,Q,$):A.text,A.style,E,A.hyperlink,A.onClick)}function A8(A,Q,$=0){if(Q<=0)return A;return tA(A).map((E,D)=>{if(E.trim()==="")return E;return PR4($+D)<Q?" ":E}).join("")}function PR4(A){let Q=Math.sin((A+1)*12.9898)*43758.5453;return Q-Math.floor(Q)}function pF6(A){let $=A.observer.protocolMessages().filter((B)=>B.role==="assistant").at(-1);if(!$)return null;return $.content.filter((B)=>B.type==="text").map((B)=>B.text).join("")}function TR4(A){A.client.cancelAgentLoop().catch((Q)=>{S.warn("Failed to cancel plugin agent run",{error:Q})})}function lF6(A,Q={}){return new Promise(($,B)=>{if(Q.signal?.aborted){TR4(A),B(Error("Agent run cancelled"));return}let E=!1,D=null,J=setTimeout(()=>{D?.(),Y.unsubscribe(),B(Error("Timed out waiting for agent response"))},Q.timeoutMs??600000),U=()=>{clearTimeout(J),Y.unsubscribe(),TR4(A),B(Error("Agent run cancelled"))};if(Q.signal!==void 0)Q.signal.addEventListener("abort",U,{once:!0}),D=()=>Q.signal?.removeEventListener("abort",U);let Y=A.observer.agentState().subscribe((Z)=>{if(h3(Z)){E=!0;return}if(!E)return;let F=pF6(A);if(F===null)return;clearTimeout(J),D?.(),Y.unsubscribe(),$(F)})})}class Up0 extends d0{listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;updateService;initialThreadIDs;showWelcome;welcomeVariant;onWelcomeDismissed;notificationService;mcpTrustHandler;onThreadArchived;onActiveThreadChange;onRelaunchRequested;onFirstFrame;initialUserInput;getDefaultNewThreadVisibility;observeThreadSummaries;openThreadPickerOnStart;workspaceSettingsFilePath;context;constructor(A){super();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.updateService=A.updateService,this.initialThreadIDs=A.initialThreadIDs??[],this.showWelcome=A.showWelcome??!1,this.welcomeVariant=A.welcomeVariant??"intro",this.onWelcomeDismissed=A.onWelcomeDismissed,this.notificationService=A.notificationService,this.mcpTrustHandler=A.mcpTrustHandler,this.onThreadArchived=A.onThreadArchived,this.onActiveThreadChange=A.onActiveThreadChange,this.onRelaunchRequested=A.onRelaunchRequested,this.onFirstFrame=A.onFirstFrame,this.initialUserInput=A.initialUserInput,this.getDefaultNewThreadVisibility=A.getDefaultNewThreadVisibility,this.observeThreadSummaries=A.observeThreadSummaries,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.workspaceSettingsFilePath=A.workspaceSettingsFilePath,this.context=A.context}createState(){return new _R4}}class _R4 extends m0{editorController=new $Z;commandPalette=new vb0(this);commandRegistry=new Lm0;toastController=new kb0;relaunchNotificationController=new Wm0;exitHintTimer=new Op(this,1000);ideStatus=new c3(this,{});threadNavigationHistory=new Nm0;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;activeThreadIDSubscription=null;activePluginMessageSubscription=null;activePluginUIRequestsSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;executorAlreadyConnectedDialog=null;switchThreadPickerVisible=!1;welcomeVisible=!1;endCreditsVisible=!1;invadersHighScore=0;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;emptyThreadTerminalTitleController=new dl;pluginIntegration=null;mcpTrustIntegration=null;updateRelaunchIntegration=null;noticesPollingTimeout=null;notices;editorFocusNode=new a7({debugLabel:"EditorPanel"});loadThreads=async()=>{return this.widget.context.listThreads()};focusEditor=()=>{this.editorFocusNode.requestFocus()};focusEditorAfterNextFrame(){W6.instance.addPostFrameCallback(()=>{if(!this.mounted)return;this.focusEditor()},"Neo focus editor")}analyzeContextForThread=async(A,Q)=>{return Nz4({ampURL:this.widget.context.ampURL,configService:this.widget.configService,threadID:A,signal:Q})};onSwitchThread=(A)=>{return this.connectToExistingThread(A,{recordNavigation:!0,rethrowError:!0})};onSelectSidebarThread=async(A)=>{this.focusEditor(),await this.onSwitchThread(A)};threadListSidebar=new ec0({state:this,isBlocked:()=>this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal(),getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,getWorkspaceRoot:()=>this.widget.context.workspaceRoot,loadThreads:this.loadThreads,observeThreadSummaries:()=>this.widget.observeThreadSummaries(),archiveThread:(A)=>this.archiveThread(A),onSelectThread:this.onSelectSidebarThread,focusMainContent:this.focusEditor,getInitialVisible:()=>this.widget.context.threadListSidebarVisible});sendFeedbackReport=async(A)=>h80({configService:this.widget.configService,settingsFilePath:this.widget.context.settingsFilePath},A);archiveThread=async(A)=>{let Q=await TH4({configService:this.widget.configService},A);if(Q===null){let $=this.activeThreadContext?.client.getThreadId()??null;if(this.widget.clientPool.disconnectThread(A),this.widget.onThreadArchived?.(A),$===A)this.startNewDraftThread()}return Q};addThreadLabel=async(A,Q)=>{let $=await ON4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};removeThreadLabel=async(A,Q)=>{let $=await LN4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};initState(){if(LX.getInstance().interceptConsole(),this.invadersHighScore=this.widget.context.invadersHighScore??0,this.notices=new Am0(this.widget.configService,($)=>this.setState($)),W6.instance.addPostFrameCallback(()=>{setTimeout(()=>this.widget.onFirstFrame?.(),0),this.noticesPollingTimeout=setTimeout(()=>{this.noticesPollingTimeout=null,this.notices.startPolling()},500)},"Neo notices polling"),this.widget.showWelcome)this.welcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:$,error:B})=>{if(S.error("Neo failed to connect to thread",{threadID:$,error:B}),!$)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configSubscription=this.widget.configService.config.subscribe(($)=>{this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(I00($.settings)))}),this.updateRelaunchIntegration=new qm0({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested,relaunchNotificationController:this.relaunchNotificationController,updateService:this.widget.updateService}),this.updateRelaunchIntegration.init(),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput,Q=this.widget.initialThreadIDs[0];if(Q){let $={};if(A)$.initialUserInput=A;this.connectToInitialThreads(Q,$)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.context.sessionAgentMode);this.pluginIntegration=new Km0({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,context:this.widget.context,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread,readThreadMessages:this.readPluginThreadMessages,readThreadTitle:this.readPluginThreadTitle,subscribeThreadTitle:this.subscribePluginThreadTitle,runAgent:this.runPluginAgent,onBlockingConfirmDialogChange:this.syncEmptyThreadPluginConfirmationTitle}),this.pluginIntegration.init(),this.mcpTrustIntegration=new sh0({state:this,mcpTrustHandler:this.widget.mcpTrustHandler,toastController:this.toastController,workspaceSettingsFilePath:this.widget.workspaceSettingsFilePath}),this.mcpTrustIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=V1.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this,Q=this.widget.context.pluginService?iw4({pluginService:this.widget.context.pluginService,workspaceRoot:this.widget.context.workspaceRoot,logFilePath:this.widget.context.logFilePath,toastController:this.toastController}):[],B=[Au4({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["resume"],status:{type:"enabled"},sortBoost:100,run:(E,D,J)=>{E.pushWithDismiss((U)=>td0({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,loadThreadTail:this.widget.context.loadThreadTail,onSelectThread:this.onSwitchThread,onDismiss:U,onThreadSelected:J}))}},...this.threadListSidebar.commands(),{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(E,D,J)=>{A.navigateBack(),J()}},aM4({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(E,D,J)=>{A.navigateForward(),J()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",status:{type:"enabled"},run:(E,D,J)=>{E.push(new Yd0({mcpServers:this.widget.context.mcpServers,onDismiss:J}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",status:{type:"enabled"},run:(E)=>{E.pushWithDismiss((D)=>new Ap0({toolboxes:this.widget.context.toolboxes,onDismiss:D}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","blog","announcements"],status:{type:"enabled"},run:async(E,D,J)=>{try{await i6(D,"https://ampcode.com/chronicle")}finally{J()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config"],status:{type:"enabled"},run:()=>{TK(this.widget.context.settingsFilePath).catch((E)=>{S.error("Failed to open settings file in editor",{error:E})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains"],status:{type:"enabled"},run:(E,D,J)=>{E.pushWithDismiss((U)=>new Ud0({onCancel:U,onSelect:(Y)=>{this.handleIdeSelection(Y),J()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["manual","?"],status:{type:"enabled"},run:(E,D,J)=>{E.push(new Rm0({commands:aB.of(D).commands,onDismiss:J}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",status:{type:"enabled"},run:(E,D,J)=>{J(),A.showWelcome()}},{noun:"amp",verb:"end credits",description:"Roll the full-screen Amp credits",status:{type:"enabled"},run:(E,D,J)=>{J(),A.showEndCredits()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["v"],status:{type:"enabled"},run:(E,D,J)=>{E.push(new E1({header:"Amp Version",maxWidth:72,onDismiss:J,child:new D0({text:new g(r50({version:"0.0.1780694019-g120cbb",buildTimestamp:"2026-06-05T21:18:30.332Z",buildType:"release"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","bye"],shortcut:CA.ctrl("c"),status:{type:"enabled"},run:(E,D)=>{w4.maybeInvoke(D,new hK)}},...Q,...MN4(this.widget.context.logFilePath)].map((E)=>this.commandRegistry.register(E));return()=>{for(let E of B)E()}}build(A){let Q=this.buildHints(),$=this.ideStatus.getValue(),B=this.notices.current,E=new nc0({initialAgentMode:this.widget.context.sessionAgentMode,initialPluginAgentModeKey:this.widget.context.initialPluginAgentModeKey,analyzeContextForThread:this.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,editorFocusNode:this.editorFocusNode,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,sendFeedbackReport:this.sendFeedbackReport,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:$,statusItems:this.pluginIntegration?.getStatusItems()??[],pluginConfirmationBlocked:this.pluginIntegration?.hasBlockingConfirmDialog()??!1,notificationService:this.widget.notificationService,notice:this.activeThreadContext||this.welcomeVisible?null:B,onDismissNotice:(I)=>this.notices.dismiss(I)}),D=W4.of(A),J=D.capabilities.animationSupport!=="disabled",U=this.threadListSidebar.visibleWidth(),Y=Math.max(0,D.size.width-U),F=[new KA({constraints:Z4.tight(D.size.width,D.size.height),child:this.threadListSidebar.buildBody(E)})];if(this.commandPalette.isEnabled())F.push(new C6({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new jm0({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.welcomeVisible)F.push(td0({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,loadThreadTail:this.widget.context.loadThreadTail,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.welcomeVisible)F.push(new C6({debugLabel:"WelcomeDialogOverlay",child:new Jp0({onDismiss:this.dismissWelcome,onQuit:()=>V1.instance.stop(),animationsEnabled:J,variant:this.widget.welcomeVariant})}));let X=this.executorAlreadyConnectedDialog;if(X)F.push(new C6({debugLabel:"ExecutorAlreadyConnectedDialogOverlay",child:new Ed0({existingExecutorPid:X.existingExecutorPid,onChoice:this.handleExecutorAlreadyConnectedChoice})}));if(F.push(...this.mcpTrustIntegration?.buildDialogLayers()??[]),F.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.context.isInternalUser)F.push(new Tm0({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:s90.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,observerSnapshot$:this.activeThreadContext?.observer.observerSnapshot()??null}));if(this.focusDebugVisible)F.push(new Dd0);if(this.endCreditsVisible)F.push(new tm0({onComplete:this.completeEndCredits,highScore:this.invadersHighScore,onHighScoreChange:this.updateInvadersHighScore}));return new SQ({context:this.widget.context,child:new aB({commandRegistry:this.commandRegistry,child:new qT({completionBuilder:this.widget.completionBuilder,child:new UQ({controller:this.toastController,child:new w4({actions:this.buildActions(),child:new aQ({debugLabel:"AppShortcuts",shortcuts:this.buildShortcuts(),child:new TQ({debugLabel:"AppShellFocus",canRequestFocus:!1,skipTraversal:!0,child:new fb0({controller:this.toastController,complexToastControllers:[this.relaunchNotificationController,...B&&this.activeThreadContext&&!this.welcomeVisible?[this.notices]:[]],child:new Pm0({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new ap({left:U,width:Y,child:new EQ({children:F})})})})})})})})})})})}buildShortcuts(){let A=new Map([[CA.ctrl("c"),new g70],[CA.ctrl("o"),new d70],[CA.alt("i"),new p70],[CA.alt("p"),new Up],[CA.ctrl("."),new n70],[CA.ctrl("t"),new r70],...this.threadListSidebar.shortcutEntries()]);if(s90.env.NODE_ENV==="development"&&s90.platform==="darwin")A.set(CA.meta("r"),new m70);return A}buildActions(){let A=new cA(()=>{if(y2.hasAnyCopyableSelection())return y2.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new cA(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),$=new cA(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),B=new cA(()=>{return this.startNewDraftThread(),"handled"}),E=new cA(()=>{return V1.instance.stop(),"handled"}),D=new cA(()=>{return _l({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),"handled"}),J=new cA((I)=>{if(!I.text)return"ignored";return V1.instance.tuiInstance.clipboard.writeText(I.text).then((G)=>{if(G.ok)this.toastController.show(I.successMessage,"success",2000);else this.toastController.show(`${I.failureMessage}: ${G.userFacingErrorMessage}`,"error",4000)}).catch((G)=>{S.error("Failed to copy Neo text to clipboard",{error:G}),this.toastController.show(I.failureMessage,"error",2000)}),"handled"}),U=new cA(()=>{return V1.instance.toggleFrameStatsOverlay(),"handled"}),Y=new cA(()=>this.notices.dismissCurrent()?"handled":"ignored"),Z=new cA(()=>{if(!this.widget.context.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),F=Gu4({getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,context:this.widget.context,toastController:this.toastController,startNewDraftThread:this.startNewDraftThread,sendFeedbackReport:this.sendFeedbackReport}),X=new cA(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[g70,A],[Lq,B],[hK,E],[m70,D],[FB,J],[Dl,$],[d70,Q],[p70,Z],...this.threadListSidebar.actionEntries(),[n70,Y],...F,[Up,U],[r70,X]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.cancelOwnerUIRequests(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),this.widget.onActiveThreadChange?.(null),this.syncEmptyThreadPluginConfirmationTitle(),A.prompt!==void 0)this.editorController.text=A.prompt;this.focusEditorAfterNextFrame()}syncEmptyThreadPluginConfirmationTitle=()=>{this.emptyThreadTerminalTitleController.setPluginConfirmationBlocked(this.activeThreadContext===null&&(this.pluginIntegration?.hasBlockingConfirmDialog()??!1))};closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=this.applySessionDefaultsToThreadSettings(await gP(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){S.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.context.sessionAgentMode,$=A,B=$q(Q),E=q50(this.widget.context,Q);if(B!==void 0&&E!==void 0)$={...$,[B]:E};return H50($,{agentMode:Q,explicitEffort:this.widget.context.explicitReasoningEffort,sessionState:this.widget.context})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=vR4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(aU(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=vR4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(bK);if(this.exitHintTimer.isActive())A.add(ZT);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),V1.instance.stop();else this.exitHintTimer.activate()};dismissWelcome=()=>{if(!this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!1}),this.widget.onWelcomeDismissed?.()};updateInvadersHighScore=(A)=>{if(A<=this.invadersHighScore)return;this.setState(()=>{this.invadersHighScore=A}),AJ((Q)=>({...Q,neoInvadersHighScore:Math.max(Q.neoInvadersHighScore,A)})).catch((Q)=>{S.warn("Failed to save Neo Invaders high score",{error:Q instanceof Error?Q.message:String(Q)})})};showWelcome=()=>{if(this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!0})};showEndCredits=()=>{if(this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!0})};completeEndCredits=()=>{if(!this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!1})};promptExecutorAlreadyConnected(A){return new Promise((Q)=>{this.setState(()=>{this.executorAlreadyConnectedDialog={existingExecutorPid:A.existingExecutorPid,resolve:($)=>{Q($==="watch"?"observe":"disconnect")}}})})}handleExecutorAlreadyConnectedChoice=(A)=>{if(this.resolveExecutorAlreadyConnectedDialog(A),A==="exit")V1.instance.stop()};resolveExecutorAlreadyConnectedDialog(A){let Q=this.executorAlreadyConnectedDialog;if(!Q)return;this.setState(()=>{this.executorAlreadyConnectedDialog=null}),Q.resolve(A)}closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1}),this.focusEditorAfterNextFrame()};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,$=null,B,E,D)=>{await this.ensureDraftThreadSettingsInitialized();let J=this.activeThreadContext?.client.getThreadId(),U=A.find(D00);if(U)this.widget.history.add(U.text,s90.cwd()),this.widget.history.reset();let Y=$?void 0:await this.widget.getDefaultNewThreadVisibility?.(),Z=$??Y??null,F=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,Z??void 0,E,D);if(this.sendUserMessage(F,A,E?void 0:Q,E?void 0:B),!E)this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings);this.threadNavigationHistory.recordNavigation(J),this.setActiveClient(F)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.context.sessionAgentMode=A;let $=Q["reasoning.effort"];if($!==void 0)this.widget.context.lastReasoningEffortByMode={...this.widget.context.lastReasoningEffortByMode??{},[A]:$};let B=$q(A),E=B?Q[B]:void 0;if(E!==void 0)this.widget.context.lastSpeedByMode={...this.widget.context.lastSpeedByMode??{},[A]:E};AJ((D)=>{let J={...D,agentMode:A};if($!==void 0)J={...J,lastReasoningEffortByMode:{...J.lastReasoningEffortByMode??{},[A]:$}};if(E!==void 0)J={...J,lastSpeedByMode:{...J.lastSpeedByMode??{},[A]:E}};return J}).catch((D)=>{S.warn("Failed to persist Neo session defaults for new message",{error:D instanceof Error?D.message:String(D)})})}sendUserMessage(A,Q,$,B,E){let D=o50(this.ideStatus.getValue());if(B===void 0){A.client.sendUserMessage(Q,$,{steer:E?.steer,userState:D}).catch((J)=>{S.warn("Failed to send user message",{error:J})});return}A.client.sendUserMessage(Q,$,{reasoningEffort:B,steer:E?.steer,userState:D}).catch((J)=>{S.warn("Failed to send user message",{error:J})})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};getRelaunchThreadIDs=()=>{let A=new Set,Q=this.getActiveThreadID();if(Q)A.add(Q);for(let $ of this.widget.clientPool.activeThreadIDs)A.add($);return[...A]};appendPluginMessagesToThread=async(A,Q,$)=>{let B=this.activeThreadContext;if(!B){if(Q){for(let D of A)await this.widget.clientPool.appendUserMessageToThread(Q,D.content,$);return}throw Error("appendToThread is not available - no active thread")}let E=B.client.getThreadId();if(Q&&E!==Q){for(let D of A)await this.widget.clientPool.appendUserMessageToThread(Q,D.content,$);return}for(let D of A)this.sendUserMessage(B,[{type:"text",text:D.content}],void 0,void 0,$)};readPluginThreadMessages=async(A,Q)=>{let $=this.activeThreadContext;if(!$)throw Error("thread.messages is not available - no active thread");let B=$.client.getThreadId();if(Q&&B!==Q)throw Error("thread.messages is only available for the active thread");return QoA($oA($.observer.protocolMessages()),A)};readPluginThreadTitle=async(A)=>{let Q=this.activeThreadContext;if(!Q)throw Error("thread.title is not available - no active thread");let $=Q.client.getThreadId();if(A&&$!==A)throw Error("thread.title is only available for the active thread");return Q.observer.title().getValue()??null};subscribePluginThreadTitle=(A,Q)=>{let $=this.activeThreadContext;if(!$)throw Error("thread.title.subscribe is not available - no active thread");let B=$.client.getThreadId();if(A&&B!==A)throw Error("thread.title.subscribe is only available for the active thread");return $.observer.title().subscribe((E)=>{Q.next(E??null)})};runPluginAgent=async(A,Q,$)=>{await this.ensureDraftThreadSettingsInitialized();let B=this.widget.clientPool.createNewThread(this.widget.context.sessionAgentMode,this.draftThreadSettings,void 0,A,Q.agentModeDisplay,Q.parentThreadID,{trackAsLastActive:!1,executorClientID:cY.parse(`neo-subagent-${cF6()}`)});this.sendUserMessage(B,[{type:"text",text:Q.message}]);try{let E=await lF6(B,{timeoutMs:Q.timeoutMs,signal:$}),D=B.client.getThreadId();return D?{threadID:D,text:E}:{text:E}}finally{this.widget.clientPool.disconnect(B)}};async connectToExistingThread(A,Q={}){let $=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let B=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:(E)=>this.promptExecutorAlreadyConnected(E)});if(this.setActiveClient(B),Q.recordNavigation&&$!==A)this.threadNavigationHistory.recordNavigation($);if(Q.initialUserInput)this.sendUserMessage(B,[{type:"text",text:Q.initialUserInput}])}catch(B){if(S.error("Failed to load thread",{error:B,threadID:A}),this.toastController.show(`Failed to load ${A}: ${B instanceof Error?B.message:String(B)}`,"error",4000),Q.rethrowError)throw B}finally{this.setState(()=>{this.connectingToThreadID=null})}}async connectToInitialThreads(A,Q={}){await this.connectToExistingThread(A,Q);let $=this.widget.initialThreadIDs.filter((B)=>B!==A);await Promise.all($.map((B)=>this.resumeBackgroundThread(B)))}async resumeBackgroundThread(A){try{await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:async()=>"observe"})}catch(Q){S.error("Failed to resume background thread",{error:Q,threadID:A}),this.toastController.show(`Failed to resume ${A}: ${Q instanceof Error?Q.message:String(Q)}`,"error",4000)}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}setActiveClient({client:A,observer:Q,agentModeDisplay:$}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q,agentModeDisplay:$}}),this.syncEmptyThreadPluginConfirmationTitle(),this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe((B)=>{this.widget.onActiveThreadChange?.(B)}),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription?.unsubscribe(),this.pluginIntegration?.cancelOwnerUIRequests(),this.activePluginMessageSubscription=Q.pluginMessages().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage(B,(E)=>{A.sendPluginMessage(E)})}),this.activePluginUIRequestsSubscription=Q.pluginUIRequests().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage({type:"plugin_message",message:{type:"event",event:"plugin.ui.snapshot",data:{requests:[...B]}}},(E)=>{A.sendPluginMessage(E)})})}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){S.error("Failed to connect to IDE",{error:Q});let $=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${$}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.threadListSidebar.dispose(),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.emptyThreadTerminalTitleController.dispose(),this.mcpTrustIntegration?.dispose(),this.mcpTrustIntegration=null,this.updateRelaunchIntegration?.dispose(),this.updateRelaunchIntegration=null,this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.noticesPollingTimeout)clearTimeout(this.noticesPollingTimeout),this.noticesPollingTimeout=null;this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.notices.dispose(),this.widget.notificationService.detach(),this.toastController.dispose(),this.editorFocusNode.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.executorAlreadyConnectedDialog!==null||this.welcomeVisible||(this.mcpTrustIntegration?.hasBlockingDialog()??!1)||this.endCreditsVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function vR4(A,Q,$){let B={...A};for(let E of iF6(Q,$)){if(!aU(A[E],Q[E]))continue;let D=$[E];if(D===void 0)delete B[E];else B[E]=D}return B}function iF6(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}E3();function SR4(A,Q,$,B){let E=UbA(A),D="\x1B[0m",J="\x1B[34m",U="\x1B[90m",Y="\x1B[2m",Z=[];if(A.archived)Z.push("\x1B[90m\x1B[2mArchived\x1B[0m");Z.push(`${E}`),Z.push(`\x1B[34m${Q}\x1B[0m`),Z.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let F=14,X=7,I=new f2(F,X),G=new R5(42),V=new wT(F,X,F,X,F,X,0,A.agentMode??"smart","intensity","ascii",void 0,void 0,g0.default(),G);V.layout(Z4.tight(F,X)),V.paint(I,0,0);let K=I.getBuffer().getCells(),z=0;for(let R=0;R<X;R++)if(K[R].some((_)=>_.char!==" ")){z=R;break}let W=X-1;for(let R=X-1;R>=0;R--)if(K[R].some((_)=>_.char!==" ")){W=R;break}function C(R,_){if(!R)return"";if(R.type==="rgb"){let{r:P,g:f,b:h}=R.value;if($.getColorDepth()>=24)return`\x1B[${_?38:48};2;${P};${f};${h}m`;let x=Kp(P,f,h);return`\x1B[${_?38:48};5;${x}m`}return""}let H=[];if(W>=z)for(let R=z;R<=W;R++){let _="";for(let P=0;P<F;P++){let f=K[R][P],h=f.char,x=C(f.style.fg,!0);_+=x+h+"\x1B[0m"}H.push(_)}let N=H.length,w=Math.max(N,Z.length),u=Math.floor((w-N)/2),L=Math.floor((w-Z.length)/2);for(let R=0;R<w;R++){let _=" ".repeat(F);if(R>=u&&R<u+N)_=H[R-u];let P=" ",f="";if(R>=L&&R<L+Z.length)f=Z[R-L];$.write(_+P+f+`
3088
3090
  `)}if(B)$.write(`
3089
3091
  \x1B[90m${B}\x1B[0m
3090
3092
  `)}n0();class Yp0{status=v3.status;constructor(){this.autoConnect()}async connect(A){await v3.start(A,!0,"user-initiated"),v3.selectConfig(A)}autoConnect(){let A=v3.getSelectedConfig();if(A){v3.start(A,!0,"auto-startup").catch((Q)=>{S.error("Failed to auto-connect to IDE",{error:Q})});return}this.discoverAndConnect()}async discoverAndConnect(){try{await ThA();let A=await cC({});if(A.length===1&&A[0])v3.selectConfig(A[0]),await v3.start(A[0],!0,"auto-startup")}catch(A){S.error("Failed to auto-discover IDE",{error:A})}}}n0();n0();import{exec as aq}from"node:child_process";function kR4(A="idle"){try{if(A==="idle"){if(process.platform==="darwin")aq("afplay /System/Library/Sounds/Submarine.aiff");else if(process.platform==="win32")aq("powershell [console]::beep(800,200)");else if(process.platform==="linux")aq("paplay /usr/share/sounds/freedesktop/stereo/message.oga || beep")}else if(A==="idle-review"){if(process.platform==="darwin")aq("afplay /System/Library/Sounds/Glass.aiff")}else if(A==="requires-user-input"){if(process.platform==="darwin")aq("afplay /System/Library/Sounds/Ping.aiff");else if(process.platform==="win32")aq("powershell [console]::beep(1000,300)");else if(process.platform==="linux")aq("paplay /usr/share/sounds/freedesktop/stereo/dialog-information.oga || beep -f 1000 -l 100")}}catch(Q){S.error(`Failed to play notification sound (${A}):`,Q)}}Np();ub0();var nF6=2000,aF6="Agent is ready",oF6="Waiting for approval";function fR4(A){let Q=!0,$=!0,B=A.configService.config.subscribe((W)=>{Q=W.settings["notifications.enabled"]??!0,$=W.settings["notifications.system.enabled"]!==!1}),E=0,D=()=>{let W=G?.prepareTerminalTitleForNotification();if(W!==void 0)process.stdout.write(uK4(W))},J=(W)=>{if(!Q)return;let C=Date.now();if(C-E<nF6)return;if(E=C,PK())return;if(DG4())D(),setTimeout(JG4,Yb0);else kR4(W)},U=()=>{J("idle"),V(aF6)},Y=()=>{J("requires-user-input"),V(oF6)},Z=(W)=>W?.attempt===void 0||W.attempt===0,F=null,X=null,I=null,G,V=(W)=>{if(!Q||!$)return;if(PK()&&!wb0()&&!Fp())return;D(),setTimeout(()=>{process.stdout.write(wK4(W))},Yb0)},K=()=>{F?.unsubscribe(),X?.unsubscribe(),F=null,X=null,I=null,G=void 0};return{attach:(W,C,H)=>{if(K(),G=H,C)X=C.subscribe({next:(N)=>{if(N===null)return;if(!Z(N))return;U()},error:(N)=>{S.debug("Neo notification active error stream errored",{error:N})}});F=W.subscribe({next:(N)=>{try{let w=I!==null&&h3(I),u=I==="awaiting_approval",L=w||u;if(N==="awaiting_approval"&&!u)Y();else if(N==="idle"&&L)U()}catch(w){S.debug("Neo notification handling failed",{error:w})}finally{I=N}},error:(N)=>{S.debug("Neo notification agent state stream errored",{error:N})}})},detach:K,unsubscribe(){K(),B.unsubscribe()}}}function rF6({initialUserInput:A,showWelcome:Q,hideWelcome:$,welcomeVariant:B,welcomeDismissed:E}){if($)return{show:!1,markDismissedOnDismiss:!1};if(B==="npm-migration")return{show:!0,markDismissedOnDismiss:!1};if(Q)return{show:!0,markDismissedOnDismiss:!0};let D=!A&&!E;return{show:D,markDismissedOnDismiss:D}}async function sF6(A){await AJ((Q)=>lP(Q,A,"interactive"))}async function xR4(A,Q={}){let{initialThreadIDs:$=[],initialUserInput:B,getDefaultNewThreadVisibility:E,openThreadPickerOnStart:D=!1,observerOnly:J=!1,initialAgentMode:U,initialPluginAgentModeKey:Y,initialReasoningEffort:Z,onFirstFrame:F,showWelcome:X=!1,hideWelcome:I=!1,welcomeVariant:G="intro"}=Q,V=G==="npm-migration";if($.length>1)S.info("Resuming multiple initial threads",{threadIDs:$});let K=async(h)=>{let x=await A.getThreadFromServer(h);if(!x)return null;return b30(x)},z=async(h)=>{let x=await A.getThreadFromServer(h);if(!x)throw Error(`Thread ${h} not found`);let v=await JB(h,A.configService,A.apiKey,{usesThreadActors:!0}),k=B7({endpoint:A.rivetEndpoint,poolName:v.poolName}),c={wsToken:v.wsToken,transport:"json-rpc"},b=await k.threadActor.get([v.threadId],{params:c}).fetch("/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({thread:h30(x)}),skipReadyWait:!0});if(!b.ok&&b.status!==409)throw Error(`Thread import failed (${b.status}): ${await b.text()}`);try{await s30(h,A.configService,A.apiKey,{executorType:"local-client"})}catch(p){S.warn("failed to mark thread as imported on server",{threadID:h,error:p instanceof Error?p.message:String(p)})}},W=new ty0(A.rivetEndpoint,A.apiKey,A.configService,{clientID:cY.parse(`neo-${crypto.randomUUID()}`),toolService:A.toolService,skillService:A.skillService,requestPluginToolCall:(h)=>A.pluginService.event.toolCall(h),requestPluginToolResult:(h)=>A.pluginService.event.toolResult(h),pluginService:A.pluginService,pluginPlatform:A.pluginPlatform,canUseV2LocalThreadChanges:A.canUseV2LocalThreadChanges,invokeTool:async(h,x)=>{let v=typeof x.args==="object"&&x.args!==null?x.args:{},k=await qK({toolName:x.toolName,configService:A.configService,toolService:A.toolService,mcpService:A.mcpService,skillService:A.skillService,toolUseID:x.toolCallId,threadId:h});return A.toolService.invokeTool(x.toolName,{args:v},k)},persistLastThreadID:sF6,readFileSystemDirectory:A.readFileSystemDirectory},K,z),C=await Bq(),H=rF6({initialUserInput:B,showWelcome:X,hideWelcome:I,welcomeVariant:G,welcomeDismissed:C.neoWelcomeDismissed}),N={ampURL:A.ampURL,configService:A.configService,getThreadMarkdown:async(h)=>{let x=await A.getThreadFromServer(h);return x?EQ0(x):null},isInternalUser:A.isInternalUser,listThreads:A.listThreads,loadThreadTail:A.getThreadTail,logFilePath:yc,mcpServers:A.mcpService.servers,pluginPlatform:A.pluginPlatform,pluginService:A.pluginService,toolboxes:A.toolboxes,observerOnly:V?!1:J,invadersHighScore:C.neoInvadersHighScore,sessionAgentMode:U??C.agentMode,threadListSidebarVisible:C.threadListSidebarVisible,initialPluginAgentModeKey:Y,explicitReasoningEffort:Z,lastReasoningEffortByMode:C.lastReasoningEffortByMode,lastSpeedByMode:C.lastSpeedByMode,settingsFilePath:A.settingsFilePath,workspaceRoot:A.workspaceRoot},w=(h,x)=>{return EK4({ampURL:A.ampURL,configService:A.configService,threadID:h,signal:x})},u=()=>v50({apiKey:A.apiKey,configService:A.configService,rivetEndpoint:A.rivetEndpoint}),L=new Yp0,R=fR4({configService:A.configService}),_=await A.configService.getLatest();V1.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:_.settings["terminal.animation"]===!1}});let P=new Set,f=new zm0;try{await Mb0(new Up0({clientPool:W,listSkillsForThread:w,completionBuilder:A.completionBuilder,history:new _y0,ideManager:L,configService:A.configService,updateService:A.updateService,initialThreadIDs:V?[]:$,notificationService:R,mcpTrustHandler:A.mcpTrustHandler,initialUserInput:V?void 0:B,getDefaultNewThreadVisibility:E,observeThreadSummaries:u,openThreadPickerOnStart:V?!1:D,workspaceSettingsFilePath:A.workspaceSettingsFilePath,context:N,showWelcome:H.show,welcomeVariant:G,onActiveThreadChange:A.setActiveThreadID,onRelaunchRequested:f.request,onWelcomeDismissed:H.markDismissedOnDismiss?()=>{AJ(XK4).catch((x)=>{S.warn("Failed to mark Neo welcome as dismissed",{error:x})})}:void 0,onThreadArchived:(x)=>{P.add(x)},onFirstFrame:F}));let h=W.lastActiveObservingClient;if(h&&f.shouldShowExitSummary){let{client:x,observer:v}=h,k=x.getThreadId();if(k){let c={id:k,title:v.title().getValue(),agentMode:v.agentMode,archived:P.has(k)},d=`${A.ampURL.replace(/\/$/,"")}/threads/${k}`;SR4(c,d,process.stdout)}}}finally{process.stdout.write(b50("")),R.unsubscribe(),W.dispose(),await A.dispose?.()}process.exit(f.relaunchIfRequested(A.workspaceRoot)??0)}import{execFile as tF6}from"node:child_process";import{closeSync as yR4,openSync as eF6,writeSync as AX6}from"node:fs";import QX6 from"node:tty";var $X6="\x1B[c",BX6="\x1B[?1004h",EX6="\x1B[?1004l",DX6="\x1B[?u",bR4=200,JX6="\x1B[>4;2m",UX6="\x1B[?9001h",YX6="\x1B[?9001l";function hR4(){let A=null;try{if(process.stdout.isTTY){let Q=process.stdout.getWindowSize();A=[Q[0],Q[1]]}}catch{}return{isTTY:process.stdout.isTTY,columns:process.stdout.columns??null,rows:process.stdout.rows??null,windowSize:A,hasRefreshSize:typeof process.stdout._refreshSize==="function"}}function ZX6(){if(process.stdout.isTTY)return{stream:process.stdout,target:"stdout",dispose:()=>{}};if(process.stderr.isTTY)return{stream:process.stderr,target:"stderr",dispose:()=>{}};if(process.platform!=="win32")try{let A=eF6("/dev/tty","w");if(QX6.isatty(A))return{stream:{write(Q){return AX6(A,Q),!0}},target:"dev-tty",dispose:()=>{yR4(A)}};yR4(A)}catch{}return{stream:process.stdout,target:"stdout",dispose:()=>{}}}function R$(A,Q){if(!process.stdout.writable||process.stdout.destroyed){Q?.();return}let $=`${JSON.stringify(A)}
@@ -5014,7 +5016,7 @@ Start Amp from a smaller directory.`};function oX(A,Q){if(!aI4())return;S.debug(
5014
5016
  `)}function nT4(A,Q){A.command("usage").description("Show your current Amp usage and credit balance").action(async($,B)=>{let E=B.optsWithGlobals(),D=await Q(E),J=await xP(D),U=await O4.userDisplayBalanceInfo({},{config:J});if(!U.ok){if(U.error.code==="auth-required")process.stderr.write(_0.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(_0.red("Error: ")+U.error.message+`
5015
5017
  `),process.exit(1)}process.stdout.write(await lK6(U.result.displayText)+`
5016
5018
  `),process.exit(0)})}var KN6=yi.join(iU,"logs","headless.log"),Zi0=yi.join(py,"device-id.json");wX4();async function zN6(){let A=await Promise.all(dC.map(async(Q)=>{try{return{query:Q,hasConfigs:(await Q.listConfigs()).length>0}}catch($){return S.debug("Failed to detect query-based IDE integration",{ideName:Q.ideName,error:$}),{query:Q,hasConfigs:!1}}}));for(let Q of A)if(Q.hasConfigs)return Q.query;return}function Nk4(){zN6().then((A)=>{if(A){let Q=j00(A.ideName);if(Q)xC(Q)}})}try{if(process.platform==="win32")await Promise.resolve().then(() => _4(Xv(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){z7.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
5017
- `)}function WN6(A){process.emitWarning=(Q,$,B,E)=>{let D=typeof Q==="string"?Q:Q.message||String(Q),J=$||"Warning",U=!1;A.warn(D,{name:J,code:B})}}function rB(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")W00("dangerouslyAllowAll",Q.dangerouslyAllowAll)}function CN6(A,Q){if(!d9(Q))return;if(!OG(Q.user.email)){if(A.model)throw new GA("The --model flag is only available for Amp employees.",1);W00("internal.model",void 0);return}if(A.model)W00("internal.model",qN6(A.model))}function Vk4(A){let Q=A.indexOf(":");if(Q===-1)throw new GA(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let $=A.slice(0,Q).trim(),B=A.slice(Q+1).trim();if(!$||!B)throw new GA(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function HN6(A){if(A===void 0)return;let Q=A.trim();if(cy(Q))return Q;throw new GA(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function NN6(A,Q){if(hC(A))return;throw new GA(`Reasoning effort "${Q}" is not available for ${A} mode.`,1)}function qN6(A){if(!A.includes("="))return Vk4(A),A;let Q={};for(let $ of A.split(",")){let B=$.trim();if(!B)continue;let E=B.indexOf("=");if(E===-1)throw new GA(`Invalid mode-specific model entry "${B}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let D=B.slice(0,E).trim(),J=B.slice(E+1).trim();if(!D)throw new GA(`Missing mode name in "${B}". Expected "mode=provider:model".`,1);if(!J)throw new GA(`Missing model value for mode "${D}". Expected "${D}=provider:model".`,1);Vk4(J),Q[D]=J}if(Object.keys(Q).length===0)throw new GA("No valid model overrides found in --model flag value.",1);return Q}function QD0(A,Q,$){let B=Number(A);if(!Number.isInteger(B)||B<$.min)throw new u30(`${Q} must be an integer >= ${$.min}`);if($.max!==void 0&&B>$.max)throw new u30(`${Q} must be an integer <= ${$.max}`);return B}function wN6(A,Q){return A?.some(($)=>$.name===Q&&$.enabled)??!1}async function uN6(A,Q){let $=await O4.getUserInfo({},{config:A});return $.ok?wN6($.result.features,Q):!1}function MN6(A){return A!=="pending"}function Yw(A){if(!d9(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function ON6(A){let Q=Yw(A);if(Q)return Q.id;if(yC(A))throw Error(A.error.message);throw Error("unreachable")}function LN6(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 jN6(A){let B=LN6(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 GA(`Couldn't connect to the Amp server at ${A}.`,1,B)}function Ii0(A,Q){let $=yx0(Error(A.error.message));if($.message===z3.networkOffline||$.message===z3.networkTimeout)return jN6(Q);if($.message!==z3.internalBug)return new GA($.message,1,$.suggestion);return new GA(A.error.message.replace(/^Error: /,""),1)}async function RN6(){if(process.versions.bun)return!1;try{return await aY()==="npm"}catch(A){return S.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var Kk4=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH or with AMP_FORCE_BEL; 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??sJ,description:`Custom settings file path (overrides the default location ${sJ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(S).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${yc})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:B9(),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:c9.SMART.key,description:`Set the agent mode (${bG({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Show migration instructions for the removed legacy runtime",hidden:!0},{name:"orb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"hideWelcome",long:"hide-welcome",type:"switch",description:"Skip the welcome experience on startup",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"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}],zk4=(A)=>("deprecated"in A)&&A.deprecated===!0,PN6=(A)=>("hidden"in A)&&A.hidden===!0,TN6=(A)=>("default"in A),vN6=(A)=>("default"in A)?A.default:void 0;function Wk4(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let $=HN6(Q.effort);if($!==void 0){if(bi(Q.mode))NN6(Q.mode,$)}return $}var _N6="Amp Neo is now Amp and available to everyone. If you need to finish work in the old Amp, you can use an older version. For instructions on how to do that and more information: https://ampcode.com/news/drop-the-neo";function bi(A){return Object.values(c9).some((Q)=>Q.key===A)}function SN6(A,Q){if(bi(A))return A;throw new GA(`${Q} does not support plugin-defined agent modes`,1)}function qk4(A,Q){if(bi(Q))return{agentMode:Q};let $=A.agentModes.list().find((E)=>E.key===Q||E.label===Q);if(!$){let E=bG({}).map((U)=>U.mode).join(", "),D=A.agentModes.list().map((U)=>U.label).join(", "),J=D?` Plugin modes: ${D}.`:"";throw new GA(`Unknown agent mode '${Q}'. Built-in modes: ${E}.${J}`,1)}let B={label:$.label};if($.color!==void 0)B.color=$.color;return{agentMode:c9.SMART.key,agent:$.agent,agentModeDisplay:B,pluginAgentModeKey:$.key}}async function kN6(A,Q,$){if(A.getOptionValueSourceWithGlobals("mode")!=="cli")return;return await Q.initialized,qk4(Q,$)}function fN6(A,Q){let $=Q.args[0],B=Q.commands.map((D)=>D.name());if($&&!$.includes(" ")&&$.length<30&&!/[./\\]/.test($)){let D=B.filter((U)=>$.includes(U)||U.includes($)),J="Run amp --help for a list of available commands.";if(D.length>0)J=`Did you mean: ${D.join(", ")}? Or run amp --help for all commands.`;throw new GA(z3.unknownCommand($),1,J)}}var $D0=c0.file(VN6.homedir()),Fi0=process.env.XDG_CONFIG_HOME?c0.file(process.env.XDG_CONFIG_HOME):EA.joinPath($D0,".config");async function GB(A,Q,$){let B=$?.deferAuth??!1,E=$?.skipToolProviders??!1;CbA("0.0.1780677932-g159ed8");let D=N00({storage:A.settings,secretStorage:A.secrets,workspaceRoot:process.cwd(),defaultAmpURL:A.ampURL,homeDir:$D0,userConfigDir:Fi0}),J=A.secrets.get("apiKey",A.ampURL),U=iO(D),Y=null,Z=()=>{return},F=new Promise((B0)=>{Z=B0}),X=J.then(async(B0)=>{if(!B0&&!B)await F;return Y??=U.subscribe(()=>{}),n4(U.pipe(U5(MN6)))});X.catch(()=>{return}),uT4(D);let I=await D.getLatest();S.debug("Global configuration initialized",{settingsKeys:Object.keys(I.settings)});let G=!1;{let B0=await J;if(G=Boolean(B0),S.info("API key lookup before login",{found:Boolean(B0),ampURL:A.ampURL,deferAuth:B}),!B0)if(B)S.info("No API key found, continuing startup with deferred auth");else{fQ.write(`No API key found. Starting login flow...
5019
+ `)}function WN6(A){process.emitWarning=(Q,$,B,E)=>{let D=typeof Q==="string"?Q:Q.message||String(Q),J=$||"Warning",U=!1;A.warn(D,{name:J,code:B})}}function rB(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")W00("dangerouslyAllowAll",Q.dangerouslyAllowAll)}function CN6(A,Q){if(!d9(Q))return;if(!OG(Q.user.email)){if(A.model)throw new GA("The --model flag is only available for Amp employees.",1);W00("internal.model",void 0);return}if(A.model)W00("internal.model",qN6(A.model))}function Vk4(A){let Q=A.indexOf(":");if(Q===-1)throw new GA(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let $=A.slice(0,Q).trim(),B=A.slice(Q+1).trim();if(!$||!B)throw new GA(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function HN6(A){if(A===void 0)return;let Q=A.trim();if(cy(Q))return Q;throw new GA(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function NN6(A,Q){if(hC(A))return;throw new GA(`Reasoning effort "${Q}" is not available for ${A} mode.`,1)}function qN6(A){if(!A.includes("="))return Vk4(A),A;let Q={};for(let $ of A.split(",")){let B=$.trim();if(!B)continue;let E=B.indexOf("=");if(E===-1)throw new GA(`Invalid mode-specific model entry "${B}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let D=B.slice(0,E).trim(),J=B.slice(E+1).trim();if(!D)throw new GA(`Missing mode name in "${B}". Expected "mode=provider:model".`,1);if(!J)throw new GA(`Missing model value for mode "${D}". Expected "${D}=provider:model".`,1);Vk4(J),Q[D]=J}if(Object.keys(Q).length===0)throw new GA("No valid model overrides found in --model flag value.",1);return Q}function QD0(A,Q,$){let B=Number(A);if(!Number.isInteger(B)||B<$.min)throw new u30(`${Q} must be an integer >= ${$.min}`);if($.max!==void 0&&B>$.max)throw new u30(`${Q} must be an integer <= ${$.max}`);return B}function wN6(A,Q){return A?.some(($)=>$.name===Q&&$.enabled)??!1}async function uN6(A,Q){let $=await O4.getUserInfo({},{config:A});return $.ok?wN6($.result.features,Q):!1}function MN6(A){return A!=="pending"}function Yw(A){if(!d9(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function ON6(A){let Q=Yw(A);if(Q)return Q.id;if(yC(A))throw Error(A.error.message);throw Error("unreachable")}function LN6(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 jN6(A){let B=LN6(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 GA(`Couldn't connect to the Amp server at ${A}.`,1,B)}function Ii0(A,Q){let $=yx0(Error(A.error.message));if($.message===z3.networkOffline||$.message===z3.networkTimeout)return jN6(Q);if($.message!==z3.internalBug)return new GA($.message,1,$.suggestion);return new GA(A.error.message.replace(/^Error: /,""),1)}async function RN6(){if(process.versions.bun)return!1;try{return await aY()==="npm"}catch(A){return S.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var Kk4=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH or with AMP_FORCE_BEL; 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??sJ,description:`Custom settings file path (overrides the default location ${sJ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(S).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${yc})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:B9(),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:c9.SMART.key,description:`Set the agent mode (${bG({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Show migration instructions for the removed legacy runtime",hidden:!0},{name:"orb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"hideWelcome",long:"hide-welcome",type:"switch",description:"Skip the welcome experience on startup",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"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}],zk4=(A)=>("deprecated"in A)&&A.deprecated===!0,PN6=(A)=>("hidden"in A)&&A.hidden===!0,TN6=(A)=>("default"in A),vN6=(A)=>("default"in A)?A.default:void 0;function Wk4(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let $=HN6(Q.effort);if($!==void 0){if(bi(Q.mode))NN6(Q.mode,$)}return $}var _N6="Amp Neo is now Amp and available to everyone. If you need to finish work in the old Amp, you can use an older version. For instructions on how to do that and more information: https://ampcode.com/news/drop-the-neo";function bi(A){return Object.values(c9).some((Q)=>Q.key===A)}function SN6(A,Q){if(bi(A))return A;throw new GA(`${Q} does not support plugin-defined agent modes`,1)}function qk4(A,Q){if(bi(Q))return{agentMode:Q};let $=A.agentModes.list().find((E)=>E.key===Q||E.label===Q);if(!$){let E=bG({}).map((U)=>U.mode).join(", "),D=A.agentModes.list().map((U)=>U.label).join(", "),J=D?` Plugin modes: ${D}.`:"";throw new GA(`Unknown agent mode '${Q}'. Built-in modes: ${E}.${J}`,1)}let B={label:$.label};if($.color!==void 0)B.color=$.color;return{agentMode:c9.SMART.key,agent:$.agent,agentModeDisplay:B,pluginAgentModeKey:$.key}}async function kN6(A,Q,$){if(A.getOptionValueSourceWithGlobals("mode")!=="cli")return;return await Q.initialized,qk4(Q,$)}function fN6(A,Q){let $=Q.args[0],B=Q.commands.map((D)=>D.name());if($&&!$.includes(" ")&&$.length<30&&!/[./\\]/.test($)){let D=B.filter((U)=>$.includes(U)||U.includes($)),J="Run amp --help for a list of available commands.";if(D.length>0)J=`Did you mean: ${D.join(", ")}? Or run amp --help for all commands.`;throw new GA(z3.unknownCommand($),1,J)}}var $D0=c0.file(VN6.homedir()),Fi0=process.env.XDG_CONFIG_HOME?c0.file(process.env.XDG_CONFIG_HOME):EA.joinPath($D0,".config");async function GB(A,Q,$){let B=$?.deferAuth??!1,E=$?.skipToolProviders??!1;CbA("0.0.1780694019-g120cbb");let D=N00({storage:A.settings,secretStorage:A.secrets,workspaceRoot:process.cwd(),defaultAmpURL:A.ampURL,homeDir:$D0,userConfigDir:Fi0}),J=A.secrets.get("apiKey",A.ampURL),U=iO(D),Y=null,Z=()=>{return},F=new Promise((B0)=>{Z=B0}),X=J.then(async(B0)=>{if(!B0&&!B)await F;return Y??=U.subscribe(()=>{}),n4(U.pipe(U5(MN6)))});X.catch(()=>{return}),uT4(D);let I=await D.getLatest();S.debug("Global configuration initialized",{settingsKeys:Object.keys(I.settings)});let G=!1;{let B0=await J;if(G=Boolean(B0),S.info("API key lookup before login",{found:Boolean(B0),ampURL:A.ampURL,deferAuth:B}),!B0)if(B)S.info("No API key found, continuing startup with deferred auth");else{fQ.write(`No API key found. Starting login flow...
5018
5020
  `);let W0=await xN6(A),l=await A.secrets.get("apiKey",A.ampURL);if(S.info("Login flow completed",{success:W0,storedKeyPresent:Boolean(l),ampURL:A.ampURL}),!W0)await iY(),process.exit(1);G=!0,Z()}}{let B0=await D.getLatest(),W0=B0.settings.url,l=B0.secrets.isSet?.[W0];S.info("Config secrets state after login",{configURL:W0,apiKeySet:l?.apiKey??!1})}let V=B?"pending":await X;if(!B)S.info("Server status resolved",{status:"ready",isAuthenticated:d9(V),isError:yC(V),errorMessage:yC(V)?V.error.message:void 0});CN6(Q,V);let K=X.then((B0)=>ON6(B0));K.catch(()=>{return});let z=d9(V),W=!1;if(process.env.AMP_DISABLE_PLUGINS==="1")S.warn("Ignoring AMP_DISABLE_PLUGINS outside development");let C=W?"off":"all",{toolService:H,dispose:N}=aD4({configService:D}),w=new Map,u=()=>w.clear(),L=new yM0(D,A.settings.getWorkspaceRootPath()),R=TtA({configService:D}),_=OaA({configService:D,trustStore:L,skillMCPServers:R.skillMCPServers,uploadImageAttachments:z,createOAuthProvider:async(B0,W0,l)=>{let i=`${B0}:${W0}`,Q0=w.get(i);if(Q0)return S.debug("Reusing existing OAuth provider for server",{serverName:B0,serverUrl:W0}),Q0;S.debug("Creating OAuth provider for server",{serverName:B0,serverUrl:W0});let s=(async()=>{let E0=new oC(A.secrets),A0=await E0.getClientInfo(B0,W0),G0=l?.scopes??A0?.scopes,V0=XG4();S.info("OAuth headless mode check",{useHeadless:V0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:fQ.isTTY});let w0;if(V0)w0=A.executeMode?FG4():ZG4(B0);let I0=new Pq0({storage:E0,serverName:B0,serverUrl:W0,clientId:l?.clientId??A0?.clientId,clientSecret:l?.clientSecret??A0?.clientSecret,authUrl:l?.authUrl??A0?.authUrl,tokenUrl:l?.tokenUrl??A0?.tokenUrl,scopes:G0,headlessAuthHandler:w0});return S.debug("OAuth provider created",{serverName:B0,serverUrl:W0,hasManualClientId:!!(l?.clientId??A0?.clientId),willUseDCR:!(l?.clientId??A0?.clientId),scopes:G0,headlessMode:V0,executeMode:A.executeMode}),I0})();return w.set(i,s),s}}),P=xL0({configService:D,spawn:UQ0}),f=Q.headless?yP4():void 0,h=f??new ZE0({configService:D}),x=h instanceof ZE0?h:void 0;if(x)x.pluginExecutorKind="local";let v=new C4(null),k=null,c=z&&!W?[...gP4(I.settings)?[{name:"permissions",entryPoint:Mp0}]:[],{name:"thread-visibility",entryPoint:cP4(D,()=>X.then(Yw),()=>k,(B0)=>{k=B0}),alwaysLoad:!0}]:[],d=sM0({configService:D,platform:h,loadGlobalPlugins:By0(D),pluginFilter:C,activeThread$:v,internalPlugins:c}),b=OoA(d),p=[_,P,b],n;if(E)n=new Map;else if(A.executeMode){let B0=await $04({toolService:H,providers:p,initialTimeout:15000});n=B0.registrations;for(let[W0,l]of B0.initErrors)S.warn(`${W0} provider initialization slow or failed:`,l)}else n=yL0({toolService:H,providers:p});if(Q.jetbrains)xC("JetBrains");else if(Q.ide&&WG4())xC("VS Code");else if(Q.ide&&CG4())xC("Neovim");else if(Q.ide&&A.executeMode)Nk4();if(A.executeMode)HbA(!0);let a,X0=v3.status.pipe(sA((B0)=>Boolean(B0.connected&&B0.authenticated&&B0.ideName&&uhA(B0.ideName))),FQ()).subscribe((B0)=>{if(B0){if(!a)a=H.registerTool(Q04)}else a?.dispose(),a=void 0}),t;if(!A.executeMode){let B0=await A.settings.get("fuzzy.alwaysIncludePaths")??[];t=new e30(process.cwd(),{alwaysIncludePaths:B0},!0)}else t=new class extends e30{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let Y0=Ag(D);S.info("Starting Amp background services");let K0=new _p0,R0={configService:D,toolService:H,mcpService:_,skillService:R,toolboxService:P,trustStore:L,threadRemote:Y0,setThreadMeta:Y0.setThreadMeta,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:t,terminal:K0,pluginService:d,pluginPlatform:x,headlessPluginPlatform:f,activeThread$:v,serverStatus:V,serverStatusPromise:X,viewerUserIDPromise:K,hasAPIKeyAtStartup:G,consumeDraftNewThreadVisibility:()=>{let B0=k;return k=null,B0}};return{...R0,async asyncDispose(){if(R0.mcpService.hasAuthenticatingClients())S.info("Waiting for OAuth authentication to complete before exit..."),await R0.mcpService.waitForAuthentication();for(let B0 of n.values())B0.dispose();await R0.mcpService.dispose(),u(),R0.configService.unsubscribe(),Y?.unsubscribe(),N(),R0.fuzzyServer.dispose(),R0.settingsStorage[Symbol.dispose](),X0.unsubscribe(),a?.dispose(),await R0.pluginService.dispose()}}}async function xN6(A){if(!A.executeMode){if(!await JE0("Would you like to log in to Amp? [(y)es, (n)o]: "))return fQ.write(`Login cancelled. Run the command again to retry.
5019
5021
  `),!1}return await wk4(A)}async function wk4(A){let Q=FN6(32).toString("hex"),$=await Cp0(A.ampURL,Q),B=new AbortController;try{await iJ($,B.signal)}catch(D){S.error("Error opening browser",{error:D})}let E=await Cp0(A.ampURL,Q,!1);fQ.write(`If your browser does not open automatically, visit:
5020
5022
 
@@ -5022,7 +5024,7 @@ ${_0.blue.bold(E)}
5022
5024
 
5023
5025
  `);try{return await CP4(A.ampURL,Q,A.secrets,B),fQ.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(D){return S.error("Login failed",{error:D}),z7.write(`
5024
5026
  Login failed: ${D instanceof Error?D.message:String(D)}
5025
- `),!1}}async function yN6(A,Q,$){let B=await Q.get("apiKey",A);if(!B)throw new GA("No Amp API key found. Run `amp login` first.",1);let E=ZN6("curl",["-H",`Authorization: Bearer ${B}`,...$],{stdio:"inherit"});process.exitCode=await new Promise((D,J)=>{E.on("error",J),E.on("close",(U)=>D(U??1))})}function bN6(A){let Q=new NX().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, unlisted, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)pN(),process.exit(0);let N=H.originalError??H;dX4(N)}),wz4(Q,{version:"0.0.1780677932-g159ed8",buildTimestamp:"2026-06-05T16:49:58.070Z",buildType:"release"}),Q.addHelpText("after",kG4()),Q.configureHelp({formatHelp:fG4}),Q.command("logout").description("Log out by removing stored API key").action(async(H,N)=>{let w=N.optsWithGlobals(),u=await lQ(w);await oN6(u)}),Q.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(H,N)=>{let w=N.optsWithGlobals(),u=await lQ(w);await aN6(u,await jp0(w,u.settings))}),$T4(Q,lQ);let B=Q.command("internal",{hidden:!0}).description("Internal commands").command("curl [args...]").description("Internal: run curl with the current Amp API key as a bearer token").allowUnknownOption(!0).allowExcessArguments(!0).action(async(...H)=>{let N=H.find((R)=>typeof R==="object"&&R!==null&&typeof R.optsWithGlobals==="function")??B,w=H.filter((R)=>R!==N).flatMap((R)=>Array.isArray(R)?R:typeof R==="string"?[R]:[]),u=N.optsWithGlobals(),L=await lQ(u);await yN6(L.ampURL,L.secrets,w),process.exit(process.exitCode??0)});Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(H,N,w)=>{let u=w.optsWithGlobals(),L=await lQ(u);await sI4(H??"get",L.ampURL,L.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit [args...]",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements Git signing helper interfaces. Used inside sandboxes for commit signing.").allowUnknownOption(!0).allowExcessArguments(!0).action(async(H,N,w)=>{let u=w.optsWithGlobals(),L=await lQ(u);await eI4(L,H),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(H)=>{await dR4({raw:H.raw===!0}),process.exit(process.exitCode??0)}),dT4(Q,{createContext:lQ,createThreadDependencies:GB,initializeCLIOverrides:rB}),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(`
5027
+ `),!1}}async function yN6(A,Q,$){let B=await Q.get("apiKey",A);if(!B)throw new GA("No Amp API key found. Run `amp login` first.",1);let E=ZN6("curl",["-H",`Authorization: Bearer ${B}`,...$],{stdio:"inherit"});process.exitCode=await new Promise((D,J)=>{E.on("error",J),E.on("close",(U)=>D(U??1))})}function bN6(A){let Q=new NX().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, unlisted, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)pN(),process.exit(0);let N=H.originalError??H;dX4(N)}),wz4(Q,{version:"0.0.1780694019-g120cbb",buildTimestamp:"2026-06-05T21:18:30.332Z",buildType:"release"}),Q.addHelpText("after",kG4()),Q.configureHelp({formatHelp:fG4}),Q.command("logout").description("Log out by removing stored API key").action(async(H,N)=>{let w=N.optsWithGlobals(),u=await lQ(w);await oN6(u)}),Q.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(H,N)=>{let w=N.optsWithGlobals(),u=await lQ(w);await aN6(u,await jp0(w,u.settings))}),$T4(Q,lQ);let B=Q.command("internal",{hidden:!0}).description("Internal commands").command("curl [args...]").description("Internal: run curl with the current Amp API key as a bearer token").allowUnknownOption(!0).allowExcessArguments(!0).action(async(...H)=>{let N=H.find((R)=>typeof R==="object"&&R!==null&&typeof R.optsWithGlobals==="function")??B,w=H.filter((R)=>R!==N).flatMap((R)=>Array.isArray(R)?R:typeof R==="string"?[R]:[]),u=N.optsWithGlobals(),L=await lQ(u);await yN6(L.ampURL,L.secrets,w),process.exit(process.exitCode??0)});Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(H,N,w)=>{let u=w.optsWithGlobals(),L=await lQ(u);await sI4(H??"get",L.ampURL,L.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit [args...]",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements Git signing helper interfaces. Used inside sandboxes for commit signing.").allowUnknownOption(!0).allowExcessArguments(!0).action(async(H,N,w)=>{let u=w.optsWithGlobals(),L=await lQ(u);await eI4(L,H),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(H)=>{await dR4({raw:H.raw===!0}),process.exit(process.exitCode??0)}),dT4(Q,{createContext:lQ,createThreadDependencies:GB,initializeCLIOverrides:rB}),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(`
5026
5028
  `)).option("--apply <threadIDOrURL>","Apply the current DTW thread snapshot once and exit").option("--checkout","Automatically check out the thread commit when it differs").option("--skip-checkout","Skip the startup checkout prompt when commits differ").action(async(H,N,w)=>{if(H&&N.apply)throw new GA("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let u=N.apply??H;if(!u||u.trim().length===0)fQ.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.
5027
5029
 
5028
5030
  `),w.outputHelp(),process.exit(0);let L=B3(u)??i7(u),R=w.optsWithGlobals(),_=await lQ(R);rB(w,R);let P=await GB(_,R),f=!1;try{if(N.checkout&&N.skipCheckout)throw new GA("Choose either --checkout or --skip-checkout, not both.",1);if(yC(P.serverStatus))throw Ii0(P.serverStatus,_.ampURL);await JP4({ampURL:_.ampURL,threadId:L,configService:P.configService,threadSnapshotReader:{get:P.threadRemote.getThread},apiKey:process.env.AMP_API_KEY,applyOnce:typeof N.apply==="string",checkoutMode:N.checkout?"always":N.skipCheckout?"never":"prompt",promptForYesNo:JE0}),f=!0}finally{if(await P.asyncDispose(),f)process.exit(0)}});let E=async(H,N,w)=>{N00({storage:N.settings,secretStorage:N.secrets,workspaceRoot:process.cwd(),defaultAmpURL:N.ampURL,homeDir:$D0,userConfigDir:Fi0});let u={...N,executeMode:!1};await Xi0(u,{...H,openThreadSwitcher:!0},w)},D=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").option("--limit <number>","Maximum number of threads to return",(H)=>QD0(H,"--limit",{min:1,max:500})).option("--offset <number>","Number of threads to skip",(H)=>QD0(H,"--offset",{min:0})).action(async(H,N)=>{let w=N.optsWithGlobals(),u=await lQ(w);await Hk4(w,u,N)});D.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, unlisted, workspace, group)").action(async(H,N)=>{let w=N.optsWithGlobals(),u=await lQ(w);await Yq6(w,u,N)}),D.command("continue [threadIDOrURLs...]").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. When multiple thread are given, all are resumed and the first is shown in the foreground.").option("--last","Continue the last thread for the current mode directly").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(H,N,w)=>{let u=w.optsWithGlobals(),L=await lQ(u),R=Array.isArray(H)?H:[];if(N.pick)z7.write(`${_0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
@@ -5047,8 +5049,8 @@ ${_}
5047
5049
 
5048
5050
  `)},async input(){return},async confirm(){return!1},async select(){return},async ask(){return{result:"uncertain",probability:0.5,reason:"AI not available"}}},loadGlobalPlugins:By0(u),pluginFilter:process.env.PLUGINS??"all"}),asyncDispose:async()=>{}}}),XT4(Q,async(H)=>{let N=H.optsWithGlobals(),w=await lQ(N);rB(H,N);let u=await GB(w,N),L=await u.secretStorage.get("apiKey",w.ampURL);if(!L)throw await u.asyncDispose(),new GA("API key required. Please run `amp login` first.",1);return{configService:u.configService,actorOptions:{apiKey:L,ampURL:w.ampURL,workspaceRoot:process.cwd(),dependencies:u},cleanupTerminal:pN,asyncDispose:u.asyncDispose.bind(u)}}),NT4(Q,async(H)=>{let N=H.optsWithGlobals(),w=await lQ(N);rB(H,N);let u=await GB(w,N);return{settings:w.settings,configService:u.configService,skillService:u.skillService,asyncDispose:u.asyncDispose.bind(u)}}),_P4(Q,async(H)=>{let N=H.optsWithGlobals();return await lQ(N)}),MP4(Q,async(H)=>{let N=await lQ(H);return{settings:N.settings,secretStorage:N.secrets,getThreadDeps:async(w)=>{rB(w,H);let u=await GB(N,H);return{mcpService:u.mcpService,settings:N.settings,asyncDispose:u.asyncDispose.bind(u)}}}}),HX4(Q,lQ),kX4(Q,lQ),nT4(Q,lQ),qT4(Q,lQ);function Z(H,N,w){let L=typeof H.description==="string"?H.description:w===void 0?H.description(!0):H.description(w),R=new oD(N,L),_=vN6(H);if(_)R.default(_);if(R.hidden=PN6(H)||zk4(H),"choices"in H&&Array.isArray(H.choices))if("hiddenChoices"in H){let P=[...H.choices],f=Array.isArray(H.hiddenChoices)?H.hiddenChoices:[],h=new Set([...P,...f]);R.argParser((x)=>{if(!h.has(x))throw new u30(`Allowed choices are ${P.join(", ")}.`);return x})}else R.choices([...H.choices]);return R}for(let H of Kk4){switch(H.type){case"flag":{Q.addOption(Z(H,`--${H.long}`)),Q.addOption(Z(H,`--no-${H.long}`,!1));break}case"switch":{Q.addOption(Z(H,`--${H.long}`,!0));break}case"optional-option":{Q.addOption(Z(H,`${"short"in H?`-${H.short}, `:""}--${H.long} [value]`));break}default:{Q.addOption(Z(H,`${"short"in H?`-${H.short}, `:""}--${H.long} <value>`));break}}if("aliases"in H&&Array.isArray(H.aliases))for(let N of H.aliases){let w=new oD(`--${N}`,H.description);w.hidden=!0,w.implies({[H.name]:!0}),Q.addOption(w)}}Q.hook("preAction",(H,N)=>{let w=N.optsWithGlobals();if(w.takeMeBack)E6(_N6);if(w.archive&&!process.env.AMP_SDK_VERSION)E6("--archive is now the default and has been removed. Rerun without --archive. (If you want to not archive, use --no-archive-after-execute.)")});let F=new oD("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);Q.addOption(F);let X=new oD("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp(!0);Q.addOption(X);let I=new oD("--stream-json","When used with --execute, output in Claude Code-compatible stream JSON format instead of plain text.").default(!1);Q.addOption(I);let G=new oD("--stream-json-thinking","Include thinking blocks in stream JSON output (non-Claude Code extension). Implies --stream-json.").default(!1);Q.addOption(G);let V=new oD("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);Q.addOption(V);let K=new oD("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);Q.addOption(K);let z=new oD("--no-archive-after-execute","When used with --execute on a new thread, leave the thread unarchived after the command finishes.");Q.addOption(z);let W=new oD("--archive").default(!1).hideHelp(!0);Q.addOption(W);let C=new oD("-l, --label <label>","When used with --execute, add a label to the thread. Repeat the flag for multiple labels.").argParser((H,N)=>{if(N===void 0)return[H];return[...N,H]});return Q.addOption(C),Q.action(async(H,N)=>{let w=H,u=await lQ(w);if(Object.keys(w).forEach((L)=>{let R=Kk4.find((_)=>_.name===L);if(R&&zk4(R)&&!TN6(R))z7.write(_0.yellow(`Warning: '--${L}' flag is deprecated
5049
5051
  `))}),N.args.length>0)fN6(u,N);await Xi0(u,w,N)}),ZV4(Q),Q}async function uk4(A,Q){await AJ(($)=>lP($,A,Q))}async function hN6(A){if(A.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof A.execute==="string"){let Q=(await Rp0()).trimEnd();return{userInput:A.execute,stdinInput:Q||null}}return{userInput:(await Rp0()).trimEnd(),stdinInput:null}}function gN6(A,Q,$){if(A.remote&&!Q)throw new GA("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(A.streamJson&&!Q)throw new GA("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new GA("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new GA("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new GA("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 GA("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archiveAfterExecute===!1&&!Q)throw new GA("The --no-archive-after-execute flag requires --execute mode",1,'Use: amp --execute "your message" --no-archive-after-execute');if(A.streamJsonInput&&typeof A.execute==="string"&&A.execute.trim()!=="")throw new GA("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&&$===""&&!A.streamJsonInput&&!A.headless)throw new GA("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"
5050
- Or pipe via stdin: echo "your message" | amp --execute`)}function mN6(){amA([C00.parse({tool:"*",action:"allow"})]),wmA({bypass:!0})}function dN6(A){if(A.threadId&&!T7(A.threadId))delete A.threadId}async function Xi0(A,Q,$){if(Q.headless)return cN6(A,Q,$);let B=await GB(A,Q);if(Q.showWelcome&&Q.hideWelcome)throw await B.asyncDispose(),new GA("Cannot use --show-welcome and --hide-welcome together",1);let E=!A.executeMode&&await RN6();return mN6(),dN6(Q),pN6(A,Q,$,B,{showNpmMigrationWelcome:E})}async function cN6(A,Q,$){let B=(W,C)=>{let H=Number(process.hrtime.bigint()-C)/1e6,N=qX4();S.info("Startup phase",{phase:W,phaseMs:Math.round(H),sinceMainMs:N===null?void 0:Math.round(N)})};rB($,Q);let E=process.hrtime.bigint(),D=await GB(A,Q);B("runMainThread:createThreadDependencies",E);let{serverStatus:J}=D;if(yC(J))throw Ii0(J,A.ampURL);let U=d9(J)?J:null,Y=U?.user.email,Z=Yw(J),F=Xi(Q,Z);if(F instanceof Error)E6(F.message);if(U&&bi(Q.mode)&&!Z00(Q.mode,Y))throw new GA(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!Y||!OG(Y)))throw new GA("Headless executor mode is only available for Amp employees",1);kx0();let I=await D.secretStorage.get("apiKey",A.ampURL);if(!I)throw new GA("API key required for headless mode. Please run `amp login` first.",1);let G=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(G&&!T7(G))throw new GA(`Invalid thread ID: ${G}`,1);let V=G?void 0:await Jq6({dependencies:D,apiKey:I,visibility:F??void 0}),K=G??V?.threadId;if(!K)throw new GA("Failed to resolve headless thread ID",1);let z=await KG4(K);if(z.status==="already-running")await D.asyncDispose(),await iY(),process.exit(0);try{await BG4({ampURL:A.ampURL,apiKey:I,workspaceRoot:process.cwd(),threadId:K,ownerUserId:V?.ownerUserId,threadVersion:V?.threadVersion,agentMode:V?.agentMode,initialToolDiscovery:Promise.all([D.mcpService.initialized,D.toolboxService.initialized,D.pluginService.initialized]).then(()=>{return}),configService:D.configService,mcpService:D.mcpService,toolService:D.toolService,skillService:D.skillService,pluginService:D.pluginService,pluginPlatform:D.headlessPluginPlatform,setActiveThreadID:(W)=>D.activeThread$.next(W)})}finally{await z.release(),await D.asyncDispose()}await iY(),process.exit(0)}async function pN6(A,Q,$,B,E){let{userInput:D,stdinInput:J}=await hN6(Q),U=!!Q.streamJson||!!Q.streamJsonThinking;gN6({...Q,streamJson:U},A.executeMode,D),rB($,Q),RX4(),kx0();let Y=Q.threadId,Z=Q.resumeThreadIDs??(Y?[Y]:[]),F=Q.observe?B3(Q.observe)??i7(Q.observe):void 0,X=await B.serverStatusPromise;if(yC(X))throw Ii0(X,A.ampURL);let I=Yw(X),G=()=>uN6(B.configService,CkA.V2_LOCAL_THREAD_CHANGES),V=Xi(Q,I);if(V instanceof Error)E6(V.message);if(A.executeMode&&Q.remote){if(!bi(Q.mode))throw new GA("Remote execute mode does not support plugin-defined agent modes",1);if(!d9(X)||!OG(X.user.email))throw new GA("Remote execute mode is only available for Amp employees",1);await oP4(D,J,B.configService,Q.mode),await B.asyncDispose(),await iY(),process.exit(0)}let K=null,z=async()=>{let H=B.consumeDraftNewThreadVisibility();if(H!==null)return H;return K??=(async()=>{let N=await k30(A.settings,process.cwd(),I,V);if(N instanceof Error)E6(N.message);return N})(),K},W=await B.secretStorage.get("apiKey",A.ampURL);if(!W)throw new GA("API key required. Please run `amp login` first.",1);let C=d9(X)&&OG(X.user.email);if(A.executeMode){if(Z.length>1)throw new GA("Execute mode can only resume one thread.",1);RP4(B.mcpService,A.settings);try{await B.pluginService.initialized;let H=qk4(B.pluginService,Q.mode),N=Wk4($,Q),w=await Bq(),u=Y?N:ky0({agentMode:H.agentMode,explicitEffort:N,sessionState:w}),L=Y?void 0:H50(await gP(B.configService),{agentMode:H.agentMode,explicitEffort:N,sessionState:w}),R=Y?void 0:await z(),{threadID:_}=await t30({apiKey:W,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:B,userInput:D,stdinInput:J,stats:!!Q.stats,streamJson:U,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:H.agentMode,reasoningEffort:H.agent?void 0:u,agent:H.agent,labels:Q.label,initialThreadID:Y,initialThreadMeta:R,initialSettings:L});if(await uk4(_,"execute"),Q.archive||!Y&&Q.archiveAfterExecute!==!1)await B.threadRemote.archiveThread(_,!0)}finally{await B.asyncDispose()}await iY(),process.exit(0)}else{let H=Wk4($,Q),N=await kN6($,B.pluginService,Q.mode),w=E.showNpmMigrationWelcome?"npm-migration":"intro",u=Py0("0.0.1780677932-g159ed8",B.settingsStorage,{startDelayMs:3000}),L=new Hp0(B.mcpService,A.settings.getWorkspaceRootPath()),R=Ag(B.configService),_=new xp0(B.fuzzyServer),P=process.cwd();await xR4({ampURL:A.ampURL,apiKey:W,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??E7(A.ampURL),configService:B.configService,toolService:B.toolService,pluginPlatform:B.pluginPlatform,pluginService:B.pluginService,skillService:B.skillService,mcpService:B.mcpService,readFileSystemDirectory:({uri:f})=>vP({workspaceRoot:P},f),canUseV2LocalThreadChanges:G,completionBuilder:_,updateService:u,workspaceRoot:P,listThreads:()=>R.listThreads(),getThreadFromServer:(f)=>R.getThread(f),getThreadTail:async(f,h)=>{let x=await O4.getThreadTail({thread:f,limit:h},{config:B.configService});if(!x.ok){if(x.error.code==="thread-not-found")return null;throw Error(x.error.message??x.error.code)}return{...x.result.thread.data,messages:x.result.messages}},toolboxes:B.toolboxService.toolboxes,isInternalUser:C,settingsFilePath:B.settingsStorage.getSettingsFilePath(),workspaceSettingsFilePath:B.settingsStorage.getWorkspaceSettingsPath(),mcpTrustHandler:L,setActiveThreadID:(f)=>B.activeThread$.next(f),dispose:()=>{return L.dispose(),u.dispose(),B.asyncDispose()}},{initialThreadIDs:F?[F]:Z,initialUserInput:D||void 0,getDefaultNewThreadVisibility:z,onFirstFrame:Q.ide?Nk4:void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!F,hideWelcome:!!Q.hideWelcome,showWelcome:Q.showWelcome,welcomeVariant:w,initialAgentMode:N?.agentMode,initialPluginAgentModeKey:N?.pluginAgentModeKey,initialReasoningEffort:H}),process.exit(0)}}async function lQ(A){if(S.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)z7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
5051
- `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,$=process.stdout.isTTY&&process.stderr.isTTY;S.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let B=await TaA({get:async(U)=>{if(U!==Xh)return;try{let Y=await IN6(Zi0,"utf-8");return JSON.parse(Y).installationID}catch{return}},set:async(U,Y)=>{if(U!==Xh)return;await XN6(yi.dirname(Zi0),{recursive:!0}),await GN6(Zi0,JSON.stringify({installationID:Y},null,2),{mode:384})}},{clientType:"cli",platform:f40()});NbA(B);let E=await CT4({...A,workspaceTrust:{current:!0,changes:$y},getHook:process.env.AMP_URL?(U,Y)=>{if(U==="url")return Promise.resolve(process.env.AMP_URL);return Y()}:void 0});if(A.mcpConfig){let U=await LP4(A.mcpConfig);E=jP4(E,U)}let D=yi.dirname(E.getSettingsFilePath());tD4(py,D),E=XkA(E);let J=await E.get("url","admin")??await E.get("url","global");if(!J)J=v8;if(S.info("Resolved Amp URL",{ampURL:J,settingsFile:E.getSettingsFilePath(),workspaceRoot:E.getWorkspaceRootPath()}),!hO(J))S.info("Targeting custom Amp server",{ampURL:J});return{executeMode:Q,isTTY:$,ampURL:J,settings:E,secrets:IT4(await jp0(A,E))}}function lN6(A){let Q={};for(let $=0;$<A.length;$++){let B=A[$];if(B?.startsWith("--")){let D=B.slice(2).replace(/-([a-z])/g,(U,Y)=>Y.toUpperCase()),J=A[$+1];if(J&&!J.startsWith("--"))Q[D]=J,$++}}return Q}function iN6(A,Q){let $=A.includes("--headless")||A.some((E)=>E.startsWith("--headless=")),B=yi.resolve(Q.logFile??process.env.AMP_LOG_FILE??($?KN6:yc));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:B}}async function nN6(){NX4();let A=lN6(process.argv),Q=iN6(process.argv,A),$=PX4(Q);TB0("silent");let B=process.argv.includes("--no-color"),E=process.argv.includes("--color"),D=process.stdout.isTTY&&process.stderr.isTTY;if(B||!E&&!D)_0.level=0;if(WN6(S),S.info("Starting Amp CLI.",{version:"0.0.1780677932-g159ed8",buildTimestamp:"2026-06-05T16:49:58.070Z"}),process.platform==="win32"&&Qq())EV4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new GA(z3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await bN6($).parseAsync(process.argv)}rD4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await nN6().catch(f30)});async function aN6(A,Q){let $=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!$)await A.settings.set("url",process.env.AMP_URL,"global"),fQ.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
5052
+ Or pipe via stdin: echo "your message" | amp --execute`)}function mN6(){amA([C00.parse({tool:"*",action:"allow"})]),wmA({bypass:!0})}function dN6(A){if(A.threadId&&!T7(A.threadId))delete A.threadId}async function Xi0(A,Q,$){if(Q.headless)return cN6(A,Q,$);let B=await GB(A,Q);if(Q.showWelcome&&Q.hideWelcome)throw await B.asyncDispose(),new GA("Cannot use --show-welcome and --hide-welcome together",1);let E=!A.executeMode&&await RN6();return mN6(),dN6(Q),pN6(A,Q,$,B,{showNpmMigrationWelcome:E})}async function cN6(A,Q,$){let B=(W,C)=>{let H=Number(process.hrtime.bigint()-C)/1e6,N=qX4();S.info("Startup phase",{phase:W,phaseMs:Math.round(H),sinceMainMs:N===null?void 0:Math.round(N)})};rB($,Q);let E=process.hrtime.bigint(),D=await GB(A,Q);B("runMainThread:createThreadDependencies",E);let{serverStatus:J}=D;if(yC(J))throw Ii0(J,A.ampURL);let U=d9(J)?J:null,Y=U?.user.email,Z=Yw(J),F=Xi(Q,Z);if(F instanceof Error)E6(F.message);if(U&&bi(Q.mode)&&!Z00(Q.mode,Y))throw new GA(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!Y||!OG(Y)))throw new GA("Headless executor mode is only available for Amp employees",1);kx0();let I=await D.secretStorage.get("apiKey",A.ampURL);if(!I)throw new GA("API key required for headless mode. Please run `amp login` first.",1);let G=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(G&&!T7(G))throw new GA(`Invalid thread ID: ${G}`,1);let V=G?void 0:await Jq6({dependencies:D,apiKey:I,visibility:F??void 0}),K=G??V?.threadId;if(!K)throw new GA("Failed to resolve headless thread ID",1);let z=await KG4(K);if(z.status==="already-running")await D.asyncDispose(),await iY(),process.exit(0);try{await BG4({ampURL:A.ampURL,apiKey:I,workspaceRoot:process.cwd(),threadId:K,ownerUserId:V?.ownerUserId,threadVersion:V?.threadVersion,agentMode:V?.agentMode,initialToolDiscovery:Promise.all([D.mcpService.initialized,D.toolboxService.initialized,D.pluginService.initialized]).then(()=>{return}),configService:D.configService,mcpService:D.mcpService,toolService:D.toolService,skillService:D.skillService,pluginService:D.pluginService,pluginPlatform:D.headlessPluginPlatform,setActiveThreadID:(W)=>D.activeThread$.next(W)})}finally{await z.release(),await D.asyncDispose()}await iY(),process.exit(0)}async function pN6(A,Q,$,B,E){let{userInput:D,stdinInput:J}=await hN6(Q),U=!!Q.streamJson||!!Q.streamJsonThinking;gN6({...Q,streamJson:U},A.executeMode,D),rB($,Q),RX4(),kx0();let Y=Q.threadId,Z=Q.resumeThreadIDs??(Y?[Y]:[]),F=Q.observe?B3(Q.observe)??i7(Q.observe):void 0,X=await B.serverStatusPromise;if(yC(X))throw Ii0(X,A.ampURL);let I=Yw(X),G=()=>uN6(B.configService,CkA.V2_LOCAL_THREAD_CHANGES),V=Xi(Q,I);if(V instanceof Error)E6(V.message);if(A.executeMode&&Q.remote){if(!bi(Q.mode))throw new GA("Remote execute mode does not support plugin-defined agent modes",1);if(!d9(X)||!OG(X.user.email))throw new GA("Remote execute mode is only available for Amp employees",1);await oP4(D,J,B.configService,Q.mode),await B.asyncDispose(),await iY(),process.exit(0)}let K=null,z=async()=>{let H=B.consumeDraftNewThreadVisibility();if(H!==null)return H;return K??=(async()=>{let N=await k30(A.settings,process.cwd(),I,V);if(N instanceof Error)E6(N.message);return N})(),K},W=await B.secretStorage.get("apiKey",A.ampURL);if(!W)throw new GA("API key required. Please run `amp login` first.",1);let C=d9(X)&&OG(X.user.email);if(A.executeMode){if(Z.length>1)throw new GA("Execute mode can only resume one thread.",1);RP4(B.mcpService,A.settings);try{await B.pluginService.initialized;let H=qk4(B.pluginService,Q.mode),N=Wk4($,Q),w=await Bq(),u=Y?N:ky0({agentMode:H.agentMode,explicitEffort:N,sessionState:w}),L=Y?void 0:H50(await gP(B.configService),{agentMode:H.agentMode,explicitEffort:N,sessionState:w}),R=Y?void 0:await z(),{threadID:_}=await t30({apiKey:W,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:B,userInput:D,stdinInput:J,stats:!!Q.stats,streamJson:U,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:H.agentMode,reasoningEffort:H.agent?void 0:u,agent:H.agent,labels:Q.label,initialThreadID:Y,initialThreadMeta:R,initialSettings:L});if(await uk4(_,"execute"),Q.archive||!Y&&Q.archiveAfterExecute!==!1)await B.threadRemote.archiveThread(_,!0)}finally{await B.asyncDispose()}await iY(),process.exit(0)}else{let H=Wk4($,Q),N=await kN6($,B.pluginService,Q.mode),w=E.showNpmMigrationWelcome?"npm-migration":"intro",u=Py0("0.0.1780694019-g120cbb",B.settingsStorage,{startDelayMs:3000}),L=new Hp0(B.mcpService,A.settings.getWorkspaceRootPath()),R=Ag(B.configService),_=new xp0(B.fuzzyServer),P=process.cwd();await xR4({ampURL:A.ampURL,apiKey:W,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??E7(A.ampURL),configService:B.configService,toolService:B.toolService,pluginPlatform:B.pluginPlatform,pluginService:B.pluginService,skillService:B.skillService,mcpService:B.mcpService,readFileSystemDirectory:({uri:f})=>vP({workspaceRoot:P},f),canUseV2LocalThreadChanges:G,completionBuilder:_,updateService:u,workspaceRoot:P,listThreads:()=>R.listThreads(),getThreadFromServer:(f)=>R.getThread(f),getThreadTail:async(f,h)=>{let x=await O4.getThreadTail({thread:f,limit:h},{config:B.configService});if(!x.ok){if(x.error.code==="thread-not-found")return null;throw Error(x.error.message??x.error.code)}return{...x.result.thread.data,messages:x.result.messages}},toolboxes:B.toolboxService.toolboxes,isInternalUser:C,settingsFilePath:B.settingsStorage.getSettingsFilePath(),workspaceSettingsFilePath:B.settingsStorage.getWorkspaceSettingsPath(),mcpTrustHandler:L,setActiveThreadID:(f)=>B.activeThread$.next(f),dispose:()=>{return L.dispose(),u.dispose(),B.asyncDispose()}},{initialThreadIDs:F?[F]:Z,initialUserInput:D||void 0,getDefaultNewThreadVisibility:z,onFirstFrame:Q.ide?Nk4:void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!F,hideWelcome:!!Q.hideWelcome,showWelcome:Q.showWelcome,welcomeVariant:w,initialAgentMode:N?.agentMode,initialPluginAgentModeKey:N?.pluginAgentModeKey,initialReasoningEffort:H}),process.exit(0)}}async function lQ(A){if(S.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)z7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
5053
+ `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,$=process.stdout.isTTY&&process.stderr.isTTY;S.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let B=await TaA({get:async(U)=>{if(U!==Xh)return;try{let Y=await IN6(Zi0,"utf-8");return JSON.parse(Y).installationID}catch{return}},set:async(U,Y)=>{if(U!==Xh)return;await XN6(yi.dirname(Zi0),{recursive:!0}),await GN6(Zi0,JSON.stringify({installationID:Y},null,2),{mode:384})}},{clientType:"cli",platform:f40()});NbA(B);let E=await CT4({...A,workspaceTrust:{current:!0,changes:$y},getHook:process.env.AMP_URL?(U,Y)=>{if(U==="url")return Promise.resolve(process.env.AMP_URL);return Y()}:void 0});if(A.mcpConfig){let U=await LP4(A.mcpConfig);E=jP4(E,U)}let D=yi.dirname(E.getSettingsFilePath());tD4(py,D),E=XkA(E);let J=await E.get("url","admin")??await E.get("url","global");if(!J)J=v8;if(S.info("Resolved Amp URL",{ampURL:J,settingsFile:E.getSettingsFilePath(),workspaceRoot:E.getWorkspaceRootPath()}),!hO(J))S.info("Targeting custom Amp server",{ampURL:J});return{executeMode:Q,isTTY:$,ampURL:J,settings:E,secrets:IT4(await jp0(A,E))}}function lN6(A){let Q={};for(let $=0;$<A.length;$++){let B=A[$];if(B?.startsWith("--")){let D=B.slice(2).replace(/-([a-z])/g,(U,Y)=>Y.toUpperCase()),J=A[$+1];if(J&&!J.startsWith("--"))Q[D]=J,$++}}return Q}function iN6(A,Q){let $=A.includes("--headless")||A.some((E)=>E.startsWith("--headless=")),B=yi.resolve(Q.logFile??process.env.AMP_LOG_FILE??($?KN6:yc));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:B}}async function nN6(){NX4();let A=lN6(process.argv),Q=iN6(process.argv,A),$=PX4(Q);TB0("silent");let B=process.argv.includes("--no-color"),E=process.argv.includes("--color"),D=process.stdout.isTTY&&process.stderr.isTTY;if(B||!E&&!D)_0.level=0;if(WN6(S),S.info("Starting Amp CLI.",{version:"0.0.1780694019-g120cbb",buildTimestamp:"2026-06-05T21:18:30.332Z"}),process.platform==="win32"&&Qq())EV4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new GA(z3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await bN6($).parseAsync(process.argv)}rD4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await nN6().catch(f30)});async function aN6(A,Q){let $=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!$)await A.settings.set("url",process.env.AMP_URL,"global"),fQ.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
5052
5054
  `);else if(!hO(A.ampURL))fQ.write(`Logging in to ${new URL(A.ampURL).hostname}
5053
5055
  `);let B=process.env.AMP_API_KEY;if(B)fQ.write(`API key found in environment variable, storing...
5054
5056
  `),await Q.set("apiKey",B,A.ampURL),fQ.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1780677932-g159ed8",
3
+ "version": "0.0.1780694019-g120cbb",
4
4
  "description": "Renamed to @ampcode/cli - see https://ampcode.com/news/npm-package-changes",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "license": "SEE LICENSE IN LICENSE.md",
@@ -8,7 +8,7 @@
8
8
  "amp": "node_modules/@ampcode/cli/bin/amp.exe"
9
9
  },
10
10
  "dependencies": {
11
- "@ampcode/cli": "0.0.1780677932-g159ed8"
11
+ "@ampcode/cli": "0.0.1780694019-g120cbb"
12
12
  },
13
13
  "files": [
14
14
  "dist/main.js",