@sourcegraph/amp 0.0.1760817685-gfa6192 → 0.0.1760832099-g685d5f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +7 -7
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -6137,7 +6137,7 @@ See https://ampcode.com/manual#toolboxes`);return Q[0]||lR}function YX6(J,Q){let
6137
6137
  `;async function UX6(J,Q,Z,X){let Y=performance.now(),K=[...r_(tM1(J)),{role:"user",parts:[{text:BJ9.replace("{USER_GOAL}",Q)}]}],q=await y$(gr,K,[],J,Z,X,{responseMimeType:"application/json",responseJsonSchema:M0.toJSONSchema(zX6)}),G=zX6.parse(JSON.parse(q.message.text??"")),z=performance.now()-Y;return l.debug("Thread handoff prepared",{threadId:J.id,goalLength:Q.length,instructionsLength:G.instructions.length,fileCount:G.relevantFiles.length,durationMs:Math.round(z)}),{instructions:G.instructions,relevantFiles:G.relevantFiles}}HL();x6();function WX6(J){let Q=J.trim();if(Q==="quit"||Q==="exit")return"/quit";return J}function FX6(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 DJ9 from"node:fs";import HX6 from"node:path";function BX6(J){let Q=J.trim().replace(/^["']|["']$/g,"");if(Q=Q.replace(/\\(.)/g,"$1"),!/\.(png|jpe?g|gif|webp)$/i.test(Q))return null;if(!HX6.isAbsolute(Q))return null;return l.debug("Extracted image path",{original:J,extracted:Q}),Q}function DX6(J){try{let Q=HX6.extname(J).toLowerCase(),Z=ie1(Q);if(!Z)return l.warn("Unsupported image file extension",{ext:Q}),null;try{let X=DJ9.readFileSync(J);return MJ9(X,Z)}catch(X){l.error(`Failed to read image file ${J}:`,X)}}catch(Q){l.error("Error handling image file path",{imagePath:J,error:Q})}return null}function MJ9(J,Q){if(J.length>jW)return l.warn(`Image file too large: ${J.length} bytes (max: ${jW})`),null;return{type:"image",source:{type:"base64",data:J.toString("base64"),mediaType:Q}}}import{execSync as gK6}from"node:child_process";import{rmdir as UK9}from"node:fs/promises";import{tmpdir as WK9}from"node:os";import mK6 from"node:path";tO();z0();import{spawn as VJ9}from"node:child_process";import{promises as NJ9}from"node:fs";function MX6(J){return J.kind==="executable"}function VX6(J){return J.kind==="markdown"}var cH=50000,NX6=300000;async function xy1(J,Q,Z,X={}){let{timeoutMs:Y=NX6,signal:K}=X;try{let q=await Z.getCommand(J);if(!q)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Z.isCommandAvailable(J))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(l.debug("Executing command",{commandName:J,filePath:q.filePath,args:Q}),VX6(q))return await LJ9(q,Q);else if(MX6(q))return await AJ9(q,Q,Y,K);else return{success:!1,output:"",error:"Unsupported command type"}}catch(q){return l.error("Failed to execute command",{commandName:J,error:q}),{success:!1,output:"",error:q instanceof Error?q.message:"Unknown error occurred"}}}async function LJ9(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await NJ9.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>cH?Z.slice(0,cH)+`
6138
6138
  ... (output truncated at ${cH} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function AJ9(J,Q,Z=NX6,X){return new Promise((Y)=>{let[K,q]=wJ9(J,Q);l.debug("Spawning command",{spawnCommand:K,spawnArgs:q.slice(0,10),filePath:J.filePath,timeoutMs:Z});let G=pe1(X),z=!1,U=setTimeout(()=>{z=!0,G.abort(),l.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),W=VJ9(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<=cH)F.push(V);else{let N=cH-(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<=cH)H.push(V);else{let N=cH-(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?`
6139
6139
  ${L}`:L;if(B>cH)A+=`
6140
- ... (output truncated at ${cH} 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 wJ9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return OJ9(Z,X?[...X]:null,Y,Q);else return RJ9(Z,X?[...X]:null,Y,Q)}function RJ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function OJ9(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();kj();W2();CB();SY();fW();x6();I0();import{mkdtemp as FK9,readFile as HK9,unlink as BK9,writeFile as AO2}from"fs/promises";var U51={};O6(U51,{scrollUp:()=>pJ9,scrollDown:()=>dJ9,link:()=>rJ9,image:()=>sJ9,iTerm:()=>oJ9,exitAlternativeScreen:()=>nJ9,eraseUp:()=>uJ9,eraseStartLine:()=>gJ9,eraseScreen:()=>by1,eraseLines:()=>fJ9,eraseLine:()=>RX6,eraseEndLine:()=>hJ9,eraseDown:()=>mJ9,enterAlternativeScreen:()=>iJ9,cursorUp:()=>AX6,cursorTo:()=>EJ9,cursorShow:()=>yJ9,cursorSavePosition:()=>SJ9,cursorRestorePosition:()=>vJ9,cursorPrevLine:()=>xJ9,cursorNextLine:()=>_J9,cursorMove:()=>IJ9,cursorLeft:()=>wX6,cursorHide:()=>bJ9,cursorGetPosition:()=>kJ9,cursorForward:()=>TJ9,cursorDown:()=>PJ9,cursorBackward:()=>CJ9,clearTerminal:()=>lJ9,clearScreen:()=>cJ9,beep:()=>aJ9});import yy1 from"node:process";var z51=globalThis.window?.document!==void 0,Aw2=globalThis.process?.versions?.node!==void 0,ww2=globalThis.process?.versions?.bun!==void 0,Rw2=globalThis.Deno?.version?.deno!==void 0,Ow2=globalThis.process?.versions?.electron!==void 0,jw2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,$w2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,Ew2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,Iw2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,Pw2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,bu=globalThis.navigator?.userAgentData?.platform,Tw2=bu==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",Cw2=bu==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",Sw2=bu==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",vw2=bu==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),kw2=bu==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var L2="\x1B[",fu="\x1B]",NC="\x07",yu=";",LX6=!z51&&yy1.env.TERM_PROGRAM==="Apple_Terminal",jJ9=!z51&&yy1.platform==="win32",$J9=z51?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:yy1.cwd,EJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return L2+(J+1)+"G";return L2+(Q+1)+yu+(J+1)+"H"},IJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=L2+-J+"D";else if(J>0)Z+=L2+J+"C";if(Q<0)Z+=L2+-Q+"A";else if(Q>0)Z+=L2+Q+"B";return Z},AX6=(J=1)=>L2+J+"A",PJ9=(J=1)=>L2+J+"B",TJ9=(J=1)=>L2+J+"C",CJ9=(J=1)=>L2+J+"D",wX6=L2+"G",SJ9=LX6?"\x1B7":L2+"s",vJ9=LX6?"\x1B8":L2+"u",kJ9=L2+"6n",_J9=L2+"E",xJ9=L2+"F",bJ9=L2+"?25l",yJ9=L2+"?25h",fJ9=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=RX6+(Z<J-1?AX6():"");if(J)Q+=wX6;return Q},hJ9=L2+"K",gJ9=L2+"1K",RX6=L2+"2K",mJ9=L2+"J",uJ9=L2+"1J",by1=L2+"2J",pJ9=L2+"S",dJ9=L2+"T",cJ9="\x1Bc",lJ9=jJ9?`${by1}${L2}0f`:`${by1}${L2}3J${L2}H`,iJ9=L2+"?1049h",nJ9=L2+"?1049l",aJ9=NC,rJ9=(J,Q)=>[fu,"8",yu,yu,Q,NC,J,fu,"8",yu,yu,NC].join(""),sJ9=(J,Q={})=>{let Z=`${fu}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")+NC},oJ9={setCwd:(J=$J9())=>`${fu}50;CurrentDir=${J}${NC}`,annotation(J,Q={}){let Z=`${fu}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+NC}};var W51=_6(TX6(),1);function sV(J,Q,{target:Z="stdout",...X}={}){if(!W51.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (​${Q}​)`}return U51.link(J,Q)}sV.isSupported=W51.default.stdout;sV.stderr=(J,Q,Z={})=>sV(J,Q,{target:"stderr",...Z});sV.stderr.isSupported=W51.default.stderr;z0();SY();class uy1{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.1760817685-gfa6192"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await on(Q,this.configService)}catch(Q){l.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}import{execFile as H51}from"node:child_process";import{platform as py1}from"node:os";import{promisify as QQ9}from"node:util";var F51=QQ9(H51),ZQ9=(J)=>`\x1B]52;c;${J}\x1B\\`,XQ9="\x1B]52;c;?\x1B\\",YQ9="\x1B]52;p;?\x1B\\";class CX6{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 F51("which",[J]),!0}catch{return!1}}async writeToPbcopy(J){try{let Q=H51("pbcopy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`pbcopy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToWlCopy(J){try{let Q=H51("wl-copy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`wl-copy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToXclip(J){try{let Q=H51("xclip",["-selection","clipboard"]);return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`xclip exited with code ${Y}`))})}),!0}catch{return!1}}async readFromOSC52WithQuery(J){if(!this.isOsc52Supported())return null;if(this.pendingReadPromise)return this.pendingReadPromise;this.pendingReadPromise=new Promise((Z)=>{this.readResolve=Z,this.readTimeout=setTimeout(()=>{this.readResolve=null,this.pendingReadPromise=null,Z(null)},2000),process.stdout.write(J)});let Q=await this.pendingReadPromise;return this.pendingReadPromise=null,Q}async readFromOSC52(){return this.readFromOSC52WithQuery(XQ9)}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 F51("pbpaste");return J}catch{return null}}async readFromWlPaste(J){try{let Q=["--no-newline"];if(J==="primary")Q.push("--primary");let{stdout:Z}=await F51("wl-paste",Q);return Z}catch{return null}}async readFromXclip(J){try{let{stdout:Q}=await F51("xclip",["-selection",J,"-o"]);return Q}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(YQ9)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if(py1()==="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(py1()==="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=ZQ9(Z);process.stdout.write(X);return}if(py1()==="darwin"){if(await this.writeToPbcopy(J))return}else{if(await this.commandExists("wl-copy")&&await this.writeToWlCopy(J))return;if(await this.commandExists("xclip")&&await this.writeToXclip(J))return}}}var FY=new CX6;z0();class B51 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}class c7{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function SX6(J){if(J instanceof B51)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof c7)return{title:"Info",description:J.message,type:"info"};return l.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var XN=null,DK9={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(XN)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(() => (sb1(),sJ6)),q=await K({worker:J.worker},J.configService,{clientId:J.clientId,onUserDisconnect:()=>{XN=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});XN=q,q.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((M)=>{XN=null,Z.sendStatus({connected:!1,errorMessage:M.message})});let z=(await J.configService.getLatest()).settings.url,U=J.worker.thread.id,W=new URL(`/clients/${Y}/${U}`,z).toString(),F=new URL("/clients",z).toString(),H="";try{H=await(await Promise.resolve().then(() => _6(yf1(),1))).toString(W,{type:"utf8",margin:2,color:{dark:"#000000",light:"#FFFFFF"}})}catch(M){l.error("Failed to generate QR code:",M)}if((process.stdout.rows||24)>=30&&H&&J.onShowQRCodeOverlay)J.onShowQRCodeOverlay({url:F,qrCode:H});else return new c7(`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(!XN)return new c7("Not connected to Amp web interface");try{XN.disconnect();let Z=XN.clientID;return XN=null,J.connectedClientsService.sendStatus({connected:!1,enabled:!1,errorMessage:void 0}),new c7(`Disconnected from Amp web interface
6140
+ ... (output truncated at ${cH} 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 wJ9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return OJ9(Z,X?[...X]:null,Y,Q);else return RJ9(Z,X?[...X]:null,Y,Q)}function RJ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function OJ9(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();kj();W2();CB();SY();fW();x6();I0();import{mkdtemp as FK9,readFile as HK9,unlink as BK9,writeFile as AO2}from"fs/promises";var U51={};O6(U51,{scrollUp:()=>pJ9,scrollDown:()=>dJ9,link:()=>rJ9,image:()=>sJ9,iTerm:()=>oJ9,exitAlternativeScreen:()=>nJ9,eraseUp:()=>uJ9,eraseStartLine:()=>gJ9,eraseScreen:()=>by1,eraseLines:()=>fJ9,eraseLine:()=>RX6,eraseEndLine:()=>hJ9,eraseDown:()=>mJ9,enterAlternativeScreen:()=>iJ9,cursorUp:()=>AX6,cursorTo:()=>EJ9,cursorShow:()=>yJ9,cursorSavePosition:()=>SJ9,cursorRestorePosition:()=>vJ9,cursorPrevLine:()=>xJ9,cursorNextLine:()=>_J9,cursorMove:()=>IJ9,cursorLeft:()=>wX6,cursorHide:()=>bJ9,cursorGetPosition:()=>kJ9,cursorForward:()=>TJ9,cursorDown:()=>PJ9,cursorBackward:()=>CJ9,clearTerminal:()=>lJ9,clearScreen:()=>cJ9,beep:()=>aJ9});import yy1 from"node:process";var z51=globalThis.window?.document!==void 0,Aw2=globalThis.process?.versions?.node!==void 0,ww2=globalThis.process?.versions?.bun!==void 0,Rw2=globalThis.Deno?.version?.deno!==void 0,Ow2=globalThis.process?.versions?.electron!==void 0,jw2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,$w2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,Ew2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,Iw2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,Pw2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,bu=globalThis.navigator?.userAgentData?.platform,Tw2=bu==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",Cw2=bu==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",Sw2=bu==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",vw2=bu==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),kw2=bu==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var L2="\x1B[",fu="\x1B]",NC="\x07",yu=";",LX6=!z51&&yy1.env.TERM_PROGRAM==="Apple_Terminal",jJ9=!z51&&yy1.platform==="win32",$J9=z51?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:yy1.cwd,EJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return L2+(J+1)+"G";return L2+(Q+1)+yu+(J+1)+"H"},IJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=L2+-J+"D";else if(J>0)Z+=L2+J+"C";if(Q<0)Z+=L2+-Q+"A";else if(Q>0)Z+=L2+Q+"B";return Z},AX6=(J=1)=>L2+J+"A",PJ9=(J=1)=>L2+J+"B",TJ9=(J=1)=>L2+J+"C",CJ9=(J=1)=>L2+J+"D",wX6=L2+"G",SJ9=LX6?"\x1B7":L2+"s",vJ9=LX6?"\x1B8":L2+"u",kJ9=L2+"6n",_J9=L2+"E",xJ9=L2+"F",bJ9=L2+"?25l",yJ9=L2+"?25h",fJ9=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=RX6+(Z<J-1?AX6():"");if(J)Q+=wX6;return Q},hJ9=L2+"K",gJ9=L2+"1K",RX6=L2+"2K",mJ9=L2+"J",uJ9=L2+"1J",by1=L2+"2J",pJ9=L2+"S",dJ9=L2+"T",cJ9="\x1Bc",lJ9=jJ9?`${by1}${L2}0f`:`${by1}${L2}3J${L2}H`,iJ9=L2+"?1049h",nJ9=L2+"?1049l",aJ9=NC,rJ9=(J,Q)=>[fu,"8",yu,yu,Q,NC,J,fu,"8",yu,yu,NC].join(""),sJ9=(J,Q={})=>{let Z=`${fu}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")+NC},oJ9={setCwd:(J=$J9())=>`${fu}50;CurrentDir=${J}${NC}`,annotation(J,Q={}){let Z=`${fu}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+NC}};var W51=_6(TX6(),1);function sV(J,Q,{target:Z="stdout",...X}={}){if(!W51.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (​${Q}​)`}return U51.link(J,Q)}sV.isSupported=W51.default.stdout;sV.stderr=(J,Q,Z={})=>sV(J,Q,{target:"stderr",...Z});sV.stderr.isSupported=W51.default.stderr;z0();SY();class uy1{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.1760832099-g685d5f"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await on(Q,this.configService)}catch(Q){l.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}import{execFile as H51}from"node:child_process";import{platform as py1}from"node:os";import{promisify as QQ9}from"node:util";var F51=QQ9(H51),ZQ9=(J)=>`\x1B]52;c;${J}\x1B\\`,XQ9="\x1B]52;c;?\x1B\\",YQ9="\x1B]52;p;?\x1B\\";class CX6{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 F51("which",[J]),!0}catch{return!1}}async writeToPbcopy(J){try{let Q=H51("pbcopy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`pbcopy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToWlCopy(J){try{let Q=H51("wl-copy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`wl-copy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToXclip(J){try{let Q=H51("xclip",["-selection","clipboard"]);return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`xclip exited with code ${Y}`))})}),!0}catch{return!1}}async readFromOSC52WithQuery(J){if(!this.isOsc52Supported())return null;if(this.pendingReadPromise)return this.pendingReadPromise;this.pendingReadPromise=new Promise((Z)=>{this.readResolve=Z,this.readTimeout=setTimeout(()=>{this.readResolve=null,this.pendingReadPromise=null,Z(null)},2000),process.stdout.write(J)});let Q=await this.pendingReadPromise;return this.pendingReadPromise=null,Q}async readFromOSC52(){return this.readFromOSC52WithQuery(XQ9)}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 F51("pbpaste");return J}catch{return null}}async readFromWlPaste(J){try{let Q=["--no-newline"];if(J==="primary")Q.push("--primary");let{stdout:Z}=await F51("wl-paste",Q);return Z}catch{return null}}async readFromXclip(J){try{let{stdout:Q}=await F51("xclip",["-selection",J,"-o"]);return Q}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(YQ9)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if(py1()==="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(py1()==="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=ZQ9(Z);process.stdout.write(X);return}if(py1()==="darwin"){if(await this.writeToPbcopy(J))return}else{if(await this.commandExists("wl-copy")&&await this.writeToWlCopy(J))return;if(await this.commandExists("xclip")&&await this.writeToXclip(J))return}}}var FY=new CX6;z0();class B51 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}class c7{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function SX6(J){if(J instanceof B51)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof c7)return{title:"Info",description:J.message,type:"info"};return l.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var XN=null,DK9={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(XN)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(() => (sb1(),sJ6)),q=await K({worker:J.worker},J.configService,{clientId:J.clientId,onUserDisconnect:()=>{XN=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});XN=q,q.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((M)=>{XN=null,Z.sendStatus({connected:!1,errorMessage:M.message})});let z=(await J.configService.getLatest()).settings.url,U=J.worker.thread.id,W=new URL(`/clients/${Y}/${U}`,z).toString(),F=new URL("/clients",z).toString(),H="";try{H=await(await Promise.resolve().then(() => _6(yf1(),1))).toString(W,{type:"utf8",margin:2,color:{dark:"#000000",light:"#FFFFFF"}})}catch(M){l.error("Failed to generate QR code:",M)}if((process.stdout.rows||24)>=30&&H&&J.onShowQRCodeOverlay)J.onShowQRCodeOverlay({url:F,qrCode:H});else return new c7(`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(!XN)return new c7("Not connected to Amp web interface");try{XN.disconnect();let Z=XN.clientID;return XN=null,J.connectedClientsService.sendStatus({connected:!1,enabled:!1,errorMessage:void 0}),new c7(`Disconnected from Amp web interface
6141
6141
  Client ID: ${Z}
6142
6142
  Server will clean up automatically within 60 seconds`)}catch(Z){return Error(`Failed to disconnect: ${Z.message}`)}}}};class ff1{configService;commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=YS(),Q){this.configService=Q;this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Z)=>this.latestCustom=Z),this.telemetrySubmitter=new uy1(async()=>{try{return(await this.configService.getLatest()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}},this.configService),this.configService.config.pipe(C0((Z)=>wB(Z.settings)),c6()).subscribe((Z)=>{this._initBaseCommands(Z.length>1)})}_initBaseCommands(J){if(this.commands={...MK9},process.env.AMP_CONNECT==="1")Object.assign(this.commands,DK9);if(J)Object.assign(this.commands,VK9)}async execute(J,Q,Z=[],X){this.telemetrySubmitter.submit(J).catch((G)=>{l.debug("Failed to submit command telemetry",G)});let Y=this.commands[J];if(Y)return Y.execute(Q,Z);let K=this.latestCustom.find((G)=>G.name===J),q=await xy1(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 MK9={"generate-agent-file":{name:"generate-agent-file",description:`Generate an ${X5} file in the current workspace`,execute:async(J,Q)=>{let Z=await J.configService.getLatest(),X=bq(Z.settings),K=J.getInMemoryAgentModeOverride()??X;J.worker.handle({type:"user:message",message:{content:[{type:"text",text:j90}],agentMode:K}});return}},compact:{name:"compact",description:"Compact the thread. Optional: /compact [message] to queue a message after compaction",execute:async(J,Q)=>{if(J.thread.messages.length===0)return new B51;if(Q&&Q.length>0){let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}try{await J.worker.summarizeThread(new AbortController().signal)}catch(Z){return Z instanceof Error?Z:Error("Failed to compact thread")}},isVisible:(J)=>J.agentMode!=="free"},editor:{name:"editor",description:"Open $EDITOR to write a prompt",launchesWindow:!0,execute:async(J,Q)=>{try{let Z=process.env.EDITOR||process.env.VISUAL||"nano",X=await FK9(mK6.join(WK9(),"amp-edit-")),Y=mK6.join(X,"message.amp.md");gK6(`${Z} "${Y}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let q=(await HK9(Y,"utf-8")).trim();if(q)J.editorDispatch({type:"set-input",input:q})}catch(K){if(K?.code==="ENOENT")return;return l.error("Failed to read temporary file",K),Error("Failed to read editor content")}try{await BK9(Y),await UK9(X)}catch(K){l.warn("Failed to clean up temporary file",K)}return}catch(Z){return l.error("Failed to open editor",Z),Error("Failed to open editor")}}},help:{name:"help",description:"Show help and hotkeys",execute:async(J,Q)=>{J.openHelp();return}},permissions:{name:"permissions",description:"Edit permission rules in $EDITOR, or `/permissions off|on` to toggle for this session",launchesWindow:!0,execute:async(J,Q)=>{if(Q&&Q.length>0){let Y=Q[0]?.trim().toLowerCase();switch(Y){case"on":try{return rG("dangerouslyAllowAll",!1),new c7("Amp is now following permissions rules for this session")}catch(K){return l.error("Failed to set dangerously allow all setting",K),Error("Failed to enable permissions for this session")}case"off":try{return rG("dangerouslyAllowAll",!0),new c7("Permissions disabled for this session - you will NOT be asked for confirmation before Amp runs a command.")}catch(K){return l.error("Failed to set dangerously allow all setting",K),Error("Failed to disable permissions for this session")}case"edit":break;default:return Error(`Invalid option: ${Y}. Use: on, off, or edit (or no argument for edit)`)}}let Z=await MC();if(Z===null)return Error("No editor found, please set $EDITOR to edit permissions");let X="";try{let Y={stdin:process.stdin,stdout:process.stdout,stderr:{write:(K)=>{return X=K.toString(),!0}},exit:(K)=>{if(K!==0)throw l.error("editPermissions exited with status",K),Error(X)},settingsFile:J.settingsFilePath,resolveEditor:MC};await K51(Y);return}catch(Y){l.error("failed to open permissions editor:",Y);let K=Y instanceof Error?`: ${Y.message}`:"";return Error(`Failed to open ${Z}${K}`)}finally{process.stdout.write("\x1B[?25l")}}},new:{name:"new",description:"Start a new thread",execute:async(J,Q)=>{try{await J.startNewThread();return}catch(Z){return l.error("Failed to start new thread",Z),Error("Failed to start new thread")}},isVisible:(J)=>J.messages.length!==0},handoff:{name:"handoff",description:"Start new focused thread with relevant files and prompt: /handoff <your goal>",statusMessage:"Handing off...",requiresArgs:!0,execute:async()=>{return},isVisible:(J)=>J.messages.length!==0&&J.agentMode!=="free"},continue:{name:"continue",description:"Continue an existing thread",requiresArgs:!1,requiresPicker:!0,execute:async(J,Q)=>{try{if(Q&&Q.length>0){let Z=Q[0]?.trim();if(!Z)return Error("Invalid thread ID provided");return await J.switchToThread(Z),new c7(`Switched to existing thread: ${Z}`)}await J.pickAndContinueThread();return}catch(Z){return l.error("Failed to continue thread",Z),Error("Failed to continue thread")}}},queue:{name:"queue",description:"Queue a message to send when inference completes. If no inference running, sends immediately.",requiresArgs:!0,execute:async(J,Q)=>{if(!Q||Q.length===0)return Error("Queue command requires a message argument. Usage: /queue <message>");let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}},dequeue:{name:"dequeue",description:"Dequeue all messages and restore them to the prompt editor",execute:async(J,Q)=>{let Z=J.thread.queuedMessages??[];if(Z.length===0)return;let Y=Z.map((K)=>{return K.queuedMessage.content.filter((G)=>G.type==="text").map((G)=>G.text).join("").trim()}).filter(Boolean).join(`
6143
6143
  `).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=_j(new URL(Y),Z.id).toString(),G=`Thread URL: ${sV(K,K,{fallback:()=>K})}`,z=Q[0]?.trim().toLowerCase(),U;switch(z){case"private":U={visibility:"private",sharedGroupIDs:[]};break;case"workspace":U={visibility:"thread_workspace_shared"};break;case"group":U={visibility:"private",sharedGroupIDs:[],shareWithAllCreatorGroups:!0};break;case"public":U={visibility:"public"};break;default:return Error(`Invalid visibility option: ${z}. Use: private, workspace, group, or public`)}try{return await X.updateThreadMeta(Z.id,U),new c7(`${G}
@@ -6342,7 +6342,7 @@ ${Q}`),this.textController.clear(),this.textController.insertText(this.pendingTr
6342
6342
  `),J.stdout.write(`Thread: ${H}
6343
6343
  `),J.stdout.write(`Continue this thread with: amp threads continue ${W}
6344
6344
  `)}}function Su1(J){return J==="smart"?v1.rgb(3,197,97):J==="fast"?v1.rgb(228,180,2):J==="free"?v1.rgb(0,184,255):YH9(J)}function YH9(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 v1.index(Z[X])}Xh1();if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){q4.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
6345
- `)}var ku1=vu1.join(ql1||vu1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function UH9(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 GB(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")rG("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: ${H8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")rG("experimental.agentMode",Q.agentMode)}async function xu1(J){try{await qH9(vu1.dirname(ku1),{recursive:!0}),await GH9(ku1,J,"utf-8")}catch(Q){l.debug("Failed to save last thread ID",Q)}}async function WH9(){try{return(await YF6(ku1,"utf-8")).trim()}catch(J){return null}}function FH9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return qi1("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 QF6=[{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??WY,description:`Custom settings file path (overrides the default location ${WY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(l).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${gb1})`},{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:gK(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration."},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection."},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:Cd}],ZF6=(J)=>("deprecated"in J)&&J.deprecated===!0,HH9=(J)=>("hidden"in J)&&J.hidden===!0,BH9=(J)=>("default"in J),DH9=(J)=>("default"in J)?J.default:void 0;function MH9(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(hK.unknownCommand(Z),1,q)}}var KF6=null;function $14(){return KF6}function tJ1(J){return{...J,getThreadEnvironment:k71,vfs:G40({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new M_(J.fileSystem),generateThreadTitle:IG0,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var bu1=j0.file(zH9.homedir()),qF6=process.env.XDG_CONFIG_HOME?j0.file(process.env.XDG_CONFIG_HOME):f0.joinPath(bu1,".config");async function zB(J,Q){Wn1("0.0.1760817685-gfa6192");let Z=JX1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:e1.of([j0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:bu1,userConfigDir:qF6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (sJ1(),rJ1));X(Z);let Y=await Z.getLatest();l.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let K=Ba(HO({configService:Z})),q=f20({configService:Z,toolService:K}),G=pR0(K,C9,pe).catch((w)=>{l.warn("Toolbox registration failed, continuing anyway:",w)}),z=q.initialized.catch((w)=>{l.warn("MCP service initialization failed, continuing anyway:",w)});if(J.executeMode)await Promise.all([z,G]);if(Q.jetbrains)MO("JetBrains");else if(Q.ide&&ZZ6())MO("VS Code");else if(Q.ide&&XZ6())MO("Neovim");if(J.executeMode)Fn1(!0);a96(K,{configService:Z});let U,W=k5.status.pipe(C0((w)=>Boolean(w.connected&&w.authenticated)),c6()).subscribe((w)=>{if(w){if(!U)U=K.registerTool(Us)}else U?.dispose(),U=void 0}),F;if(!J.executeMode)F=new i71(process.cwd(),{},!0);else F=new class extends i71{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(s2.write(`No API key found. Starting login flow...
6345
+ `)}var ku1=vu1.join(ql1||vu1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function UH9(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 GB(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")rG("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: ${H8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")rG("experimental.agentMode",Q.agentMode)}async function xu1(J){try{await qH9(vu1.dirname(ku1),{recursive:!0}),await GH9(ku1,J,"utf-8")}catch(Q){l.debug("Failed to save last thread ID",Q)}}async function WH9(){try{return(await YF6(ku1,"utf-8")).trim()}catch(J){return null}}function FH9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return qi1("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 QF6=[{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??WY,description:`Custom settings file path (overrides the default location ${WY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(l).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${gb1})`},{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:gK(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration."},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection."},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:Cd}],ZF6=(J)=>("deprecated"in J)&&J.deprecated===!0,HH9=(J)=>("hidden"in J)&&J.hidden===!0,BH9=(J)=>("default"in J),DH9=(J)=>("default"in J)?J.default:void 0;function MH9(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(hK.unknownCommand(Z),1,q)}}var KF6=null;function $14(){return KF6}function tJ1(J){return{...J,getThreadEnvironment:k71,vfs:G40({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new M_(J.fileSystem),generateThreadTitle:IG0,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var bu1=j0.file(zH9.homedir()),qF6=process.env.XDG_CONFIG_HOME?j0.file(process.env.XDG_CONFIG_HOME):f0.joinPath(bu1,".config");async function zB(J,Q){Wn1("0.0.1760832099-g685d5f");let Z=JX1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:e1.of([j0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:bu1,userConfigDir:qF6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (sJ1(),rJ1));X(Z);let Y=await Z.getLatest();l.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let K=Ba(HO({configService:Z})),q=f20({configService:Z,toolService:K}),G=pR0(K,C9,pe).catch((w)=>{l.warn("Toolbox registration failed, continuing anyway:",w)}),z=q.initialized.catch((w)=>{l.warn("MCP service initialization failed, continuing anyway:",w)});if(J.executeMode)await Promise.all([z,G]);if(Q.jetbrains)MO("JetBrains");else if(Q.ide&&ZZ6())MO("VS Code");else if(Q.ide&&XZ6())MO("Neovim");if(J.executeMode)Fn1(!0);a96(K,{configService:Z});let U,W=k5.status.pipe(C0((w)=>Boolean(w.connected&&w.authenticated)),c6()).subscribe((w)=>{if(w){if(!U)U=K.registerTool(Us)}else U?.dispose(),U=void 0}),F;if(!J.executeMode)F=new i71(process.cwd(),{},!0);else F=new class extends i71{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(s2.write(`No API key found. Starting login flow...
6346
6346
  `),!await VH9(J))await QR(),process.exit(1)}let H=await H40({isDevelopment:!1}),B=new fH1(H),M=new bH1(H,Z,{lazy:!0}),V=Q.notifications!==void 0?Q.notifications:!J.executeMode,N=s96({playNotificationSound:async(w)=>{if(V){r96(w);let R=Qh1(),O=Zh1();if((!R||O)&&Y.settings["notifications.system.enabled"]!==!1){if(w==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(w==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:B,configService:Z});l.info("Starting Amp background services");let L=w40({threadService:B,threadHistoryService:M,configService:Z,isExtensionDevelopment:!1}),A={configService:Z,toolService:K,mcpService:q,threadService:B,threadHistoryService:M,threadSyncService:L,threadStorage:H,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:F,notificationService:N,fileSystem:Q.jetbrains||Q.ide?Y40:C9};return{...A,async asyncDispose(){await A.mcpService.dispose(),await A.threadService.asyncDispose(),A.configService.unsubscribe(),A.toolService.dispose(),A.fuzzyServer.dispose(),A.threadSyncService.dispose(),A.settingsStorage[Symbol.dispose](),W.unsubscribe(),U?.dispose()}}}async function VH9(J){if(!J.executeMode){if(!await Iy1("Would you like to log in to Amp? [(y)es, (n)o]: "))return s2.write(`Login cancelled. Run the command again to retry.
6347
6347
  `),!1}return await GF6(J)}async function GF6(J){let Q=KH9(32).toString("hex"),Z=await Ey1(J.ampURL,Q);try{await KZ(Z)}catch(Y){l.error("Failed to open browser",{error:Y})}let X=await Ey1(J.ampURL,Q,!1);s2.write(`If your browser did not open automatically, visit:
6348
6348
 
@@ -6352,12 +6352,12 @@ ${H8.blue.bold(X)}
6352
6352
  Login successful! You can now use the Amp CLI.
6353
6353
  `),!0}catch(Y){return l.error("Login failed",{error:Y}),q4.write(`
6354
6354
  Login failed: ${Y instanceof Error?Y.message:String(Y)}
6355
- `),!1}}function NH9(){let J=new lm().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)KR(),process.exit(0);let H=F.originalError??F;eJ6(H)}),J.option("-V, --version","output the version number",()=>{s2.write(`0.0.1760817685-gfa6192 (released 2025-10-18T20:06:48.358Z)
6356
- `),process.exit(0)}),J.addHelpText("after",eQ6()),J.configureHelp({formatHelp:JZ6}),J.command("logout").description("Log out by removing stored API key").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await VY(B);await RH9(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 VY(B);await wH9(M,await By1(B,M.settings))});let Q=async(F,H,B)=>{JX1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:e1.of([j0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:bu1,userConfigDir:qF6});let M={...H,executeMode:!1};await _u1(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 VY(B);await XF6(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 VY(B);await TH9(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 VY(M);if(H.pick)await Q(M,V,B);else await PH9(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 VY(M);await IH9(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 VY(B);await XF6(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 VY(M);await EH9(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 VY(M);await $H9(M,V,F,B)}),YX6(J,async(F,H)=>{let B=await VY(H);GB(F,H);let M=await zB(B,H);return{context:B,mcpService:M.mcpService,toolService:M.toolService,configService:M.configService,cleanupTerminal:KR,asyncDispose:M.asyncDispose.bind(M)}}),vZ6(J),jZ6(J,async(F)=>{let H=await VY(F);return{settings:H.settings,getThreadDeps:async(B)=>{GB(B,F);let M=await zB(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 VY(B);GB(H,B);let V=await zB(M,B);try{await rb1(V,V.configService,{})}finally{await V.asyncDispose(),await KR()}});let X=new lm().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 wy1(F.force||!1,F.verbose||!1,"0.0.1760817685-gfa6192"),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=DH9(F);if(L)N.default(L);if(N.hidden=HH9(F)||ZF6(F),"choices"in F)N.choices([...F.choices]);return N}for(let F of QF6)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);if(J.addOption(K),process.env.AMP_CLI_REMOTE){let F=new gV("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1);J.addOption(F)}let q=new gV("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1);J.addOption(q);let G=new gV("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(G);let z=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(z),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 VY(B);if(Object.keys(B).forEach((V)=>{let N=QF6.find((L)=>L.name===V);if(N&&ZF6(N)&&!BH9(N))q4.write(H8.yellow(`Warning: '--${V}' flag is deprecated
6355
+ `),!1}}function NH9(){let J=new lm().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)KR(),process.exit(0);let H=F.originalError??F;eJ6(H)}),J.option("-V, --version","output the version number",()=>{s2.write(`0.0.1760832099-g685d5f (released 2025-10-19T00:07:12.709Z)
6356
+ `),process.exit(0)}),J.addHelpText("after",eQ6()),J.configureHelp({formatHelp:JZ6}),J.command("logout").description("Log out by removing stored API key").action(async(F,H)=>{let B=H.optsWithGlobals(),M=await VY(B);await RH9(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 VY(B);await wH9(M,await By1(B,M.settings))});let Q=async(F,H,B)=>{JX1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:e1.of([j0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:bu1,userConfigDir:qF6});let M={...H,executeMode:!1};await _u1(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 VY(B);await XF6(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 VY(B);await TH9(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 VY(M);if(H.pick)await Q(M,V,B);else await PH9(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 VY(M);await IH9(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 VY(B);await XF6(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 VY(M);await EH9(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 VY(M);await $H9(M,V,F,B)}),YX6(J,async(F,H)=>{let B=await VY(H);GB(F,H);let M=await zB(B,H);return{context:B,mcpService:M.mcpService,toolService:M.toolService,configService:M.configService,cleanupTerminal:KR,asyncDispose:M.asyncDispose.bind(M)}}),vZ6(J),jZ6(J,async(F)=>{let H=await VY(F);return{settings:H.settings,getThreadDeps:async(B)=>{GB(B,F);let M=await zB(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 VY(B);GB(H,B);let V=await zB(M,B);try{await rb1(V,V.configService,{})}finally{await V.asyncDispose(),await KR()}});let X=new lm().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 wy1(F.force||!1,F.verbose||!1,"0.0.1760832099-g685d5f"),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=DH9(F);if(L)N.default(L);if(N.hidden=HH9(F)||ZF6(F),"choices"in F)N.choices([...F.choices]);return N}for(let F of QF6)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);if(J.addOption(K),process.env.AMP_CLI_REMOTE){let F=new gV("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1);J.addOption(F)}let q=new gV("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1);J.addOption(q);let G=new gV("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(G);let z=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(z),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 VY(B);if(Object.keys(B).forEach((V)=>{let N=QF6.find((L)=>L.name===V);if(N&&ZF6(N)&&!BH9(N))q4.write(H8.yellow(`Warning: '--${V}' flag is deprecated
6357
6357
  `))}),H.args.length>0)MH9(M,H);await _u1(M,B,H)});let U=new lm("doctor").summary("Generate support bundle").description("Generate a support bundle for troubleshooting issues. This collects logs, configuration, and system information into a file that can be shared with Amp support for debugging.").option("--output-dir <path>","Directory to save the support bundle",process.cwd()).option("--include-full-logs","Include full log history",!1).allowUnknownOption(!1).action(async(F)=>{await jH9(F.outputDir,F.includeFullLogs)});J.addCommand(U);let W=new lm("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 OH9(F.version)});return J.addCommand(W),J}async function oJ1(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??Zq(),K=tJ1(J);if(Z)await J.threadStorage.set(Y,Z);let q=await uJ.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,X51(X));let G=J.threadService.observe(Y).subscribe(async(z)=>{if(r7(z,"assistant"))await xu1(Y),G.unsubscribe()});return await q.resume(),q}async function _u1(J,Q,Z){let X=Z51(Q);if(X instanceof Error)HX(X.message);let Y,K=null;if(Q.streamJsonInput)Y="";else if(typeof Q.execute==="string"){Y=Q.execute;let R=(await Ty1()).trimEnd();if(R)K=R}else Y=(await Ty1()).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"
6358
6358
  Or pipe via stdin: echo "your message" | amp --execute`);GB(Z,Q);let q=await zB(J,Q);KF6=q;let G=tJ1(q),z=async(R)=>{let O=await YF6(R,"utf-8"),j=JSON.parse(O);if(!UW(j.id))throw new m9(hK.invalidThreadId);return oJ1(q,{visibility:X,thread:j})},U=async(R)=>{if(!UW(R))throw new m9(hK.invalidThreadId);let O=await q.threadService.get(R)??void 0;if(l.info(`[fetchAndStartThread] Loaded thread ${R}, agentMode: ${O?.agentMode??"undefined"}`),O?.agentMode)l.info(`[fetchAndStartThread] Setting runtime override for agentMode to: ${O.agentMode}`),rG("experimental.agentMode",O.agentMode);else l.info("[fetchAndStartThread] No agentMode on thread, not setting override");return oJ1(q,{visibility:X,thread:O})},W=async()=>{try{if(Q.threadId)return U(Q.threadId);else return oJ1(q,{visibility:X})}catch(R){if(R instanceof m9)throw R;throw await h71(R,Q.threadId),Error("handleError should have called process.exit()")}},F=async()=>{return oJ1(q,{visibility:X})};if(Q.format==="jsonl")q4.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
6359
- `),await QR(),process.exit(1);if(J.executeMode&&Q.remote)await kZ6(Y,K,q.configService),await q.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await HQ6(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 Pr1();let R=await CO({jetbrainsOnly:Q.jetbrains});if(R.length===0){if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall")}else if(R.length===1){let O=R[0];if(O)k5.selectConfig(O)}else B=!0}let V=jy1("0.0.1760817685-gfa6192",q.settingsStorage),N=e1.of([j0.file(process.cwd())]),L=YS(void 0,N);if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let A=await Y5.getUserFreeTierStatus({},{config:q.configService});l.info("User free tier status:",A);let w=await yZ6();l.info("Loaded session state:",w),await JF6({stdout:process.stdout,history:new Jy1,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadSyncService:q.threadSyncService,threadID:H.threadID,worker:H,workerDeps:G,configService:q.configService,internalAPIClient:Y5,ampURL:J.ampURL,startNewThread:F,pickAndContinueThread:async()=>{l.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:k5,connectedClientsService:new Zc,commandRegistry:L,showJetBrainsInstaller:M,showIdePicker:B,startWithPicker:Q.startWithPicker,updateService:V,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:w,freeTierStatus:A.ok?A.result:void 0}),await q.asyncDispose(),process.exit(0)}async function VY(J){if(J.interactive)q4.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6360
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await pU(J.settingsFile),Y=dU({...J,settingsFile:X,getHook:process.env.AMP_URL?(G,z)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return z()}:void 0});if(await fZ6(Y),await hZ6(Y),J.mcpConfig){let G=await $Z6(J.mcpConfig);Y=FH9(Y,G)}let K=await Y.get("url","global");if(!K)K=WZ;if(!RB(K))l.info("Targeting custom Amp server",{ampURL:K});if(Y=Il1(Y),await Y.get("debug.httpLogging"))jl1();return{executeMode:Q,isTTY:Z,ampURL:K,settings:Y,secrets:_Z6(await By1(J,Y))}}function LH9(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 AH9(){let J=LH9(process.argv);if(xJ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),UH9(l),l.info("Starting Amp CLI.",{version:"0.0.1760817685-gfa6192",buildTimestamp:"2025-10-18T20:06:48.358Z",buildType:"'release'"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new m9(hK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await NH9().parseAsync(process.argv)}AH9().catch(h71);async function wH9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),s2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6359
+ `),await QR(),process.exit(1);if(J.executeMode&&Q.remote)await kZ6(Y,K,q.configService),await q.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await HQ6(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 Pr1();let R=await CO({jetbrainsOnly:Q.jetbrains});if(R.length===0){if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall")}else if(R.length===1){let O=R[0];if(O)k5.selectConfig(O)}else B=!0}let V=jy1("0.0.1760832099-g685d5f",q.settingsStorage),N=e1.of([j0.file(process.cwd())]),L=YS(void 0,N);if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let A=await Y5.getUserFreeTierStatus({},{config:q.configService});l.info("User free tier status:",A);let w=await yZ6();l.info("Loaded session state:",w),await JF6({stdout:process.stdout,history:new Jy1,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadSyncService:q.threadSyncService,threadID:H.threadID,worker:H,workerDeps:G,configService:q.configService,internalAPIClient:Y5,ampURL:J.ampURL,startNewThread:F,pickAndContinueThread:async()=>{l.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:k5,connectedClientsService:new Zc,commandRegistry:L,showJetBrainsInstaller:M,showIdePicker:B,startWithPicker:Q.startWithPicker,updateService:V,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:w,freeTierStatus:A.ok?A.result:void 0}),await q.asyncDispose(),process.exit(0)}async function VY(J){if(J.interactive)q4.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6360
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await pU(J.settingsFile),Y=dU({...J,settingsFile:X,getHook:process.env.AMP_URL?(G,z)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return z()}:void 0});if(await fZ6(Y),await hZ6(Y),J.mcpConfig){let G=await $Z6(J.mcpConfig);Y=FH9(Y,G)}let K=await Y.get("url","global");if(!K)K=WZ;if(!RB(K))l.info("Targeting custom Amp server",{ampURL:K});if(Y=Il1(Y),await Y.get("debug.httpLogging"))jl1();return{executeMode:Q,isTTY:Z,ampURL:K,settings:Y,secrets:_Z6(await By1(J,Y))}}function LH9(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 AH9(){let J=LH9(process.argv);if(xJ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),UH9(l),l.info("Starting Amp CLI.",{version:"0.0.1760832099-g685d5f",buildTimestamp:"2025-10-19T00:07:12.709Z",buildType:"'release'"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new m9(hK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await NH9().parseAsync(process.argv)}AH9().catch(h71);async function wH9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),s2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6361
6361
  `);else if(!RB(J.ampURL))s2.write(`Logging in to ${new URL(J.ampURL).hostname}
6362
6362
  `);let Z=process.env.AMP_API_KEY;if(Z)s2.write(`API key found in environment variable, storing...
6363
6363
  `),await Q.set("apiKey",Z,J.ampURL),s2.write(`API key successfully stored.
@@ -6373,7 +6373,7 @@ Or pipe via stdin: echo "your message" | amp --execute`);GB(Z,Q);let q=await zB(
6373
6373
  `));try{let Q;if(J)Q=J,q4.write(H8.blue(`Updating to version ${J}...
6374
6374
  `)),await BC(J),q4.write(H8.green(`✓ Successfully updated to version ${J}
6375
6375
  `));else{q4.write(H8.blue(`Checking for updates...
6376
- `));let{hasUpdate:X,latestVersion:Y}=await pj("0.0.1760817685-gfa6192");if(!X)q4.write(H8.green(`✓ Amp CLI is already up to date.
6376
+ `));let{hasUpdate:X,latestVersion:Y}=await pj("0.0.1760832099-g685d5f");if(!X)q4.write(H8.green(`✓ Amp CLI is already up to date.
6377
6377
  `)),process.exit(0);if(!Y)q4.write(H8.yellow("[WARN] could not find latest version")),process.exit(0);Q=Y,q4.write(H8.blue(`Updating to version ${Y}...
6378
6378
  `)),await BC(Y),q4.write(H8.green(`✓ Successfully updated to version ${Y}
6379
6379
  `))}let Z=await UR(Q);if(Z.warning)q4.write(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1760817685-gfa6192",
3
+ "version": "0.0.1760832099-g685d5f",
4
4
  "description": "CLI for Amp, an agentic coding tool built by Sourcegraph.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {