@sourcegraph/amp 0.0.1761171705-g6918a0 → 0.0.1761177703-gb6ee2a
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +8 -8
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -6210,7 +6210,7 @@ See https://ampcode.com/manual#toolboxes`);return Q[0]||lw}function eZ6(J,Q){let
|
|
|
6210
6210
|
`;async function XX6(J,Q,Z,X){let Y=performance.now(),K=[...Qx(tM1(J)),{role:"user",parts:[{text:r59.replace("{USER_GOAL}",Q)}]}],q=await k$(lr,K,[],J,Z,X,{responseMimeType:"application/json",responseJsonSchema:M0.toJSONSchema(ZX6)}),G=ZX6.parse(JSON.parse(q.message.text??"")),z=performance.now()-Y;return d.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}}BL();H8();k6();function YX6(J){let Q=J.trim();if(Q==="quit"||Q==="exit")return"/quit";return J}function KX6(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();aB();import s59 from"node:fs";import qX6 from"node:path";function GX6(J){let Q=J.trim().replace(/^["']|["']$/g,"");if(Q=Q.replace(/\\(.)/g,"$1"),!/\.(png|jpe?g|gif|webp)$/i.test(Q))return null;if(!qX6.isAbsolute(Q))return null;return d.debug("Extracted image path",{original:J,extracted:Q}),Q}function zX6(J){try{let Q=qX6.extname(J).toLowerCase(),Z=fe1(Q);if(!Z)return d.warn("Unsupported image file extension",{ext:Q}),null;try{let X=s59.readFileSync(J);return o59(X,Z)}catch(X){d.error(`Failed to read image file ${J}:`,X)}}catch(Q){d.error("Error handling image file path",{imagePath:J,error:Q})}return null}function o59(J,Q){if(J.length>EW)return d.warn(`Image file too large: ${J.length} bytes (max: ${EW})`),null;return{type:"image",source:{type:"base64",data:J.toString("base64"),mediaType:Q}}}import{execSync as _K6}from"node:child_process";import{rmdir as lY9}from"node:fs/promises";import{tmpdir as iY9}from"node:os";import xK6 from"node:path";oO();z0();import{spawn as t59}from"node:child_process";import{promises as e59}from"node:fs";function UX6(J){return J.kind==="executable"}function WX6(J){return J.kind==="markdown"}var lH=50000,FX6=300000;async function ky1(J,Q,Z,X={}){let{timeoutMs:Y=FX6,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(d.debug("Executing command",{commandName:J,filePath:q.filePath,args:Q}),WX6(q))return await JJ9(q,Q);else if(UX6(q))return await QJ9(q,Q,Y,K);else return{success:!1,output:"",error:"Unsupported command type"}}catch(q){return d.error("Failed to execute command",{commandName:J,error:q}),{success:!1,output:"",error:q instanceof Error?q.message:"Unknown error occurred"}}}async function JJ9(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await e59.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 QJ9(J,Q,Z=FX6,X){return new Promise((Y)=>{let[K,q]=ZJ9(J,Q);d.debug("Spawning command",{spawnCommand:K,spawnArgs:q.slice(0,10),filePath:J.filePath,timeoutMs:Z});let G=_e1(X),z=!1,U=setTimeout(()=>{z=!0,G.abort(),d.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),W=t59(K,q,{stdio:["pipe","pipe","pipe"],signal:G.signal,detached:!0}),F=[],H=[],B=0;W.stdout?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=lH)F.push(V);else{let N=lH-(B-V.length);if(N>0)F.push(V.slice(0,N))}}),W.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))}}),W.on("close",(M)=>{if(clearTimeout(U),z){Y({success:!1,output:F.join(""),error:`Command timed out after ${Z}ms`,exitCode:void 0});return}if(G.signal.aborted){Y({success:!1,output:F.join(""),error:"The command was aborted",exitCode:M??void 0});return}let V=M===0||M===1,N=F.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})}),W.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:F.join(""),error:V})})})}function ZJ9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return YJ9(Z,X?[...X]:null,Y,Q);else return XJ9(Z,X?[...X]:null,Y,Q)}function XJ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function YJ9(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();vj();F2();TB();vY();hW();k6();I0();import{mkdtemp as nY9,readFile as aY9,unlink as rY9,writeFile as _w2}from"fs/promises";var A51={};R6(A51,{scrollUp:()=>$J9,scrollDown:()=>EJ9,link:()=>vJ9,image:()=>kJ9,iTerm:()=>_J9,exitAlternativeScreen:()=>CJ9,eraseUp:()=>jJ9,eraseStartLine:()=>wJ9,eraseScreen:()=>_y1,eraseLines:()=>AJ9,eraseLine:()=>MX6,eraseEndLine:()=>RJ9,eraseDown:()=>OJ9,enterAlternativeScreen:()=>TJ9,cursorUp:()=>BX6,cursorTo:()=>GJ9,cursorShow:()=>LJ9,cursorSavePosition:()=>HJ9,cursorRestorePosition:()=>BJ9,cursorPrevLine:()=>VJ9,cursorNextLine:()=>MJ9,cursorMove:()=>zJ9,cursorLeft:()=>DX6,cursorHide:()=>NJ9,cursorGetPosition:()=>DJ9,cursorForward:()=>WJ9,cursorDown:()=>UJ9,cursorBackward:()=>FJ9,clearTerminal:()=>PJ9,clearScreen:()=>IJ9,beep:()=>SJ9});import xy1 from"node:process";var L51=globalThis.window?.document!==void 0,_A2=globalThis.process?.versions?.node!==void 0,xA2=globalThis.process?.versions?.bun!==void 0,bA2=globalThis.Deno?.version?.deno!==void 0,yA2=globalThis.process?.versions?.electron!==void 0,fA2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,hA2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,gA2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,mA2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,uA2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,mu=globalThis.navigator?.userAgentData?.platform,pA2=mu==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",dA2=mu==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",cA2=mu==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",lA2=mu==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),iA2=mu==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var A2="\x1B[",pu="\x1B]",DC="\x07",uu=";",HX6=!L51&&xy1.env.TERM_PROGRAM==="Apple_Terminal",KJ9=!L51&&xy1.platform==="win32",qJ9=L51?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:xy1.cwd,GJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return A2+(J+1)+"G";return A2+(Q+1)+uu+(J+1)+"H"},zJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=A2+-J+"D";else if(J>0)Z+=A2+J+"C";if(Q<0)Z+=A2+-Q+"A";else if(Q>0)Z+=A2+Q+"B";return Z},BX6=(J=1)=>A2+J+"A",UJ9=(J=1)=>A2+J+"B",WJ9=(J=1)=>A2+J+"C",FJ9=(J=1)=>A2+J+"D",DX6=A2+"G",HJ9=HX6?"\x1B7":A2+"s",BJ9=HX6?"\x1B8":A2+"u",DJ9=A2+"6n",MJ9=A2+"E",VJ9=A2+"F",NJ9=A2+"?25l",LJ9=A2+"?25h",AJ9=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=MX6+(Z<J-1?BX6():"");if(J)Q+=DX6;return Q},RJ9=A2+"K",wJ9=A2+"1K",MX6=A2+"2K",OJ9=A2+"J",jJ9=A2+"1J",_y1=A2+"2J",$J9=A2+"S",EJ9=A2+"T",IJ9="\x1Bc",PJ9=KJ9?`${_y1}${A2}0f`:`${_y1}${A2}3J${A2}H`,TJ9=A2+"?1049h",CJ9=A2+"?1049l",SJ9=DC,vJ9=(J,Q)=>[pu,"8",uu,uu,Q,DC,J,pu,"8",uu,uu,DC].join(""),kJ9=(J,Q={})=>{let Z=`${pu}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")+DC},_J9={setCwd:(J=qJ9())=>`${pu}50;CurrentDir=${J}${DC}`,annotation(J,Q={}){let Z=`${pu}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+DC}};var R51=x6(OX6(),1);function oV(J,Q,{target:Z="stdout",...X}={}){if(!R51.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (${Q})`}return A51.link(J,Q)}oV.isSupported=R51.default.stdout;oV.stderr=(J,Q,Z={})=>oV(J,Q,{target:"stderr",...Z});oV.stderr.isSupported=R51.default.stderr;z0();vY();class gy1{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.1761171705-g6918a0"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await qa(Q,this.configService)}catch(Q){d.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 O51}from"node:child_process";import{platform as my1}from"node:os";import{promisify as fJ9}from"node:util";var w51=fJ9(O51),hJ9=(J)=>`\x1B]52;c;${J}\x1B\\`,gJ9="\x1B]52;c;?\x1B\\",mJ9="\x1B]52;p;?\x1B\\";class jX6{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=O51("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=O51("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=O51("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(gJ9)}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(mJ9)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if(my1()==="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(my1()==="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=hJ9(Z);process.stdout.write(X);return}if(my1()==="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 BY=new jX6;z0();class j51 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}class l7{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function $X6(J){if(J instanceof j51)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof l7)return{title:"Info",description:J.message,type:"info"};return d.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 YN=null,sY9={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(YN)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(() => (rb1(),nJ6)),q=await K({worker:J.worker},J.configService,{clientId:J.clientId,onUserDisconnect:()=>{YN=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});YN=q,q.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((M)=>{YN=null,Z.sendStatus({connected:!1,errorMessage:M.message})});let z=(await J.configService.getLatest()).settings.url,U=J.worker.thread.id,W=new URL(`/threads/${U}`,z).toString(),F=new URL("/clients",z).toString(),H="";try{H=await(await Promise.resolve().then(() => x6(xf1(),1))).toString(W,{type:"utf8",margin:2,color:{dark:"#000000",light:"#FFFFFF"}})}catch(M){d.error("Failed to generate QR code:",M)}if((process.stdout.rows||24)>=30&&H&&J.onShowQRCodeOverlay)J.onShowQRCodeOverlay({url:F,qrCode:H});else return new l7(`Continue at ${F}`)}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(!YN)return new l7("Not connected to Amp web interface");try{YN.disconnect();let Z=YN.clientID;return YN=null,J.connectedClientsService.sendStatus({connected:!1,enabled:!1,errorMessage:void 0}),new l7(`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})}),W.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:F.join(""),error:V})})})}function ZJ9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return YJ9(Z,X?[...X]:null,Y,Q);else return XJ9(Z,X?[...X]:null,Y,Q)}function XJ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function YJ9(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();vj();F2();TB();vY();hW();k6();I0();import{mkdtemp as nY9,readFile as aY9,unlink as rY9,writeFile as _w2}from"fs/promises";var A51={};R6(A51,{scrollUp:()=>$J9,scrollDown:()=>EJ9,link:()=>vJ9,image:()=>kJ9,iTerm:()=>_J9,exitAlternativeScreen:()=>CJ9,eraseUp:()=>jJ9,eraseStartLine:()=>wJ9,eraseScreen:()=>_y1,eraseLines:()=>AJ9,eraseLine:()=>MX6,eraseEndLine:()=>RJ9,eraseDown:()=>OJ9,enterAlternativeScreen:()=>TJ9,cursorUp:()=>BX6,cursorTo:()=>GJ9,cursorShow:()=>LJ9,cursorSavePosition:()=>HJ9,cursorRestorePosition:()=>BJ9,cursorPrevLine:()=>VJ9,cursorNextLine:()=>MJ9,cursorMove:()=>zJ9,cursorLeft:()=>DX6,cursorHide:()=>NJ9,cursorGetPosition:()=>DJ9,cursorForward:()=>WJ9,cursorDown:()=>UJ9,cursorBackward:()=>FJ9,clearTerminal:()=>PJ9,clearScreen:()=>IJ9,beep:()=>SJ9});import xy1 from"node:process";var L51=globalThis.window?.document!==void 0,_A2=globalThis.process?.versions?.node!==void 0,xA2=globalThis.process?.versions?.bun!==void 0,bA2=globalThis.Deno?.version?.deno!==void 0,yA2=globalThis.process?.versions?.electron!==void 0,fA2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,hA2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,gA2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,mA2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,uA2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,mu=globalThis.navigator?.userAgentData?.platform,pA2=mu==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",dA2=mu==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",cA2=mu==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",lA2=mu==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),iA2=mu==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var A2="\x1B[",pu="\x1B]",DC="\x07",uu=";",HX6=!L51&&xy1.env.TERM_PROGRAM==="Apple_Terminal",KJ9=!L51&&xy1.platform==="win32",qJ9=L51?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:xy1.cwd,GJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return A2+(J+1)+"G";return A2+(Q+1)+uu+(J+1)+"H"},zJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=A2+-J+"D";else if(J>0)Z+=A2+J+"C";if(Q<0)Z+=A2+-Q+"A";else if(Q>0)Z+=A2+Q+"B";return Z},BX6=(J=1)=>A2+J+"A",UJ9=(J=1)=>A2+J+"B",WJ9=(J=1)=>A2+J+"C",FJ9=(J=1)=>A2+J+"D",DX6=A2+"G",HJ9=HX6?"\x1B7":A2+"s",BJ9=HX6?"\x1B8":A2+"u",DJ9=A2+"6n",MJ9=A2+"E",VJ9=A2+"F",NJ9=A2+"?25l",LJ9=A2+"?25h",AJ9=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=MX6+(Z<J-1?BX6():"");if(J)Q+=DX6;return Q},RJ9=A2+"K",wJ9=A2+"1K",MX6=A2+"2K",OJ9=A2+"J",jJ9=A2+"1J",_y1=A2+"2J",$J9=A2+"S",EJ9=A2+"T",IJ9="\x1Bc",PJ9=KJ9?`${_y1}${A2}0f`:`${_y1}${A2}3J${A2}H`,TJ9=A2+"?1049h",CJ9=A2+"?1049l",SJ9=DC,vJ9=(J,Q)=>[pu,"8",uu,uu,Q,DC,J,pu,"8",uu,uu,DC].join(""),kJ9=(J,Q={})=>{let Z=`${pu}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")+DC},_J9={setCwd:(J=qJ9())=>`${pu}50;CurrentDir=${J}${DC}`,annotation(J,Q={}){let Z=`${pu}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+DC}};var R51=x6(OX6(),1);function oV(J,Q,{target:Z="stdout",...X}={}){if(!R51.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (${Q})`}return A51.link(J,Q)}oV.isSupported=R51.default.stdout;oV.stderr=(J,Q,Z={})=>oV(J,Q,{target:"stderr",...Z});oV.stderr.isSupported=R51.default.stderr;z0();vY();class gy1{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.1761177703-gb6ee2a"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await qa(Q,this.configService)}catch(Q){d.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 O51}from"node:child_process";import{platform as my1}from"node:os";import{promisify as fJ9}from"node:util";var w51=fJ9(O51),hJ9=(J)=>`\x1B]52;c;${J}\x1B\\`,gJ9="\x1B]52;c;?\x1B\\",mJ9="\x1B]52;p;?\x1B\\";class jX6{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=O51("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=O51("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=O51("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(gJ9)}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(mJ9)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if(my1()==="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(my1()==="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=hJ9(Z);process.stdout.write(X);return}if(my1()==="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 BY=new jX6;z0();class j51 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}class l7{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function $X6(J){if(J instanceof j51)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof l7)return{title:"Info",description:J.message,type:"info"};return d.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 YN=null,sY9={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(YN)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(() => (rb1(),nJ6)),q=await K({worker:J.worker},J.configService,{clientId:J.clientId,onUserDisconnect:()=>{YN=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});YN=q,q.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((M)=>{YN=null,Z.sendStatus({connected:!1,errorMessage:M.message})});let z=(await J.configService.getLatest()).settings.url,U=J.worker.thread.id,W=new URL(`/threads/${U}`,z).toString(),F=new URL("/clients",z).toString(),H="";try{H=await(await Promise.resolve().then(() => x6(xf1(),1))).toString(W,{type:"utf8",margin:2,color:{dark:"#000000",light:"#FFFFFF"}})}catch(M){d.error("Failed to generate QR code:",M)}if((process.stdout.rows||24)>=30&&H&&J.onShowQRCodeOverlay)J.onShowQRCodeOverlay({url:F,qrCode:H});else return new l7(`Continue at ${F}`)}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(!YN)return new l7("Not connected to Amp web interface");try{YN.disconnect();let Z=YN.clientID;return YN=null,J.connectedClientsService.sendStatus({connected:!1,enabled:!1,errorMessage:void 0}),new l7(`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 bf1{configService;commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=KS(),Q){this.configService=Q;this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Z)=>this.latestCustom=Z),this.telemetrySubmitter=new gy1(async()=>{try{return(await this.configService.getLatest()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}},this.configService),this.configService.config.pipe(v0((Z)=>AB(Z.settings)),e6()).subscribe((Z)=>{this._initBaseCommands(Z.length>1)})}_initBaseCommands(J){if(this.commands={...oY9},process.env.AMP_CONNECT==="1")Object.assign(this.commands,sY9);if(J)Object.assign(this.commands,tY9)}async execute(J,Q,Z=[],X){this.telemetrySubmitter.submit(J).catch((G)=>{d.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 ky1(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 oY9={"generate-agent-file":{name:"generate-agent-file",description:`Generate an ${Y5} file in the current workspace`,execute:async(J,Q)=>{let Z=await J.configService.getLatest(),X=hq(Z.settings),K=J.getInMemoryAgentModeOverride()??X;J.worker.handle({type:"user:message",message:{content:[{type:"text",text:M90}],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 j51;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 nY9(xK6.join(iY9(),"amp-edit-")),Y=xK6.join(X,"message.amp.md");_K6(`${Z} "${Y}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let q=(await aY9(Y,"utf-8")).trim();if(q)J.editorDispatch({type:"set-input",input:q})}catch(K){if(K?.code==="ENOENT")return;return d.error("Failed to read temporary file",K),Error("Failed to read editor content")}try{await rY9(Y),await lY9(X)}catch(K){d.warn("Failed to clean up temporary file",K)}return}catch(Z){return d.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 tG("dangerouslyAllowAll",!1),new l7("Amp is now following permissions rules for this session")}catch(K){return d.error("Failed to set dangerously allow all setting",K),Error("Failed to enable permissions for this session")}case"off":try{return tG("dangerouslyAllowAll",!0),new l7("Permissions disabled for this session - you will NOT be asked for confirmation before Amp runs a command.")}catch(K){return d.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 HC();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 d.error("editPermissions exited with status",K),Error(X)},settingsFile:J.settingsFilePath,resolveEditor:HC};await M51(Y);return}catch(Y){d.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 d.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 l7(`Switched to existing thread: ${Z}`)}await J.pickAndContinueThread();return}catch(Z){return d.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=kj(new URL(Y),Z.id).toString(),G=`Thread URL: ${oV(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 l7(`${G}
|
|
@@ -6405,11 +6405,11 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
|
|
|
6405
6405
|
${G}
|
|
6406
6406
|
`:K}catch(Z){return d.error("Failed to prepare handoff",Z),`${J}
|
|
6407
6407
|
|
|
6408
|
-
(Note: AI handoff preparation failed, starting with your goal only)`}};switchToExistingThread=async(J)=>{try{d.info(`[switchToExistingThread] Switching to thread: ${J}`);let Q=await this.widget.dependencies.switchToThread(J),Z=Q.thread.agentMode??null;d.info(`[switchToExistingThread] Thread ${J} has agentMode: ${Z??"null"}`),this.widget.dependencies.worker=Q,this.widget.dependencies.threadID=Q.thread.id,nV(Q),c71()?.switchWorker(this.widget.dependencies.worker),this.setState(()=>{d.info(`[switchToExistingThread] Setting inMemoryAgentModeOverride to: ${Z??"null"}`),this.inMemoryAgentModeOverride=Z})}catch(Q){throw d.error("Failed to switch to thread:",J,Q),Error(`Failed to switch to thread: ${J}`)}};sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J)=>{this.cancelBashInvocations(),this.widget.dependencies.history.add(J);let Q=gK()||this.widget.dependencies.worker,Z=Q.thread.messages.length===0,X=this.getEffectiveAgentMode();if(Q.thread.agentMode&&!Z&&X!==Q.thread.agentMode){await this.showErrorMessage(`This thread uses ${Q.thread.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let Y=[{type:"text",text:J}];if(this.imageAttachments.length>0)Y.push(...this.imageAttachments);await Q.handle({type:"user:message",message:{content:Y,agentMode:this.getEffectiveAgentMode()}}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;let J=this.getEffectiveAgentMode();Iy1({agentMode:J}).catch((Q)=>{d.warn("Failed to save session state on exit:",Q)}).finally(()=>{T5.instance.stop()})}else{if(this.setState(()=>{this.isConfirmingExit=!0}),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout);this.exitConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingExit=!1}),this.exitConfirmTimeout=null},1000)}};toHomeRelative(J){let Q=yF9();if(J===Q)return"~";if(J.startsWith(Q+ip.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(ip.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(ip.sep),"…",Q.slice(-2).join(ip.sep)].join(ip.sep)}build(J){let Q=C8.of(J),Z=t6.of(J),X=Z.base;this.themeColors=X;let{colors:Y,app:K}=Z;this.themeApp=K;let G=(gK()||this.widget.dependencies.worker).thread.agentMode==="free"&&this.randomAd!==null,{threadState:z}=this.widget.dependencies;if(this.isShowingThreadPicker)return new GN({child:new Du1({onSelect:async(K1)=>{if(K1)this.isShowingThreadPicker=!1,this.setState(),await this.switchToExistingThread(K1);else process.exit(0)},pageSize:50,threadFetcher:new XQ1(this.widget.dependencies.configService)})});this.updateTerminalTitle(),this.updateProgressBar();let U=this.getCurrentConfirmation(),W=z.todosList,F=z.mainThread?.id,H=z.mainThread||void 0,M=this.isTranscriptEmpty()?new uJ1({agentMode:this.getEffectiveAgentMode()}):new hm1({key:F?new E5(`message-view-${F}`):void 0,items:z.items,subagentToolsByParentID:z.subagentToolsByParentID,controller:F?this.getMessageScrollController(F):new sU,autofocus:!1,onCopy:this._handleTextCopy.bind(this),thread:H,onMessageEditSubmit:this.handleMessageEditSubmit,onMessageRestoreSubmit:this.handleMessageRestoreSubmit,onMessageForkSubmit:this.forkMessage,focusNode:this.messageViewFocusNode,onDismissFocus:()=>{this.autocompleteFocusNode.requestFocus()}}),V=Math.max(Math.floor(Q.size.height*0.4),12),N=this.getCurrentEphemeralError(),L=this.buildBottomWidget(N,U,Y,Z,z,W,V,G?this.randomAd:null),A=Q.size.width<40,R=z.mainThread?pi1(z.mainThread):void 0,w=new zJ1({threadViewState:z.viewState,threadTokenUsage:R,threadID:F??null,thread:z.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onCostBreakdownClick:()=>{this.setState(()=>{this.isShowingCostBreakdownOverlay=!this.isShowingCostBreakdownOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,connectedClientsStatus:this.connectedClientsStatus,isNarrow:A,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!U,showingEphemeralError:Boolean(z.viewState.state==="active"&&z.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),O=new GJ1({bashInvocations:this.bashInvocations}),$=[],j=this.getEffectiveAgentMode(),E=this.currentShellModeStatus,I=ju1(j),T=!E?j.length+1:0,v=Q.capabilities.animationSupport,x=v==="disabled"?0:v==="slow"?30:60,h=j==="fast"?3:1,S=x>0&&this.agentModePulseSeq>0?new UZ({children:[L,new DX({top:0,left:1,right:1,height:1,child:new Wu1({color:I,trigger:this.agentModePulseSeq,fps:x,speed:h,leftOffset:T})})]}):L;if($.push(new I9({child:M}),O),G)$.push(new mm1({ad:this.randomAd,onButtonClick:async()=>{let K1=this.randomAd;if(this.lastAdImpressionId)Promise.resolve().then(() => (KQ1(),YQ1)).then(({recordAdEvent:z1})=>{let A1=this.widget.dependencies.worker.thread,D1=A1.messages[A1.messages.length-1];z1("clicked",{adId:K1.id,advertiserId:K1.advertiserId,threadId:A1.id,messageId:D1?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to"})});try{await _G(K1.shortDestinationUrl)}catch(z1){let D1=T5.instance.tuiInstance.clipboard.isOsc52Supported();this.setState(()=>{this.adActionModal={showCopyOption:D1,url:K1.shortDestinationUrl}})}}}));$.push(new N6({constraints:new j6(0,Q.size.width,0,V),child:S}),new V0({height:1,child:new u6({padding:u0.horizontal(1),child:w})}));let _=new o0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:$}),b=new W2(()=>{if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingCostBreakdownOverlay)return this.setState(()=>{this.isShowingCostBreakdownOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingQRCodeOverlay)return this.setState(()=>{this.isShowingQRCodeOverlay=!1,this.qrCodeOverlayData=null}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.clearActiveSelection())return"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.bashInvocations.length>0)return this.cancelBashInvocations(),"handled";if(this.executingCommand)return d.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.isProcessing())return this.markLastUserMessageAsInterrupted().catch((z1)=>{d.error("Failed to mark message as interrupted:",z1)}),this.cancelStreamingMessage().catch((z1)=>{d.error("Failed to cancel streaming message:",z1)}),"handled";if(this.textController.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return"ignored"}),g=new W2(()=>{return this.onExitPressed(),"handled"}),k=new W2(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),y=new W2(()=>{return mG.instance.toggleAll(),"handled"}),f=new W2(()=>{return this.widget.dependencies.configService.getLatest().then((K1)=>{tG("internal.showCost",!(K1.settings["internal.showCost"]??!0))}),"handled"}),m=new W2(()=>{return T5.instance.toggleFrameStatsOverlay(),"handled"}),n=new W2(()=>{return T5.instance.tuiInstance.getScreen().markForRefresh(),G7.instance.requestFrame(),"handled"}),u=new W2(()=>{return this.toggleAgentMode(),"handled"}),e=new W2(()=>{let K1=this.findElementByKey("message-view-selection-area");if(K1?.state){let z1=K1.state,A1=z1.controller?.copySelection();if(A1&&A1.length>0)return this.setState(()=>{this.showingSelectionCopiedHint=!0}),setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1})},2000),setTimeout(()=>{z1.controller.endCopyHighlight(),z1.controller.clear()},350),"handled"}return this.onExitPressed(),"handled"}),G1=new W2(()=>{let{threadState:K1}=this.widget.dependencies,z1=K1.mainThread?.id;if(z1){let A1=this.getMessageScrollController(z1),D1=Math.max(Math.floor(Q.size.height*0.4),10),p1=Q.size.height-D1;A1.animatePageUp(p1,100)}return"handled"}),W1=new W2(()=>{let{threadState:K1}=this.widget.dependencies,z1=K1.mainThread?.id;if(z1){let A1=this.getMessageScrollController(z1),D1=Math.max(Math.floor(Q.size.height*0.4),10),p1=Q.size.height-D1;A1.animatePageDown(p1,100)}return"handled"}),Z1=new W2(()=>{let{threadState:K1}=this.widget.dependencies,z1=K1.mainThread?.id;if(z1)this.getMessageScrollController(z1).animateTo(0,100);return"handled"}),F1=new W2(()=>{let{threadState:K1}=this.widget.dependencies,z1=K1.mainThread?.id;if(z1)this.getMessageScrollController(z1).animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),l=new W2(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";let{threadState:K1}=this.widget.dependencies;if(!K1.mainThread?.messages.some((A1)=>A1.role==="user"))return"ignored";return this.messageViewFocusNode.requestFocus(),"handled"}),p=new W2((K1)=>{if(K1.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),i=new Map([[g8.ctrl("c"),new TC],[g8.ctrl("l"),new Lp],[g8.alt("s"),new CC],[g8.ctrl("s"),new CC],[g8.alt("p"),new Np],[g8.ctrl("r"),new Mp],[g8.alt("d"),new Vp],[g8.key("PageUp"),new d51],[g8.key("PageDown"),new c51],[g8.key("Home"),new l51],[g8.key("End"),new i51],[g8.key("Escape"),new Bp],[g8.ctrl("p"),new SC("previous")],[g8.ctrl("n"),new SC("next")],[g8.key("Tab"),new n51]]);if(!1)i.set(g8.alt("c"),new Dp);if(process.platform==="darwin")i.set(g8.meta("c"),new TC);let o=new Map([[Bp,b],[u51,g],[Lp,n],[CC,u],[Dp,k],[Mp,y],[Vp,f],[Np,m],[TC,e],[d51,G1],[c51,W1],[l51,Z1],[i51,F1],[n51,l],[SC,p]]),X1=[_];if(this.isShowingConsoleOverlay)X1.push(new im1);if(this.isShowingHelp)X1.push(new rm1);if(this.adActionModal)X1.push(new um1({title:"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(K1)=>{let z1=this.adActionModal.url;if(K1==="copy")try{await T5.instance.tuiInstance.clipboard.writeText(z1),this.setState(()=>{this.displayMessage=new l7("Link copied to clipboard")})}catch(A1){d.error("Failed to copy to clipboard",{error:A1}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null})}}));if(this.isShowingFileChangesOverlay)X1.push(new nh1);if(this.isShowingCostBreakdownOverlay&&z.mainThread)X1.push(new nm1({thread:z.mainThread}));if(this.isShowingConfirmationOverlay)X1.push(new cm1({details:this.confirmationOverlayContent}));if(this.isShowingQRCodeOverlay&&this.qrCodeOverlayData)X1.push(new Hu1({url:this.qrCodeOverlayData.url,qrCode:this.qrCodeOverlayData.qrCode}));if(this.isShowingIdePicker)X1.push(new sm1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode}));let J1=new UZ({children:X1});if(this.isShowingJetBrainsInstaller)return new GN({child:new VY({actions:o,child:new tH({shortcuts:i,debugLabel:"jetbrains-installer-shortcuts",child:new Uu1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});let H1=new zN({onError:(K1)=>{this.showErrorMessage(K1.message)},child:J1});return new GN({child:new VY({actions:o,child:new tH({shortcuts:i,debugLabel:"main-app-shortcuts",child:H1})})})}buildBottomWidget(J,Q,Z,X,Y,K,q,G){if(J)return new am1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new lm1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new Fu1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let z=X.app,U=fF9(X),W=this.isInRestrictedFreeMode(),F=new o51({key:this.textFieldKey,controller:this.textController,triggers:[Nu1()],optionsBuilder:this.buildOptions,onSelected:this.onOptionSelected,displayStringForOption:(v)=>pm1(v),overlayBorderColor:Z.border,focusNode:this.autocompleteFocusNode,textFieldProps:{placeholder:W?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,wrap:!0,minLines:3,maxLines:null,expands:!0,autofocus:!1,enabled:this.isTextfieldAndAutocompleteFocused&&!W,onSubmitted:this.onTextSubmitted,onOpenInEditor:this.onOpenInEditor,submitKey:{character:"Enter"},prompts:U,style:{border:null},clipboard:T5.instance.tuiInstance.clipboard},optionViewBuilder:(v,x,h)=>{let S=h?Z.selection:void 0,_=x.type==="command"?Z.warning:Z.secondary,b=Z.foreground,g=Z.foreground,k,y;switch(x.type){case"command":k="/",y=x.name;break;case"file":k="@",y=x.path;break;case"thread":k="",y=x.title;break;default:k="",y=pm1(x);break}let f=hU6(x),m=new R1(k,new S1({color:_})),n=new R1(y,new S1({color:b})),u=[m,n];if(f){let e=new R1(" - ",new S1({color:g,dim:!0})),G1=new R1(f,new S1({color:g,dim:!0}));u.push(e,G1)}return new N6({decoration:new Q9(S),child:new o1({text:new R1("",void 0,u),maxLines:1,overflow:"ellipsis"})})}}),H=Y.mainThread?.queuedMessages??[],B=this.currentShellModeStatus,M=this.imageAttachments.length>0?new N6({padding:u0.only({bottom:1,left:1}),child:new o1({text:new R1("",void 0,[new R1("Images: ",new S1({color:Z.foreground,dim:!0})),...this.imageAttachments.flatMap((v,x)=>[new R1(`[image ${x+1}]`,new S1({color:Z.success})),...x<this.imageAttachments.length-1?[new R1(" ")]:[]])])})}):null,V=Array.isArray(K)&&K.length>0,N=Array.isArray(H)&&H.length>0,L=[];if(M)L.push(M);L.push(new I9({child:F}));let A=new o0({crossAxisAlignment:"start",children:L}),R=N?new Bu1({queuedMessages:H}):void 0,w=V?new Yh1(new gm1({todos:K,enabled:this.isTextfieldAndAutocompleteFocused&&!W}),{clipBehavior:"antiAlias"}):void 0,O=[];if(B)O.push({text:new R1(B==="hidden"?"shell mode (incognito)":"shell mode",new S1({color:B==="hidden"?X.app.shellModeHidden:X.app.shellMode})),position:"top-left",offsetY:M?1:0});let $=this.getEffectiveAgentMode();if(!B&&this.cachedVisibleModes.length>1){let v=ju1($),h=ud($,this.cachedVisibleModes)!==$,_=(gK()||this.widget.dependencies.worker).thread.messages.length===0,g=W||!this.hasToggledAgentMode&&h&&_?new R1("",void 0,[new R1($,new S1({color:v})),new R1(" (click or ",new S1({color:Z.foreground,dim:!0})),new R1("Ctrl+S",new S1({color:z.keybind})),new R1(" to switch)",new S1({color:Z.foreground,dim:!0}))]):new R1($,new S1({color:v}));O.push({text:g,position:"top-left",offsetY:0,onClick:_?this.toggleAgentMode:void 0})}let j=Y.mainThread?.metadata?.treeInfo?.uri,E;if(j)E=L0.isUri(j)?j.fsPath:j;else E=process.cwd();let I=this.toHomeRelative(E),T=this.shorten(I);return O.push({text:new R1(T,new S1({color:Z.foreground,dim:!0})),position:"bottom-right"}),new fh1({leftChild:A,rightChild1:R,rightChild2:w,maxHeight:q,overlayTexts:O,borderColor:W||!this.isTextfieldAndAutocompleteFocused?k1.index(8):void 0,hasBanner:G!==null})}}async function hW6(J){let X=new iH(!1,1000,J.inspectorPort),Y=new lb1({threadService:J.threadService,worker:J.worker,builder:(H,B)=>{let M=gK(),V=M?.thread.id||J.threadID,N={...J,worker:M||J.worker,threadID:V};return new yW6({...N,threadState:B})}}),K=new dh1({configService:J.configService,child:Y}),q=new mh1({configService:J.configService,child:K}),G=new o6({data:oH.default(),child:q}),z=new t6({data:xC.fromBaseTheme(oH.default()),child:G});try{await Zh1(z,{onRootElementMounted:void 0})}finally{}let W=gK()?.thread.id||J.threadID;if((await J.threadService.get(W))?.messages.length!==0){let H=`${J.ampURL.replace(/\/$/,"")}/threads/${W}`;J.stdout.write(`
|
|
6408
|
+
(Note: AI handoff preparation failed, starting with your goal only)`}};switchToExistingThread=async(J)=>{try{d.info(`[switchToExistingThread] Switching to thread: ${J}`);let Q=await this.widget.dependencies.switchToThread(J),Z=Q.thread.agentMode??null;d.info(`[switchToExistingThread] Thread ${J} has agentMode: ${Z??"null"}`),this.widget.dependencies.worker=Q,this.widget.dependencies.threadID=Q.thread.id,nV(Q),c71()?.switchWorker(this.widget.dependencies.worker),this.setState(()=>{d.info(`[switchToExistingThread] Setting inMemoryAgentModeOverride to: ${Z??"null"}`),this.inMemoryAgentModeOverride=Z})}catch(Q){throw d.error("Failed to switch to thread:",J,Q),Error(`Failed to switch to thread: ${J}`)}};sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J)=>{this.cancelBashInvocations(),this.widget.dependencies.history.add(J);let Q=gK()||this.widget.dependencies.worker,Z=Q.thread.messages.length===0,X=this.getEffectiveAgentMode();if(Q.thread.agentMode&&!Z&&X!==Q.thread.agentMode){await this.showErrorMessage(`This thread uses ${Q.thread.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let Y=[{type:"text",text:J}];if(this.imageAttachments.length>0)Y.push(...this.imageAttachments);await Q.handle({type:"user:message",message:{content:Y,agentMode:this.getEffectiveAgentMode()}}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;let J=this.getEffectiveAgentMode();Iy1({agentMode:J}).catch((Q)=>{d.warn("Failed to save session state on exit:",Q)}).finally(()=>{T5.instance.stop()})}else{if(this.setState(()=>{this.isConfirmingExit=!0}),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout);this.exitConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingExit=!1}),this.exitConfirmTimeout=null},1000)}};toHomeRelative(J){let Q=yF9();if(J===Q)return"~";if(J.startsWith(Q+ip.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(ip.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(ip.sep),"…",Q.slice(-2).join(ip.sep)].join(ip.sep)}build(J){let Q=C8.of(J),Z=t6.of(J),X=Z.base;this.themeColors=X;let{colors:Y,app:K}=Z;this.themeApp=K;let G=(gK()||this.widget.dependencies.worker).thread.agentMode==="free"&&this.randomAd!==null,{threadState:z}=this.widget.dependencies;if(this.isShowingThreadPicker)return new GN({child:new Du1({onSelect:async(K1)=>{if(K1)this.isShowingThreadPicker=!1,this.setState(),await this.switchToExistingThread(K1);else process.exit(0)},pageSize:50,threadFetcher:new XQ1(this.widget.dependencies.configService)})});this.updateTerminalTitle(),this.updateProgressBar();let U=this.getCurrentConfirmation(),W=z.todosList,F=z.mainThread?.id,H=z.mainThread||void 0,M=this.isTranscriptEmpty()?new uJ1({agentMode:this.getEffectiveAgentMode()}):new hm1({key:F?new E5(`message-view-${F}`):void 0,items:z.items,subagentToolsByParentID:z.subagentToolsByParentID,controller:F?this.getMessageScrollController(F):new sU,autofocus:!1,onCopy:this._handleTextCopy.bind(this),thread:H,onMessageEditSubmit:this.handleMessageEditSubmit,onMessageRestoreSubmit:this.handleMessageRestoreSubmit,onMessageForkSubmit:this.forkMessage,focusNode:this.messageViewFocusNode,onDismissFocus:()=>{if(!this.getCurrentConfirmation())this.autocompleteFocusNode.requestFocus()}}),V=Math.max(Math.floor(Q.size.height*0.4),12),N=this.getCurrentEphemeralError(),L=this.buildBottomWidget(N,U,Y,Z,z,W,V,G?this.randomAd:null),A=Q.size.width<40,R=z.mainThread?pi1(z.mainThread):void 0,w=new zJ1({threadViewState:z.viewState,threadTokenUsage:R,threadID:F??null,thread:z.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onCostBreakdownClick:()=>{this.setState(()=>{this.isShowingCostBreakdownOverlay=!this.isShowingCostBreakdownOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,connectedClientsStatus:this.connectedClientsStatus,isNarrow:A,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!U,showingEphemeralError:Boolean(z.viewState.state==="active"&&z.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),O=new GJ1({bashInvocations:this.bashInvocations}),$=[],j=this.getEffectiveAgentMode(),E=this.currentShellModeStatus,I=ju1(j),T=!E?j.length+1:0,v=Q.capabilities.animationSupport,x=v==="disabled"?0:v==="slow"?30:60,h=j==="fast"?3:1,S=x>0&&this.agentModePulseSeq>0?new UZ({children:[L,new DX({top:0,left:1,right:1,height:1,child:new Wu1({color:I,trigger:this.agentModePulseSeq,fps:x,speed:h,leftOffset:T})})]}):L;if($.push(new I9({child:M}),O),G)$.push(new mm1({ad:this.randomAd,onButtonClick:async()=>{let K1=this.randomAd;if(this.lastAdImpressionId)Promise.resolve().then(() => (KQ1(),YQ1)).then(({recordAdEvent:z1})=>{let A1=this.widget.dependencies.worker.thread,D1=A1.messages[A1.messages.length-1];z1("clicked",{adId:K1.id,advertiserId:K1.advertiserId,threadId:A1.id,messageId:D1?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to"})});try{await _G(K1.shortDestinationUrl)}catch(z1){let D1=T5.instance.tuiInstance.clipboard.isOsc52Supported();this.setState(()=>{this.adActionModal={showCopyOption:D1,url:K1.shortDestinationUrl}})}}}));$.push(new N6({constraints:new j6(0,Q.size.width,0,V),child:S}),new V0({height:1,child:new u6({padding:u0.horizontal(1),child:w})}));let _=new o0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:$}),b=new W2(()=>{if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingCostBreakdownOverlay)return this.setState(()=>{this.isShowingCostBreakdownOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingQRCodeOverlay)return this.setState(()=>{this.isShowingQRCodeOverlay=!1,this.qrCodeOverlayData=null}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.clearActiveSelection())return"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.bashInvocations.length>0)return this.cancelBashInvocations(),"handled";if(this.executingCommand)return d.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.isProcessing())return this.markLastUserMessageAsInterrupted().catch((z1)=>{d.error("Failed to mark message as interrupted:",z1)}),this.cancelStreamingMessage().catch((z1)=>{d.error("Failed to cancel streaming message:",z1)}),"handled";if(this.textController.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return"ignored"}),g=new W2(()=>{return this.onExitPressed(),"handled"}),k=new W2(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),y=new W2(()=>{return mG.instance.toggleAll(),"handled"}),f=new W2(()=>{return this.widget.dependencies.configService.getLatest().then((K1)=>{tG("internal.showCost",!(K1.settings["internal.showCost"]??!0))}),"handled"}),m=new W2(()=>{return T5.instance.toggleFrameStatsOverlay(),"handled"}),n=new W2(()=>{return T5.instance.tuiInstance.getScreen().markForRefresh(),G7.instance.requestFrame(),"handled"}),u=new W2(()=>{return this.toggleAgentMode(),"handled"}),e=new W2(()=>{let K1=this.findElementByKey("message-view-selection-area");if(K1?.state){let z1=K1.state,A1=z1.controller?.copySelection();if(A1&&A1.length>0)return this.setState(()=>{this.showingSelectionCopiedHint=!0}),setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1})},2000),setTimeout(()=>{z1.controller.endCopyHighlight(),z1.controller.clear()},350),"handled"}return this.onExitPressed(),"handled"}),G1=new W2(()=>{let{threadState:K1}=this.widget.dependencies,z1=K1.mainThread?.id;if(z1){let A1=this.getMessageScrollController(z1),D1=Math.max(Math.floor(Q.size.height*0.4),10),p1=Q.size.height-D1;A1.animatePageUp(p1,100)}return"handled"}),W1=new W2(()=>{let{threadState:K1}=this.widget.dependencies,z1=K1.mainThread?.id;if(z1){let A1=this.getMessageScrollController(z1),D1=Math.max(Math.floor(Q.size.height*0.4),10),p1=Q.size.height-D1;A1.animatePageDown(p1,100)}return"handled"}),Z1=new W2(()=>{let{threadState:K1}=this.widget.dependencies,z1=K1.mainThread?.id;if(z1)this.getMessageScrollController(z1).animateTo(0,100);return"handled"}),F1=new W2(()=>{let{threadState:K1}=this.widget.dependencies,z1=K1.mainThread?.id;if(z1)this.getMessageScrollController(z1).animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),l=new W2(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";let{threadState:K1}=this.widget.dependencies;if(!K1.mainThread?.messages.some((A1)=>A1.role==="user"))return"ignored";return this.messageViewFocusNode.requestFocus(),"handled"}),p=new W2((K1)=>{if(K1.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),i=new Map([[g8.ctrl("c"),new TC],[g8.ctrl("l"),new Lp],[g8.alt("s"),new CC],[g8.ctrl("s"),new CC],[g8.alt("p"),new Np],[g8.ctrl("r"),new Mp],[g8.alt("d"),new Vp],[g8.key("PageUp"),new d51],[g8.key("PageDown"),new c51],[g8.key("Home"),new l51],[g8.key("End"),new i51],[g8.key("Escape"),new Bp],[g8.ctrl("p"),new SC("previous")],[g8.ctrl("n"),new SC("next")],[g8.key("Tab"),new n51]]);if(!1)i.set(g8.alt("c"),new Dp);if(process.platform==="darwin")i.set(g8.meta("c"),new TC);let o=new Map([[Bp,b],[u51,g],[Lp,n],[CC,u],[Dp,k],[Mp,y],[Vp,f],[Np,m],[TC,e],[d51,G1],[c51,W1],[l51,Z1],[i51,F1],[n51,l],[SC,p]]),X1=[_];if(this.isShowingConsoleOverlay)X1.push(new im1);if(this.isShowingHelp)X1.push(new rm1);if(this.adActionModal)X1.push(new um1({title:"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(K1)=>{let z1=this.adActionModal.url;if(K1==="copy")try{await T5.instance.tuiInstance.clipboard.writeText(z1),this.setState(()=>{this.displayMessage=new l7("Link copied to clipboard")})}catch(A1){d.error("Failed to copy to clipboard",{error:A1}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null})}}));if(this.isShowingFileChangesOverlay)X1.push(new nh1);if(this.isShowingCostBreakdownOverlay&&z.mainThread)X1.push(new nm1({thread:z.mainThread}));if(this.isShowingConfirmationOverlay)X1.push(new cm1({details:this.confirmationOverlayContent}));if(this.isShowingQRCodeOverlay&&this.qrCodeOverlayData)X1.push(new Hu1({url:this.qrCodeOverlayData.url,qrCode:this.qrCodeOverlayData.qrCode}));if(this.isShowingIdePicker)X1.push(new sm1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode}));let J1=new UZ({children:X1});if(this.isShowingJetBrainsInstaller)return new GN({child:new VY({actions:o,child:new tH({shortcuts:i,debugLabel:"jetbrains-installer-shortcuts",child:new Uu1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});let H1=new zN({onError:(K1)=>{this.showErrorMessage(K1.message)},child:J1});return new GN({child:new VY({actions:o,child:new tH({shortcuts:i,debugLabel:"main-app-shortcuts",child:H1})})})}buildBottomWidget(J,Q,Z,X,Y,K,q,G){if(J)return new am1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new lm1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new Fu1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let z=X.app,U=fF9(X),W=this.isInRestrictedFreeMode(),F=new o51({key:this.textFieldKey,controller:this.textController,triggers:[Nu1()],optionsBuilder:this.buildOptions,onSelected:this.onOptionSelected,displayStringForOption:(v)=>pm1(v),overlayBorderColor:Z.border,focusNode:this.autocompleteFocusNode,textFieldProps:{placeholder:W?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,wrap:!0,minLines:3,maxLines:null,expands:!0,autofocus:!1,enabled:this.isTextfieldAndAutocompleteFocused&&!W,onSubmitted:this.onTextSubmitted,onOpenInEditor:this.onOpenInEditor,submitKey:{character:"Enter"},prompts:U,style:{border:null},clipboard:T5.instance.tuiInstance.clipboard},optionViewBuilder:(v,x,h)=>{let S=h?Z.selection:void 0,_=x.type==="command"?Z.warning:Z.secondary,b=Z.foreground,g=Z.foreground,k,y;switch(x.type){case"command":k="/",y=x.name;break;case"file":k="@",y=x.path;break;case"thread":k="",y=x.title;break;default:k="",y=pm1(x);break}let f=hU6(x),m=new R1(k,new S1({color:_})),n=new R1(y,new S1({color:b})),u=[m,n];if(f){let e=new R1(" - ",new S1({color:g,dim:!0})),G1=new R1(f,new S1({color:g,dim:!0}));u.push(e,G1)}return new N6({decoration:new Q9(S),child:new o1({text:new R1("",void 0,u),maxLines:1,overflow:"ellipsis"})})}}),H=Y.mainThread?.queuedMessages??[],B=this.currentShellModeStatus,M=this.imageAttachments.length>0?new N6({padding:u0.only({bottom:1,left:1}),child:new o1({text:new R1("",void 0,[new R1("Images: ",new S1({color:Z.foreground,dim:!0})),...this.imageAttachments.flatMap((v,x)=>[new R1(`[image ${x+1}]`,new S1({color:Z.success})),...x<this.imageAttachments.length-1?[new R1(" ")]:[]])])})}):null,V=Array.isArray(K)&&K.length>0,N=Array.isArray(H)&&H.length>0,L=[];if(M)L.push(M);L.push(new I9({child:F}));let A=new o0({crossAxisAlignment:"start",children:L}),R=N?new Bu1({queuedMessages:H}):void 0,w=V?new Yh1(new gm1({todos:K,enabled:this.isTextfieldAndAutocompleteFocused&&!W}),{clipBehavior:"antiAlias"}):void 0,O=[];if(B)O.push({text:new R1(B==="hidden"?"shell mode (incognito)":"shell mode",new S1({color:B==="hidden"?X.app.shellModeHidden:X.app.shellMode})),position:"top-left",offsetY:M?1:0});let $=this.getEffectiveAgentMode();if(!B&&this.cachedVisibleModes.length>1){let v=ju1($),h=ud($,this.cachedVisibleModes)!==$,_=(gK()||this.widget.dependencies.worker).thread.messages.length===0,g=W||!this.hasToggledAgentMode&&h&&_?new R1("",void 0,[new R1($,new S1({color:v})),new R1(" (click or ",new S1({color:Z.foreground,dim:!0})),new R1("Ctrl+S",new S1({color:z.keybind})),new R1(" to switch)",new S1({color:Z.foreground,dim:!0}))]):new R1($,new S1({color:v}));O.push({text:g,position:"top-left",offsetY:0,onClick:_?this.toggleAgentMode:void 0})}let j=Y.mainThread?.metadata?.treeInfo?.uri,E;if(j)E=L0.isUri(j)?j.fsPath:j;else E=process.cwd();let I=this.toHomeRelative(E),T=this.shorten(I);return O.push({text:new R1(T,new S1({color:Z.foreground,dim:!0})),position:"bottom-right"}),new fh1({leftChild:A,rightChild1:R,rightChild2:w,maxHeight:q,overlayTexts:O,borderColor:W||!this.isTextfieldAndAutocompleteFocused?k1.index(8):void 0,hasBanner:G!==null})}}async function hW6(J){let X=new iH(!1,1000,J.inspectorPort),Y=new lb1({threadService:J.threadService,worker:J.worker,builder:(H,B)=>{let M=gK(),V=M?.thread.id||J.threadID,N={...J,worker:M||J.worker,threadID:V};return new yW6({...N,threadState:B})}}),K=new dh1({configService:J.configService,child:Y}),q=new mh1({configService:J.configService,child:K}),G=new o6({data:oH.default(),child:q}),z=new t6({data:xC.fromBaseTheme(oH.default()),child:G});try{await Zh1(z,{onRootElementMounted:void 0})}finally{}let W=gK()?.thread.id||J.threadID;if((await J.threadService.get(W))?.messages.length!==0){let H=`${J.ampURL.replace(/\/$/,"")}/threads/${W}`;J.stdout.write(`
|
|
6409
6409
|
`),J.stdout.write(`Thread: ${H}
|
|
6410
6410
|
`),J.stdout.write(`Continue this thread with: amp threads continue ${W}
|
|
6411
6411
|
`)}}function ju1(J){return J==="smart"?k1.rgb(3,197,97):J==="fast"?k1.rgb(228,180,2):J==="free"?k1.rgb(0,184,255):hF9(J)}function hF9(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])}Qh1();if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){a7.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
6412
|
-
`)}var Eu1=$u1.join(oc1||$u1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function dF9(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 aK(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")tG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new m9("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${D8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")tG("experimental.agentMode",Q.agentMode)}async function Pu1(J){try{await mF9($u1.dirname(Eu1),{recursive:!0}),await uF9(Eu1,J,"utf-8")}catch(Q){d.debug("Failed to save last thread ID",Q)}}async function cF9(){try{return(await pW6(Eu1,"utf-8")).trim()}catch(J){return null}}function lF9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return ol1("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 gW6=[{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??uK,description:`Custom settings file path (overrides the default location ${uK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(d).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${hb1})`},{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:pK(),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:gd}],mW6=(J)=>("deprecated"in J)&&J.deprecated===!0,iF9=(J)=>("hidden"in J)&&J.hidden===!0,nF9=(J)=>("default"in J),aF9=(J)=>("default"in J)?J.default:void 0;function rF9(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 m9(mK.unknownCommand(Z),1,q)}}var dW6=null;function ct2(){return dW6}function np(J){return{...J,getThreadEnvironment:u71,vfs:X40({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new w_(J.fileSystem),generateThreadTitle:LG0,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var Tu1=L0.file(pF9.homedir()),cW6=process.env.XDG_CONFIG_HOME?L0.file(process.env.XDG_CONFIG_HOME):_0.joinPath(Tu1,".config");async function rK(J,Q){Qn1("0.0.
|
|
6412
|
+
`)}var Eu1=$u1.join(oc1||$u1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function dF9(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 aK(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")tG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new m9("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${D8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")tG("experimental.agentMode",Q.agentMode)}async function Pu1(J){try{await mF9($u1.dirname(Eu1),{recursive:!0}),await uF9(Eu1,J,"utf-8")}catch(Q){d.debug("Failed to save last thread ID",Q)}}async function cF9(){try{return(await pW6(Eu1,"utf-8")).trim()}catch(J){return null}}function lF9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return ol1("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 gW6=[{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??uK,description:`Custom settings file path (overrides the default location ${uK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(d).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${hb1})`},{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:pK(),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:gd}],mW6=(J)=>("deprecated"in J)&&J.deprecated===!0,iF9=(J)=>("hidden"in J)&&J.hidden===!0,nF9=(J)=>("default"in J),aF9=(J)=>("default"in J)?J.default:void 0;function rF9(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 m9(mK.unknownCommand(Z),1,q)}}var dW6=null;function ct2(){return dW6}function np(J){return{...J,getThreadEnvironment:u71,vfs:X40({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new w_(J.fileSystem),generateThreadTitle:LG0,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var Tu1=L0.file(pF9.homedir()),cW6=process.env.XDG_CONFIG_HOME?L0.file(process.env.XDG_CONFIG_HOME):_0.joinPath(Tu1,".config");async function rK(J,Q){Qn1("0.0.1761177703-gb6ee2a");let Z=zX1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:t1.of([L0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:Tu1,userConfigDir:cW6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (KQ1(),YQ1));X(Z);let Y=await Z.getLatest();d.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let K=ja(HO({configService:Z})),q=_20({configService:Z,toolService:K}),G=gw0(K,C9,re).catch((O)=>{d.warn("Toolbox registration failed, continuing anyway:",O)}),z=q.initialized.catch((O)=>{d.warn("MCP service initialization failed, continuing anyway:",O)});if(J.executeMode)await Promise.all([z,G]);if(Q.jetbrains)MO("JetBrains");else if(Q.ide&&eQ6())MO("VS Code");else if(Q.ide&&JZ6())MO("Neovim");if(J.executeMode)Zn1(!0);l96(K,{configService:Z});let U,W=W7.status.pipe(v0((O)=>Boolean(O.connected&&O.authenticated)),e6()).subscribe((O)=>{if(O){if(!U)U=K.registerTool(Vs)}else U?.dispose(),U=void 0}),F;if(!J.executeMode)F=new Q51(process.cwd(),{},!0);else F=new class extends Q51{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(x2.write(`No API key found. Starting login flow...
|
|
6413
6413
|
`),!await sF9(J))await Zw(),process.exit(1)}let H=await z40({isDevelopment:!1}),B=new fH1(H),M=new bH1(H,Z,{lazy:!0}),V=Q.notifications!==void 0?Q.notifications:!J.executeMode,N=n96({playNotificationSound:async(O)=>{if(V){i96(O);let $=ef1(),j=Jh1();if((!$||j)&&Y.settings["notifications.system.enabled"]!==!1){if(O==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(O==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:B,configService:Z});d.info("Starting Amp background services");let L=H40({threadService:B,threadHistoryService:M,configService:Z,isExtensionDevelopment:!1}),A;W7.status.subscribe((O)=>{A=O});let w={codebaseContextService:new KZ1({workspaceRoots:[L0.file(process.cwd())],getCurrentFile:()=>{if(!A?.openFile)return;try{return L0.parse(A.openFile)}catch(O){d.warn("Failed to parse current file URI",{uri:A.openFile,error:O});return}},getOpenFiles:()=>{if(!A?.visibleFiles?.length)return[];let O=A.openFile;return A.visibleFiles.filter(($)=>$!==O).map(($)=>{try{return L0.parse($)}catch(j){return d.warn("Failed to parse visible file URI",{uri:$,error:j}),null}}).filter(($)=>$!==null)}}),configService:Z,toolService:K,mcpService:q,threadService:B,threadHistoryService:M,threadSyncService:L,threadStorage:H,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:F,notificationService:N,fileSystem:Q.jetbrains||Q.ide?J40:C9};return{...w,async asyncDispose(){await w.mcpService.dispose(),await w.threadService.asyncDispose(),w.configService.unsubscribe(),w.toolService.dispose(),w.fuzzyServer.dispose(),w.threadSyncService.dispose(),w.settingsStorage[Symbol.dispose](),W.unsubscribe(),U?.dispose()}}}async function sF9(J){if(!J.executeMode){if(!await Ey1("Would you like to log in to Amp? [(y)es, (n)o]: "))return x2.write(`Login cancelled. Run the command again to retry.
|
|
6414
6414
|
`),!1}return await lW6(J)}async function lW6(J){let Q=gF9(32).toString("hex"),Z=await $y1(J.ampURL,Q);try{await _G(Z)}catch(Y){d.error("Failed to open browser",{error:Y})}let X=await $y1(J.ampURL,Q,!1);x2.write(`If your browser did not open automatically, visit:
|
|
6415
6415
|
|
|
@@ -6419,12 +6419,12 @@ ${D8.blue.bold(X)}
|
|
|
6419
6419
|
Login successful! You can now use the Amp CLI.
|
|
6420
6420
|
`),!0}catch(Y){return d.error("Login failed",{error:Y}),a7.write(`
|
|
6421
6421
|
Login failed: ${Y instanceof Error?Y.message:String(Y)}
|
|
6422
|
-
`),!1}}function oF9(){let J=new H71().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((F)=>{if(F.code==="commander.help"||F.code==="commander.version"||F.exitCode===0)Kw(),process.exit(0);let H=F.originalError??F;sJ6(H)}),J.option("-V, --version","output the version number",()=>{x2.write(`0.0.
|
|
6423
|
-
`),process.exit(0)}),J.addHelpText("after",sQ6()),J.configureHelp({formatHelp:oQ6}),J.command("logout").description("Log out by removing stored API key").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await FZ(B);await QH9(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(F,H)=>{let B=H.optsWithGlobals(),M=await FZ(B);await JH9(M,await Hy1(B,M.settings))});let Q=async(F,H,B)=>{zX1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:t1.of([L0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:Tu1,userConfigDir:cW6});let M={...H,executeMode:!1};await Iu1(M,{...F,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(F,H)=>{let B=H.optsWithGlobals(),M=await FZ(B);await uW6(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(F,H)=>{let B=H.optsWithGlobals(),M=await FZ(B);await UH9(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(F,H,B)=>{let M=B.optsWithGlobals(),V=await FZ(M);if(H.pick)await Q(M,V,B);else await zH9(M,V,F,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(F,H,B)=>{let M=B.optsWithGlobals(),V=await FZ(M);await GH9(M,V,F,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(F,H)=>{let B=H.optsWithGlobals(),M=await FZ(B);await uW6(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(F,H,B)=>{let M=B.optsWithGlobals(),V=await FZ(M);await qH9(M,V,F,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(F,H,B)=>{let M=B.optsWithGlobals(),V=await FZ(M);await XH9(M,V,F,B)}),Z.command("rename <threadId> <newName>").alias("r").summary("Rename a thread").description('Change the title of a thread. Quote names with spaces: amp threads rename T-123 "New thread name"').action(async(F,H,B,M)=>{let V=M.optsWithGlobals(),N=await FZ(V);await YH9(V,N,F,H,M)}),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(F,H,B)=>{let M=B.optsWithGlobals(),V=await FZ(M);await KH9(M,V,F,B)}),eZ6(J,async(F,H)=>{let B=await FZ(H);aK(F,H);let M=await rK(B,H);return{context:B,mcpService:M.mcpService,toolService:M.toolService,configService:M.configService,cleanupTerminal:Kw,asyncDispose:M.asyncDispose.bind(M)}}),TZ6(J),RZ6(J,async(F)=>{let H=await FZ(F);return{settings:H.settings,getThreadDeps:async(B)=>{aK(B,F);let M=await rK(H,F);return{mcpService:M.mcpService,asyncDispose:M.asyncDispose.bind(M)}}}}),J.command("connect").description("Connect CLI to web interface for multi-thread management").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await FZ(B);aK(H,B);let V=await rK(M,B);try{await ab1(V,V.configService,{})}finally{await V.asyncDispose(),await Kw()}});let X=new H71().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(F)=>{await Ay1(F.force||!1,F.verbose||!1,"0.0.
|
|
6422
|
+
`),!1}}function oF9(){let J=new H71().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((F)=>{if(F.code==="commander.help"||F.code==="commander.version"||F.exitCode===0)Kw(),process.exit(0);let H=F.originalError??F;sJ6(H)}),J.option("-V, --version","output the version number",()=>{x2.write(`0.0.1761177703-gb6ee2a (released 2025-10-23T00:07:07.792Z)
|
|
6423
|
+
`),process.exit(0)}),J.addHelpText("after",sQ6()),J.configureHelp({formatHelp:oQ6}),J.command("logout").description("Log out by removing stored API key").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await FZ(B);await QH9(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(F,H)=>{let B=H.optsWithGlobals(),M=await FZ(B);await JH9(M,await Hy1(B,M.settings))});let Q=async(F,H,B)=>{zX1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:t1.of([L0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:Tu1,userConfigDir:cW6});let M={...H,executeMode:!1};await Iu1(M,{...F,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(F,H)=>{let B=H.optsWithGlobals(),M=await FZ(B);await uW6(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(F,H)=>{let B=H.optsWithGlobals(),M=await FZ(B);await UH9(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(F,H,B)=>{let M=B.optsWithGlobals(),V=await FZ(M);if(H.pick)await Q(M,V,B);else await zH9(M,V,F,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(F,H,B)=>{let M=B.optsWithGlobals(),V=await FZ(M);await GH9(M,V,F,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(F,H)=>{let B=H.optsWithGlobals(),M=await FZ(B);await uW6(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(F,H,B)=>{let M=B.optsWithGlobals(),V=await FZ(M);await qH9(M,V,F,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(F,H,B)=>{let M=B.optsWithGlobals(),V=await FZ(M);await XH9(M,V,F,B)}),Z.command("rename <threadId> <newName>").alias("r").summary("Rename a thread").description('Change the title of a thread. Quote names with spaces: amp threads rename T-123 "New thread name"').action(async(F,H,B,M)=>{let V=M.optsWithGlobals(),N=await FZ(V);await YH9(V,N,F,H,M)}),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(F,H,B)=>{let M=B.optsWithGlobals(),V=await FZ(M);await KH9(M,V,F,B)}),eZ6(J,async(F,H)=>{let B=await FZ(H);aK(F,H);let M=await rK(B,H);return{context:B,mcpService:M.mcpService,toolService:M.toolService,configService:M.configService,cleanupTerminal:Kw,asyncDispose:M.asyncDispose.bind(M)}}),TZ6(J),RZ6(J,async(F)=>{let H=await FZ(F);return{settings:H.settings,getThreadDeps:async(B)=>{aK(B,F);let M=await rK(H,F);return{mcpService:M.mcpService,asyncDispose:M.asyncDispose.bind(M)}}}}),J.command("connect").description("Connect CLI to web interface for multi-thread management").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await FZ(B);aK(H,B);let V=await rK(M,B);try{await ab1(V,V.configService,{})}finally{await V.asyncDispose(),await Kw()}});let X=new H71().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(F)=>{await Ay1(F.force||!1,F.verbose||!1,"0.0.1761177703-gb6ee2a"),process.exit()});J.addCommand(X,{hidden:!0});function Y(F,H,B){let V=typeof F.description==="string"?F.description:B===void 0?F.description(!0):F.description(B),N=new gV(H,V),L=aF9(F);if(L)N.default(L);if(N.hidden=iF9(F)||mW6(F),"choices"in F)N.choices([...F.choices]);return N}for(let F of gW6)switch(F.type){case"flag":{J.addOption(Y(F,`--${F.long}`)),J.addOption(Y(F,`--no-${F.long}`,!1));break}case"switch":{J.addOption(Y(F,`--${F.long}`,!0));break}default:{J.addOption(Y(F,`--${F.long} <value>`));break}}let K=new gV("-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 gV("-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 gV("--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 gV("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(z);let U=new gV("--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 F=new gV("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(F)}J.action(async(F,H)=>{let B=F,M=await FZ(B);if(Object.keys(B).forEach((V)=>{let N=gW6.find((L)=>L.name===V);if(N&&mW6(N)&&!nF9(N))a7.write(D8.yellow(`Warning: '--${V}' flag is deprecated
|
|
6424
6424
|
`))}),H.args.length>0)rF9(M,H);await Iu1(M,B,H)});let W=new H71("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(F)=>{await ZH9(F.version)});return J.addCommand(W),J}async function qQ1(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??qq(),K=np(J);if(Z)await J.threadStorage.set(Y,Z);let q=await u5.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,B51(X));let G=J.threadService.observe(Y).subscribe(async(z)=>{if(s7(z,"assistant"))await Pu1(Y),G.unsubscribe()});return await q.resume(),q}async function Iu1(J,Q,Z){let X=H51(Q);if(X instanceof Error)LQ(X.message);let Y,K=null;if(Q.streamJsonInput)Y="";else if(typeof Q.execute==="string"){Y=Q.execute;let w=(await Py1()).trimEnd();if(w)K=w}else Y=(await Py1()).trimEnd();if(Q.remote&&!J.executeMode)throw new m9("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new m9("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new m9("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new m9("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 m9(`Execute mode is not permitted with --agent-mode '${Q.agentMode}'`,1);if(Q.stats&&!J.executeMode)throw new m9("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 m9("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 m9("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"
|
|
6425
6425
|
Or pipe via stdin: echo "your message" | amp --execute`);aK(Z,Q);let q=await rK(J,Q);dW6=q;let G=np(q),z=async(w)=>{let O=await pW6(w,"utf-8"),$=JSON.parse(O);if(!FW($.id))throw new m9(mK.invalidThreadId);return qQ1(q,{visibility:X,thread:$})},U=async(w)=>{if(!FW(w))throw new m9(mK.invalidThreadId);let O=await q.threadService.get(w)??void 0;if(d.info(`[fetchAndStartThread] Loaded thread ${w}, agentMode: ${O?.agentMode??"undefined"}`),O?.agentMode)d.info(`[fetchAndStartThread] Setting runtime override for agentMode to: ${O.agentMode}`),tG("experimental.agentMode",O.agentMode);else d.info("[fetchAndStartThread] No agentMode on thread, not setting override");return qQ1(q,{visibility:X,thread:O})},W=async()=>{try{if(Q.threadId)return U(Q.threadId);else return qQ1(q,{visibility:X})}catch(w){if(w instanceof m9)throw w;throw await n71(w,Q.threadId),Error("handleError should have called process.exit()")}},F=async()=>{return qQ1(q,{visibility:X})};if(Q.format==="jsonl")a7.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
6426
|
-
`),await Zw(),process.exit(1);if(J.executeMode&&Q.remote)await CZ6(Y,K,q.configService),await q.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await UQ6(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 Lr1();let w=await bB({jetbrainsOnly:Q.jetbrains});if(w.length===0){if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall")}else if(w.length===1){let O=w[0];if(O)W7.selectConfig(O)}else B=!0}let V=Oy1("0.0.
|
|
6427
|
-
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await iU({...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 wZ6(J.mcpConfig);X=lF9(X,q)}let Y=await X.get("url","global");if(!Y)Y=BZ;if(!RB(Y))d.info("Targeting custom Amp server",{ampURL:Y});if(X=Nl1(X),await X.get("debug.httpLogging"))Dl1();return{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:SZ6(await Hy1(J,X))}}function tF9(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 eF9(){let J=tF9(process.argv);if(vJ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),dF9(d),d.info("Starting Amp CLI.",{version:"0.0.
|
|
6426
|
+
`),await Zw(),process.exit(1);if(J.executeMode&&Q.remote)await CZ6(Y,K,q.configService),await q.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await UQ6(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 Lr1();let w=await bB({jetbrainsOnly:Q.jetbrains});if(w.length===0){if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall")}else if(w.length===1){let O=w[0];if(O)W7.selectConfig(O)}else B=!0}let V=Oy1("0.0.1761177703-gb6ee2a",q.settingsStorage),N=t1.of([L0.file(process.cwd())]),L=KS(void 0,N);if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let A;try{A=await qJ.getUserFreeTierStatus({},{config:q.configService})}catch(w){A={ok:!1,error:w}}d.info("User free tier status:",A);let R=await _Z6();d.info("Loaded session state:",R),await hW6({codebaseContextService:q.codebaseContextService,stdout:process.stdout,history:new eb1,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadSyncService:q.threadSyncService,threadID:H.threadID,worker:H,workerDeps:G,configService:q.configService,internalAPIClient:qJ,ampURL:J.ampURL,startNewThread:F,pickAndContinueThread:async()=>{d.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:W7,connectedClientsService:new Hc,commandRegistry:L,showJetBrainsInstaller:M,showIdePicker:B,startWithPicker:Q.startWithPicker,updateService:V,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:R,freeTierStatus:A.ok?A.result:void 0}),await q.asyncDispose(),process.exit(0)}async function FZ(J){if(J.interactive)a7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
6427
|
+
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await iU({...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 wZ6(J.mcpConfig);X=lF9(X,q)}let Y=await X.get("url","global");if(!Y)Y=BZ;if(!RB(Y))d.info("Targeting custom Amp server",{ampURL:Y});if(X=Nl1(X),await X.get("debug.httpLogging"))Dl1();return{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:SZ6(await Hy1(J,X))}}function tF9(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 eF9(){let J=tF9(process.argv);if(vJ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),dF9(d),d.info("Starting Amp CLI.",{version:"0.0.1761177703-gb6ee2a",buildTimestamp:"2025-10-23T00:07:07.792Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new m9(mK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await oF9().parseAsync(process.argv)}eF9().catch(n71);async function JH9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),x2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
6428
6428
|
`);else if(!RB(J.ampURL))x2.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
6429
6429
|
`);let Z=process.env.AMP_API_KEY;if(Z)x2.write(`API key found in environment variable, storing...
|
|
6430
6430
|
`),await Q.set("apiKey",Z,J.ampURL),x2.write(`API key successfully stored.
|
|
@@ -6440,7 +6440,7 @@ Or pipe via stdin: echo "your message" | amp --execute`);aK(Z,Q);let q=await rK(
|
|
|
6440
6440
|
`));try{let Q;if(J)Q=J,a7.write(D8.blue(`Updating to version ${J}...
|
|
6441
6441
|
`)),await WC(J),a7.write(D8.green(`✓ Successfully updated to version ${J}
|
|
6442
6442
|
`));else{a7.write(D8.blue(`Checking for updates...
|
|
6443
|
-
`));let{hasUpdate:X,latestVersion:Y}=await z71("0.0.
|
|
6443
|
+
`));let{hasUpdate:X,latestVersion:Y}=await z71("0.0.1761177703-gb6ee2a");if(!X)a7.write(D8.green(`✓ Amp CLI is already up to date.
|
|
6444
6444
|
`)),process.exit(0);if(!Y)a7.write(D8.yellow("[WARN] could not find latest version")),process.exit(0);Q=Y,a7.write(D8.blue(`Updating to version ${Y}...
|
|
6445
6445
|
`)),await WC(Y),a7.write(D8.green(`✓ Successfully updated to version ${Y}
|
|
6446
6446
|
`))}let Z=await Uw(Q);if(Z.warning)a7.write(`
|
package/package.json
CHANGED