@sourcegraph/amp 0.0.1761062513-gf7c5f2 → 0.0.1761062777-g4520cb

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 +9 -9
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -6210,7 +6210,7 @@ See https://ampcode.com/manual#toolboxes`);return Q[0]||uR}function nZ6(J,Q){let
6210
6210
  `;async function oZ6(J,Q,Z,X){let Y=performance.now(),K=[...n_(lM1(J)),{role:"user",parts:[{text:i59.replace("{USER_GOAL}",Q)}]}],q=await C$(xr,K,[],J,Z,X,{responseMimeType:"application/json",responseJsonSchema:M0.toJSONSchema(sZ6)}),G=sZ6.parse(JSON.parse(q.message.text??"")),z=performance.now()-Y;return l.debug("Thread handoff prepared",{threadId:J.id,goalLength:Q.length,instructionsLength:G.instructions.length,fileCount:G.relevantFiles.length,durationMs:Math.round(z)}),{instructions:G.instructions,relevantFiles:G.relevantFiles}}FL();H8();k6();function tZ6(J){let Q=J.trim();if(Q==="quit"||Q==="exit")return"/quit";return J}function eZ6(J,Q,Z){if(J.agentMode)return J.agentMode;if(Q?.agentMode){let X=Q.agentMode;if(X==="free"){if(Z?.canUseAmpFree??!1)return"free";return"smart"}return X}return"smart"}z0();iB();import n59 from"node:fs";import JX6 from"node:path";function QX6(J){let Q=J.trim().replace(/^["']|["']$/g,"");if(Q=Q.replace(/\\(.)/g,"$1"),!/\.(png|jpe?g|gif|webp)$/i.test(Q))return null;if(!JX6.isAbsolute(Q))return null;return l.debug("Extracted image path",{original:J,extracted:Q}),Q}function ZX6(J){try{let Q=JX6.extname(J).toLowerCase(),Z=_e1(Q);if(!Z)return l.warn("Unsupported image file extension",{ext:Q}),null;try{let X=n59.readFileSync(J);return a59(X,Z)}catch(X){l.error(`Failed to read image file ${J}:`,X)}}catch(Q){l.error("Error handling image file path",{imagePath:J,error:Q})}return null}function a59(J,Q){if(J.length>EF)return l.warn(`Image file too large: ${J.length} bytes (max: ${EF})`),null;return{type:"image",source:{type:"base64",data:J.toString("base64"),mediaType:Q}}}import{execSync as PK6}from"node:child_process";import{rmdir as pY9}from"node:fs/promises";import{tmpdir as dY9}from"node:os";import TK6 from"node:path";aO();z0();import{spawn as r59}from"node:child_process";import{promises as s59}from"node:fs";function XX6(J){return J.kind==="executable"}function YX6(J){return J.kind==="markdown"}var lH=50000,KX6=300000;async function Iy1(J,Q,Z,X={}){let{timeoutMs:Y=KX6,signal:K}=X;try{let q=await Z.getCommand(J);if(!q)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Z.isCommandAvailable(J))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(l.debug("Executing command",{commandName:J,filePath:q.filePath,args:Q}),YX6(q))return await o59(q,Q);else if(XX6(q))return await t59(q,Q,Y,K);else return{success:!1,output:"",error:"Unsupported command type"}}catch(q){return l.error("Failed to execute command",{commandName:J,error:q}),{success:!1,output:"",error:q instanceof Error?q.message:"Unknown error occurred"}}}async function o59(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await s59.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>lH?Z.slice(0,lH)+`
6211
6211
  ... (output truncated at ${lH} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function t59(J,Q,Z=KX6,X){return new Promise((Y)=>{let[K,q]=e59(J,Q);l.debug("Spawning command",{spawnCommand:K,spawnArgs:q.slice(0,10),filePath:J.filePath,timeoutMs:Z});let G=Ce1(X),z=!1,U=setTimeout(()=>{z=!0,G.abort(),l.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),F=r59(K,q,{stdio:["pipe","pipe","pipe"],signal:G.signal,detached:!0}),W=[],H=[],B=0;F.stdout?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=lH)W.push(V);else{let N=lH-(B-V.length);if(N>0)W.push(V.slice(0,N))}}),F.stderr?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=lH)H.push(V);else{let N=lH-(B-V.length);if(N>0)H.push(V.slice(0,N))}}),F.on("close",(M)=>{if(clearTimeout(U),z){Y({success:!1,output:W.join(""),error:`Command timed out after ${Z}ms`,exitCode:void 0});return}if(G.signal.aborted){Y({success:!1,output:W.join(""),error:"The command was aborted",exitCode:M??void 0});return}let V=M===0||M===1,N=W.join(""),L=H.join(""),A=N;if(!V&&!N.trim()&&L.trim())A=L;else if(L.trim())A+=N?`
6212
6212
  ${L}`:L;if(B>lH)A+=`
6213
- ... (output truncated at ${lH} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),F.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:W.join(""),error:V})})})}function e59(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return QJ9(Z,X?[...X]:null,Y,Q);else return JJ9(Z,X?[...X]:null,Y,Q)}function JJ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function QJ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}z0();Tj();U2();PB();SY();hF();k6();T0();import{mkdtemp as cY9,readFile as lY9,unlink as iY9,writeFile as AR2}from"fs/promises";var U51={};w6(U51,{scrollUp:()=>RJ9,scrollDown:()=>OJ9,link:()=>TJ9,image:()=>CJ9,iTerm:()=>SJ9,exitAlternativeScreen:()=>IJ9,eraseUp:()=>wJ9,eraseStartLine:()=>LJ9,eraseScreen:()=>Py1,eraseLines:()=>VJ9,eraseLine:()=>UX6,eraseEndLine:()=>NJ9,eraseDown:()=>AJ9,enterAlternativeScreen:()=>EJ9,cursorUp:()=>GX6,cursorTo:()=>YJ9,cursorShow:()=>MJ9,cursorSavePosition:()=>UJ9,cursorRestorePosition:()=>FJ9,cursorPrevLine:()=>BJ9,cursorNextLine:()=>HJ9,cursorMove:()=>KJ9,cursorLeft:()=>zX6,cursorHide:()=>DJ9,cursorGetPosition:()=>WJ9,cursorForward:()=>GJ9,cursorDown:()=>qJ9,cursorBackward:()=>zJ9,clearTerminal:()=>$J9,clearScreen:()=>jJ9,beep:()=>PJ9});import Ty1 from"node:process";var z51=globalThis.window?.document!==void 0,AA2=globalThis.process?.versions?.node!==void 0,wA2=globalThis.process?.versions?.bun!==void 0,RA2=globalThis.Deno?.version?.deno!==void 0,OA2=globalThis.process?.versions?.electron!==void 0,jA2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,$A2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,EA2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,IA2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,PA2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,ku=globalThis.navigator?.userAgentData?.platform,TA2=ku==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",CA2=ku==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",SA2=ku==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",vA2=ku==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),kA2=ku==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var N2="\x1B[",xu="\x1B]",WC="\x07",_u=";",qX6=!z51&&Ty1.env.TERM_PROGRAM==="Apple_Terminal",ZJ9=!z51&&Ty1.platform==="win32",XJ9=z51?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Ty1.cwd,YJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return N2+(J+1)+"G";return N2+(Q+1)+_u+(J+1)+"H"},KJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=N2+-J+"D";else if(J>0)Z+=N2+J+"C";if(Q<0)Z+=N2+-Q+"A";else if(Q>0)Z+=N2+Q+"B";return Z},GX6=(J=1)=>N2+J+"A",qJ9=(J=1)=>N2+J+"B",GJ9=(J=1)=>N2+J+"C",zJ9=(J=1)=>N2+J+"D",zX6=N2+"G",UJ9=qX6?"\x1B7":N2+"s",FJ9=qX6?"\x1B8":N2+"u",WJ9=N2+"6n",HJ9=N2+"E",BJ9=N2+"F",DJ9=N2+"?25l",MJ9=N2+"?25h",VJ9=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=UX6+(Z<J-1?GX6():"");if(J)Q+=zX6;return Q},NJ9=N2+"K",LJ9=N2+"1K",UX6=N2+"2K",AJ9=N2+"J",wJ9=N2+"1J",Py1=N2+"2J",RJ9=N2+"S",OJ9=N2+"T",jJ9="\x1Bc",$J9=ZJ9?`${Py1}${N2}0f`:`${Py1}${N2}3J${N2}H`,EJ9=N2+"?1049h",IJ9=N2+"?1049l",PJ9=WC,TJ9=(J,Q)=>[xu,"8",_u,_u,Q,WC,J,xu,"8",_u,_u,WC].join(""),CJ9=(J,Q={})=>{let Z=`${xu}1337;File=inline=1`;if(Q.width)Z+=`;width=${Q.width}`;if(Q.height)Z+=`;height=${Q.height}`;if(Q.preserveAspectRatio===!1)Z+=";preserveAspectRatio=0";return Z+":"+Buffer.from(J).toString("base64")+WC},SJ9={setCwd:(J=XJ9())=>`${xu}50;CurrentDir=${J}${WC}`,annotation(J,Q={}){let Z=`${xu}1337;`,X=Q.x!==void 0,Y=Q.y!==void 0;if((X||Y)&&!(X&&Y&&Q.length!==void 0))throw Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");if(J=J.replaceAll("|",""),Z+=Q.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",Q.length>0)Z+=(X?[J,Q.length,Q.x,Q.y]:[Q.length,J]).join("|");else Z+=J;return Z+WC}};var F51=g6(VX6(),1);function rV(J,Q,{target:Z="stdout",...X}={}){if(!F51.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (​${Q}​)`}return U51.link(J,Q)}rV.isSupported=F51.default.stdout;rV.stderr=(J,Q,Z={})=>rV(J,Q,{target:"stderr",...Z});rV.stderr.isSupported=F51.default.stderr;z0();SY();class _y1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1761062513-gf7c5f2"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await sn(Q,this.configService)}catch(Q){l.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}import{execFile as H51}from"node:child_process";import{platform as xy1}from"node:os";import{promisify as xJ9}from"node:util";var W51=xJ9(H51),bJ9=(J)=>`\x1B]52;c;${J}\x1B\\`,yJ9="\x1B]52;c;?\x1B\\",fJ9="\x1B]52;p;?\x1B\\";class NX6{capabilities=null;pendingReadPromise=null;readResolve=null;readTimeout=null;setCapabilities(J){this.capabilities=J}isOsc52Supported(){return this.capabilities?.osc52??!1}async commandExists(J){try{return await W51("which",[J]),!0}catch{return!1}}async writeToPbcopy(J){try{let Q=H51("pbcopy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`pbcopy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToWlCopy(J){try{let Q=H51("wl-copy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`wl-copy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToXclip(J){try{let Q=H51("xclip",["-selection","clipboard"]);return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`xclip exited with code ${Y}`))})}),!0}catch{return!1}}async readFromOSC52WithQuery(J){if(!this.isOsc52Supported())return null;if(this.pendingReadPromise)return this.pendingReadPromise;this.pendingReadPromise=new Promise((Z)=>{this.readResolve=Z,this.readTimeout=setTimeout(()=>{this.readResolve=null,this.pendingReadPromise=null,Z(null)},2000),process.stdout.write(J)});let Q=await this.pendingReadPromise;return this.pendingReadPromise=null,Q}async readFromOSC52(){return this.readFromOSC52WithQuery(yJ9)}handleOSC52Response(J){if(this.readResolve&&this.readTimeout){clearTimeout(this.readTimeout),this.readTimeout=null;try{let Q=Buffer.from(J,"base64").toString("utf8");this.readResolve(Q)}catch{this.readResolve(null)}this.readResolve=null,this.pendingReadPromise=null}}async readFromPbpaste(){try{let{stdout:J}=await W51("pbpaste");return J}catch{return null}}async readFromWlPaste(J){try{let Q=["--no-newline"];if(J==="primary")Q.push("--primary");let{stdout:Z}=await W51("wl-paste",Q);return Z}catch{return null}}async readFromXclip(J){try{let{stdout:Q}=await W51("xclip",["-selection",J,"-o"]);return Q}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(fJ9)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if(xy1()==="darwin"){let Q=await this.readFromPbpaste();if(Q!==null)return Q}else{if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("clipboard");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("clipboard");if(Q!==null)return Q}}return null}async readPrimarySelection(){if(xy1()==="darwin")return this.readText();if(this.isOsc52Supported()){let Q=await this.readFromOSC52Primary();if(Q!==null)return Q}if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("primary");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("primary");if(Q!==null)return Q}return null}async writeText(J){if(this.isOsc52Supported()){let Z=Buffer.from(J).toString("base64"),X=bJ9(Z);process.stdout.write(X);return}if(xy1()==="darwin"){if(await this.writeToPbcopy(J))return}else{if(await this.commandExists("wl-copy")&&await this.writeToWlCopy(J))return;if(await this.commandExists("xclip")&&await this.writeToXclip(J))return}}}var FY=new NX6;z0();class B51 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}class c7{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function LX6(J){if(J instanceof B51)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof c7)return{title:"Info",description:J.message,type:"info"};return l.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var ZN=null,nY9={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(ZN)return Error("Already connected. Use /disconnect first to reconnect.");let{connectedClientsService:Z}=J;await Z.start({clientId:J.clientId,currentThreadID:J.worker.thread.id});let Y=Z.getCurrentStatus().clientID||"unknown",{connectBackground:K}=await Promise.resolve().then(() => (db1(),uJ6)),q=await K({worker:J.worker},J.configService,{clientId:J.clientId,onUserDisconnect:()=>{ZN=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});ZN=q,q.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((M)=>{ZN=null,Z.sendStatus({connected:!1,errorMessage:M.message})});let z=(await J.configService.getLatest()).settings.url,U=J.worker.thread.id,F=new URL(`/threads/${U}`,z).toString(),W=new URL("/clients",z).toString(),H="";try{H=await(await Promise.resolve().then(() => g6(Tf1(),1))).toString(F,{type:"utf8",margin:2,color:{dark:"#000000",light:"#FFFFFF"}})}catch(M){l.error("Failed to generate QR code:",M)}if((process.stdout.rows||24)>=30&&H&&J.onShowQRCodeOverlay)J.onShowQRCodeOverlay({url:W,qrCode:H});else return new c7(`Continue at ${W}`)}catch(Z){return J.connectedClientsService.sendStatus({connected:!1,errorMessage:Z.message}),Error(`Failed to start connection: ${Z.message}`)}}},disconnect:{name:"disconnect",description:"Disconnect from web interface",execute:async(J,Q)=>{if(!ZN)return new c7("Not connected to Amp web interface");try{ZN.disconnect();let Z=ZN.clientID;return ZN=null,J.connectedClientsService.sendStatus({connected:!1,enabled:!1,errorMessage:void 0}),new c7(`Disconnected from Amp web interface
6213
+ ... (output truncated at ${lH} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),F.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:W.join(""),error:V})})})}function e59(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return QJ9(Z,X?[...X]:null,Y,Q);else return JJ9(Z,X?[...X]:null,Y,Q)}function JJ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function QJ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}z0();Tj();U2();PB();SY();hF();k6();T0();import{mkdtemp as cY9,readFile as lY9,unlink as iY9,writeFile as AR2}from"fs/promises";var U51={};w6(U51,{scrollUp:()=>RJ9,scrollDown:()=>OJ9,link:()=>TJ9,image:()=>CJ9,iTerm:()=>SJ9,exitAlternativeScreen:()=>IJ9,eraseUp:()=>wJ9,eraseStartLine:()=>LJ9,eraseScreen:()=>Py1,eraseLines:()=>VJ9,eraseLine:()=>UX6,eraseEndLine:()=>NJ9,eraseDown:()=>AJ9,enterAlternativeScreen:()=>EJ9,cursorUp:()=>GX6,cursorTo:()=>YJ9,cursorShow:()=>MJ9,cursorSavePosition:()=>UJ9,cursorRestorePosition:()=>FJ9,cursorPrevLine:()=>BJ9,cursorNextLine:()=>HJ9,cursorMove:()=>KJ9,cursorLeft:()=>zX6,cursorHide:()=>DJ9,cursorGetPosition:()=>WJ9,cursorForward:()=>GJ9,cursorDown:()=>qJ9,cursorBackward:()=>zJ9,clearTerminal:()=>$J9,clearScreen:()=>jJ9,beep:()=>PJ9});import Ty1 from"node:process";var z51=globalThis.window?.document!==void 0,AA2=globalThis.process?.versions?.node!==void 0,wA2=globalThis.process?.versions?.bun!==void 0,RA2=globalThis.Deno?.version?.deno!==void 0,OA2=globalThis.process?.versions?.electron!==void 0,jA2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,$A2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,EA2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,IA2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,PA2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,ku=globalThis.navigator?.userAgentData?.platform,TA2=ku==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",CA2=ku==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",SA2=ku==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",vA2=ku==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),kA2=ku==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var N2="\x1B[",xu="\x1B]",WC="\x07",_u=";",qX6=!z51&&Ty1.env.TERM_PROGRAM==="Apple_Terminal",ZJ9=!z51&&Ty1.platform==="win32",XJ9=z51?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Ty1.cwd,YJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return N2+(J+1)+"G";return N2+(Q+1)+_u+(J+1)+"H"},KJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=N2+-J+"D";else if(J>0)Z+=N2+J+"C";if(Q<0)Z+=N2+-Q+"A";else if(Q>0)Z+=N2+Q+"B";return Z},GX6=(J=1)=>N2+J+"A",qJ9=(J=1)=>N2+J+"B",GJ9=(J=1)=>N2+J+"C",zJ9=(J=1)=>N2+J+"D",zX6=N2+"G",UJ9=qX6?"\x1B7":N2+"s",FJ9=qX6?"\x1B8":N2+"u",WJ9=N2+"6n",HJ9=N2+"E",BJ9=N2+"F",DJ9=N2+"?25l",MJ9=N2+"?25h",VJ9=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=UX6+(Z<J-1?GX6():"");if(J)Q+=zX6;return Q},NJ9=N2+"K",LJ9=N2+"1K",UX6=N2+"2K",AJ9=N2+"J",wJ9=N2+"1J",Py1=N2+"2J",RJ9=N2+"S",OJ9=N2+"T",jJ9="\x1Bc",$J9=ZJ9?`${Py1}${N2}0f`:`${Py1}${N2}3J${N2}H`,EJ9=N2+"?1049h",IJ9=N2+"?1049l",PJ9=WC,TJ9=(J,Q)=>[xu,"8",_u,_u,Q,WC,J,xu,"8",_u,_u,WC].join(""),CJ9=(J,Q={})=>{let Z=`${xu}1337;File=inline=1`;if(Q.width)Z+=`;width=${Q.width}`;if(Q.height)Z+=`;height=${Q.height}`;if(Q.preserveAspectRatio===!1)Z+=";preserveAspectRatio=0";return Z+":"+Buffer.from(J).toString("base64")+WC},SJ9={setCwd:(J=XJ9())=>`${xu}50;CurrentDir=${J}${WC}`,annotation(J,Q={}){let Z=`${xu}1337;`,X=Q.x!==void 0,Y=Q.y!==void 0;if((X||Y)&&!(X&&Y&&Q.length!==void 0))throw Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");if(J=J.replaceAll("|",""),Z+=Q.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",Q.length>0)Z+=(X?[J,Q.length,Q.x,Q.y]:[Q.length,J]).join("|");else Z+=J;return Z+WC}};var F51=g6(VX6(),1);function rV(J,Q,{target:Z="stdout",...X}={}){if(!F51.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (​${Q}​)`}return U51.link(J,Q)}rV.isSupported=F51.default.stdout;rV.stderr=(J,Q,Z={})=>rV(J,Q,{target:"stderr",...Z});rV.stderr.isSupported=F51.default.stderr;z0();SY();class _y1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1761062777-g4520cb"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await sn(Q,this.configService)}catch(Q){l.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}import{execFile as H51}from"node:child_process";import{platform as xy1}from"node:os";import{promisify as xJ9}from"node:util";var W51=xJ9(H51),bJ9=(J)=>`\x1B]52;c;${J}\x1B\\`,yJ9="\x1B]52;c;?\x1B\\",fJ9="\x1B]52;p;?\x1B\\";class NX6{capabilities=null;pendingReadPromise=null;readResolve=null;readTimeout=null;setCapabilities(J){this.capabilities=J}isOsc52Supported(){return this.capabilities?.osc52??!1}async commandExists(J){try{return await W51("which",[J]),!0}catch{return!1}}async writeToPbcopy(J){try{let Q=H51("pbcopy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`pbcopy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToWlCopy(J){try{let Q=H51("wl-copy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`wl-copy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToXclip(J){try{let Q=H51("xclip",["-selection","clipboard"]);return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`xclip exited with code ${Y}`))})}),!0}catch{return!1}}async readFromOSC52WithQuery(J){if(!this.isOsc52Supported())return null;if(this.pendingReadPromise)return this.pendingReadPromise;this.pendingReadPromise=new Promise((Z)=>{this.readResolve=Z,this.readTimeout=setTimeout(()=>{this.readResolve=null,this.pendingReadPromise=null,Z(null)},2000),process.stdout.write(J)});let Q=await this.pendingReadPromise;return this.pendingReadPromise=null,Q}async readFromOSC52(){return this.readFromOSC52WithQuery(yJ9)}handleOSC52Response(J){if(this.readResolve&&this.readTimeout){clearTimeout(this.readTimeout),this.readTimeout=null;try{let Q=Buffer.from(J,"base64").toString("utf8");this.readResolve(Q)}catch{this.readResolve(null)}this.readResolve=null,this.pendingReadPromise=null}}async readFromPbpaste(){try{let{stdout:J}=await W51("pbpaste");return J}catch{return null}}async readFromWlPaste(J){try{let Q=["--no-newline"];if(J==="primary")Q.push("--primary");let{stdout:Z}=await W51("wl-paste",Q);return Z}catch{return null}}async readFromXclip(J){try{let{stdout:Q}=await W51("xclip",["-selection",J,"-o"]);return Q}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(fJ9)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if(xy1()==="darwin"){let Q=await this.readFromPbpaste();if(Q!==null)return Q}else{if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("clipboard");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("clipboard");if(Q!==null)return Q}}return null}async readPrimarySelection(){if(xy1()==="darwin")return this.readText();if(this.isOsc52Supported()){let Q=await this.readFromOSC52Primary();if(Q!==null)return Q}if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("primary");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("primary");if(Q!==null)return Q}return null}async writeText(J){if(this.isOsc52Supported()){let Z=Buffer.from(J).toString("base64"),X=bJ9(Z);process.stdout.write(X);return}if(xy1()==="darwin"){if(await this.writeToPbcopy(J))return}else{if(await this.commandExists("wl-copy")&&await this.writeToWlCopy(J))return;if(await this.commandExists("xclip")&&await this.writeToXclip(J))return}}}var FY=new NX6;z0();class B51 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}class c7{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function LX6(J){if(J instanceof B51)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof c7)return{title:"Info",description:J.message,type:"info"};return l.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var ZN=null,nY9={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(ZN)return Error("Already connected. Use /disconnect first to reconnect.");let{connectedClientsService:Z}=J;await Z.start({clientId:J.clientId,currentThreadID:J.worker.thread.id});let Y=Z.getCurrentStatus().clientID||"unknown",{connectBackground:K}=await Promise.resolve().then(() => (db1(),uJ6)),q=await K({worker:J.worker},J.configService,{clientId:J.clientId,onUserDisconnect:()=>{ZN=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});ZN=q,q.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((M)=>{ZN=null,Z.sendStatus({connected:!1,errorMessage:M.message})});let z=(await J.configService.getLatest()).settings.url,U=J.worker.thread.id,F=new URL(`/threads/${U}`,z).toString(),W=new URL("/clients",z).toString(),H="";try{H=await(await Promise.resolve().then(() => g6(Tf1(),1))).toString(F,{type:"utf8",margin:2,color:{dark:"#000000",light:"#FFFFFF"}})}catch(M){l.error("Failed to generate QR code:",M)}if((process.stdout.rows||24)>=30&&H&&J.onShowQRCodeOverlay)J.onShowQRCodeOverlay({url:W,qrCode:H});else return new c7(`Continue at ${W}`)}catch(Z){return J.connectedClientsService.sendStatus({connected:!1,errorMessage:Z.message}),Error(`Failed to start connection: ${Z.message}`)}}},disconnect:{name:"disconnect",description:"Disconnect from web interface",execute:async(J,Q)=>{if(!ZN)return new c7("Not connected to Amp web interface");try{ZN.disconnect();let Z=ZN.clientID;return ZN=null,J.connectedClientsService.sendStatus({connected:!1,enabled:!1,errorMessage:void 0}),new c7(`Disconnected from Amp web interface
6214
6214
  Client ID: ${Z}
6215
6215
  Server will clean up automatically within 60 seconds`)}catch(Z){return Error(`Failed to disconnect: ${Z.message}`)}}}};class Cf1{configService;commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=JS(),Q){this.configService=Q;this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Z)=>this.latestCustom=Z),this.telemetrySubmitter=new _y1(async()=>{try{return(await this.configService.getLatest()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}},this.configService),this.configService.config.pipe(C0((Z)=>LB(Z.settings)),t6()).subscribe((Z)=>{this._initBaseCommands(Z.length>1)})}_initBaseCommands(J){if(this.commands={...aY9},process.env.AMP_CONNECT==="1")Object.assign(this.commands,nY9);if(J)Object.assign(this.commands,rY9)}async execute(J,Q,Z=[],X){this.telemetrySubmitter.submit(J).catch((G)=>{l.debug("Failed to submit command telemetry",G)});let Y=this.commands[J];if(Y)return Y.execute(Q,Z);let K=this.latestCustom.find((G)=>G.name===J),q=await Iy1(J,Z,this.customRegistry,{signal:X});if(q.success)if(K?.kind==="markdown"){Q.editorDispatch({type:"set-input",input:q.output});return}else{Q.submitMessage(q.output);return}return Error(q.error??`Command '${J}' failed`)}query(J,Q,Z){let X=J.toLowerCase(),Y=Object.values(this.commands).filter((q)=>q.name.toLowerCase().includes(X)).filter((q)=>{if(!Q||!q.isVisible)return!0;return q.isVisible(Q,Z)}),K=this.latestCustom.filter((q)=>q.available&&q.name.toLowerCase().includes(X)).map((q)=>({name:q.name,description:"Custom command",requiresArgs:q.kind==="executable",execute:(G,z)=>this.execute(q.name,G,z??[])}));return[...Y,...K]}async cleanup(){await this.telemetrySubmitter.dispose()}get(J){let Q=this.commands[J];if(Q)return Q;let Z=this.latestCustom.find((X)=>X.name===J);return{name:J,description:"Custom command",requiresArgs:Z?.kind==="executable",execute:(X,Y)=>this.execute(J,X,Y??[])}}}var aY9={"generate-agent-file":{name:"generate-agent-file",description:`Generate an ${X5} file in the current workspace`,execute:async(J,Q)=>{let Z=await J.configService.getLatest(),X=fq(Z.settings),K=J.getInMemoryAgentModeOverride()??X;J.worker.handle({type:"user:message",message:{content:[{type:"text",text:W90}],agentMode:K}});return}},compact:{name:"compact",description:"Compact the thread. Optional: /compact [message] to queue a message after compaction",execute:async(J,Q)=>{if(J.thread.messages.length===0)return new B51;if(Q&&Q.length>0){let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}try{await J.worker.summarizeThread(new AbortController().signal)}catch(Z){return Z instanceof Error?Z:Error("Failed to compact thread")}},isVisible:(J)=>J.agentMode!=="free"},editor:{name:"editor",description:"Open $EDITOR to write a prompt",launchesWindow:!0,execute:async(J,Q)=>{try{let Z=process.env.EDITOR||process.env.VISUAL||"nano",X=await cY9(TK6.join(dY9(),"amp-edit-")),Y=TK6.join(X,"message.amp.md");PK6(`${Z} "${Y}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let q=(await lY9(Y,"utf-8")).trim();if(q)J.editorDispatch({type:"set-input",input:q})}catch(K){if(K?.code==="ENOENT")return;return l.error("Failed to read temporary file",K),Error("Failed to read editor content")}try{await iY9(Y),await pY9(X)}catch(K){l.warn("Failed to clean up temporary file",K)}return}catch(Z){return l.error("Failed to open editor",Z),Error("Failed to open editor")}}},help:{name:"help",description:"Show help and hotkeys",execute:async(J,Q)=>{J.openHelp();return}},permissions:{name:"permissions",description:"Edit permission rules in $EDITOR, or `/permissions off|on` to toggle for this session",launchesWindow:!0,execute:async(J,Q)=>{if(Q&&Q.length>0){let Y=Q[0]?.trim().toLowerCase();switch(Y){case"on":try{return oG("dangerouslyAllowAll",!1),new c7("Amp is now following permissions rules for this session")}catch(K){return l.error("Failed to set dangerously allow all setting",K),Error("Failed to enable permissions for this session")}case"off":try{return oG("dangerouslyAllowAll",!0),new c7("Permissions disabled for this session - you will NOT be asked for confirmation before Amp runs a command.")}catch(K){return l.error("Failed to set dangerously allow all setting",K),Error("Failed to disable permissions for this session")}case"edit":break;default:return Error(`Invalid option: ${Y}. Use: on, off, or edit (or no argument for edit)`)}}let Z=await UC();if(Z===null)return Error("No editor found, please set $EDITOR to edit permissions");let X="";try{let Y={stdin:process.stdin,stdout:process.stdout,stderr:{write:(K)=>{return X=K.toString(),!0}},exit:(K)=>{if(K!==0)throw l.error("editPermissions exited with status",K),Error(X)},settingsFile:J.settingsFilePath,resolveEditor:UC};await K51(Y);return}catch(Y){l.error("failed to open permissions editor:",Y);let K=Y instanceof Error?`: ${Y.message}`:"";return Error(`Failed to open ${Z}${K}`)}finally{process.stdout.write("\x1B[?25l")}}},new:{name:"new",description:"Start a new thread",execute:async(J,Q)=>{try{await J.startNewThread();return}catch(Z){return l.error("Failed to start new thread",Z),Error("Failed to start new thread")}},isVisible:(J)=>J.messages.length!==0},handoff:{name:"handoff",description:"Start new focused thread with relevant files and prompt: /handoff <your goal>",statusMessage:"Handing off...",requiresArgs:!0,execute:async()=>{return},isVisible:(J)=>J.messages.length!==0&&J.agentMode!=="free"},continue:{name:"continue",description:"Continue an existing thread",requiresArgs:!1,requiresPicker:!0,execute:async(J,Q)=>{try{if(Q&&Q.length>0){let Z=Q[0]?.trim();if(!Z)return Error("Invalid thread ID provided");return await J.switchToThread(Z),new c7(`Switched to existing thread: ${Z}`)}await J.pickAndContinueThread();return}catch(Z){return l.error("Failed to continue thread",Z),Error("Failed to continue thread")}}},queue:{name:"queue",description:"Queue a message to send when inference completes. If no inference running, sends immediately.",requiresArgs:!0,execute:async(J,Q)=>{if(!Q||Q.length===0)return Error("Queue command requires a message argument. Usage: /queue <message>");let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}},dequeue:{name:"dequeue",description:"Dequeue all messages and restore them to the prompt editor",execute:async(J,Q)=>{let Z=J.thread.queuedMessages??[];if(Z.length===0)return;let Y=Z.map((K)=>{return K.queuedMessage.content.filter((G)=>G.type==="text").map((G)=>G.text).join("").trim()}).filter(Boolean).join(`
6216
6216
  `).trim();await J.worker.handle({type:"user:message-queue:discard"}),J.editorDispatch({type:"set-input",input:Y})},isVisible:(J)=>(J.queuedMessages?.length??0)>0},share:{name:"share",description:"Set thread visibility - `/share private|workspace|group|public`",execute:async(J,Q)=>{let{thread:Z,threadSyncService:X,ampURL:Y}=J;if(!Q||Q.length===0)return Error("Please specify a visibility option: private, workspace, group, or public");let K=Cj(new URL(Y),Z.id).toString(),G=`Thread URL: ${rV(K,K,{fallback:()=>K})}`,z=Q[0]?.trim().toLowerCase(),U;switch(z){case"private":U={visibility:"private",sharedGroupIDs:[]};break;case"workspace":U={visibility:"thread_workspace_shared"};break;case"group":U={visibility:"private",sharedGroupIDs:[],shareWithAllCreatorGroups:!0};break;case"public":U={visibility:"public"};break;default:return Error(`Invalid visibility option: ${z}. Use: private, workspace, group, or public`)}try{return await X.updateThreadMeta(Z.id,U),new c7(`${G}
@@ -6348,7 +6348,7 @@ exit code: ${G}`,new S1({color:X.foreground,dim:!0,italic:!0})));if(z)U.push(new
6348
6348
 
6349
6349
  (${z}, command and output not shown to agent)`,new S1({color:X.foreground,dim:!0,italic:!0})));else if(Y)U.push(new O1(`
6350
6350
 
6351
- (Command and output not shown to agent)`,new S1({color:X.foreground,dim:!0,italic:!0})));return new t1({text:new O1("",void 0,U)})}class km1 extends t0{items;subagentToolsByParentID;controller;autofocus;onNewMessage;showScrollbar;onCopy;onMessageEditSubmit;onMessageRestoreSubmit;onMessageForkSubmit;thread;focusNode;onDismissFocus;get userMessageIndices(){let J=[];for(let Q=0;Q<this.items.length;Q++){let Z=this.items[Q];if(Z?.type==="message"&&Z.message.role==="user")J.push(Q)}return J}constructor({key:J,items:Q,subagentToolsByParentID:Z={},controller:X,autofocus:Y=!1,onNewMessage:K,showScrollbar:q=!0,onCopy:G,onMessageEditSubmit:z,onMessageRestoreSubmit:U,onMessageForkSubmit:F,thread:W,focusNode:H,onDismissFocus:B}){super(J?{key:J}:{});this.items=Q,this.subagentToolsByParentID=Z,this.controller=X,this.autofocus=Y,this.onNewMessage=K,this.showScrollbar=q,this.onCopy=G,this.onMessageEditSubmit=z,this.onMessageRestoreSubmit=U,this.onMessageForkSubmit=F,this.thread=W,this.focusNode=H,this.onDismissFocus=B}createState(){return new jU6}}class jU6 extends o0{_controller=null;_isDisposed=!1;_thinkingBlockStates=new Map;_globalToggleListener;_streamingIndexes=new Set;_viewportHeight=25;_widgetCache=new Map;_lastCostDisplayState=null;_selectedUserMessageOrdinal=null;_editingMessageOrdinal=null;_isShowingRestoreConfirmation=!1;_inFocus=!1;_focusListener;get controller(){return this._controller}_navigateUp(J,Q){if(Q<=0)return null;if(J===null)return Q-1;if(J<=0)return 0;return J-1}_navigateDown(J,Q){if(Q<=0)return null;if(J===null)return null;if(J>=Q-1)return null;return J+1}_ordinalToIndex(J,Q){if(Q===null)return null;if(Q<0||Q>=J.length)return null;return J[Q]??null}_getUserCount(){return this.widget.userMessageIndices.length}_clearSelectedUserMessage(){let J=this._selectedUserMessageOrdinal,Q=J!==null?this.getUserMessageIndexFromOrdinal(J):null;this.setState(()=>{if(Q!=null)this._widgetCache.delete(Q);this._selectedUserMessageOrdinal=null})}_selectUserMessageByOrdinal(J){let Q=this._selectedUserMessageOrdinal,Z=J,X=Q!==null?this.getUserMessageIndexFromOrdinal(Q):null,Y=this.getUserMessageIndexFromOrdinal(Z);if(X!==null)this._widgetCache.delete(X);if(Y!==null)this._widgetCache.delete(Y);if(this.setState(()=>{this._selectedUserMessageOrdinal=Z}),Y!==null)G7.instance.addPostFrameCallback(()=>{this.scrollToMessage(Y,{animated:!0,offset:0,edge:"top",duration:200})})}_selectEditingUserMessageByOrdinal(J){let Q=this._editingMessageOrdinal,Z=J,X=Q!==null?this.getUserMessageIndexFromOrdinal(Q):null,Y=Z!==null?this.getUserMessageIndexFromOrdinal(Z):null;if(X!==null)this._widgetCache.delete(X);if(Y!==null)this._widgetCache.delete(Y);this.setState(()=>{this._editingMessageOrdinal=Z})}getUserMessageIndexFromOrdinal(J){return this.widget.userMessageIndices[J]??null}getOrdinalFromUserMessageIndex(J){let Z=this.widget.userMessageIndices.indexOf(J);return Z>=0?Z:null}getLatestUserMessageOrdinal(){let J=this.widget.userMessageIndices;return J.length>0?J.length-1:null}navigateToUserMessage(J){let Q=this._getUserCount(),Z=J==="up"?this._navigateUp(this._selectedUserMessageOrdinal,Q):this._navigateDown(this._selectedUserMessageOrdinal,Q);if(Z===null&&J==="down"){this._controller?.animateToBottom(100),this._clearSelectedUserMessage(),this.widget.onDismissFocus?.();return}if(Z!==null)this._selectUserMessageByOrdinal(Z)}handleNavigateUserMessageUp=()=>{if(this._editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("up"),"handled"};handleNavigateUserMessageDown=()=>{if(this._editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("down"),"handled"};handleEscape=()=>{if(this._editingMessageOrdinal!==null)return this.setState(()=>{let J=this._ordinalToIndex(this.widget.userMessageIndices,this._editingMessageOrdinal);if(J!=null)this._widgetCache.delete(J);this._editingMessageOrdinal=null}),"handled";else if(this._selectedUserMessageOrdinal!==null)return this._clearSelectedUserMessage(),this.setState(()=>{this._editingMessageOrdinal=null}),this.widget.onDismissFocus?.(),this._controller?.animateToBottom(100),"handled";return"ignored"};handleScrollDown=()=>{if(this._selectedUserMessageOrdinal!==null)return this._controller?.scrollDown(1),"handled";return"ignored"};handleScrollUp=()=>{if(this._selectedUserMessageOrdinal!==null)return this._controller?.scrollUp(1),"handled";return"ignored"};handleEditMessage=()=>{if(this._selectedUserMessageOrdinal!==null)return this._selectEditingUserMessageByOrdinal(this._selectedUserMessageOrdinal),"handled";return"ignored"};handleRestoreMessage=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(J===0)return"ignored";let Q=this.widget.items[J];if(Q?.type==="message"&&Q.message.role==="user")this.setState(()=>{this._widgetCache.delete(J),this._isShowingRestoreConfirmation=!0}),G7.instance.addPostFrameCallback(()=>{this.scrollToMessage(J)})}return"handled"}return"ignored"};handleRestoreConfirm=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(J===0)return"ignored";let Q=this.widget.items[J];if(Q?.type==="message"&&Q.message.role==="user")this.widget.onMessageRestoreSubmit?.(J),this._clearSelectedUserMessage(),this.setState(()=>{this._isShowingRestoreConfirmation=!1}),this.widget.onDismissFocus?.()}return"handled"}return"ignored"};handleRestoreCancel=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null)this.setState(()=>{this._widgetCache.delete(J),this._isShowingRestoreConfirmation=!1}),G7.instance.addPostFrameCallback(()=>{this.scrollToMessage(J)})}return"handled"};handleForkMessage=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){let Q=this.widget.items[J];if(Q?.type==="message"&&Q.message.role==="user"){if(J===0)return"ignored";this.widget.onMessageForkSubmit?.(J),this._clearSelectedUserMessage(),this.setState(()=>{}),this.widget.onDismissFocus?.()}}return"handled"}return"ignored"};_signatureFor(J){if(J.type==="message"){let Q=J.message;if(Q.role==="user"){let Z=a7(Q.content),X=Q.content.filter((Y)=>Y.type==="image").length;return`${J.id}|user|${Q.interrupted?1:0}|${X}|${Z}`}else if(Q.role==="assistant"){let Z=a7(Q.content),X=Q.state.type==="complete",Y=Q.content.filter((q)=>q.type==="thinking"),K=Q.content.filter((q)=>q.type==="tool_use");return`${J.id}|assistant|${X?1:0}|${Y.length}|${K.length}|${Z}`}else{let X=Q.content.map((Y)=>Y.type).join(",");return`${J.id}|info|${X}`}}else{let Z=J.toolResult.run.status;return`${J.id}|tool|${Z}|${J.toolUse.id}`}}getThinkingBlockExpanded(J,Q){let Z=`${J}-${Q}`;return this._thinkingBlockStates.get(Z)??fG.instance.allExpanded}toggleThinkingBlock=(J,Q)=>{return(Z)=>{let X=`${J}-${Q}`;this.setState(()=>{this._thinkingBlockStates.set(X,Z),this._widgetCache.delete(J)})}};buildThinkingBlock(J,Q,Z,X){let Y=Z===X.content.length-1,K=X.state?.type==="streaming"&&Y;return new kp({key:new j5(`thinking-${Q}-${Z}`),thinkingBlock:J,expanded:this.getThinkingBlockExpanded(Q,Z),onToggle:this.toggleThinkingBlock(Q,Z),isStreaming:K})}buildAssistantMessageWidget(J,Q,Z,X){let Y=Q.content.map((H,B)=>({block:H,index:B})).filter((H)=>H.block.type==="thinking"),K=Y.some(({block:H})=>Bm1(H.thinking).length>0),q=Q.content.filter((H)=>H.type==="text"),G=[];if(G.push(...Y.map(({block:H,index:B})=>this.buildThinkingBlock(H,Z,B,Q))),K&&q.length>0)G.push(new A0({height:1}));let z=a7(q);if(z.trim())G.push(LF9(J,z,X));let U=eH(J),F=Q.usage!=null&&(Q.usage.inputTokens>0||Q.usage.outputTokens>0);if(U&&F){let B=o6.maybeOf(J)?.colors??Q8.of(J).colorScheme,M=Hq6(Q.usage);G.push(new s6({padding:p0.only({top:1}),child:new t1({text:new O1(M,new S1({color:B.foreground,dim:!0}))})}))}let W;if(G.length===0)W=new A6;else if(G.length===1)W=G[0];else W=new G6({crossAxisAlignment:"stretch",mainAxisSize:"min",children:G});return W}buildThreadItemWidget(J,Q,Z){let X=new j5(`thread-item-${Q.id}`);if(Q.type==="message"){let Y=Q.message;if(Y.role==="user"){if(!this._inFocus)return new _p({message:Y});let K=this.getOrdinalFromUserMessageIndex(Z);if(K===null)return new _p({message:Y});if(this._editingMessageOrdinal===K)return new Em1({initialText:a7(Y.content),onSubmitted:(G)=>{if(G.trim()==="")return;this.widget.onMessageEditSubmit?.(Z,G),this._selectEditingUserMessageByOrdinal(null),this._clearSelectedUserMessage(),this.widget.onDismissFocus?.(),this.controller.animateToBottom(100)}});if(this._selectedUserMessageOrdinal===K)return new $m1({message:Y,isFirstMessage:Z>0,isShowingRestoreConfirmation:this._isShowingRestoreConfirmation,onRestoreConfirm:()=>{this.handleRestoreConfirm()},onRestoreCancel:()=>{this.handleRestoreCancel()}});else return new _p({message:Y})}else if(Y.role==="assistant"){let K=this.buildAssistantMessageWidget(J,Y,Z,Q.id);return new A6({key:X,child:K})}else{let K=Y,q=[];for(let G of K.content)if(G.type==="manual_bash_invocation")q.push(wF9(J,G));else if(G.type==="summary"&&G.summary.type==="message")q.push(AF9(J,G));if(q.length===0)return new A6;if(q.length===1)return q[0];return new G6({crossAxisAlignment:"stretch",children:q})}}else{let Y=new ER({toolUse:Q.toolUse,toolRun:Q.toolResult.run,subagentTools:this.widget.subagentToolsByParentID[Q.toolUse.id],thread:this.widget.thread});return new A6({key:X,child:Y})}return new A6}initState(){if(super.initState(),this._controller=this.widget.controller||new KN,this._globalToggleListener=()=>{this.setState(()=>{this._thinkingBlockStates.clear(),this._widgetCache.clear()})},fG.instance.addListener(this._globalToggleListener),this.widget.focusNode)this._focusListener=()=>{G7.instance.addPostFrameCallback(()=>{if(!this._inFocus){let J=this.getLatestUserMessageOrdinal();if(J!==null)this._selectUserMessageByOrdinal(J)}this.setState(()=>{this._inFocus=this.widget.focusNode.hasFocus})})},this.widget.focusNode.addListener(this._focusListener),this._inFocus=this.widget.focusNode.hasFocus;if(this.widget.items.length>0)G7.instance.requestFrame()}didUpdateWidget(J){if(super.didUpdateWidget(J),J.items===this.widget.items)return;let Q=Math.min(J.items.length,this.widget.items.length);for(let Z=0;Z<Q;Z++){let X=J.items[Z],Y=this.widget.items[Z];if(X&&Y){if(X.type!==Y.type){this._widgetCache.delete(Z);continue}if(X.type==="toolResult"&&Y.type==="toolResult"){let K=X.toolResult.run,q=Y.toolResult.run;if(K.status!==q.status||"result"in K!=="result"in q||"error"in K!=="error"in q)this._widgetCache.delete(Z)}}}if(this.widget.items.length<J.items.length)this._cleanupOrphanedCacheEntries();this._updateStreamingIndexes();for(let Z of this._streamingIndexes)if(Z>=this.widget.items.length)this._streamingIndexes.delete(Z)}_cleanupOrphanedCacheEntries(){for(let J of this._widgetCache.keys())if(J>=this.widget.items.length)this._widgetCache.delete(J)}_isMessageStreaming(J){if(J.type!=="message")return!1;let Q=J.message;if(Q.role!=="assistant")return!1;if(Q.state.type==="streaming")return!0;return Q.content.at(-1)?.type==="thinking"}_updateStreamingIndexes(){for(let J of this._streamingIndexes)if(J>=this.widget.items.length)this._streamingIndexes.delete(J);for(let J=0;J<this.widget.items.length;J++){let Q=this.widget.items[J];if(!Q)continue;let Z=this._isMessageStreaming(Q);if(Z&&!this._streamingIndexes.has(J))this._streamingIndexes.add(J);else if(!Z&&this._streamingIndexes.has(J))this._streamingIndexes.delete(J)}}_getViewportHeight(){let J=this.context.findRenderObject();if(J&&"size"in J){let Q=J.size;if(typeof Q.height==="number"&&Q.height>0)return this._viewportHeight=Q.height,Q.height}return this._viewportHeight}dispose(){if(this._isDisposed=!0,this._widgetCache.clear(),this._globalToggleListener)fG.instance.removeListener(this._globalToggleListener);if(this._focusListener&&this.widget.focusNode)this.widget.focusNode.removeListener(this._focusListener);if(!this.widget.controller)this._controller?.dispose();this.widget.focusNode?.dispose(),super.dispose()}build(J){let Q=o6.of(J),Z=eH(J);if(this._lastCostDisplayState!==null&&this._lastCostDisplayState!==Z)this._widgetCache.clear();this._lastCostDisplayState=Z;let X=this._getTotalItemCount(J),Y=[];for(let H=0;H<X;H++)if(Y.push(this._buildItemAtIndex(J,H)),H<X-1)Y.push(new A0({height:1}));let K=new bG({controller:this._controller,autofocus:this.widget.autofocus,position:"bottom",child:new G6({key:new j5("message-list-column"),crossAxisAlignment:"start",children:Y})}),G=[new s6({padding:p0.only({left:2,right:this.widget.showScrollbar?3:2,bottom:1}),child:K})];if(this.widget.showScrollbar&&this._controller){let H=new $R({controller:this._controller,getScrollInfo:()=>this._getScrollbarInfo(),thickness:1,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack});G.push(new FX({right:1,top:0,bottom:0,child:new A0({width:1,child:H})}))}let z=new GZ({children:G}),U=new Hp({key:new j5("message-view-selection-area"),child:z,onCopy:this.widget.onCopy}),F=new Map([[Im1,new z2(this.handleNavigateUserMessageUp)],[Pm1,new z2(this.handleNavigateUserMessageDown)],[Tm1,new z2(this.handleEscape)],[CJ1,new z2(this.handleScrollDown)],[SJ1,new z2(this.handleScrollUp)],[Cm1,new z2(this.handleEditMessage)],[Sm1,new z2(this.handleRestoreMessage)],[vm1,new z2(this.handleForkMessage)]]),W=new Map([[g8.key("Tab"),new Im1],[g8.shift("Tab"),new Pm1],[g8.key("Escape"),new Tm1],[g8.key("j"),new CJ1],[g8.key("ArrowDown"),new CJ1],[g8.key("k"),new SJ1],[g8.key("ArrowUp"),new SJ1],[g8.key("e"),new Cm1],[g8.key("r"),new Sm1],[g8.key("f"),new vm1]]);if(this.widget.focusNode)return new d8({focusNode:this.widget.focusNode,child:new WX({actions:F,child:new sU({shortcuts:W,focusNode:this.widget.focusNode,child:U})})});return U}_getTotalItemCount(J){return this.widget.items.length}_buildItemAtIndex(J,Q){let Z=this.widget.items[Q];if(!Z)return new A6;let X=Z.type==="message"&&this._isMessageStreaming(Z),Y=Z.type==="toolResult"&&(Z.toolResult.run.status==="queued"||Z.toolResult.run.status==="in-progress")&&!("result"in Z.toolResult.run)&&!("error"in Z.toolResult.run);if(!X&&!Y){let G=this._signatureFor(Z),z=this._widgetCache.get(Q);if(z&&z.sig===G)return z.widget;let U=this.buildThreadItemWidget(J,Z,Q);return this._widgetCache.set(Q,{sig:G,widget:U}),U}return this.buildThreadItemWidget(J,Z,Q)}onNewMessage(){if(this._isDisposed)return;this.widget.onNewMessage?.()}scrollToTop(){if(this._isDisposed||!this._controller)return;this._controller.scrollToTop()}scrollToMessage(J,{animated:Q=!1,offset:Z=0,edge:X="top",duration:Y}={}){if(this._isDisposed||!this._controller)return!1;let K=this._getMessageRelativeOffset(J,X);if(K===null)return!1;let q=K-Z;if(Q)this._controller.animateTo(q,Y);else this._controller.jumpTo(q);return!0}_getColumnElement(){let J=this.context.element;if(!J)return null;let Q=new j5("message-list-column"),Z=(X)=>{if(X.widget.key?.equals(Q))return X;for(let Y of X.children){let K=Z(Y);if(K)return K}return null};return Z(J)}_getMessageRelativeOffset(J,Q){let Z=this._getColumnElement();if(!Z)return null;let X=J*2,Y=Z.children[X];if(!Y?.renderObject)return null;let K=Y.renderObject,q=Z.renderObject;if(!q)return null;let G=K.localToGlobal({x:0,y:0}),z=q.localToGlobal({x:0,y:0}),U=0;if(Q==="bottom")U=K.size.height;return G.y+U-z.y}_getScrollbarInfo(){let J=this._controller?.maxScrollExtent??0,Q=this._getViewportHeight(),Z=this._controller?.offset??0,X=J+Q;return{totalContentHeight:Math.max(X,0),viewportHeight:Math.max(Q,1),scrollOffset:Math.max(Z,0)}}}G9();var $U6=[{type:"command",text:'amp -x "What package manager do we use here?"'},{type:"command",text:'amp -x "Run the linter and fix the errors"'},{type:"hint",text:"Use /queue to enqueue messages without interrupting the agent"},{type:"hint",text:"Use Ctrl+G to edit the prompt in your $EDITOR"},{type:"hint",text:"Generate an AGENTS.md file with the /generate-agent-file command"},{type:"hint",text:"Open your thread in the browser with /browser"},{type:"hint",text:"Create a new thread with /new"},{type:"hint",text:"Change the visiblity settings of your thread with /visibility"},{type:"hint",text:"Open the settings with the /settings slash command"},{type:"hint",text:"Reduce the size of the thread with /compact"},{type:"hint",text:"Use Tab/Shift+Tab to navigate to previous messages to edit or restore to a previous state"},{type:"prompt",text:'"Use the oracle to review the code we just wrote."'},{type:"prompt",text:'"Use subagents to update these components to use the new attribute we added."'},{type:"prompt",text:'"Do not write any code yet. Plan first."'},{type:"prompt",text:'"Think hard before you start implementing."'},{type:"prompt",text:`"Use 'psql' to change all blog_posts to have comments"`},{type:"prompt",text:'"Run <build command> and fix all the errors"'},{type:"quote",text:`"We are at the 'introduction of photography' period of programming. Painting by hand just doesn't have the same appeal anymore" - Orta Therox`},{type:"quote",text:'"Programming in the normal way feels like walking. You type out each expression, stepping incrementally toward your goal. When programming with AI, each move is bigger than a step. You lift off the ground." - Mary Rose Cook'},{type:"quote",text:'"Tomorrow all this may change, but right now after daily experience writing code with LLMs I strongly believe the maximum quality of work is reached using the human+LLM equation." - antirez'},{type:"quote",text:`"The magic that's coming now is the most powerful yet. And that means that we're beginning a profound period of exploration and creativity, trying to understand how to make that magic work and to derive new advantages from its power." - Tim O'Reilly`},{type:"quote",text:`"They're applying years of hard-won engineering wisdom to shape and constrain the AI's output. The AI is accelerating their implementation, but their expertise is what keeps the code maintainable." - Addy Osmani`}];class vJ1 extends j6{agentMode;constructor(J={}){super(J.key?{key:J.key}:{});this.agentMode=J.agentMode}build(J){let Z=Q8.of(J).colorScheme,Y=o6.of(J).app,q=T8.of(J).capabilities.animationSupport,G=process.pid%$U6.length,z=$U6[G],U=z.type==="quote"?new S1({color:Z.foreground,dim:!0}):z.type==="hint"?new S1({color:Z.secondary}):new S1({color:z.type==="prompt"?Z.primary:Z.warning}),F=new S1({color:Y.keybind}),W=new S1({color:Y.command}),H=new S1({color:Z.secondary}),B=new S1({color:Z.foreground,dim:!0}),M=[];if(z.type==="hint"){let A=z.text.split(/(\s\/[\w-]+)/g);for(let w of A)if(w.match(/^\s\/[\w-]+$/)){let R=w.trim();M.push(new O1(w.slice(0,w.length-R.length),U)),M.push(new O1(R,W))}else M.push(new O1(w,U))}else M.push(new O1(z.text,U));let V=[new O1("Welcome to Amp",new S1({color:Z.foreground})),new O1(`
6351
+ (Command and output not shown to agent)`,new S1({color:X.foreground,dim:!0,italic:!0})));return new t1({text:new O1("",void 0,U)})}class km1 extends t0{items;subagentToolsByParentID;controller;autofocus;onNewMessage;showScrollbar;onCopy;onMessageEditSubmit;onMessageRestoreSubmit;onMessageForkSubmit;thread;focusNode;onDismissFocus;get userMessageIndices(){let J=[];for(let Q=0;Q<this.items.length;Q++){let Z=this.items[Q];if(Z?.type==="message"&&Z.message.role==="user")J.push(Q)}return J}constructor({key:J,items:Q,subagentToolsByParentID:Z={},controller:X,autofocus:Y=!1,onNewMessage:K,showScrollbar:q=!0,onCopy:G,onMessageEditSubmit:z,onMessageRestoreSubmit:U,onMessageForkSubmit:F,thread:W,focusNode:H,onDismissFocus:B}){super(J?{key:J}:{});this.items=Q,this.subagentToolsByParentID=Z,this.controller=X,this.autofocus=Y,this.onNewMessage=K,this.showScrollbar=q,this.onCopy=G,this.onMessageEditSubmit=z,this.onMessageRestoreSubmit=U,this.onMessageForkSubmit=F,this.thread=W,this.focusNode=H,this.onDismissFocus=B}createState(){return new jU6}}class jU6 extends o0{_controller=null;_isDisposed=!1;_thinkingBlockStates=new Map;_globalToggleListener;_streamingIndexes=new Set;_viewportHeight=25;_widgetCache=new Map;_lastCostDisplayState=null;_selectedUserMessageOrdinal=null;_editingMessageOrdinal=null;_isShowingRestoreConfirmation=!1;_inFocus=!1;_focusListener;get controller(){return this._controller}_navigateUp(J,Q){if(Q<=0)return null;if(J===null)return Q-1;if(J<=0)return 0;return J-1}_navigateDown(J,Q){if(Q<=0)return null;if(J===null)return null;if(J>=Q-1)return null;return J+1}_ordinalToIndex(J,Q){if(Q===null)return null;if(Q<0||Q>=J.length)return null;return J[Q]??null}_getUserCount(){return this.widget.userMessageIndices.length}_clearSelectedUserMessage(){let J=this._selectedUserMessageOrdinal,Q=J!==null?this.getUserMessageIndexFromOrdinal(J):null;this.setState(()=>{if(Q!=null)this._widgetCache.delete(Q);this._selectedUserMessageOrdinal=null})}_selectUserMessageByOrdinal(J){let Q=this._selectedUserMessageOrdinal,Z=J,X=Q!==null?this.getUserMessageIndexFromOrdinal(Q):null,Y=this.getUserMessageIndexFromOrdinal(Z);if(X!==null)this._widgetCache.delete(X);if(Y!==null)this._widgetCache.delete(Y);if(this.setState(()=>{this._selectedUserMessageOrdinal=Z}),Y!==null)G7.instance.addPostFrameCallback(()=>{this.scrollToMessage(Y,{animated:!0,offset:0,edge:"top",duration:200})})}_selectEditingUserMessageByOrdinal(J){let Q=this._editingMessageOrdinal,Z=J,X=Q!==null?this.getUserMessageIndexFromOrdinal(Q):null,Y=Z!==null?this.getUserMessageIndexFromOrdinal(Z):null;if(X!==null)this._widgetCache.delete(X);if(Y!==null)this._widgetCache.delete(Y);this.setState(()=>{this._editingMessageOrdinal=Z})}getUserMessageIndexFromOrdinal(J){return this.widget.userMessageIndices[J]??null}getOrdinalFromUserMessageIndex(J){let Z=this.widget.userMessageIndices.indexOf(J);return Z>=0?Z:null}getLatestUserMessageOrdinal(){let J=this.widget.userMessageIndices;return J.length>0?J.length-1:null}navigateToUserMessage(J){let Q=this._getUserCount(),Z=J==="up"?this._navigateUp(this._selectedUserMessageOrdinal,Q):this._navigateDown(this._selectedUserMessageOrdinal,Q);if(Z===null&&J==="down"){this._controller?.animateToBottom(100),this._clearSelectedUserMessage(),this.widget.onDismissFocus?.();return}if(Z!==null)this._selectUserMessageByOrdinal(Z)}handleNavigateUserMessageUp=()=>{if(this._editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("up"),"handled"};handleNavigateUserMessageDown=()=>{if(this._editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("down"),"handled"};handleEscape=()=>{if(this._editingMessageOrdinal!==null)return this.setState(()=>{let J=this._ordinalToIndex(this.widget.userMessageIndices,this._editingMessageOrdinal);if(J!=null)this._widgetCache.delete(J);this._editingMessageOrdinal=null}),"handled";else if(this._selectedUserMessageOrdinal!==null)return this._clearSelectedUserMessage(),this.setState(()=>{this._editingMessageOrdinal=null}),this.widget.onDismissFocus?.(),this._controller?.animateToBottom(100),"handled";return"ignored"};handleScrollDown=()=>{if(this._selectedUserMessageOrdinal!==null)return this._controller?.scrollDown(1),"handled";return"ignored"};handleScrollUp=()=>{if(this._selectedUserMessageOrdinal!==null)return this._controller?.scrollUp(1),"handled";return"ignored"};handleEditMessage=()=>{if(this._selectedUserMessageOrdinal!==null)return this._selectEditingUserMessageByOrdinal(this._selectedUserMessageOrdinal),"handled";return"ignored"};handleRestoreMessage=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(J===0)return"ignored";let Q=this.widget.items[J];if(Q?.type==="message"&&Q.message.role==="user")this.setState(()=>{this._widgetCache.delete(J),this._isShowingRestoreConfirmation=!0}),G7.instance.addPostFrameCallback(()=>{this.scrollToMessage(J)})}return"handled"}return"ignored"};handleRestoreConfirm=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(J===0)return"ignored";let Q=this.widget.items[J];if(Q?.type==="message"&&Q.message.role==="user")this.widget.onMessageRestoreSubmit?.(Q.message),this._clearSelectedUserMessage(),this.setState(()=>{this._isShowingRestoreConfirmation=!1}),this.widget.onDismissFocus?.()}return"handled"}return"ignored"};handleRestoreCancel=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null)this.setState(()=>{this._widgetCache.delete(J),this._isShowingRestoreConfirmation=!1}),G7.instance.addPostFrameCallback(()=>{this.scrollToMessage(J)})}return"handled"};handleForkMessage=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){let Q=this.widget.items[J];if(Q?.type==="message"&&Q.message.role==="user"){if(J===0)return"ignored";this.widget.onMessageForkSubmit?.(Q.message),this._clearSelectedUserMessage(),this.setState(()=>{}),this.widget.onDismissFocus?.()}}return"handled"}return"ignored"};_signatureFor(J){if(J.type==="message"){let Q=J.message;if(Q.role==="user"){let Z=a7(Q.content),X=Q.content.filter((Y)=>Y.type==="image").length;return`${J.id}|user|${Q.interrupted?1:0}|${X}|${Z}`}else if(Q.role==="assistant"){let Z=a7(Q.content),X=Q.state.type==="complete",Y=Q.content.filter((q)=>q.type==="thinking"),K=Q.content.filter((q)=>q.type==="tool_use");return`${J.id}|assistant|${X?1:0}|${Y.length}|${K.length}|${Z}`}else{let X=Q.content.map((Y)=>Y.type).join(",");return`${J.id}|info|${X}`}}else{let Z=J.toolResult.run.status;return`${J.id}|tool|${Z}|${J.toolUse.id}`}}getThinkingBlockExpanded(J,Q){let Z=`${J}-${Q}`;return this._thinkingBlockStates.get(Z)??fG.instance.allExpanded}toggleThinkingBlock=(J,Q)=>{return(Z)=>{let X=`${J}-${Q}`;this.setState(()=>{this._thinkingBlockStates.set(X,Z),this._widgetCache.delete(J)})}};buildThinkingBlock(J,Q,Z,X){let Y=Z===X.content.length-1,K=X.state?.type==="streaming"&&Y;return new kp({key:new j5(`thinking-${Q}-${Z}`),thinkingBlock:J,expanded:this.getThinkingBlockExpanded(Q,Z),onToggle:this.toggleThinkingBlock(Q,Z),isStreaming:K})}buildAssistantMessageWidget(J,Q,Z,X){let Y=Q.content.map((H,B)=>({block:H,index:B})).filter((H)=>H.block.type==="thinking"),K=Y.some(({block:H})=>Bm1(H.thinking).length>0),q=Q.content.filter((H)=>H.type==="text"),G=[];if(G.push(...Y.map(({block:H,index:B})=>this.buildThinkingBlock(H,Z,B,Q))),K&&q.length>0)G.push(new A0({height:1}));let z=a7(q);if(z.trim())G.push(LF9(J,z,X));let U=eH(J),F=Q.usage!=null&&(Q.usage.inputTokens>0||Q.usage.outputTokens>0);if(U&&F){let B=o6.maybeOf(J)?.colors??Q8.of(J).colorScheme,M=Hq6(Q.usage);G.push(new s6({padding:p0.only({top:1}),child:new t1({text:new O1(M,new S1({color:B.foreground,dim:!0}))})}))}let W;if(G.length===0)W=new A6;else if(G.length===1)W=G[0];else W=new G6({crossAxisAlignment:"stretch",mainAxisSize:"min",children:G});return W}buildThreadItemWidget(J,Q,Z){let X=new j5(`thread-item-${Q.id}`);if(Q.type==="message"){let Y=Q.message;if(Y.role==="user"){if(!this._inFocus)return new _p({message:Y});let K=this.getOrdinalFromUserMessageIndex(Z);if(K===null)return new _p({message:Y});if(this._editingMessageOrdinal===K)return new Em1({initialText:a7(Y.content),onSubmitted:(G)=>{if(G.trim()==="")return;this.widget.onMessageEditSubmit?.(Y,G),this._selectEditingUserMessageByOrdinal(null),this._clearSelectedUserMessage(),this.widget.onDismissFocus?.(),this.controller.animateToBottom(100)}});if(this._selectedUserMessageOrdinal===K)return new $m1({message:Y,isFirstMessage:Z>0,isShowingRestoreConfirmation:this._isShowingRestoreConfirmation,onRestoreConfirm:()=>{this.handleRestoreConfirm()},onRestoreCancel:()=>{this.handleRestoreCancel()}});else return new _p({message:Y})}else if(Y.role==="assistant"){let K=this.buildAssistantMessageWidget(J,Y,Z,Q.id);return new A6({key:X,child:K})}else{let K=Y,q=[];for(let G of K.content)if(G.type==="manual_bash_invocation")q.push(wF9(J,G));else if(G.type==="summary"&&G.summary.type==="message")q.push(AF9(J,G));if(q.length===0)return new A6;if(q.length===1)return q[0];return new G6({crossAxisAlignment:"stretch",children:q})}}else{let Y=new ER({toolUse:Q.toolUse,toolRun:Q.toolResult.run,subagentTools:this.widget.subagentToolsByParentID[Q.toolUse.id],thread:this.widget.thread});return new A6({key:X,child:Y})}return new A6}initState(){if(super.initState(),this._controller=this.widget.controller||new KN,this._globalToggleListener=()=>{this.setState(()=>{this._thinkingBlockStates.clear(),this._widgetCache.clear()})},fG.instance.addListener(this._globalToggleListener),this.widget.focusNode)this._focusListener=()=>{G7.instance.addPostFrameCallback(()=>{if(!this._inFocus){let J=this.getLatestUserMessageOrdinal();if(J!==null)this._selectUserMessageByOrdinal(J)}this.setState(()=>{this._inFocus=this.widget.focusNode.hasFocus})})},this.widget.focusNode.addListener(this._focusListener),this._inFocus=this.widget.focusNode.hasFocus;if(this.widget.items.length>0)G7.instance.requestFrame()}didUpdateWidget(J){if(super.didUpdateWidget(J),J.items===this.widget.items)return;let Q=Math.min(J.items.length,this.widget.items.length);for(let Z=0;Z<Q;Z++){let X=J.items[Z],Y=this.widget.items[Z];if(X&&Y){if(X.type!==Y.type){this._widgetCache.delete(Z);continue}if(X.type==="toolResult"&&Y.type==="toolResult"){let K=X.toolResult.run,q=Y.toolResult.run;if(K.status!==q.status||"result"in K!=="result"in q||"error"in K!=="error"in q)this._widgetCache.delete(Z)}}}if(this.widget.items.length<J.items.length)this._cleanupOrphanedCacheEntries();this._updateStreamingIndexes();for(let Z of this._streamingIndexes)if(Z>=this.widget.items.length)this._streamingIndexes.delete(Z)}_cleanupOrphanedCacheEntries(){for(let J of this._widgetCache.keys())if(J>=this.widget.items.length)this._widgetCache.delete(J)}_isMessageStreaming(J){if(J.type!=="message")return!1;let Q=J.message;if(Q.role!=="assistant")return!1;if(Q.state.type==="streaming")return!0;return Q.content.at(-1)?.type==="thinking"}_updateStreamingIndexes(){for(let J of this._streamingIndexes)if(J>=this.widget.items.length)this._streamingIndexes.delete(J);for(let J=0;J<this.widget.items.length;J++){let Q=this.widget.items[J];if(!Q)continue;let Z=this._isMessageStreaming(Q);if(Z&&!this._streamingIndexes.has(J))this._streamingIndexes.add(J);else if(!Z&&this._streamingIndexes.has(J))this._streamingIndexes.delete(J)}}_getViewportHeight(){let J=this.context.findRenderObject();if(J&&"size"in J){let Q=J.size;if(typeof Q.height==="number"&&Q.height>0)return this._viewportHeight=Q.height,Q.height}return this._viewportHeight}dispose(){if(this._isDisposed=!0,this._widgetCache.clear(),this._globalToggleListener)fG.instance.removeListener(this._globalToggleListener);if(this._focusListener&&this.widget.focusNode)this.widget.focusNode.removeListener(this._focusListener);if(!this.widget.controller)this._controller?.dispose();this.widget.focusNode?.dispose(),super.dispose()}build(J){let Q=o6.of(J),Z=eH(J);if(this._lastCostDisplayState!==null&&this._lastCostDisplayState!==Z)this._widgetCache.clear();this._lastCostDisplayState=Z;let X=this._getTotalItemCount(J),Y=[];for(let H=0;H<X;H++)if(Y.push(this._buildItemAtIndex(J,H)),H<X-1)Y.push(new A0({height:1}));let K=new bG({controller:this._controller,autofocus:this.widget.autofocus,position:"bottom",child:new G6({key:new j5("message-list-column"),crossAxisAlignment:"start",children:Y})}),G=[new s6({padding:p0.only({left:2,right:this.widget.showScrollbar?3:2,bottom:1}),child:K})];if(this.widget.showScrollbar&&this._controller){let H=new $R({controller:this._controller,getScrollInfo:()=>this._getScrollbarInfo(),thickness:1,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack});G.push(new FX({right:1,top:0,bottom:0,child:new A0({width:1,child:H})}))}let z=new GZ({children:G}),U=new Hp({key:new j5("message-view-selection-area"),child:z,onCopy:this.widget.onCopy}),F=new Map([[Im1,new z2(this.handleNavigateUserMessageUp)],[Pm1,new z2(this.handleNavigateUserMessageDown)],[Tm1,new z2(this.handleEscape)],[CJ1,new z2(this.handleScrollDown)],[SJ1,new z2(this.handleScrollUp)],[Cm1,new z2(this.handleEditMessage)],[Sm1,new z2(this.handleRestoreMessage)],[vm1,new z2(this.handleForkMessage)]]),W=new Map([[g8.key("Tab"),new Im1],[g8.shift("Tab"),new Pm1],[g8.key("Escape"),new Tm1],[g8.key("j"),new CJ1],[g8.key("ArrowDown"),new CJ1],[g8.key("k"),new SJ1],[g8.key("ArrowUp"),new SJ1],[g8.key("e"),new Cm1],[g8.key("r"),new Sm1],[g8.key("f"),new vm1]]);if(this.widget.focusNode)return new d8({focusNode:this.widget.focusNode,child:new WX({actions:F,child:new sU({shortcuts:W,focusNode:this.widget.focusNode,child:U})})});return U}_getTotalItemCount(J){return this.widget.items.length}_buildItemAtIndex(J,Q){let Z=this.widget.items[Q];if(!Z)return new A6;let X=Z.type==="message"&&this._isMessageStreaming(Z),Y=Z.type==="toolResult"&&(Z.toolResult.run.status==="queued"||Z.toolResult.run.status==="in-progress")&&!("result"in Z.toolResult.run)&&!("error"in Z.toolResult.run);if(!X&&!Y){let G=this._signatureFor(Z),z=this._widgetCache.get(Q);if(z&&z.sig===G)return z.widget;let U=this.buildThreadItemWidget(J,Z,Q);return this._widgetCache.set(Q,{sig:G,widget:U}),U}return this.buildThreadItemWidget(J,Z,Q)}onNewMessage(){if(this._isDisposed)return;this.widget.onNewMessage?.()}scrollToTop(){if(this._isDisposed||!this._controller)return;this._controller.scrollToTop()}scrollToMessage(J,{animated:Q=!1,offset:Z=0,edge:X="top",duration:Y}={}){if(this._isDisposed||!this._controller)return!1;let K=this._getMessageRelativeOffset(J,X);if(K===null)return!1;let q=K-Z;if(Q)this._controller.animateTo(q,Y);else this._controller.jumpTo(q);return!0}_getColumnElement(){let J=this.context.element;if(!J)return null;let Q=new j5("message-list-column"),Z=(X)=>{if(X.widget.key?.equals(Q))return X;for(let Y of X.children){let K=Z(Y);if(K)return K}return null};return Z(J)}_getMessageRelativeOffset(J,Q){let Z=this._getColumnElement();if(!Z)return null;let X=J*2,Y=Z.children[X];if(!Y?.renderObject)return null;let K=Y.renderObject,q=Z.renderObject;if(!q)return null;let G=K.localToGlobal({x:0,y:0}),z=q.localToGlobal({x:0,y:0}),U=0;if(Q==="bottom")U=K.size.height;return G.y+U-z.y}_getScrollbarInfo(){let J=this._controller?.maxScrollExtent??0,Q=this._getViewportHeight(),Z=this._controller?.offset??0,X=J+Q;return{totalContentHeight:Math.max(X,0),viewportHeight:Math.max(Q,1),scrollOffset:Math.max(Z,0)}}}G9();var $U6=[{type:"command",text:'amp -x "What package manager do we use here?"'},{type:"command",text:'amp -x "Run the linter and fix the errors"'},{type:"hint",text:"Use /queue to enqueue messages without interrupting the agent"},{type:"hint",text:"Use Ctrl+G to edit the prompt in your $EDITOR"},{type:"hint",text:"Generate an AGENTS.md file with the /generate-agent-file command"},{type:"hint",text:"Open your thread in the browser with /browser"},{type:"hint",text:"Create a new thread with /new"},{type:"hint",text:"Change the visiblity settings of your thread with /visibility"},{type:"hint",text:"Open the settings with the /settings slash command"},{type:"hint",text:"Reduce the size of the thread with /compact"},{type:"hint",text:"Use Tab/Shift+Tab to navigate to previous messages to edit or restore to a previous state"},{type:"prompt",text:'"Use the oracle to review the code we just wrote."'},{type:"prompt",text:'"Use subagents to update these components to use the new attribute we added."'},{type:"prompt",text:'"Do not write any code yet. Plan first."'},{type:"prompt",text:'"Think hard before you start implementing."'},{type:"prompt",text:`"Use 'psql' to change all blog_posts to have comments"`},{type:"prompt",text:'"Run <build command> and fix all the errors"'},{type:"quote",text:`"We are at the 'introduction of photography' period of programming. Painting by hand just doesn't have the same appeal anymore" - Orta Therox`},{type:"quote",text:'"Programming in the normal way feels like walking. You type out each expression, stepping incrementally toward your goal. When programming with AI, each move is bigger than a step. You lift off the ground." - Mary Rose Cook'},{type:"quote",text:'"Tomorrow all this may change, but right now after daily experience writing code with LLMs I strongly believe the maximum quality of work is reached using the human+LLM equation." - antirez'},{type:"quote",text:`"The magic that's coming now is the most powerful yet. And that means that we're beginning a profound period of exploration and creativity, trying to understand how to make that magic work and to derive new advantages from its power." - Tim O'Reilly`},{type:"quote",text:`"They're applying years of hard-won engineering wisdom to shape and constrain the AI's output. The AI is accelerating their implementation, but their expertise is what keeps the code maintainable." - Addy Osmani`}];class vJ1 extends j6{agentMode;constructor(J={}){super(J.key?{key:J.key}:{});this.agentMode=J.agentMode}build(J){let Z=Q8.of(J).colorScheme,Y=o6.of(J).app,q=T8.of(J).capabilities.animationSupport,G=process.pid%$U6.length,z=$U6[G],U=z.type==="quote"?new S1({color:Z.foreground,dim:!0}):z.type==="hint"?new S1({color:Z.secondary}):new S1({color:z.type==="prompt"?Z.primary:Z.warning}),F=new S1({color:Y.keybind}),W=new S1({color:Y.command}),H=new S1({color:Z.secondary}),B=new S1({color:Z.foreground,dim:!0}),M=[];if(z.type==="hint"){let A=z.text.split(/(\s\/[\w-]+)/g);for(let w of A)if(w.match(/^\s\/[\w-]+$/)){let R=w.trim();M.push(new O1(w.slice(0,w.length-R.length),U)),M.push(new O1(R,W))}else M.push(new O1(w,U))}else M.push(new O1(z.text,U));let V=[new O1("Welcome to Amp",new S1({color:Z.foreground})),new O1(`
6352
6352
 
6353
6353
 
6354
6354
  `),new O1("Type ",B),new O1("/",W),new O1(` to use slash commands
@@ -6408,7 +6408,7 @@ ${this.stateNotifier.value.getDownloadPath()}.`,new S1({color:Q.colorScheme.fore
6408
6408
  https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_disk`,new S1({color:Q.colorScheme.foreground}))}),new A0({height:1}),new t1({text:new O1(`Finally restart your JetBrains IDE${!uK()&&" and Amp"}.`,new S1({color:Q.colorScheme.foreground}))}),new A0({height:1}),new t1({text:new O1("Press any key to exit...",new S1({color:Q.colorScheme.foreground,dim:!0}))})]})})});return new d8({autofocus:!0,onKey:(U)=>{return this.widget.onExit(),"handled"},child:z})}return new A6({decoration:new E9(Q.colorScheme.background),child:new s6({padding:p0.all(2),child:new t1({text:new O1("Discovering JetBrains IDEs...",new S1({color:Q.colorScheme.foreground}))})})})}}function EW9(J){let Q=J.reduce((Z,X)=>{return(Z[X.name]??=[]).push(X),Z},{});return Object.entries(Q).map(([Z,X])=>({name:Z,versions:X.map((Y)=>Y.version).sort()}))}function IW9(J){if(J.length<=1)return"";if(J.length>=3)return` (${J[0]}-${J.at(-1)})`;return` (${J.join(", ")})`}G9();j9();class Ku1 extends t0{color;trigger;trail;fps;speed;leftOffset;constructor({key:J,color:Q,trigger:Z,trail:X=5,fps:Y=60,speed:K=1,leftOffset:q=0}){super(J?{key:J}:{});this.color=Q,this.trigger=Z,this.trail=X,this.fps=Y,this.speed=K,this.leftOffset=q}createState(){return new DF6}}class DF6 extends o0{progress=0;timer=null;initState(){this.restart()}didUpdateWidget(J){if(J.trigger!==this.widget.trigger)this.restart()}dispose(){this.stop()}restart(){this.stop(),this.progress=-this.widget.trail,this.start()}start(){if(this.timer)return;let J=Math.max(16,Math.round(1000/Math.max(1,this.widget.fps)));this.timer=setInterval(()=>{this.setState(()=>{this.progress+=this.widget.speed})},J)}stop(){if(this.timer)clearInterval(this.timer),this.timer=null}build(J){return new MF6({color:this.widget.color,trail:this.widget.trail,head:this.progress,leftOffset:this.widget.leftOffset},this.widget.key)}}class MF6 extends rH{props;constructor(J,Q){super(Q?{key:Q}:{});this.props=J}createElement(){return new YN(this)}createRenderObject(){return new VF6(this.props.color,this.props.trail,this.props.head,this.props.leftOffset)}updateRenderObject(J){J.update(this.props.color,this.props.trail,this.props.head,this.props.leftOffset)}}class VF6 extends J8{_color;_trail;_head;_leftOffset;constructor(J,Q,Z,X){super();this._color=J;this._trail=Q;this._head=Z;this._leftOffset=X}update(J,Q,Z,X){let Y=!1;if(Q!==this._trail)this._trail=Q,Y=!0;if(this._color=J,this._head=Z,this._leftOffset=X,Y)this.markNeedsLayout();this.markNeedsPaint()}performLayout(){let J=this._lastConstraints,Q=J.constrain(J.biggest.width,1);this.setSize(Q.width,Q.height),super.performLayout()}paint(J,Q=0,Z=0){let X=Math.floor(Q+this.offset.x),Y=Math.floor(Z+this.offset.y),K=Math.floor(this.size.width),q=[1,0.7,0.5,0.35,0.25,0.15];for(let G=0;G<=this._trail&&G<q.length;G++){let z=Math.floor(this._head)-G+this._leftOffset;if(z<this._leftOffset||z>=K)continue;let U=PW9(this._color,q[G]);J.setChar(X+z,Y,"━",{fg:U},1)}super.paint(J,Q,Z)}}function PW9(J,Q){if(J.type==="rgb")return k1.rgb(J.value.r,J.value.g,J.value.b,Q);if(J.type==="index")return k1.index(J.value,Q);return k1.default(Q)}class qu1 extends j6{message;onDismiss;constructor({key:J,message:Q,onDismiss:Z}){super({key:J});this.message=Q,this.onDismiss=Z}build(J){let Z=Q8.of(J).colorScheme,X=LX6(this.message),Y=[{value:"dismiss",label:"Dismiss"}],K=X.type==="error"?Z.destructive:Z.primary,q=new Hp({child:new t1({text:new O1(X.description),selectable:!0})});return new VY({title:X.title,body:q,options:Y,onSelect:(G)=>{this.onDismiss()},borderColor:K,autofocus:!0,showDismissalMessage:!1,enableMouseInteraction:!1})}}G9();class Gu1 extends j6{url;qrCode;constructor({key:J,url:Q,qrCode:Z}){super(J?{key:J}:{});this.url=Q,this.qrCode=Z}build(J){let Z=Q8.of(J).colorScheme,X=T8.of(J),Y=new S1({color:k1.rgb(0,0,0)}),K=new S1({color:Z.foreground}),q=new S1({color:Z.foreground}),G=new S1({color:Z.secondary,bold:!0}),z=X.size.width,U=X.size.height,F=z-4,W=Math.min(U-4,Math.floor(U*0.8)),H=Math.min(60,F),B=new bG({autofocus:!0,child:new s6({padding:p0.only({left:2,right:2}),child:new G6({crossAxisAlignment:"center",children:[new E2({child:new A6({decoration:new E9(k1.rgb(255,255,255)),padding:p0.all(2),child:new t1({text:new O1(this.qrCode,Y),textAlign:"left"})})}),new A0({height:1}),new E2({child:new t1({text:new O1(`Continue at ${this.url}`,K)})}),new A0({height:1})]})})}),M=new E2({child:new t1({text:new O1("",q,[new O1("Press ",q),new O1("Escape",G),new O1(" to close",q)])})}),V=new G6({crossAxisAlignment:"stretch",children:[new I9({child:B}),M]});return new E2({child:new A6({constraints:new I6(H,H,0,W),decoration:new E9(Z.background,v9.all(new z9(Z.primary,1,"rounded"))),child:V})})}}j9();class zu1 extends t0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new NF6}}class NF6 extends o0{build(J){let{queuedMessages:Q,title:Z="Queue"}=this.widget.props;if(!Array.isArray(Q)||Q.length===0)return new A0({width:0,height:0});let X=Q.map((Y)=>this.buildQueueItem(Y));return new A6({child:new s6({padding:p0.symmetric(1,0),child:new G6({crossAxisAlignment:"stretch",children:[new t1({text:new O1(Z,new S1({bold:!0}))}),...X]})})})}buildQueueItem(J){let Z=J.queuedMessage.content.filter((q)=>q.type==="text").map((q)=>q.text).join(" ").trim(),X=Z.split(`
6409
6409
  `)[0],Y=Z.includes(`
6410
6410
  `)?`${X}...`:Z,K=new S1({color:k1.index(8)});return new s6({padding:p0.only({bottom:0}),child:new C8({crossAxisAlignment:"start",children:[new s6({padding:p0.only({right:1}),child:new t1({text:new O1("•",new S1({color:k1.index(8)}))})}),new I9({child:new t1({text:new O1(Y,K)})})]})})}}FF();var TW9=Q1.string(),LF6=Q1.object({id:TW9,title:Q1.string().optional(),messageCount:Q1.number(),updatedAt:Q1.string(),firstSyncAt:Q1.string(),created:Q1.number(),creatorUserID:Q1.string(),meta:Q1.object({visibility:Q1.enum(["private","public","thread_workspace_shared"]),sharedGroupIDs:Q1.array(Q1.string())})});z0();SY();FF();var CW9=Q1.object({id:Q1.string()});function SW9(J){let Z=new Date().getTime()-J.getTime(),X=Math.floor(Z/3600000),Y=Math.floor(X/24),K=Math.floor(Y/7),q=Math.floor(Y/30);if(X<1)return"Just now";if(X<24)return`${X}h ago`;if(Y<7)return`${Y}d ago`;if(K<=4)return`${K}w ago`;return`${q}mo ago`}class nJ1{configService;constructor(J){this.configService=J}async fetchThreadSummaries(J="",Q=0,Z=20){try{let X=await gJ("/api/user",void 0,this.configService);if(!X.ok)return{ok:!1,errorMsg:`Failed to get user info (${X.status})`};let Y;try{Y=CW9.parse(await X.json())}catch(F){return{ok:!1,errorMsg:"Invalid user data format from server"}}let K=new URLSearchParams({createdByUserID:Y.id,limit:String(Z),offset:String(Q*Z)}),q=await gJ(`/api/threads?${K}`,void 0,this.configService);if(!q.ok)return{ok:!1,errorMsg:`Failed to fetch threads (${q.status})`};let G;try{G=Q1.array(LF6).parse(await q.json())}catch(F){return l.error("failed to parse thread data from server",{error:F}),{ok:!1,errorMsg:"Invalid thread data format from server"}}return{ok:!0,threads:G.filter((F)=>F.messageCount>0).filter((F)=>{if(!J.trim())return!0;let W=F.title?.toLowerCase()||"untitled",H=F.id.toLowerCase(),B=J.toLowerCase();return W.includes(B)||H.includes(B)}).slice(0,Z).map((F)=>{let W=F.title||"Untitled",H=new Date(F.updatedAt),B=SW9(H),M=F.id.slice(-8);return{id:F.id,title:W,messageCount:F.messageCount,updatedAt:F.updatedAt,description:{timeAgo:B,title:W,shortThreadID:M}}})}}catch(X){return{ok:!1,errorMsg:X instanceof Error?X.message:"An unexpected error occurred"}}}}j9();class Uu1 extends t0{props;constructor(J){super();this.props=J}createState(){return new AF6(this.props.pageSize,this.props.loadBuffer,this.props.autofocus??!0)}}class AF6 extends o0{pageSize;loadBuffer;autofocus;allThreads=[];isLoading=!1;currentPage=0;hasMoreToLoad=!0;error=null;constructor(J=20,Q=J*2,Z){super();this.pageSize=J;this.loadBuffer=Q;this.autofocus=Z}async initState(){await this.loadThreads()}async loadThreads(){if(this.isLoading||!this.hasMoreToLoad)return;this.isLoading=!0,this.error=null;try{let J=await this.widget.props.threadFetcher.fetchThreadSummaries("",this.currentPage,this.pageSize);if(!this.mounted)return;if(!J.ok){this.error=J.errorMsg,this.hasMoreToLoad=!1,this.setState();return}let Q=J.threads;if(Q.length===0)this.hasMoreToLoad=!1;else{let Z=new Set(this.allThreads.map((Y)=>Y.id)),X=Q.filter((Y)=>!Z.has(Y.id));this.allThreads=[...this.allThreads,...X],this.currentPage++}this.setState()}finally{this.isLoading=!1}}onChange=async(J)=>{if(this.allThreads.length-J<=this.loadBuffer&&this.hasMoreToLoad&&!this.isLoading)await this.loadThreads()};formatThreadDescription(J){let Z=`${String(J.messageCount)} msgs`.padEnd(8),X=J.description.timeAgo.padEnd(9);return`${Z} │ ${X}│ ${J.description.shortThreadID}`}build(J){let Q=(q)=>{if(q.ctrlKey&&q.key==="c"||q.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"};if(this.error)return new d8({autofocus:this.autofocus,onKey:Q,child:new t1({text:new O1(this.error)})});if(this.isLoading&&this.allThreads.length===0)return new d8({autofocus:this.autofocus,onKey:Q,child:new t1({text:new O1("Loading threads...")})});let Z=T8.sizeOf(J);if(this.allThreads.length===0&&!this.isLoading)return new d8({autofocus:this.autofocus,onKey:Q,child:new t1({text:new O1("No threads found.")})});let X=this.allThreads.map((q)=>({value:q.id,label:q.title,description:this.formatThreadDescription(q)})),Y=Math.max(5,Z.height);Y-=6;let K=Math.floor(Math.max(1,Y/2));return new d8({autofocus:this.autofocus,onKey:Q,child:new xp({title:"Select a thread to continue:",options:X,onSelect:(q)=>{this.widget.props.onSelect(q)},onChange:this.onChange,maxVisibleItems:K,autofocus:this.autofocus})})}}y71();var wF6="You have invoked an experimental model. To use this model, you must enable training mode, which will allow all of your threads to be used for model training. Do not accept this if you would prefer your data not be used for training.";var RF6="https://ampcode.com/security#model-training";j9();class Fu1 extends t0{onResponse;constructor({key:J,onResponse:Q}){super({key:J});this.onResponse=Q}createState(){return new OF6}}class OF6 extends o0{initState(){super.initState()}dispose(){super.dispose()}build(J){let Z=Q8.of(J).colorScheme,X="Experimental Model Warning",Y=`${wF6} See ${RF6} for details.`;return new jF6({title:"Experimental Model Warning",body:Y,options:[{value:"reject",label:"Reject"},{value:"accept",label:"Turn on training"}],onSelect:(q)=>{this.widget.onResponse(q==="accept")},borderColor:Z.warning,selectedIndex:0,autofocus:!0,showDismissalMessage:!1,enableMouseInteraction:!1})}}class jF6 extends t0{options;onSelect;title;body;borderColor;selectedIndex;autofocus;showDismissalMessage;enableMouseInteraction;constructor({key:J,options:Q,onSelect:Z,title:X,body:Y,borderColor:K=k1.index(8),selectedIndex:q=0,autofocus:G=!0,showDismissalMessage:z=!0,enableMouseInteraction:U=!0}){super({key:J});this.options=Q,this.onSelect=Z,this.title=X,this.body=Y,this.borderColor=K,this.selectedIndex=q,this.autofocus=G,this.showDismissalMessage=z,this.enableMouseInteraction=U}createState(){return new $F6}}class $F6 extends o0{focusNode=new S9({debugLabel:"TrainingModeSelect"});initState(){super.initState(),this.focusNode.addKeyHandler(this.handleKeyEvent.bind(this))}dispose(){this.focusNode.dispose(),super.dispose()}handleKeyEvent(J){if(J.key==="Escape"&&!J.shiftKey&&!J.ctrlKey&&!J.altKey&&!J.metaKey)return this.widget.onSelect("reject"),"handled";return"ignored"}build(J){let Q=new VY({title:this.widget.title,body:this.widget.body,options:this.widget.options,onSelect:this.widget.onSelect,borderColor:this.widget.borderColor,selectedIndex:this.widget.selectedIndex,autofocus:this.widget.autofocus,showDismissalMessage:this.widget.showDismissalMessage,enableMouseInteraction:this.widget.enableMouseInteraction});return new d8({focusNode:this.focusNode,child:Q,autofocus:this.widget.autofocus})}}class Wu1{detect(J,Q){if(!J||Q<1)return null;let Z=$2(J);if(Q>Z.length)return null;let X=this.findWordStart(Z,Q);if(X>=Z.length||Z[X]!=="@")return null;let Y=Z.slice(X+1,Q).join("");if(Y.includes(" ")||Y.includes("\t")||Y.includes(`
6411
- `))return null;return{start:X,end:Q,query:Y,trigger:"@"}}findWordStart(J,Q){let Z=Q;for(let X=Q-1;X>=0;X--){let Y=J[X];if(!Y||/[\s([{]/.test(Y)){Z=X+1;break}if(X===0)Z=0}return Z}}class Hu1{detect(J,Q){if(!J||Q<1)return null;let Z=$2(J);if(Q>Z.length)return null;if(Z[0]!=="/")return null;let X=Z.slice(1,Q).join("");return{start:0,end:Q,query:X,trigger:"/"}}}class EF6{triggers;constructor(J){this.triggers=J}detect(J,Q){for(let Z of this.triggers){let X=Z.detect(J,Q);if(X)return X}return null}}function Bu1(){return new EF6([new Wu1,new Hu1])}function IF6(J,Q){switch(J){case"update-available":return[new O1("A newer Amp is available. Run ",new S1({color:Q.foreground,dim:!0})),new O1("amp update",new S1({color:Q.warning}))];case"updated":return null;case"updated-with-warning":return[new O1("Update complete, run ",new S1({color:Q.foreground,dim:!0})),new O1("amp update",new S1({color:Q.warning})),new O1(" to see warnings",new S1({color:Q.foreground,dim:!0}))];case"update-error":return[new O1("Update failed, run ",new S1({color:Q.foreground,dim:!0})),new O1("amp update",new S1({color:Q.warning})),new O1(" to see warnings",new S1({color:Q.foreground,dim:!0}))];case"hidden":return null}}function xW9(J){return[{match:(Q)=>Q.startsWith("$$"),display:"$$",style:new S1({color:J.app.shellModeHidden}),spacing:1,concealPrefix:!0},{match:(Q)=>Q.startsWith("$")&&!Q.startsWith("$$"),display:"$",style:new S1({color:J.app.shellMode}),spacing:1,concealPrefix:!0}]}class xF6 extends t0{dependencies;constructor(J){super();this.dependencies=J}createState(){return new bF6}}class bF6 extends o0{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;connectedClientsStatus=null;randomAd=null;adSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();isConfirmingExit=!1;isConfirmingClearInput=!1;copyMessageTimer=null;isShowingHelp=!1;isShowingConsoleOverlay=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingCostBreakdownOverlay=!1;isShowingQRCodeOverlay=!1;confirmationOverlayContent="";qrCodeOverlayData=null;exitConfirmTimeout=null;clearInputConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];dismissedEphemeralErrorKey=null;currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;currentProgressBarState="off";progressReportTimer=null;showingSelectionCopiedHint=!1;isShowingThreadPicker=!1;agentModePulseSeq=0;messageViewFocusNode=new S9({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new S9({debugLabel:"AutocompleteFocus"});isTextfieldAndAutocompleteFocused=!1;submitDisabledHint=null;submitDisabledHintTimer=null;isShowingTrainingModeDialog=!1;pendingTrainingMode=null;showingCannotToggleMessage=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;isShowingEnableTrainingModal=!1;adActionModal=null;agentModeSubscription=null;currentAgentMode="smart";hasToggledAgentMode=!1;inMemoryAgentModeOverride=null;cachedVisibleModes=LB();freeTierStatus=void 0;updateState="hidden";updateServiceSubscription=null;getEffectiveAgentMode(){return this.inMemoryAgentModeOverride??this.currentAgentMode}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(Boolean(J.viewState.inferenceState==="running"))return!0;let Z=J.items.filter((K)=>K.type==="toolResult").filter((K)=>K.toolResult.run.status==="in-progress"||K.toolResult.run.status==="queued"),X=J.subagentActiveTools.filter((K)=>K.toolRun.status==="in-progress"||K.toolRun.status==="queued");return[...Z,...X].length>0}isSummarizing(J){return J.state==="active"&&J.summaryState!=="idle"}parseShellModeInput(J){if(J.startsWith("$$")){let Q=J.slice(2).trim();return Q?{cmd:Q,hidden:!0}:null}if(J.startsWith("$")){let Q=J.slice(1).trim();return Q?{cmd:Q,hidden:!1}:null}return null}isSlashCommand(J){if(!J.startsWith("/"))return!1;if((J.split(" ")[0]?.slice(1)||"").includes("/"))return!1;return!0}showSubmitDisabledHint(J){if(this.submitDisabledHintTimer)clearTimeout(this.submitDisabledHintTimer);this.setState(()=>{this.submitDisabledHint=J}),this.submitDisabledHintTimer=setTimeout(()=>{this.setState(()=>{this.submitDisabledHint=null}),this.submitDisabledHintTimer=null},3000)}getUIHint(){let J=this.themeColors?.colorScheme;if(!J)return null;let Q=this.themeApp;if(!Q)return null;if(this.submitDisabledHint)return new O1(this.submitDisabledHint,new S1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new O1("",void 0,[new O1("Ctrl+C",new S1({color:Q.keybind})),new O1(" again to exit",new S1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new O1("",void 0,[new O1("Esc",new S1({color:Q.keybind})),new O1(" again to clear input",new S1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new O1("",void 0,[new O1("Escape",new S1({color:Q.keybind})),new O1(" to close help",new S1({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let X=this.getEffectiveAgentMode(),Y=Au1(X);return new O1("",void 0,[new O1("Images aren't supported in ",new S1({color:J.warning,dim:!1})),new O1(X,new S1({color:Y})),new O1(" mode.",new S1({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0)return new O1("",void 0,[new O1("Esc",new S1({color:Q.keybind})),new O1(" to cancel",new S1({color:J.foreground,dim:!0}))]);if(this.showingSelectionCopiedHint)return new O1("Selection copied to clipboard",new S1({color:J.foreground,dim:!0}));if(this.showingCannotToggleMessage)return new O1(this.showingCannotToggleMessage,new S1({color:J.warning,dim:!1}));let Z=IF6(this.updateState,J);if(Z)return new O1("",void 0,Z);return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Q,worker:Z}=this.widget.dependencies;if(!Q.mainThread?.id)return;try{this.cancelBashInvocations(),await Z.cancel(),await Z.handle({type:"thread:truncate",fromIndex:J}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(Y){l.error("Failed to edit message:",Y)}};forkMessage=async(J)=>{let{threadState:Q,workerDeps:Z,threadSyncService:X,switchToThread:Y}=this.widget.dependencies,K=Q.mainThread?.id;if(!K)return;if(J<=0)return;try{let q=await UJ.getOrCreateForThread(Z,K),G=await yr(q,X,J),z=await Y(G);lV(z),this.widget.dependencies.worker=z,this.widget.dependencies.threadID=z.thread.id;let U=z.thread.agentMode??null;this.setState(()=>{this.inMemoryAgentModeOverride=U})}catch(q){l.error("Failed to fork thread:",q),this.showErrorMessage(`Failed to fork thread: ${q}`)}};handleMessageEditSubmit=async(J,Q)=>{let{threadState:Z,worker:X}=this.widget.dependencies,Y=Z.mainThread;if(!Y)return;try{this.cancelBashInvocations(),await X.cancel(),this.widget.dependencies.history.add(Q);let K=[{type:"text",text:Q}];if(this.imageAttachments.length>0)K.push(...this.imageAttachments);let q={content:K,agentMode:Y.agentMode},G=J===0;if(Y.agentMode&&!G&&q.agentMode!==Y.agentMode){l.error(`Cannot edit message: This thread uses ${Y.agentMode} mode. To change mode, create a new thread.`);return}await X.handle({type:"user:message",message:q,index:J}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(K){l.error("Failed to edit message:",K)}};textController=new CC;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new KN);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.id;if(!Q)return;this.getMessageScrollController(Q).scrollToBottom()}findElementByKey(J){return this.searchElementTreeByKey(this.context.element,J)}searchElementTreeByKey(J,Q){if(!J)return null;if(J?.widget?.key?.value===Q)return J;if(J?.child){let X=this.searchElementTreeByKey(J.child,Q);if(X)return X}if(J?.children)for(let X of J.children){let Y=this.searchElementTreeByKey(X,Q);if(Y)return Y}return null}clearActiveSelection(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller?.hasSelection)return Q.controller.clearSelection(),this.setState(()=>{}),!0}return!1}setupSelectionListener(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller&&!this.selectionListener)this.selectionListener=()=>{this.setState(()=>{})},Q.controller.addListener(this.selectionListener),Q.controller.onSelectionCopied=()=>{if(this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}}updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.title;if(Q!==this.currentTitle){this.currentTitle=Q;let Z=process.cwd().replace(process.env.HOME||"","~"),X=Q?`amp - ${Q} - ${Z}`:"";process.stdout.write(ff1(X))}}_handleTextCopy(J){if(J&&J.length>0){if(this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}textFieldKey=new j5("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;connectedClientsStatusSubscription=null;commands=null;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text,Q=J.startsWith("$$")?"hidden":J.startsWith("$")?"normal":void 0;if(Q!==this.currentShellModeStatus)this.currentShellModeStatus=Q,this.setState(()=>{})};getCommands(){if(!this.commands)this.commands=new Cf1(this.widget.dependencies.commandRegistry,this.widget.dependencies.configService);return this.commands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new fm1(this.getCommands(),this.widget.dependencies.fuzzyServer,new nJ1(this.widget.dependencies.configService),this.widget.dependencies.configService);return this.completionBuilder}navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.widget.dependencies.ideClient.sendStatus({enabled:!1}),this.setState(()=>{this.isShowingIdePicker=!1})};handleIdeSelection=async(J,Q)=>{try{await this.connectToSelectedIde(J,Q)}catch(Z){let X=Z instanceof Error?Z.message:String(Z);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.setState(()=>{this.isShowingIdePicker=!1})};async connectToSelectedIde(J,Q){await this.widget.dependencies.ideClient.start(J,!0,Q)}removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Q)=>Q.id!==J)})};invokeBashCommand=(J,{hidden:Q})=>{let Z=Date.now(),X=`bash-${Z}-${Math.random().toString(36).substring(7)}`,Y={cmd:J},K=new AbortController;this.widget.dependencies.worker.invokeBashTool(Y,K.signal,Q).subscribe({next:(q)=>{this.setState(()=>{if(this.bashInvocations.find((z)=>z.id===X))this.bashInvocations=this.bashInvocations.map((z)=>z.id===X?{...z,toolRun:q}:z);else{let z={id:X,args:Y,toolRun:q,startTime:Z,abortController:K,hidden:Q};this.bashInvocations=[...this.bashInvocations,z]}})},error:()=>this.removeBashInvocation(X),complete:()=>this.removeBashInvocation(X)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Q)=>Q.toolRun.status==="in-progress");if(J)J.abortController.abort()};toggleAgentMode=()=>{if((hK()||this.widget.dependencies.worker).thread.messages.length>0)return;if(this.freeTierStatus?.canUseAmpFree){let X=this.inMemoryAgentModeOverride??this.currentAgentMode,Y=vd(X,this.cachedVisibleModes);if(Y!==X)this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=Y,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1});return}let Q=this.inMemoryAgentModeOverride??this.currentAgentMode,Z=vd(Q,this.cachedVisibleModes);if(Z===Q)return;if(this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=Z,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1,this.isShowingEnableTrainingModal=!1}),Z==="free")this.checkAndShowFreeModeModal()};checkAndShowFreeModeModal=()=>{if(this.freeTierStatus?.canUseAmpFree)return;if(this.freeTierStatus&&!this.freeTierStatus.eligible){this.setState(()=>{this.showingCannotToggleMessage="Amp Free is unavailable. Switch to another mode."}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}else if(this.freeTierStatus?.trainingMode&&!this.freeTierStatus.trainingMode.canToggle){let J=this.freeTierStatus.trainingMode.cannotToggleReason||"Training mode cannot be toggled at this time.";this.setState(()=>{this.showingCannotToggleMessage=`Amp Free not available: ${J}`}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}if(this.freeTierStatus&&this.freeTierStatus.trainingMode.canToggle&&!this.freeTierStatus.trainingMode.enabled&&this.freeTierStatus.eligible){this.setState(()=>{this.isShowingEnableTrainingModal=!0});return}};isInRestrictedFreeMode(){if(this.getEffectiveAgentMode()!=="free")return!1;if(this.freeTierStatus?.canUseAmpFree)return!1;return!0}onOpenInEditor=async(J)=>{let{execSync:Q}=await import("node:child_process"),{mkdtemp:Z,readFile:X,unlink:Y,rmdir:K,writeFile:q}=await import("node:fs/promises"),{tmpdir:G}=await import("node:os"),z=await import("node:path"),U=process.env.EDITOR||process.env.VISUAL||"nano";try{I5.instance.tuiInstance.suspend();let F=await Z(z.join(G(),"amp-edit-")),W=z.join(F,"message.amp.md");await q(W,J,"utf-8"),Q(`${U} "${W}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let H=await X(W,"utf-8");this.textController.text=H}catch(H){if(H?.code!=="ENOENT")l.error("Failed to read temporary file",H)}try{await Y(W),await K(F)}catch(H){l.warn("Failed to clean up temporary file",H)}I5.instance.tuiInstance.resume()}catch(F){try{I5.instance.tuiInstance.resume()}catch{}l.error("Error opening editor:",F)}};onTextSubmitted=async(J)=>{let{threadState:Q}=this.widget.dependencies;if(this.isSummarizing(Q.viewState)){this.showSubmitDisabledHint("Unable to submit while compacting.");return}if(!J.trim())return;let Z=this.parseShellModeInput(J);if(Z){if(Z.cmd&&!this.isProcessing())this.invokeBashCommand(Z.cmd,{hidden:Z.hidden}),this.widget.dependencies.history.add(J),this.textController.clear(),this.resetHistory();else this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}let X=tZ6(J);if(this.isSlashCommand(X)&&Q.mainThread){let Y=X.slice(1).split(" "),K=Y[0],q=Y.slice(1).filter((G)=>G.trim()!=="");if(K){let G=Q.viewState,z=this.getCommands().query(K,Q.mainThread,G).filter((U)=>U.name===K).pop();if(z){if((z.requiresArgs||z.requiresPicker)&&q.length===0){this.textController.clear(),this.textController.insertText(`/${K} `);return}this.textController.clear(),this.resetHistory(),await this.executeCommand(z,q)}return}}this.textController.clear(),this.resetHistory(),await this.sendUserMessage(X)};onOptionSelected=(J)=>{switch(J.type){case"command":{let Q=`/${J.name} `;this.onTextSubmitted(Q);break}case"file":{let Q=this.textController.text,Z=this.textController.cursorPosition,Y=Q.slice(0,Z).lastIndexOf("@");if(Y!==-1){let K=Q.slice(0,Y),q=Q.slice(Z),G=K+`@${J.path} `+q;this.textController.clear(),this.textController.insertText(G),this.textController.cursorPosition=Y+1+J.path.length+1}break}case"thread":{let Z=this.textController.text.split(" ");if(Z.length>=1&&Z[0]==="/continue"){let X=`/continue ${J.threadId} `;this.onTextSubmitted(X)}break}case"argument":{let Z=this.textController.text.split(" ");if(Z.length>=1&&Z[0]?.startsWith("/")){let Y=`${Z[0]} ${J.value} `;this.onTextSubmitted(Y)}break}}};executeCommand=async(J,Q)=>{let{threadState:Z}=this.widget.dependencies;if(!Z.mainThread||!J)return;let X=new AbortController,Y=Date.now(),q={id:`command-${Y}-${Math.random().toString(36).substring(7)}`,name:J.name,statusMessage:J.statusMessage,startTime:Y,abortController:X};this.setState(()=>{this.executingCommand=q});try{if(J.name==="new"){let z=await this.widget.dependencies.startNewThread();lV(z);return}if(J.name==="handoff"){let z=Q?.join(" ").trim()||"";if(!z){this.setState(()=>{this.displayMessage=Error("Usage: /handoff <describe your goal>")});return}let U=await this.prepareHandoffInput(z),F=await this.widget.dependencies.startNewThread();lV(F),this.textController.clear(),this.textController.insertText(U);return}if(J.launchesWindow)I5.instance.tuiInstance.suspend();let G=await this.getCommands().execute(J.name,{worker:this.widget.dependencies.worker,thread:Z.mainThread,ampURL:this.widget.dependencies.ampURL,threadSyncService:this.widget.dependencies.threadSyncService,configService:this.widget.dependencies.configService,takeImageAttachments:()=>{let z=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),z},editorDispatch:(z)=>{if(z.type==="set-input")this.textController.clear(),this.textController.insertText(z.input);else if(z.type==="clear")this.textController.clear()},submitMessage:(z)=>{return this.proceedWithUserMessage(z)},exitApp:()=>{process.exit(0)},openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},showCommandOverlay:(z)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=z})},onShowQRCodeOverlay:this.showQRCodeOverlay,settingsFilePath:this.widget.dependencies.settingsStorage.getSettingsFilePath(),settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,connectedClientsService:this.widget.dependencies.connectedClientsService,startNewThread:async()=>{await this.widget.dependencies.startNewThread()},pickAndContinueThread:this.widget.dependencies.pickAndContinueThread,switchToThread:async(z)=>{await this.switchToExistingThread(z)},getGuidanceFiles:async()=>{if(!Z.mainThread)return[];return(await rn({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},Z.mainThread,X.signal)).map((U)=>({uri:U.uri,type:U.type}))},openIdePicker:()=>{this.openIdePicker()},getInMemoryAgentModeOverride:()=>{return this.inMemoryAgentModeOverride},setInMemoryAgentModeOverride:(z)=>{this.setState(()=>{this.inMemoryAgentModeOverride=z,this.hasToggledAgentMode=!0})},toggleAgentMode:this.toggleAgentMode},Q,X.signal);if(J.launchesWindow)I5.instance.tuiInstance.resume();if(G)this.setState(()=>{this.displayMessage=G})}catch(G){l.error("Error executing command:",G)}finally{this.setState(()=>{this.executingCommand=null})}};buildOptions=async(J)=>{let Q=this.textController.text,Z=this.textController.cursorPosition,Y=Bu1().detect(Q,Z);if(Y){let{threadState:K}=this.widget.dependencies;return await this.getCompletionBuilder().buildOptions(Y,K.mainThread,K.viewState)}return[]};initState(){if(GY.getInstance().interceptConsole(),this.widget.dependencies.startWithPicker)this.isShowingThreadPicker=!0;I5.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),I5.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),I5.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()}),this.autocompleteFocusNode.addListener((Z)=>{G7.instance.addPostFrameCallback(()=>{this.setState(()=>{this.isTextfieldAndAutocompleteFocused=Z.hasFocus})})}),this.freeTierStatus=this.widget.dependencies.freeTierStatus;let J=eZ6(this.widget.dependencies.worker.thread,this.widget.dependencies.sessionState??null,this.freeTierStatus);if(l.info(`[initState] Resolved agentMode: ${J}`),this.inMemoryAgentModeOverride=J,this.freeTierStatus?.trainingMode.canToggle!==!1)this.adSubscription=Ey1(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>{return(this.inMemoryAgentModeOverride==="free"||this.randomAd===null)&&$y1(this.lastUserInteractionTime)}).subscribe({next:(Z)=>{if(Z){let X=kW9(16).toString("hex");this.lastAdImpressionId=X,Promise.resolve().then(() => (rJ1(),aJ1)).then(({recordAdEvent:Y})=>{let K=this.widget.dependencies.worker.thread,q=K.messages[K.messages.length-1];Y("viewed",{adId:Z.id,advertiserId:Z.advertiserId,threadId:K.id,messageId:q?.messageId,impressionId:X,placement:"tui"})})}this.setState(()=>{this.randomAd=Z})}});lV(this.widget.dependencies.worker),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((Z)=>{this.setState(()=>{this.ideStatus=Z})}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(Z)=>{let X=hK();if(!X){l.warn("No active thread worker found to handle IDE message");return}await new Promise((Y)=>setTimeout(Y,50)),await X.handle({type:"user:message",message:{content:[{type:"text",text:Z}]}}),l.debug("Message sent from IDE to agent",{message:Z.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Z)=>{this.textController.insertText(Z),l.debug("Appended text to CLI prompt from IDE",{text:Z.slice(0,100)})}),this.connectedClientsStatusSubscription=this.widget.dependencies.connectedClientsService.status.subscribe((Z)=>{this.setState(()=>{this.connectedClientsStatus=Z})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((Z)=>{this.setState(()=>{this.updateState=Z})}),this.agentModeSubscription=this.widget.dependencies.configService.config.subscribe((Z)=>{let X=LB(Z.settings);this.setState(()=>{this.cachedVisibleModes=X})}),this.textController.addListener(this.textChangeListener),this.getCommands(),this.textController.onInsertText=(Z,X)=>{if(Z.length<=3)return!0;let Y=QX6(Z);if(!Y)return!0;let K=this.getEffectiveAgentMode();if(!Sd(K)){if(this.imageUnsupportedHintTimer)clearTimeout(this.imageUnsupportedHintTimer);return this.setState(()=>{this.showImageUnsupportedHint=!0}),this.imageUnsupportedHintTimer=setTimeout(()=>{this.setState(()=>{this.showImageUnsupportedHint=!1}),this.imageUnsupportedHintTimer=null},5000),!1}if(this.imageAttachments.length>=xe1)return!1;let q=ZX6(Y);if(q)return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,q]}),!1;return!0},this.updateTerminalTitle();let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q)this.connectToSelectedIde(Q,"auto-startup").catch((Z)=>{let X=Z instanceof Error?Z.message:String(Z);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller()}onEnableTraining=async()=>{this.setState(()=>{this.isShowingEnableTrainingModal=!1});try{let J=await this.widget.dependencies.internalAPIClient.updateUserTrainingMode({enabled:!0},{config:this.widget.dependencies.configService});if(!J.ok){let Z=J.error.message||"Failed to enable training mode";await this.showErrorMessage(Z);return}let Q=await this.widget.dependencies.internalAPIClient.getUserFreeTierStatus({},{config:this.widget.dependencies.configService});if(Q.ok)this.setState(()=>{this.freeTierStatus=Q.result,this.inMemoryAgentModeOverride="free",this.hasToggledAgentMode=!0,this.agentModePulseSeq++})}catch(J){l.error("Error enabling training mode",{error:J}),await this.showErrorMessage("An error occurred. Please try again.")}};onEnableTrainingLearnMore=()=>{dK("https://ampcode.com/free")};onEnableTrainingDismiss=()=>{this.setState(()=>{this.isShowingEnableTrainingModal=!1})};didUpdateWidget(J){super.didUpdateWidget(J),this.setupSelectionListener()}dispose(){if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.connectedClientsStatusSubscription)this.connectedClientsStatusSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeSubscription)this.agentModeSubscription.unsubscribe();if(this.adSubscription)this.adSubscription.unsubscribe();if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;if(this.textController.removeListener(this.textChangeListener),this.commands)this.commands.cleanup().catch((J)=>{l.debug("Failed to cleanup commands during disposal",J)});for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(ff1("")),this.shouldUseProgressBar())process.stdout.write(hf1());if(this.progressReportTimer)clearTimeout(this.progressReportTimer),this.progressReportTimer=null}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,X=[...J.items.filter((G)=>G.type==="toolResult").map((G)=>({toolUse:G.toolUse,toolRun:G.toolResult.run,subthreadID:void 0})),...J.subagentActiveTools].filter((G)=>G.toolRun.status==="blocked-on-user");if(X.length===0)return null;let Y=X[0],K=Y.toolRun.status==="blocked-on-user"?Y.toolRun.toAllow??[]:[],q=Y.toolRun.status==="blocked-on-user"?Y.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:Y.toolUse,toAllow:K}],subthreadID:Y.subthreadID,reason:q}}shouldUseProgressBar(){return T8.of(this.context).capabilities.xtversion?.toLowerCase().startsWith("ghostty")??!1}updateProgressBar(){if(!this.shouldUseProgressBar())return;let J=this.getCurrentConfirmation(),Q="off";if(J)Q="paused";else if(this.isProcessing())Q="indeterminate";if(Q!==this.currentProgressBarState)this.currentProgressBarState=Q,this.sendProgressReport(Q),this.scheduleProgressReportTimer()}sendProgressReport(J){switch(J){case"indeterminate":process.stdout.write(rK6());break;case"paused":process.stdout.write(sK6());break;case"off":process.stdout.write(hf1());break}}scheduleProgressReportTimer(){if(this.progressReportTimer)clearTimeout(this.progressReportTimer),this.progressReportTimer=null;if(this.getCurrentConfirmation()||this.isProcessing())this.progressReportTimer=setTimeout(()=>{this.sendProgressReport(this.currentProgressBarState),this.scheduleProgressReportTimer()},1e4)}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){l.error("No current tool confirmation found");return}let Z=Q.tools[0]?.useBlock;if(!Z){l.error("No tool use block found in confirmation");return}if(J==="allow-all-session")oG("dangerouslyAllowAll",!0);if(J==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0)}catch(Y){if(Y&&Y instanceof Error)this.setState(()=>{this.displayMessage=Y});else l.error("Failed to write dangerouslyAllowAll setting:",Y);return}if(J==="always-guarded"){let Y=Q.tools[0]?.toAllow??[],K=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],q=[...Y,...K];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",q)}if(J==="connect-github"){let Y=new URL("/settings#code-host-connections",this.widget.dependencies.ampURL).toString();try{await dK(Y)}catch(K){l.error("Failed to open settings page:",K),await this.showErrorMessage(`Cannot open browser. Please go to ${Y} to connect to GitHub`)}return}if(J==="disable-librarian"){let Y=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!Y.includes(aG))await this.widget.dependencies.settingsStorage.set("tools.disable",[...Y,aG])}let X=J!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(J);try{let Y={type:"user:tool-input",toolUse:Z.id,value:{accepted:X}};if(Q.subthreadID)await(await UJ.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(Y);else await this.widget.dependencies.worker.handle(Y)}catch(Y){l.error("Failed to send tool confirmation:",Y)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};showQRCodeOverlay=(J)=>{this.setState(()=>{this.isShowingQRCodeOverlay=!0,this.qrCodeOverlayData=J})};getErrorKey(J){return`${J.constructor.name}:${J.message}`}getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Q=J.viewState;if(Q.state!=="active"||!Q.ephemeralError)return null;let Z=this.getErrorKey(Q.ephemeralError);if(this.dismissedEphemeralErrorKey===Z)return null;return Q.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let Q=this.getCurrentEphemeralError(),Z=this.widget.dependencies.worker;switch(J){case"retry":this.dismissedEphemeralErrorKey=null,await Z.retry();break;case"compact":this.dismissedEphemeralErrorKey=null,await Z.summarizeThread(new AbortController().signal);break;case"dismiss":if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);break;case"new-thread":{this.setState(()=>{this.dismissedEphemeralErrorKey=null});let X=await this.widget.dependencies.startNewThread();lV(X);break}case"new-smart-thread":{this.setState(()=>{this.inMemoryAgentModeOverride="smart",this.dismissedEphemeralErrorKey=null}),wy1({agentMode:"smart"});let X=await this.widget.dependencies.startNewThread();lV(X);break}}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};cancelStreamingMessage=async()=>{await UJ.cancel(this.widget.dependencies.threadID)};markLastUserMessageAsInterrupted=async()=>{let J=this.widget.dependencies.threadState.mainThread;if(!J)return;for(let Q=J.messages.length-1;Q>=0;Q--){let Z=J.messages[Q];if(Z?.role==="user"&&!Z.interrupted){await this.widget.dependencies.worker.handle({type:"user:message:interrupt",messageIndex:Q});break}}};prepareHandoffInput=async(J)=>{let Q=this.widget.dependencies.threadState.mainThread;if(!Q||Q.messages.length===0)return J;try{let Z=await this.widget.dependencies.configService.getLatest(),X=new AbortController,Y=setTimeout(()=>X.abort(),20000),{instructions:K,relevantFiles:q}=await oZ6(Q,J,Z,X.signal);clearTimeout(Y);let G=q.map((z)=>{try{return"@"+HZ(NQ(z))}catch{return null}}).filter(Boolean).join(" ");return G?`${K}
6411
+ `))return null;return{start:X,end:Q,query:Y,trigger:"@"}}findWordStart(J,Q){let Z=Q;for(let X=Q-1;X>=0;X--){let Y=J[X];if(!Y||/[\s([{]/.test(Y)){Z=X+1;break}if(X===0)Z=0}return Z}}class Hu1{detect(J,Q){if(!J||Q<1)return null;let Z=$2(J);if(Q>Z.length)return null;if(Z[0]!=="/")return null;let X=Z.slice(1,Q).join("");return{start:0,end:Q,query:X,trigger:"/"}}}class EF6{triggers;constructor(J){this.triggers=J}detect(J,Q){for(let Z of this.triggers){let X=Z.detect(J,Q);if(X)return X}return null}}function Bu1(){return new EF6([new Wu1,new Hu1])}function IF6(J,Q){switch(J){case"update-available":return[new O1("A newer Amp is available. Run ",new S1({color:Q.foreground,dim:!0})),new O1("amp update",new S1({color:Q.warning}))];case"updated":return null;case"updated-with-warning":return[new O1("Update complete, run ",new S1({color:Q.foreground,dim:!0})),new O1("amp update",new S1({color:Q.warning})),new O1(" to see warnings",new S1({color:Q.foreground,dim:!0}))];case"update-error":return[new O1("Update failed, run ",new S1({color:Q.foreground,dim:!0})),new O1("amp update",new S1({color:Q.warning})),new O1(" to see warnings",new S1({color:Q.foreground,dim:!0}))];case"hidden":return null}}function xW9(J){return[{match:(Q)=>Q.startsWith("$$"),display:"$$",style:new S1({color:J.app.shellModeHidden}),spacing:1,concealPrefix:!0},{match:(Q)=>Q.startsWith("$")&&!Q.startsWith("$$"),display:"$",style:new S1({color:J.app.shellMode}),spacing:1,concealPrefix:!0}]}class xF6 extends t0{dependencies;constructor(J){super();this.dependencies=J}createState(){return new bF6}}class bF6 extends o0{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;connectedClientsStatus=null;randomAd=null;adSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();isConfirmingExit=!1;isConfirmingClearInput=!1;copyMessageTimer=null;isShowingHelp=!1;isShowingConsoleOverlay=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingCostBreakdownOverlay=!1;isShowingQRCodeOverlay=!1;confirmationOverlayContent="";qrCodeOverlayData=null;exitConfirmTimeout=null;clearInputConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];dismissedEphemeralErrorKey=null;currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;currentProgressBarState="off";progressReportTimer=null;showingSelectionCopiedHint=!1;isShowingThreadPicker=!1;agentModePulseSeq=0;messageViewFocusNode=new S9({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new S9({debugLabel:"AutocompleteFocus"});isTextfieldAndAutocompleteFocused=!1;submitDisabledHint=null;submitDisabledHintTimer=null;isShowingTrainingModeDialog=!1;pendingTrainingMode=null;showingCannotToggleMessage=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;isShowingEnableTrainingModal=!1;adActionModal=null;agentModeSubscription=null;currentAgentMode="smart";hasToggledAgentMode=!1;inMemoryAgentModeOverride=null;cachedVisibleModes=LB();freeTierStatus=void 0;updateState="hidden";updateServiceSubscription=null;getEffectiveAgentMode(){return this.inMemoryAgentModeOverride??this.currentAgentMode}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(Boolean(J.viewState.inferenceState==="running"))return!0;let Z=J.items.filter((K)=>K.type==="toolResult").filter((K)=>K.toolResult.run.status==="in-progress"||K.toolResult.run.status==="queued"),X=J.subagentActiveTools.filter((K)=>K.toolRun.status==="in-progress"||K.toolRun.status==="queued");return[...Z,...X].length>0}isSummarizing(J){return J.state==="active"&&J.summaryState!=="idle"}parseShellModeInput(J){if(J.startsWith("$$")){let Q=J.slice(2).trim();return Q?{cmd:Q,hidden:!0}:null}if(J.startsWith("$")){let Q=J.slice(1).trim();return Q?{cmd:Q,hidden:!1}:null}return null}isSlashCommand(J){if(!J.startsWith("/"))return!1;if((J.split(" ")[0]?.slice(1)||"").includes("/"))return!1;return!0}showSubmitDisabledHint(J){if(this.submitDisabledHintTimer)clearTimeout(this.submitDisabledHintTimer);this.setState(()=>{this.submitDisabledHint=J}),this.submitDisabledHintTimer=setTimeout(()=>{this.setState(()=>{this.submitDisabledHint=null}),this.submitDisabledHintTimer=null},3000)}getUIHint(){let J=this.themeColors?.colorScheme;if(!J)return null;let Q=this.themeApp;if(!Q)return null;if(this.submitDisabledHint)return new O1(this.submitDisabledHint,new S1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new O1("",void 0,[new O1("Ctrl+C",new S1({color:Q.keybind})),new O1(" again to exit",new S1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new O1("",void 0,[new O1("Esc",new S1({color:Q.keybind})),new O1(" again to clear input",new S1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new O1("",void 0,[new O1("Escape",new S1({color:Q.keybind})),new O1(" to close help",new S1({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let X=this.getEffectiveAgentMode(),Y=Au1(X);return new O1("",void 0,[new O1("Images aren't supported in ",new S1({color:J.warning,dim:!1})),new O1(X,new S1({color:Y})),new O1(" mode.",new S1({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0)return new O1("",void 0,[new O1("Esc",new S1({color:Q.keybind})),new O1(" to cancel",new S1({color:J.foreground,dim:!0}))]);if(this.showingSelectionCopiedHint)return new O1("Selection copied to clipboard",new S1({color:J.foreground,dim:!0}));if(this.showingCannotToggleMessage)return new O1(this.showingCannotToggleMessage,new S1({color:J.warning,dim:!1}));let Z=IF6(this.updateState,J);if(Z)return new O1("",void 0,Z);return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Q,worker:Z}=this.widget.dependencies;if(!Q.mainThread?.id)return;let Y=Q.mainThread?.messages.findIndex((K)=>K===J);if(Y===void 0||Y===-1)return;try{this.cancelBashInvocations(),await Z.cancel(),await Z.handle({type:"thread:truncate",fromIndex:Y}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(K){l.error("Failed to edit message:",K)}};forkMessage=async(J)=>{let{threadState:Q,workerDeps:Z,threadSyncService:X,switchToThread:Y}=this.widget.dependencies,K=Q.mainThread?.id;if(!K)return;let q=Q.mainThread?.messages.findIndex((G)=>G===J);if(q===void 0||q<=0)return;try{let G=await UJ.getOrCreateForThread(Z,K),z=await yr(G,X,q),U=await Y(z);lV(U),this.widget.dependencies.worker=U,this.widget.dependencies.threadID=U.thread.id;let F=U.thread.agentMode??null;this.setState(()=>{this.inMemoryAgentModeOverride=F})}catch(G){l.error("Failed to fork thread:",G),this.showErrorMessage(`Failed to fork thread: ${G}`)}};handleMessageEditSubmit=async(J,Q)=>{let{threadState:Z,worker:X}=this.widget.dependencies,Y=Z.mainThread;if(!Y)return;let K=Y.messages.findIndex((q)=>q===J);if(K===-1)return;try{this.cancelBashInvocations(),await X.cancel(),this.widget.dependencies.history.add(Q);let q=[{type:"text",text:Q}];if(this.imageAttachments.length>0)q.push(...this.imageAttachments);let G={content:q,agentMode:Y.agentMode},z=K===0;if(Y.agentMode&&!z&&G.agentMode!==Y.agentMode){l.error(`Cannot edit message: This thread uses ${Y.agentMode} mode. To change mode, create a new thread.`);return}await X.handle({type:"user:message",message:G,index:K}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(q){l.error("Failed to edit message:",q)}};textController=new CC;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new KN);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.id;if(!Q)return;this.getMessageScrollController(Q).scrollToBottom()}findElementByKey(J){return this.searchElementTreeByKey(this.context.element,J)}searchElementTreeByKey(J,Q){if(!J)return null;if(J?.widget?.key?.value===Q)return J;if(J?.child){let X=this.searchElementTreeByKey(J.child,Q);if(X)return X}if(J?.children)for(let X of J.children){let Y=this.searchElementTreeByKey(X,Q);if(Y)return Y}return null}clearActiveSelection(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller?.hasSelection)return Q.controller.clearSelection(),this.setState(()=>{}),!0}return!1}setupSelectionListener(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller&&!this.selectionListener)this.selectionListener=()=>{this.setState(()=>{})},Q.controller.addListener(this.selectionListener),Q.controller.onSelectionCopied=()=>{if(this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}}updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.title;if(Q!==this.currentTitle){this.currentTitle=Q;let Z=process.cwd().replace(process.env.HOME||"","~"),X=Q?`amp - ${Q} - ${Z}`:"";process.stdout.write(ff1(X))}}_handleTextCopy(J){if(J&&J.length>0){if(this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}textFieldKey=new j5("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;connectedClientsStatusSubscription=null;commands=null;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text,Q=J.startsWith("$$")?"hidden":J.startsWith("$")?"normal":void 0;if(Q!==this.currentShellModeStatus)this.currentShellModeStatus=Q,this.setState(()=>{})};getCommands(){if(!this.commands)this.commands=new Cf1(this.widget.dependencies.commandRegistry,this.widget.dependencies.configService);return this.commands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new fm1(this.getCommands(),this.widget.dependencies.fuzzyServer,new nJ1(this.widget.dependencies.configService),this.widget.dependencies.configService);return this.completionBuilder}navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.widget.dependencies.ideClient.sendStatus({enabled:!1}),this.setState(()=>{this.isShowingIdePicker=!1})};handleIdeSelection=async(J,Q)=>{try{await this.connectToSelectedIde(J,Q)}catch(Z){let X=Z instanceof Error?Z.message:String(Z);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.setState(()=>{this.isShowingIdePicker=!1})};async connectToSelectedIde(J,Q){await this.widget.dependencies.ideClient.start(J,!0,Q)}removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Q)=>Q.id!==J)})};invokeBashCommand=(J,{hidden:Q})=>{let Z=Date.now(),X=`bash-${Z}-${Math.random().toString(36).substring(7)}`,Y={cmd:J},K=new AbortController;this.widget.dependencies.worker.invokeBashTool(Y,K.signal,Q).subscribe({next:(q)=>{this.setState(()=>{if(this.bashInvocations.find((z)=>z.id===X))this.bashInvocations=this.bashInvocations.map((z)=>z.id===X?{...z,toolRun:q}:z);else{let z={id:X,args:Y,toolRun:q,startTime:Z,abortController:K,hidden:Q};this.bashInvocations=[...this.bashInvocations,z]}})},error:()=>this.removeBashInvocation(X),complete:()=>this.removeBashInvocation(X)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Q)=>Q.toolRun.status==="in-progress");if(J)J.abortController.abort()};toggleAgentMode=()=>{if((hK()||this.widget.dependencies.worker).thread.messages.length>0)return;if(this.freeTierStatus?.canUseAmpFree){let X=this.inMemoryAgentModeOverride??this.currentAgentMode,Y=vd(X,this.cachedVisibleModes);if(Y!==X)this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=Y,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1});return}let Q=this.inMemoryAgentModeOverride??this.currentAgentMode,Z=vd(Q,this.cachedVisibleModes);if(Z===Q)return;if(this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=Z,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1,this.isShowingEnableTrainingModal=!1}),Z==="free")this.checkAndShowFreeModeModal()};checkAndShowFreeModeModal=()=>{if(this.freeTierStatus?.canUseAmpFree)return;if(this.freeTierStatus&&!this.freeTierStatus.eligible){this.setState(()=>{this.showingCannotToggleMessage="Amp Free is unavailable. Switch to another mode."}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}else if(this.freeTierStatus?.trainingMode&&!this.freeTierStatus.trainingMode.canToggle){let J=this.freeTierStatus.trainingMode.cannotToggleReason||"Training mode cannot be toggled at this time.";this.setState(()=>{this.showingCannotToggleMessage=`Amp Free not available: ${J}`}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}if(this.freeTierStatus&&this.freeTierStatus.trainingMode.canToggle&&!this.freeTierStatus.trainingMode.enabled&&this.freeTierStatus.eligible){this.setState(()=>{this.isShowingEnableTrainingModal=!0});return}};isInRestrictedFreeMode(){if(this.getEffectiveAgentMode()!=="free")return!1;if(this.freeTierStatus?.canUseAmpFree)return!1;return!0}onOpenInEditor=async(J)=>{let{execSync:Q}=await import("node:child_process"),{mkdtemp:Z,readFile:X,unlink:Y,rmdir:K,writeFile:q}=await import("node:fs/promises"),{tmpdir:G}=await import("node:os"),z=await import("node:path"),U=process.env.EDITOR||process.env.VISUAL||"nano";try{I5.instance.tuiInstance.suspend();let F=await Z(z.join(G(),"amp-edit-")),W=z.join(F,"message.amp.md");await q(W,J,"utf-8"),Q(`${U} "${W}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let H=await X(W,"utf-8");this.textController.text=H}catch(H){if(H?.code!=="ENOENT")l.error("Failed to read temporary file",H)}try{await Y(W),await K(F)}catch(H){l.warn("Failed to clean up temporary file",H)}I5.instance.tuiInstance.resume()}catch(F){try{I5.instance.tuiInstance.resume()}catch{}l.error("Error opening editor:",F)}};onTextSubmitted=async(J)=>{let{threadState:Q}=this.widget.dependencies;if(this.isSummarizing(Q.viewState)){this.showSubmitDisabledHint("Unable to submit while compacting.");return}if(!J.trim())return;let Z=this.parseShellModeInput(J);if(Z){if(Z.cmd&&!this.isProcessing())this.invokeBashCommand(Z.cmd,{hidden:Z.hidden}),this.widget.dependencies.history.add(J),this.textController.clear(),this.resetHistory();else this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}let X=tZ6(J);if(this.isSlashCommand(X)&&Q.mainThread){let Y=X.slice(1).split(" "),K=Y[0],q=Y.slice(1).filter((G)=>G.trim()!=="");if(K){let G=Q.viewState,z=this.getCommands().query(K,Q.mainThread,G).filter((U)=>U.name===K).pop();if(z){if((z.requiresArgs||z.requiresPicker)&&q.length===0){this.textController.clear(),this.textController.insertText(`/${K} `);return}this.textController.clear(),this.resetHistory(),await this.executeCommand(z,q)}return}}this.textController.clear(),this.resetHistory(),await this.sendUserMessage(X)};onOptionSelected=(J)=>{switch(J.type){case"command":{let Q=`/${J.name} `;this.onTextSubmitted(Q);break}case"file":{let Q=this.textController.text,Z=this.textController.cursorPosition,Y=Q.slice(0,Z).lastIndexOf("@");if(Y!==-1){let K=Q.slice(0,Y),q=Q.slice(Z),G=K+`@${J.path} `+q;this.textController.clear(),this.textController.insertText(G),this.textController.cursorPosition=Y+1+J.path.length+1}break}case"thread":{let Z=this.textController.text.split(" ");if(Z.length>=1&&Z[0]==="/continue"){let X=`/continue ${J.threadId} `;this.onTextSubmitted(X)}break}case"argument":{let Z=this.textController.text.split(" ");if(Z.length>=1&&Z[0]?.startsWith("/")){let Y=`${Z[0]} ${J.value} `;this.onTextSubmitted(Y)}break}}};executeCommand=async(J,Q)=>{let{threadState:Z}=this.widget.dependencies;if(!Z.mainThread||!J)return;let X=new AbortController,Y=Date.now(),q={id:`command-${Y}-${Math.random().toString(36).substring(7)}`,name:J.name,statusMessage:J.statusMessage,startTime:Y,abortController:X};this.setState(()=>{this.executingCommand=q});try{if(J.name==="new"){let z=await this.widget.dependencies.startNewThread();lV(z);return}if(J.name==="handoff"){let z=Q?.join(" ").trim()||"";if(!z){this.setState(()=>{this.displayMessage=Error("Usage: /handoff <describe your goal>")});return}let U=await this.prepareHandoffInput(z),F=await this.widget.dependencies.startNewThread();lV(F),this.textController.clear(),this.textController.insertText(U);return}if(J.launchesWindow)I5.instance.tuiInstance.suspend();let G=await this.getCommands().execute(J.name,{worker:this.widget.dependencies.worker,thread:Z.mainThread,ampURL:this.widget.dependencies.ampURL,threadSyncService:this.widget.dependencies.threadSyncService,configService:this.widget.dependencies.configService,takeImageAttachments:()=>{let z=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),z},editorDispatch:(z)=>{if(z.type==="set-input")this.textController.clear(),this.textController.insertText(z.input);else if(z.type==="clear")this.textController.clear()},submitMessage:(z)=>{return this.proceedWithUserMessage(z)},exitApp:()=>{process.exit(0)},openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},showCommandOverlay:(z)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=z})},onShowQRCodeOverlay:this.showQRCodeOverlay,settingsFilePath:this.widget.dependencies.settingsStorage.getSettingsFilePath(),settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,connectedClientsService:this.widget.dependencies.connectedClientsService,startNewThread:async()=>{await this.widget.dependencies.startNewThread()},pickAndContinueThread:this.widget.dependencies.pickAndContinueThread,switchToThread:async(z)=>{await this.switchToExistingThread(z)},getGuidanceFiles:async()=>{if(!Z.mainThread)return[];return(await rn({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},Z.mainThread,X.signal)).map((U)=>({uri:U.uri,type:U.type}))},openIdePicker:()=>{this.openIdePicker()},getInMemoryAgentModeOverride:()=>{return this.inMemoryAgentModeOverride},setInMemoryAgentModeOverride:(z)=>{this.setState(()=>{this.inMemoryAgentModeOverride=z,this.hasToggledAgentMode=!0})},toggleAgentMode:this.toggleAgentMode},Q,X.signal);if(J.launchesWindow)I5.instance.tuiInstance.resume();if(G)this.setState(()=>{this.displayMessage=G})}catch(G){l.error("Error executing command:",G)}finally{this.setState(()=>{this.executingCommand=null})}};buildOptions=async(J)=>{let Q=this.textController.text,Z=this.textController.cursorPosition,Y=Bu1().detect(Q,Z);if(Y){let{threadState:K}=this.widget.dependencies;return await this.getCompletionBuilder().buildOptions(Y,K.mainThread,K.viewState)}return[]};initState(){if(GY.getInstance().interceptConsole(),this.widget.dependencies.startWithPicker)this.isShowingThreadPicker=!0;I5.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),I5.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),I5.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()}),this.autocompleteFocusNode.addListener((Z)=>{G7.instance.addPostFrameCallback(()=>{this.setState(()=>{this.isTextfieldAndAutocompleteFocused=Z.hasFocus})})}),this.freeTierStatus=this.widget.dependencies.freeTierStatus;let J=eZ6(this.widget.dependencies.worker.thread,this.widget.dependencies.sessionState??null,this.freeTierStatus);if(l.info(`[initState] Resolved agentMode: ${J}`),this.inMemoryAgentModeOverride=J,this.freeTierStatus?.trainingMode.canToggle!==!1)this.adSubscription=Ey1(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>{return(this.inMemoryAgentModeOverride==="free"||this.randomAd===null)&&$y1(this.lastUserInteractionTime)}).subscribe({next:(Z)=>{if(Z){let X=kW9(16).toString("hex");this.lastAdImpressionId=X,Promise.resolve().then(() => (rJ1(),aJ1)).then(({recordAdEvent:Y})=>{let K=this.widget.dependencies.worker.thread,q=K.messages[K.messages.length-1];Y("viewed",{adId:Z.id,advertiserId:Z.advertiserId,threadId:K.id,messageId:q?.messageId,impressionId:X,placement:"tui"})})}this.setState(()=>{this.randomAd=Z})}});lV(this.widget.dependencies.worker),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((Z)=>{this.setState(()=>{this.ideStatus=Z})}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(Z)=>{let X=hK();if(!X){l.warn("No active thread worker found to handle IDE message");return}await new Promise((Y)=>setTimeout(Y,50)),await X.handle({type:"user:message",message:{content:[{type:"text",text:Z}]}}),l.debug("Message sent from IDE to agent",{message:Z.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Z)=>{this.textController.insertText(Z),l.debug("Appended text to CLI prompt from IDE",{text:Z.slice(0,100)})}),this.connectedClientsStatusSubscription=this.widget.dependencies.connectedClientsService.status.subscribe((Z)=>{this.setState(()=>{this.connectedClientsStatus=Z})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((Z)=>{this.setState(()=>{this.updateState=Z})}),this.agentModeSubscription=this.widget.dependencies.configService.config.subscribe((Z)=>{let X=LB(Z.settings);this.setState(()=>{this.cachedVisibleModes=X})}),this.textController.addListener(this.textChangeListener),this.getCommands(),this.textController.onInsertText=(Z,X)=>{if(Z.length<=3)return!0;let Y=QX6(Z);if(!Y)return!0;let K=this.getEffectiveAgentMode();if(!Sd(K)){if(this.imageUnsupportedHintTimer)clearTimeout(this.imageUnsupportedHintTimer);return this.setState(()=>{this.showImageUnsupportedHint=!0}),this.imageUnsupportedHintTimer=setTimeout(()=>{this.setState(()=>{this.showImageUnsupportedHint=!1}),this.imageUnsupportedHintTimer=null},5000),!1}if(this.imageAttachments.length>=xe1)return!1;let q=ZX6(Y);if(q)return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,q]}),!1;return!0},this.updateTerminalTitle();let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q)this.connectToSelectedIde(Q,"auto-startup").catch((Z)=>{let X=Z instanceof Error?Z.message:String(Z);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller()}onEnableTraining=async()=>{this.setState(()=>{this.isShowingEnableTrainingModal=!1});try{let J=await this.widget.dependencies.internalAPIClient.updateUserTrainingMode({enabled:!0},{config:this.widget.dependencies.configService});if(!J.ok){let Z=J.error.message||"Failed to enable training mode";await this.showErrorMessage(Z);return}let Q=await this.widget.dependencies.internalAPIClient.getUserFreeTierStatus({},{config:this.widget.dependencies.configService});if(Q.ok)this.setState(()=>{this.freeTierStatus=Q.result,this.inMemoryAgentModeOverride="free",this.hasToggledAgentMode=!0,this.agentModePulseSeq++})}catch(J){l.error("Error enabling training mode",{error:J}),await this.showErrorMessage("An error occurred. Please try again.")}};onEnableTrainingLearnMore=()=>{dK("https://ampcode.com/free")};onEnableTrainingDismiss=()=>{this.setState(()=>{this.isShowingEnableTrainingModal=!1})};didUpdateWidget(J){super.didUpdateWidget(J),this.setupSelectionListener()}dispose(){if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.connectedClientsStatusSubscription)this.connectedClientsStatusSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeSubscription)this.agentModeSubscription.unsubscribe();if(this.adSubscription)this.adSubscription.unsubscribe();if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;if(this.textController.removeListener(this.textChangeListener),this.commands)this.commands.cleanup().catch((J)=>{l.debug("Failed to cleanup commands during disposal",J)});for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(ff1("")),this.shouldUseProgressBar())process.stdout.write(hf1());if(this.progressReportTimer)clearTimeout(this.progressReportTimer),this.progressReportTimer=null}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,X=[...J.items.filter((G)=>G.type==="toolResult").map((G)=>({toolUse:G.toolUse,toolRun:G.toolResult.run,subthreadID:void 0})),...J.subagentActiveTools].filter((G)=>G.toolRun.status==="blocked-on-user");if(X.length===0)return null;let Y=X[0],K=Y.toolRun.status==="blocked-on-user"?Y.toolRun.toAllow??[]:[],q=Y.toolRun.status==="blocked-on-user"?Y.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:Y.toolUse,toAllow:K}],subthreadID:Y.subthreadID,reason:q}}shouldUseProgressBar(){return T8.of(this.context).capabilities.xtversion?.toLowerCase().startsWith("ghostty")??!1}updateProgressBar(){if(!this.shouldUseProgressBar())return;let J=this.getCurrentConfirmation(),Q="off";if(J)Q="paused";else if(this.isProcessing())Q="indeterminate";if(Q!==this.currentProgressBarState)this.currentProgressBarState=Q,this.sendProgressReport(Q),this.scheduleProgressReportTimer()}sendProgressReport(J){switch(J){case"indeterminate":process.stdout.write(rK6());break;case"paused":process.stdout.write(sK6());break;case"off":process.stdout.write(hf1());break}}scheduleProgressReportTimer(){if(this.progressReportTimer)clearTimeout(this.progressReportTimer),this.progressReportTimer=null;if(this.getCurrentConfirmation()||this.isProcessing())this.progressReportTimer=setTimeout(()=>{this.sendProgressReport(this.currentProgressBarState),this.scheduleProgressReportTimer()},1e4)}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){l.error("No current tool confirmation found");return}let Z=Q.tools[0]?.useBlock;if(!Z){l.error("No tool use block found in confirmation");return}if(J==="allow-all-session")oG("dangerouslyAllowAll",!0);if(J==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0)}catch(Y){if(Y&&Y instanceof Error)this.setState(()=>{this.displayMessage=Y});else l.error("Failed to write dangerouslyAllowAll setting:",Y);return}if(J==="always-guarded"){let Y=Q.tools[0]?.toAllow??[],K=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],q=[...Y,...K];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",q)}if(J==="connect-github"){let Y=new URL("/settings#code-host-connections",this.widget.dependencies.ampURL).toString();try{await dK(Y)}catch(K){l.error("Failed to open settings page:",K),await this.showErrorMessage(`Cannot open browser. Please go to ${Y} to connect to GitHub`)}return}if(J==="disable-librarian"){let Y=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!Y.includes(aG))await this.widget.dependencies.settingsStorage.set("tools.disable",[...Y,aG])}let X=J!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(J);try{let Y={type:"user:tool-input",toolUse:Z.id,value:{accepted:X}};if(Q.subthreadID)await(await UJ.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(Y);else await this.widget.dependencies.worker.handle(Y)}catch(Y){l.error("Failed to send tool confirmation:",Y)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};showQRCodeOverlay=(J)=>{this.setState(()=>{this.isShowingQRCodeOverlay=!0,this.qrCodeOverlayData=J})};getErrorKey(J){return`${J.constructor.name}:${J.message}`}getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Q=J.viewState;if(Q.state!=="active"||!Q.ephemeralError)return null;let Z=this.getErrorKey(Q.ephemeralError);if(this.dismissedEphemeralErrorKey===Z)return null;return Q.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let Q=this.getCurrentEphemeralError(),Z=this.widget.dependencies.worker;switch(J){case"retry":this.dismissedEphemeralErrorKey=null,await Z.retry();break;case"compact":this.dismissedEphemeralErrorKey=null,await Z.summarizeThread(new AbortController().signal);break;case"dismiss":if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);break;case"new-thread":{this.setState(()=>{this.dismissedEphemeralErrorKey=null});let X=await this.widget.dependencies.startNewThread();lV(X);break}case"new-smart-thread":{this.setState(()=>{this.inMemoryAgentModeOverride="smart",this.dismissedEphemeralErrorKey=null}),wy1({agentMode:"smart"});let X=await this.widget.dependencies.startNewThread();lV(X);break}}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};cancelStreamingMessage=async()=>{await UJ.cancel(this.widget.dependencies.threadID)};markLastUserMessageAsInterrupted=async()=>{let J=this.widget.dependencies.threadState.mainThread;if(!J)return;for(let Q=J.messages.length-1;Q>=0;Q--){let Z=J.messages[Q];if(Z?.role==="user"&&!Z.interrupted){await this.widget.dependencies.worker.handle({type:"user:message:interrupt",messageIndex:Q});break}}};prepareHandoffInput=async(J)=>{let Q=this.widget.dependencies.threadState.mainThread;if(!Q||Q.messages.length===0)return J;try{let Z=await this.widget.dependencies.configService.getLatest(),X=new AbortController,Y=setTimeout(()=>X.abort(),20000),{instructions:K,relevantFiles:q}=await oZ6(Q,J,Z,X.signal);clearTimeout(Y);let G=q.map((z)=>{try{return"@"+HZ(NQ(z))}catch{return null}}).filter(Boolean).join(" ");return G?`${K}
6412
6412
 
6413
6413
  ${G}
6414
6414
  `:K}catch(Z){return l.error("Failed to prepare handoff",Z),`${J}
@@ -6419,7 +6419,7 @@ ${Q}`),this.textController.clear(),this.textController.insertText(this.pendingTr
6419
6419
  `),J.stdout.write(`Thread: ${H}
6420
6420
  `),J.stdout.write(`Continue this thread with: amp threads continue ${F}
6421
6421
  `)}}function Au1(J){return J==="smart"?k1.rgb(3,197,97):J==="fast"?k1.rgb(228,180,2):J==="free"?k1.rgb(0,184,255):bW9(J)}function bW9(J){let Q=0;for(let Y=0;Y<J.length;Y++){let K=J.charCodeAt(Y);Q=(Q<<5)-Q+K,Q=Q&Q}let Z=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],X=Math.abs(Q)%Z.length;return k1.index(Z[X])}rf1();if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){n7.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
6422
- `)}var Ru1=wu1.join(nc1||wu1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function mW9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),q=Z||"Warning",G=!1;J.warn(K,{name:q,code:X})}}function hG(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")oG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new u9("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${V8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")oG("experimental.agentMode",Q.agentMode)}async function ju1(J){try{await fW9(wu1.dirname(Ru1),{recursive:!0}),await hW9(Ru1,J,"utf-8")}catch(Q){l.debug("Failed to save last thread ID",Q)}}async function uW9(){try{return(await mF6(Ru1,"utf-8")).trim()}catch(J){return null}}function pW9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return nl1("mcpServers",{global:X,workspace:Q})}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}var fF6=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??mK,description:`Custom settings file path (overrides the default location ${mK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(l).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${kb1})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:uK(),description:(J)=>J?"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:(J)=>J?"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:(J)=>J?"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:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:Cd}],hF6=(J)=>("deprecated"in J)&&J.deprecated===!0,dW9=(J)=>("hidden"in J)&&J.hidden===!0,cW9=(J)=>("default"in J),lW9=(J)=>("default"in J)?J.default:void 0;function iW9(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((G)=>Z.includes(G)||G.includes(Z)),q="Run amp --help for a list of available commands.";if(K.length>0)q=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new u9(gK.unknownCommand(Z),1,q)}}var uF6=null;function ft2(){return uF6}function oJ1(J){return{...J,getThreadEnvironment:k71,vfs:r20({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new B_(J.fileSystem),generateThreadTitle:WG0,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var $u1=R0.file(gW9.homedir()),pF6=process.env.XDG_CONFIG_HOME?R0.file(process.env.XDG_CONFIG_HOME):x0.joinPath($u1,".config");async function gG(J,Q){oi1("0.0.1761062513-gf7c5f2");let Z=QX1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:e1.of([R0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:$u1,userConfigDir:pF6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (rJ1(),aJ1));X(Z);let Y=await Z.getLatest();l.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let K=Ha(zO({configService:Z})),q=E20({configService:Z,toolService:K}),G=_R0(K,T9,me).catch((w)=>{l.warn("Toolbox registration failed, continuing anyway:",w)}),z=q.initialized.catch((w)=>{l.warn("MCP service initialization failed, continuing anyway:",w)});if(J.executeMode)await Promise.all([z,G]);if(Q.jetbrains)WO("JetBrains");else if(Q.ide&&nQ6())WO("VS Code");else if(Q.ide&&aQ6())WO("Neovim");if(J.executeMode)ti1(!0);g96(K,{configService:Z});let U,F=v5.status.pipe(C0((w)=>Boolean(w.connected&&w.authenticated)),t6()).subscribe((w)=>{if(w){if(!U)U=K.registerTool(Ks)}else U?.dispose(),U=void 0}),W;if(!J.executeMode)W=new i71(process.cwd(),{},!0);else W=new class extends i71{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(h2.write(`No API key found. Starting login flow...
6422
+ `)}var Ru1=wu1.join(nc1||wu1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function mW9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),q=Z||"Warning",G=!1;J.warn(K,{name:q,code:X})}}function hG(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")oG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new u9("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${V8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")oG("experimental.agentMode",Q.agentMode)}async function ju1(J){try{await fW9(wu1.dirname(Ru1),{recursive:!0}),await hW9(Ru1,J,"utf-8")}catch(Q){l.debug("Failed to save last thread ID",Q)}}async function uW9(){try{return(await mF6(Ru1,"utf-8")).trim()}catch(J){return null}}function pW9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return nl1("mcpServers",{global:X,workspace:Q})}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}var fF6=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??mK,description:`Custom settings file path (overrides the default location ${mK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(l).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${kb1})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:uK(),description:(J)=>J?"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:(J)=>J?"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:(J)=>J?"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:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:Cd}],hF6=(J)=>("deprecated"in J)&&J.deprecated===!0,dW9=(J)=>("hidden"in J)&&J.hidden===!0,cW9=(J)=>("default"in J),lW9=(J)=>("default"in J)?J.default:void 0;function iW9(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((G)=>Z.includes(G)||G.includes(Z)),q="Run amp --help for a list of available commands.";if(K.length>0)q=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new u9(gK.unknownCommand(Z),1,q)}}var uF6=null;function ft2(){return uF6}function oJ1(J){return{...J,getThreadEnvironment:k71,vfs:r20({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new B_(J.fileSystem),generateThreadTitle:WG0,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var $u1=R0.file(gW9.homedir()),pF6=process.env.XDG_CONFIG_HOME?R0.file(process.env.XDG_CONFIG_HOME):x0.joinPath($u1,".config");async function gG(J,Q){oi1("0.0.1761062777-g4520cb");let Z=QX1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:e1.of([R0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:$u1,userConfigDir:pF6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (rJ1(),aJ1));X(Z);let Y=await Z.getLatest();l.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let K=Ha(zO({configService:Z})),q=E20({configService:Z,toolService:K}),G=_R0(K,T9,me).catch((w)=>{l.warn("Toolbox registration failed, continuing anyway:",w)}),z=q.initialized.catch((w)=>{l.warn("MCP service initialization failed, continuing anyway:",w)});if(J.executeMode)await Promise.all([z,G]);if(Q.jetbrains)WO("JetBrains");else if(Q.ide&&nQ6())WO("VS Code");else if(Q.ide&&aQ6())WO("Neovim");if(J.executeMode)ti1(!0);g96(K,{configService:Z});let U,F=v5.status.pipe(C0((w)=>Boolean(w.connected&&w.authenticated)),t6()).subscribe((w)=>{if(w){if(!U)U=K.registerTool(Ks)}else U?.dispose(),U=void 0}),W;if(!J.executeMode)W=new i71(process.cwd(),{},!0);else W=new class extends i71{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(h2.write(`No API key found. Starting login flow...
6423
6423
  `),!await nW9(J))await ew(),process.exit(1)}let H=await J40({isDevelopment:!1}),B=new SH1(H),M=new PH1(H,Z,{lazy:!0}),V=Q.notifications!==void 0?Q.notifications:!J.executeMode,N=u96({playNotificationSound:async(w)=>{if(V){m96(w);let R=nf1(),O=af1();if((!R||O)&&Y.settings["notifications.system.enabled"]!==!1){if(w==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(w==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:B,configService:Z});l.info("Starting Amp background services");let L=K40({threadService:B,threadHistoryService:M,configService:Z,isExtensionDevelopment:!1}),A={configService:Z,toolService:K,mcpService:q,threadService:B,threadHistoryService:M,threadSyncService:L,threadStorage:H,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:W,notificationService:N,fileSystem:Q.jetbrains||Q.ide?i20:T9};return{...A,async asyncDispose(){await A.mcpService.dispose(),await A.threadService.asyncDispose(),A.configService.unsubscribe(),A.toolService.dispose(),A.fuzzyServer.dispose(),A.threadSyncService.dispose(),A.settingsStorage[Symbol.dispose](),F.unsubscribe(),U?.dispose()}}}async function nW9(J){if(!J.executeMode){if(!await Ay1("Would you like to log in to Amp? [(y)es, (n)o]: "))return h2.write(`Login cancelled. Run the command again to retry.
6424
6424
  `),!1}return await dF6(J)}async function dF6(J){let Q=yW9(32).toString("hex"),Z=await Ly1(J.ampURL,Q);try{await dK(Z)}catch(Y){l.error("Failed to open browser",{error:Y})}let X=await Ly1(J.ampURL,Q,!1);h2.write(`If your browser did not open automatically, visit:
6425
6425
 
@@ -6429,12 +6429,12 @@ ${V8.blue.bold(X)}
6429
6429
  Login successful! You can now use the Amp CLI.
6430
6430
  `),!0}catch(Y){return l.error("Login failed",{error:Y}),n7.write(`
6431
6431
  Login failed: ${Y instanceof Error?Y.message:String(Y)}
6432
- `),!1}}function aW9(){let J=new X71().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((W)=>{if(W.code==="commander.help"||W.code==="commander.version"||W.exitCode===0)ZR(),process.exit(0);let H=W.originalError??W;cJ6(H)}),J.option("-V, --version","output the version number",()=>{h2.write(`0.0.1761062513-gf7c5f2 (released 2025-10-21T16:07:15.682Z)
6433
- `),process.exit(0)}),J.addHelpText("after",cQ6()),J.configureHelp({formatHelp:lQ6}),J.command("logout").description("Log out by removing stored API key").action(async(W,H)=>{let B=H.optsWithGlobals(),M=await HX(B);await tW9(M)}),J.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(W,H)=>{let B=H.optsWithGlobals(),M=await HX(B);await oW9(M,await qy1(B,M.settings))});let Q=async(W,H,B)=>{QX1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:e1.of([R0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:$u1,userConfigDir:pF6});let M={...H,executeMode:!1};await Ou1(M,{...W,startWithPicker:!0},B)},Z=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(W,H)=>{let B=H.optsWithGlobals(),M=await HX(B);await gF6(B,M,H)});Z.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(W,H)=>{let B=H.optsWithGlobals(),M=await HX(B);await KH9(B,M,H)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. If no thread ID is provided, the most recently used thread will be continued.").option("--pick","Pick a thread interactively from a list").action(async(W,H,B)=>{let M=B.optsWithGlobals(),V=await HX(M);if(H.pick)await Q(M,V,B);else await YH9(M,V,W,B)}),Z.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(W,H,B)=>{let M=B.optsWithGlobals(),V=await HX(M);await XH9(M,V,W,B)}),Z.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(W,H)=>{let B=H.optsWithGlobals(),M=await HX(B);await gF6(B,M,H)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(W,H,B)=>{let M=B.optsWithGlobals(),V=await HX(M);await ZH9(M,V,W,B,H.support)}),Z.command("compact <threadId>").alias("co").summary("Compact a thread").description("Compact a thread by creating a summary of the conversation history. This reduces the thread size while preserving the key information and context, making it more token efficient for future use.").action(async(W,H,B)=>{let M=B.optsWithGlobals(),V=await HX(M);await JH9(M,V,W,B)}),Z.command("markdown <threadId>").alias("md").summary("Render thread as markdown").description("Render a thread as markdown. This outputs the entire conversation history in a readable markdown format.").action(async(W,H,B)=>{let M=B.optsWithGlobals(),V=await HX(M);await QH9(M,V,W,B)}),nZ6(J,async(W,H)=>{let B=await HX(H);hG(W,H);let M=await gG(B,H);return{context:B,mcpService:M.mcpService,toolService:M.toolService,configService:M.configService,cleanupTerminal:ZR,asyncDispose:M.asyncDispose.bind(M)}}),OZ6(J),DZ6(J,async(W)=>{let H=await HX(W);return{settings:H.settings,getThreadDeps:async(B)=>{hG(B,W);let M=await gG(H,W);return{mcpService:M.mcpService,asyncDispose:M.asyncDispose.bind(M)}}}}),J.command("connect").description("Connect CLI to web interface for multi-thread management").action(async(W,H)=>{let B=H.optsWithGlobals(),M=await HX(B);hG(H,B);let V=await gG(M,B);try{await pb1(V,V.configService,{})}finally{await V.asyncDispose(),await ZR()}});let X=new X71().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(W)=>{await By1(W.force||!1,W.verbose||!1,"0.0.1761062513-gf7c5f2"),process.exit()});J.addCommand(X,{hidden:!0});function Y(W,H,B){let V=typeof W.description==="string"?W.description:B===void 0?W.description(!0):W.description(B),N=new fV(H,V),L=lW9(W);if(L)N.default(L);if(N.hidden=dW9(W)||hF6(W),"choices"in W)N.choices([...W.choices]);return N}for(let W of fF6)switch(W.type){case"flag":{J.addOption(Y(W,`--${W.long}`)),J.addOption(Y(W,`--no-${W.long}`,!1));break}case"switch":{J.addOption(Y(W,`--${W.long}`,!0));break}default:{J.addOption(Y(W,`--${W.long} <value>`));break}}let K=new fV("-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);J.addOption(K);let q=new fV("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(q);let G=new fV("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1);J.addOption(G);let z=new fV("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(z);let U=new fV("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(U),process.env.AMP_CONNECT==="1"){let W=new fV("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(W)}J.action(async(W,H)=>{let B=W,M=await HX(B);if(Object.keys(B).forEach((V)=>{let N=fF6.find((L)=>L.name===V);if(N&&hF6(N)&&!cW9(N))n7.write(V8.yellow(`Warning: '--${V}' flag is deprecated
6432
+ `),!1}}function aW9(){let J=new X71().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((W)=>{if(W.code==="commander.help"||W.code==="commander.version"||W.exitCode===0)ZR(),process.exit(0);let H=W.originalError??W;cJ6(H)}),J.option("-V, --version","output the version number",()=>{h2.write(`0.0.1761062777-g4520cb (released 2025-10-21T16:11:47.923Z)
6433
+ `),process.exit(0)}),J.addHelpText("after",cQ6()),J.configureHelp({formatHelp:lQ6}),J.command("logout").description("Log out by removing stored API key").action(async(W,H)=>{let B=H.optsWithGlobals(),M=await HX(B);await tW9(M)}),J.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(W,H)=>{let B=H.optsWithGlobals(),M=await HX(B);await oW9(M,await qy1(B,M.settings))});let Q=async(W,H,B)=>{QX1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:e1.of([R0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:$u1,userConfigDir:pF6});let M={...H,executeMode:!1};await Ou1(M,{...W,startWithPicker:!0},B)},Z=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(W,H)=>{let B=H.optsWithGlobals(),M=await HX(B);await gF6(B,M,H)});Z.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(W,H)=>{let B=H.optsWithGlobals(),M=await HX(B);await KH9(B,M,H)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. If no thread ID is provided, the most recently used thread will be continued.").option("--pick","Pick a thread interactively from a list").action(async(W,H,B)=>{let M=B.optsWithGlobals(),V=await HX(M);if(H.pick)await Q(M,V,B);else await YH9(M,V,W,B)}),Z.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(W,H,B)=>{let M=B.optsWithGlobals(),V=await HX(M);await XH9(M,V,W,B)}),Z.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(W,H)=>{let B=H.optsWithGlobals(),M=await HX(B);await gF6(B,M,H)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(W,H,B)=>{let M=B.optsWithGlobals(),V=await HX(M);await ZH9(M,V,W,B,H.support)}),Z.command("compact <threadId>").alias("co").summary("Compact a thread").description("Compact a thread by creating a summary of the conversation history. This reduces the thread size while preserving the key information and context, making it more token efficient for future use.").action(async(W,H,B)=>{let M=B.optsWithGlobals(),V=await HX(M);await JH9(M,V,W,B)}),Z.command("markdown <threadId>").alias("md").summary("Render thread as markdown").description("Render a thread as markdown. This outputs the entire conversation history in a readable markdown format.").action(async(W,H,B)=>{let M=B.optsWithGlobals(),V=await HX(M);await QH9(M,V,W,B)}),nZ6(J,async(W,H)=>{let B=await HX(H);hG(W,H);let M=await gG(B,H);return{context:B,mcpService:M.mcpService,toolService:M.toolService,configService:M.configService,cleanupTerminal:ZR,asyncDispose:M.asyncDispose.bind(M)}}),OZ6(J),DZ6(J,async(W)=>{let H=await HX(W);return{settings:H.settings,getThreadDeps:async(B)=>{hG(B,W);let M=await gG(H,W);return{mcpService:M.mcpService,asyncDispose:M.asyncDispose.bind(M)}}}}),J.command("connect").description("Connect CLI to web interface for multi-thread management").action(async(W,H)=>{let B=H.optsWithGlobals(),M=await HX(B);hG(H,B);let V=await gG(M,B);try{await pb1(V,V.configService,{})}finally{await V.asyncDispose(),await ZR()}});let X=new X71().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(W)=>{await By1(W.force||!1,W.verbose||!1,"0.0.1761062777-g4520cb"),process.exit()});J.addCommand(X,{hidden:!0});function Y(W,H,B){let V=typeof W.description==="string"?W.description:B===void 0?W.description(!0):W.description(B),N=new fV(H,V),L=lW9(W);if(L)N.default(L);if(N.hidden=dW9(W)||hF6(W),"choices"in W)N.choices([...W.choices]);return N}for(let W of fF6)switch(W.type){case"flag":{J.addOption(Y(W,`--${W.long}`)),J.addOption(Y(W,`--no-${W.long}`,!1));break}case"switch":{J.addOption(Y(W,`--${W.long}`,!0));break}default:{J.addOption(Y(W,`--${W.long} <value>`));break}}let K=new fV("-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);J.addOption(K);let q=new fV("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(q);let G=new fV("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1);J.addOption(G);let z=new fV("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(z);let U=new fV("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(U),process.env.AMP_CONNECT==="1"){let W=new fV("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(W)}J.action(async(W,H)=>{let B=W,M=await HX(B);if(Object.keys(B).forEach((V)=>{let N=fF6.find((L)=>L.name===V);if(N&&hF6(N)&&!cW9(N))n7.write(V8.yellow(`Warning: '--${V}' flag is deprecated
6434
6434
  `))}),H.args.length>0)iW9(M,H);await Ou1(M,B,H)});let F=new X71("update").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("--version <version>","Update to a specific version").allowUnknownOption(!1).action(async(W)=>{await eW9(W.version)});return J.addCommand(F),J}async function sJ1(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??Kq(),K=oJ1(J);if(Z)await J.threadStorage.set(Y,Z);let q=await UJ.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,X51(X));let G=J.threadService.observe(Y).subscribe(async(z)=>{if(r7(z,"assistant"))await ju1(Y),G.unsubscribe()});return await q.resume(),q}async function Ou1(J,Q,Z){let X=Z51(Q);if(X instanceof Error)aK(X.message);let Y,K=null;if(Q.streamJsonInput)Y="";else if(typeof Q.execute==="string"){Y=Q.execute;let R=(await Ry1()).trimEnd();if(R)K=R}else Y=(await Ry1()).trimEnd();if(Q.remote&&!J.executeMode)throw new u9("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new u9("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new u9("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new u9("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if((J.executeMode||Q.streamJson)&&Q.agentMode&&Q.agentMode!=="smart")throw new u9(`Execute mode is not permitted with --agent-mode '${Q.agentMode}'`,1);if(Q.stats&&!J.executeMode)throw new u9("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(Q.streamJsonInput&&typeof Q.execute==="string"&&Q.execute.trim()!=="")throw new u9("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"}]}}' | amp --execute --stream-json --stream-json-input`);if(J.executeMode&&Y===""&&!Q.streamJsonInput)throw new u9("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"
6435
6435
  Or pipe via stdin: echo "your message" | amp --execute`);hG(Z,Q);let q=await gG(J,Q);uF6=q;let G=oJ1(q),z=async(R)=>{let O=await mF6(R,"utf-8"),$=JSON.parse(O);if(!WF($.id))throw new u9(gK.invalidThreadId);return sJ1(q,{visibility:X,thread:$})},U=async(R)=>{if(!WF(R))throw new u9(gK.invalidThreadId);let O=await q.threadService.get(R)??void 0;if(l.info(`[fetchAndStartThread] Loaded thread ${R}, agentMode: ${O?.agentMode??"undefined"}`),O?.agentMode)l.info(`[fetchAndStartThread] Setting runtime override for agentMode to: ${O.agentMode}`),oG("experimental.agentMode",O.agentMode);else l.info("[fetchAndStartThread] No agentMode on thread, not setting override");return sJ1(q,{visibility:X,thread:O})},F=async()=>{try{if(Q.threadId)return U(Q.threadId);else return sJ1(q,{visibility:X})}catch(R){if(R instanceof u9)throw R;throw await h71(R,Q.threadId),Error("handleError should have called process.exit()")}},W=async()=>{return sJ1(q,{visibility:X})};if(Q.format==="jsonl")n7.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
6436
- `),await ew(),process.exit(1);if(J.executeMode&&Q.remote)await jZ6(Y,K,q.configService),await q.asyncDispose(),process.exit(0);let H=await F();if(J.executeMode)await XQ6(H,H.threadID,Y,K,q,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await q.asyncDispose(),process.exit(0);let B=!1,M=!1;if(Q.jetbrains||Q.ide){await Dr1();let R=await EO({jetbrainsOnly:Q.jetbrains});if(R.length===0){if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall")}else if(R.length===1){let O=R[0];if(O)v5.selectConfig(O)}else B=!0}let V=Vy1("0.0.1761062513-gf7c5f2",q.settingsStorage),N=e1.of([R0.file(process.cwd())]),L=JS(void 0,N);if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let A;try{A=await YJ.getUserFreeTierStatus({},{config:q.configService})}catch(R){A={ok:!1,error:R}}l.info("User free tier status:",A);let w=await PZ6();l.info("Loaded session state:",w),await yF6({stdout:process.stdout,history:new nb1,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadSyncService:q.threadSyncService,threadID:H.threadID,worker:H,workerDeps:G,configService:q.configService,internalAPIClient:YJ,ampURL:J.ampURL,startNewThread:W,pickAndContinueThread:async()=>{l.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:v5,connectedClientsService:new Zc,commandRegistry:L,showJetBrainsInstaller:M,showIdePicker:B,startWithPicker:Q.startWithPicker,updateService:V,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:w,freeTierStatus:A.ok?A.result:void 0}),await q.asyncDispose(),process.exit(0)}async function HX(J){if(J.interactive)n7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6437
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await cU({...J,getHook:process.env.AMP_URL?(q,G)=>{if(q==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let q=await MZ6(J.mcpConfig);X=pW9(X,q)}let Y=await X.get("url","global");if(!Y)Y=FZ;if(!AB(Y))l.info("Targeting custom Amp server",{ampURL:Y});if(X=Bl1(X),await X.get("debug.httpLogging"))Fl1();return{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:$Z6(await qy1(J,X))}}function rW9(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(G,z)=>z.toUpperCase()),q=J[Z+1];if(q&&!q.startsWith("--"))Q[K]=q,Z++}}return Q}async function sW9(){let J=rW9(process.argv);if(EJ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),mW9(l),l.info("Starting Amp CLI.",{version:"0.0.1761062513-gf7c5f2",buildTimestamp:"2025-10-21T16:07:15.682Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new u9(gK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await aW9().parseAsync(process.argv)}sW9().catch(h71);async function oW9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),h2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6436
+ `),await ew(),process.exit(1);if(J.executeMode&&Q.remote)await jZ6(Y,K,q.configService),await q.asyncDispose(),process.exit(0);let H=await F();if(J.executeMode)await XQ6(H,H.threadID,Y,K,q,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await q.asyncDispose(),process.exit(0);let B=!1,M=!1;if(Q.jetbrains||Q.ide){await Dr1();let R=await EO({jetbrainsOnly:Q.jetbrains});if(R.length===0){if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall")}else if(R.length===1){let O=R[0];if(O)v5.selectConfig(O)}else B=!0}let V=Vy1("0.0.1761062777-g4520cb",q.settingsStorage),N=e1.of([R0.file(process.cwd())]),L=JS(void 0,N);if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let A;try{A=await YJ.getUserFreeTierStatus({},{config:q.configService})}catch(R){A={ok:!1,error:R}}l.info("User free tier status:",A);let w=await PZ6();l.info("Loaded session state:",w),await yF6({stdout:process.stdout,history:new nb1,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadSyncService:q.threadSyncService,threadID:H.threadID,worker:H,workerDeps:G,configService:q.configService,internalAPIClient:YJ,ampURL:J.ampURL,startNewThread:W,pickAndContinueThread:async()=>{l.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:v5,connectedClientsService:new Zc,commandRegistry:L,showJetBrainsInstaller:M,showIdePicker:B,startWithPicker:Q.startWithPicker,updateService:V,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:w,freeTierStatus:A.ok?A.result:void 0}),await q.asyncDispose(),process.exit(0)}async function HX(J){if(J.interactive)n7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6437
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await cU({...J,getHook:process.env.AMP_URL?(q,G)=>{if(q==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let q=await MZ6(J.mcpConfig);X=pW9(X,q)}let Y=await X.get("url","global");if(!Y)Y=FZ;if(!AB(Y))l.info("Targeting custom Amp server",{ampURL:Y});if(X=Bl1(X),await X.get("debug.httpLogging"))Fl1();return{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:$Z6(await qy1(J,X))}}function rW9(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(G,z)=>z.toUpperCase()),q=J[Z+1];if(q&&!q.startsWith("--"))Q[K]=q,Z++}}return Q}async function sW9(){let J=rW9(process.argv);if(EJ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),mW9(l),l.info("Starting Amp CLI.",{version:"0.0.1761062777-g4520cb",buildTimestamp:"2025-10-21T16:11:47.923Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new u9(gK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await aW9().parseAsync(process.argv)}sW9().catch(h71);async function oW9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),h2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6438
6438
  `);else if(!AB(J.ampURL))h2.write(`Logging in to ${new URL(J.ampURL).hostname}
6439
6439
  `);let Z=process.env.AMP_API_KEY;if(Z)h2.write(`API key found in environment variable, storing...
6440
6440
  `),await Q.set("apiKey",Z,J.ampURL),h2.write(`API key successfully stored.
@@ -6450,7 +6450,7 @@ Or pipe via stdin: echo "your message" | amp --execute`);hG(Z,Q);let q=await gG(
6450
6450
  `));try{let Q;if(J)Q=J,n7.write(V8.blue(`Updating to version ${J}...
6451
6451
  `)),await GC(J),n7.write(V8.green(`✓ Successfully updated to version ${J}
6452
6452
  `));else{n7.write(V8.blue(`Checking for updates...
6453
- `));let{hasUpdate:X,latestVersion:Y}=await e41("0.0.1761062513-gf7c5f2");if(!X)n7.write(V8.green(`✓ Amp CLI is already up to date.
6453
+ `));let{hasUpdate:X,latestVersion:Y}=await e41("0.0.1761062777-g4520cb");if(!X)n7.write(V8.green(`✓ Amp CLI is already up to date.
6454
6454
  `)),process.exit(0);if(!Y)n7.write(V8.yellow("[WARN] could not find latest version")),process.exit(0);Q=Y,n7.write(V8.blue(`Updating to version ${Y}...
6455
6455
  `)),await GC(Y),n7.write(V8.green(`✓ Successfully updated to version ${Y}
6456
6456
  `))}let Z=await qR(Q);if(Z.warning)n7.write(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1761062513-gf7c5f2",
3
+ "version": "0.0.1761062777-g4520cb",
4
4
  "description": "CLI for Amp, an agentic coding tool built by Sourcegraph.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {