@sourcegraph/amp 0.0.1761681406-gc27eeb → 0.0.1761681682-g5b9199

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 +8 -8
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -6012,11 +6012,11 @@ Actual: ${Y}`)}async function u59(J,Q,Z){let{execSync:X}=await import("node:ch
6012
6012
  ${B}`;if(Y==="pnpm"&&B.includes("Unable to find the global bin directory"))M+=`
6013
6013
 
6014
6014
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
6015
- npm install -g @sourcegraph/amp`;q(Error(M))}},error:(H)=>{if(!W)W=!0,q(Error(`Failed to spawn ${Y}: ${H.message}`))},complete:()=>{if(!W)W=!0,G()}})})}G0();G0();async function e51(J){try{let Z=new AbortController,X=setTimeout(()=>Z.abort(),5000),Y=await fetch("https://registry.npmjs.org/@sourcegraph/amp",{signal:Z.signal});if(clearTimeout(X),!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await Y.json(),G=K["dist-tags"]?.latest;if(!G)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=i59(J,G),z=q<0,U,W;if(K.time){let F=K.time[J],H=K.time[G],B=Date.now();if(F)U=Math.floor((B-new Date(F).getTime())/3600000);if(H)W=Math.floor((B-new Date(H).getTime())/3600000)}return u.info("NPM version comparison",{currentVersion:J,latestVersion:G,compareResult:q,hasUpdate:z,currentVersionAge:U,latestVersionAge:W}),{hasUpdate:z,latestVersion:G,currentVersion:J,currentVersionAge:U,latestVersionAge:W,source:"npm"}}catch(Z){return u.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function i59(J,Q){let Z=(G)=>{let[q,z]=G.split("-");return{parts:q?.split(".").map(Number)||[],label:z}},X=Z(J),Y=Z(Q),K=Math.max(X.parts.length,Y.parts.length);for(let G=0;G<K;G++){let q=X.parts[G]||0,z=Y.parts[G]||0;if(q<z)return-1;if(q>z)return 1}if(X.label===Y.label)return 0;if(!X.label&&Y.label)return 1;if(X.label&&!Y.label)return-1;if(X.label&&Y.label)return X.label<Y.label?-1:1;return 0}v0();function uf1(J,Q){let Z=new f8,X=Z.pipe(M9({shouldCountRefs:!1}));return setImmediate(async()=>{let Y=new Zz().scoped("update"),K=X.subscribe({next:(G)=>{Y.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){Y.debug("using fake update status for testing",{status:G}),await f_(500),Z.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){Y.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let q=await Q.get("updates.mode");if(q==="disabled"){Y.debug("checking disabled");return}Y.debug("checking",{currentVersion:J,mode:q});let z=await e51(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let U=await t51();if(!q)q=U==="pnpm"?"warn":"auto",Y.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:q});if(q==="warn"){Z.next("update-available");return}if(!U){Y.debug("auto-update not supported, falling back to warn mode"),Z.next("update-available");return}try{await Bp(z.latestVersion,U);let W=await GN(z.latestVersion),F={from:z.currentVersion,to:z.latestVersion,...W};if(W.status==="same")Y.info("success",F),Z.next("updated");else Y.warn("success with warning",F),Z.next("updated-with-warning")}catch(W){Z.next("update-error")}}catch(G){Y.debug("check failed",{error:G})}finally{await f_(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as KW}from"node:process";function CX6(J){let Q=new Su().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(X)=>{await hf1(X.force||!1,X.verbose||!1,"0.0.1761681406-gc27eeb"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new Su("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(X)=>{await n59(X.version)});J.addCommand(Z)}async function n59(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")KW.write(W8.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6015
+ npm install -g @sourcegraph/amp`;q(Error(M))}},error:(H)=>{if(!W)W=!0,q(Error(`Failed to spawn ${Y}: ${H.message}`))},complete:()=>{if(!W)W=!0,G()}})})}G0();G0();async function e51(J){try{let Z=new AbortController,X=setTimeout(()=>Z.abort(),5000),Y=await fetch("https://registry.npmjs.org/@sourcegraph/amp",{signal:Z.signal});if(clearTimeout(X),!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await Y.json(),G=K["dist-tags"]?.latest;if(!G)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=i59(J,G),z=q<0,U,W;if(K.time){let F=K.time[J],H=K.time[G],B=Date.now();if(F)U=Math.floor((B-new Date(F).getTime())/3600000);if(H)W=Math.floor((B-new Date(H).getTime())/3600000)}return u.info("NPM version comparison",{currentVersion:J,latestVersion:G,compareResult:q,hasUpdate:z,currentVersionAge:U,latestVersionAge:W}),{hasUpdate:z,latestVersion:G,currentVersion:J,currentVersionAge:U,latestVersionAge:W,source:"npm"}}catch(Z){return u.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function i59(J,Q){let Z=(G)=>{let[q,z]=G.split("-");return{parts:q?.split(".").map(Number)||[],label:z}},X=Z(J),Y=Z(Q),K=Math.max(X.parts.length,Y.parts.length);for(let G=0;G<K;G++){let q=X.parts[G]||0,z=Y.parts[G]||0;if(q<z)return-1;if(q>z)return 1}if(X.label===Y.label)return 0;if(!X.label&&Y.label)return 1;if(X.label&&!Y.label)return-1;if(X.label&&Y.label)return X.label<Y.label?-1:1;return 0}v0();function uf1(J,Q){let Z=new f8,X=Z.pipe(M9({shouldCountRefs:!1}));return setImmediate(async()=>{let Y=new Zz().scoped("update"),K=X.subscribe({next:(G)=>{Y.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){Y.debug("using fake update status for testing",{status:G}),await f_(500),Z.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){Y.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let q=await Q.get("updates.mode");if(q==="disabled"){Y.debug("checking disabled");return}Y.debug("checking",{currentVersion:J,mode:q});let z=await e51(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let U=await t51();if(!q)q=U==="pnpm"?"warn":"auto",Y.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:q});if(q==="warn"){Z.next("update-available");return}if(!U){Y.debug("auto-update not supported, falling back to warn mode"),Z.next("update-available");return}try{await Bp(z.latestVersion,U);let W=await GN(z.latestVersion),F={from:z.currentVersion,to:z.latestVersion,...W};if(W.status==="same")Y.info("success",F),Z.next("updated");else Y.warn("success with warning",F),Z.next("updated-with-warning")}catch(W){Z.next("update-error")}}catch(G){Y.debug("check failed",{error:G})}finally{await f_(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as KW}from"node:process";function CX6(J){let Q=new Su().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(X)=>{await hf1(X.force||!1,X.verbose||!1,"0.0.1761681682-g5b9199"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new Su("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(X)=>{await n59(X.version)});J.addCommand(Z)}async function n59(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")KW.write(W8.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6016
6016
 
6017
6017
  `));try{if(!J){KW.write(W8.blue(`Checking for updates...
6018
- `));let{hasUpdate:Z,latestVersion:X}=await e51("0.0.1761681406-gc27eeb");if(!Z){KW.write(W8.green(`✓ Amp CLI is already up to date.
6019
- `));let Y=await GN("0.0.1761681406-gc27eeb");if(Y.warning)KW.write(`
6018
+ `));let{hasUpdate:Z,latestVersion:X}=await e51("0.0.1761681682-g5b9199");if(!Z){KW.write(W8.green(`✓ Amp CLI is already up to date.
6019
+ `));let Y=await GN("0.0.1761681682-g5b9199");if(Y.warning)KW.write(`
6020
6020
  `+W8.yellow(Y.warning)+`
6021
6021
  `);process.exit(0)}if(!X)KW.write(W8.yellow("[WARN] could not find latest version")),process.exit(0);J=X}KW.write(W8.blue(`Updating to version ${J}...
6022
6022
  `)),await Bp(J,void 0,(Z)=>{KW.write(W8.dim(`Running: ${Z}
@@ -6388,7 +6388,7 @@ See https://ampcode.com/manual#toolboxes`);return Q[0]||HO}function DY6(J,Q){let
6388
6388
  `);J.command("use").argument("<tool-name>","The tool to invoke").summary("Invoke a tool with arguments or JSON input from stdin").description(Z).option("--only <field>","Extract only the specified field from the result").allowUnknownOption(!0).allowExcessArguments(!0).action(async function(X,Y,K){let G=K.optsWithGlobals(),q=await Q(K,G),z=0;await q.mcpService.initialized;let U=K.args.slice(1),W;if(HY6()){let F=[];for await(let H of process.stdin)F.push(H);W=Buffer.concat(F).toString("utf-8").trim()}await WY6({toolName:X,rawArgs:U,stdinInput:W,only:Y.only,threadDeps:q,stdout:process.stdout,stderr:process.stderr,exit:(F)=>{z=F}}),await q.asyncDispose(),q.cleanupTerminal(),process.exit(z)})}import{randomBytes as DB9}from"node:crypto";import{homedir as MB9}from"node:os";import Id from"node:path";v0();G0();var MY6=120000,VY6=180000;function rf1(J,Q=Date.now()){return Q-J<VY6}function sf1(J,Q,Z=()=>!0,X){let Y=null,K=[],G=5;return mN(t1.of(void 0),rd(MY6).pipe(C7(()=>Z()))).pipe(q8(()=>c6(async(q)=>{let z=await X?.getContext();u.debug("[Ads] Fetching ad from server",{hasContext:!!z});let U=await J.getCurrentAd({context:z,excludeAdIds:K},{config:Q,signal:q});if(!U.ok)throw u.error("[Ads] Failed to fetch ad",{error:U.error.message}),Error(U.error.message);if(U.result){if(Y=U.result,K.length>=G)K.shift();K.push(Y.id),u.debug("[Ads] Received ad from server",{adTitle:Y.title,matchType:Y.matchType,matchedPatterns:Y.matchedPatterns,candidateAdPoolCount:Y.candidateAdPoolCount,recentlyShownCount:K.length})}else u.debug("[Ads] No ad available from server");return Y})),J8((q,z)=>q?.id===z?.id))}G0();Z$();U2();ZD();t9();vL();z8();k6();function NY6(J){let Q=J.trim();if(Q==="quit"||Q==="exit")return"/quit";return J}function LY6(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"}G0();ZD();import wQ9 from"node:fs";import AY6 from"node:path";function wY6(J){let Q=J.trim().replace(/^["']|["']$/g,"");if(Q=Q.replace(/\\(.)/g,"$1"),!/\.(png|jpe?g|gif|webp)$/i.test(Q))return null;if(!AY6.isAbsolute(Q))return null;return u.debug("Extracted image path",{original:J,extracted:Q}),Q}function RY6(J){try{let Q=AY6.extname(J).toLowerCase(),Z=G00(Q);if(!Z)return u.warn("Unsupported image file extension",{ext:Q}),null;try{let X=wQ9.readFileSync(J);return RQ9(X,Z)}catch(X){u.error(`Failed to read image file ${J}:`,X)}}catch(Q){u.error("Error handling image file path",{imagePath:J,error:Q})}return null}function RQ9(J,Q){if(J.length===0)return u.warn("Image file is empty (0 bytes)"),null;if(J.length>fW)return u.warn(`Image file too large: ${J.length} bytes (max: ${fW})`),null;return{type:"image",source:{type:"base64",data:J.toString("base64"),mediaType:Q}}}import{execSync as MG9}from"node:child_process";Rj();G0();import{spawn as OQ9}from"node:child_process";import{promises as jQ9}from"node:fs";function OY6(J){return J.kind==="executable"}function jY6(J){return J.kind==="markdown"}var JB=50000,$Y6=300000;async function Vp(J,Q,Z,X={}){let{timeoutMs:Y=$Y6,signal:K}=X;try{let G=await Z.getCommand(J);if(!G)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(u.debug("Executing command",{commandName:J,filePath:G.filePath,args:Q}),jY6(G))return await $Q9(G,Q);else if(OY6(G))return await EQ9(G,Q,Y,K);else return{success:!1,output:"",error:"Unsupported command type"}}catch(G){return u.error("Failed to execute command",{commandName:J,error:G}),{success:!1,output:"",error:G instanceof Error?G.message:"Unknown error occurred"}}}async function $Q9(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await jQ9.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>JB?Z.slice(0,JB)+`
6389
6389
  ... (output truncated at ${JB} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function EQ9(J,Q,Z=$Y6,X){return new Promise((Y)=>{let[K,G]=IQ9(J,Q);u.debug("Spawning command",{spawnCommand:K,spawnArgs:G.slice(0,10),filePath:J.filePath,timeoutMs:Z});let q=e10(X),z=!1,U=setTimeout(()=>{z=!0,q.abort(),u.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),W=OQ9(K,G,{stdio:["pipe","pipe","pipe"],signal:q.signal,detached:!0}),F=[],H=[],B=0;W.stdout?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=JB)F.push(V);else{let N=JB-(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<=JB)H.push(V);else{let N=JB-(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(q.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?`
6390
6390
  ${L}`:L;if(B>JB)A+=`
6391
- ... (output truncated at ${JB} 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 IQ9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return TQ9(Z,X?[...X]:null,Y,Q);else return PQ9(Z,X?[...X]:null,Y,Q)}function PQ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function TQ9(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]}}G0();Z$();U2();jW();cX();Pz();k6();v0();var GJ1={};j6(GJ1,{scrollUp:()=>aQ9,scrollDown:()=>rQ9,link:()=>QZ9,image:()=>ZZ9,iTerm:()=>XZ9,exitAlternativeScreen:()=>eQ9,eraseUp:()=>nQ9,eraseStartLine:()=>lQ9,eraseScreen:()=>of1,eraseLines:()=>dQ9,eraseLine:()=>TY6,eraseEndLine:()=>cQ9,eraseDown:()=>iQ9,enterAlternativeScreen:()=>tQ9,cursorUp:()=>IY6,cursorTo:()=>vQ9,cursorShow:()=>pQ9,cursorSavePosition:()=>yQ9,cursorRestorePosition:()=>fQ9,cursorPrevLine:()=>mQ9,cursorNextLine:()=>gQ9,cursorMove:()=>kQ9,cursorLeft:()=>PY6,cursorHide:()=>uQ9,cursorGetPosition:()=>hQ9,cursorForward:()=>xQ9,cursorDown:()=>_Q9,cursorBackward:()=>bQ9,clearTerminal:()=>oQ9,clearScreen:()=>sQ9,beep:()=>JZ9});import tf1 from"node:process";var KJ1=globalThis.window?.document!==void 0,OO2=globalThis.process?.versions?.node!==void 0,jO2=globalThis.process?.versions?.bun!==void 0,$O2=globalThis.Deno?.version?.deno!==void 0,EO2=globalThis.process?.versions?.electron!==void 0,IO2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,PO2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,TO2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,CO2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,SO2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,Np=globalThis.navigator?.userAgentData?.platform,vO2=Np==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",kO2=Np==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",_O2=Np==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",xO2=Np==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),bO2=Np==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var O2="\x1B[",Ap="\x1B]",_C="\x07",Lp=";",EY6=!KJ1&&tf1.env.TERM_PROGRAM==="Apple_Terminal",CQ9=!KJ1&&tf1.platform==="win32",SQ9=KJ1?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:tf1.cwd,vQ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return O2+(J+1)+"G";return O2+(Q+1)+Lp+(J+1)+"H"},kQ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=O2+-J+"D";else if(J>0)Z+=O2+J+"C";if(Q<0)Z+=O2+-Q+"A";else if(Q>0)Z+=O2+Q+"B";return Z},IY6=(J=1)=>O2+J+"A",_Q9=(J=1)=>O2+J+"B",xQ9=(J=1)=>O2+J+"C",bQ9=(J=1)=>O2+J+"D",PY6=O2+"G",yQ9=EY6?"\x1B7":O2+"s",fQ9=EY6?"\x1B8":O2+"u",hQ9=O2+"6n",gQ9=O2+"E",mQ9=O2+"F",uQ9=O2+"?25l",pQ9=O2+"?25h",dQ9=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=TY6+(Z<J-1?IY6():"");if(J)Q+=PY6;return Q},cQ9=O2+"K",lQ9=O2+"1K",TY6=O2+"2K",iQ9=O2+"J",nQ9=O2+"1J",of1=O2+"2J",aQ9=O2+"S",rQ9=O2+"T",sQ9="\x1Bc",oQ9=CQ9?`${of1}${O2}0f`:`${of1}${O2}3J${O2}H`,tQ9=O2+"?1049h",eQ9=O2+"?1049l",JZ9=_C,QZ9=(J,Q)=>[Ap,"8",Lp,Lp,Q,_C,J,Ap,"8",Lp,Lp,_C].join(""),ZZ9=(J,Q={})=>{let Z=`${Ap}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")+_C},XZ9={setCwd:(J=SQ9())=>`${Ap}50;CurrentDir=${J}${_C}`,annotation(J,Q={}){let Z=`${Ap}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+_C}};var qJ1=v6(bY6(),1);function UN(J,Q,{target:Z="stdout",...X}={}){if(!qJ1.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (​${Q}​)`}return GJ1.link(J,Q)}UN.isSupported=qJ1.default.stdout;UN.stderr=(J,Q,Z={})=>UN(J,Q,{target:"stderr",...Z});UN.stderr.isSupported=qJ1.default.stderr;G0();cX();class wp{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.1761681406-gc27eeb"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await fa(Q,this.configService)}catch(Q){u.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 UJ1}from"node:child_process";import{platform as Xh1}from"node:os";import{promisify as qZ9}from"node:util";var zJ1=qZ9(UJ1),zZ9=(J)=>`\x1B]52;c;${J}\x1B\\`,UZ9="\x1B]52;c;?\x1B\\",WZ9="\x1B]52;p;?\x1B\\";class yY6{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 zJ1("which",[J]),!0}catch{return!1}}async writeToPbcopy(J){try{let Q=UJ1("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=UJ1("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=UJ1("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(UZ9)}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 zJ1("pbpaste");return J}catch{return null}}async readFromWlPaste(J){try{let Q=["--no-newline"];if(J==="primary")Q.push("--primary");let{stdout:Z}=await zJ1("wl-paste",Q);return Z}catch{return null}}async readFromXclip(J){try{let{stdout:Q}=await zJ1("xclip",["-selection",J,"-o"]);return Q}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(WZ9)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if(Xh1()==="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(Xh1()==="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=zZ9(Z);process.stdout.write(X);return}if(Xh1()==="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 OY=new yY6;G0();class z2{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function WJ1(J){if(J instanceof z2)return{title:"Info",description:J.message,type:"info"};return u.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 VN=null,VG9={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(VN)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(() => (x51(),Lf1)),G=await K({worker:J.worker},J.configService,{clientId:J.clientId,onUserDisconnect:()=>{VN=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});VN=G,G.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((M)=>{VN=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(() => v6(vp(),1))).toString(W,{type:"utf8",margin:2,color:{dark:"#000000",light:"#FFFFFF"}})}catch(M){u.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 z2(`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(!VN)return new z2("Not connected to Amp web interface");try{VN.disconnect();let Z=VN.clientID;return VN=null,J.connectedClientsService.sendStatus({connected:!1,enabled:!1,errorMessage:void 0}),new z2(`Disconnected from Amp web interface
6391
+ ... (output truncated at ${JB} 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 IQ9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return TQ9(Z,X?[...X]:null,Y,Q);else return PQ9(Z,X?[...X]:null,Y,Q)}function PQ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function TQ9(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]}}G0();Z$();U2();jW();cX();Pz();k6();v0();var GJ1={};j6(GJ1,{scrollUp:()=>aQ9,scrollDown:()=>rQ9,link:()=>QZ9,image:()=>ZZ9,iTerm:()=>XZ9,exitAlternativeScreen:()=>eQ9,eraseUp:()=>nQ9,eraseStartLine:()=>lQ9,eraseScreen:()=>of1,eraseLines:()=>dQ9,eraseLine:()=>TY6,eraseEndLine:()=>cQ9,eraseDown:()=>iQ9,enterAlternativeScreen:()=>tQ9,cursorUp:()=>IY6,cursorTo:()=>vQ9,cursorShow:()=>pQ9,cursorSavePosition:()=>yQ9,cursorRestorePosition:()=>fQ9,cursorPrevLine:()=>mQ9,cursorNextLine:()=>gQ9,cursorMove:()=>kQ9,cursorLeft:()=>PY6,cursorHide:()=>uQ9,cursorGetPosition:()=>hQ9,cursorForward:()=>xQ9,cursorDown:()=>_Q9,cursorBackward:()=>bQ9,clearTerminal:()=>oQ9,clearScreen:()=>sQ9,beep:()=>JZ9});import tf1 from"node:process";var KJ1=globalThis.window?.document!==void 0,OO2=globalThis.process?.versions?.node!==void 0,jO2=globalThis.process?.versions?.bun!==void 0,$O2=globalThis.Deno?.version?.deno!==void 0,EO2=globalThis.process?.versions?.electron!==void 0,IO2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,PO2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,TO2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,CO2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,SO2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,Np=globalThis.navigator?.userAgentData?.platform,vO2=Np==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",kO2=Np==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",_O2=Np==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",xO2=Np==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),bO2=Np==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var O2="\x1B[",Ap="\x1B]",_C="\x07",Lp=";",EY6=!KJ1&&tf1.env.TERM_PROGRAM==="Apple_Terminal",CQ9=!KJ1&&tf1.platform==="win32",SQ9=KJ1?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:tf1.cwd,vQ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return O2+(J+1)+"G";return O2+(Q+1)+Lp+(J+1)+"H"},kQ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=O2+-J+"D";else if(J>0)Z+=O2+J+"C";if(Q<0)Z+=O2+-Q+"A";else if(Q>0)Z+=O2+Q+"B";return Z},IY6=(J=1)=>O2+J+"A",_Q9=(J=1)=>O2+J+"B",xQ9=(J=1)=>O2+J+"C",bQ9=(J=1)=>O2+J+"D",PY6=O2+"G",yQ9=EY6?"\x1B7":O2+"s",fQ9=EY6?"\x1B8":O2+"u",hQ9=O2+"6n",gQ9=O2+"E",mQ9=O2+"F",uQ9=O2+"?25l",pQ9=O2+"?25h",dQ9=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=TY6+(Z<J-1?IY6():"");if(J)Q+=PY6;return Q},cQ9=O2+"K",lQ9=O2+"1K",TY6=O2+"2K",iQ9=O2+"J",nQ9=O2+"1J",of1=O2+"2J",aQ9=O2+"S",rQ9=O2+"T",sQ9="\x1Bc",oQ9=CQ9?`${of1}${O2}0f`:`${of1}${O2}3J${O2}H`,tQ9=O2+"?1049h",eQ9=O2+"?1049l",JZ9=_C,QZ9=(J,Q)=>[Ap,"8",Lp,Lp,Q,_C,J,Ap,"8",Lp,Lp,_C].join(""),ZZ9=(J,Q={})=>{let Z=`${Ap}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")+_C},XZ9={setCwd:(J=SQ9())=>`${Ap}50;CurrentDir=${J}${_C}`,annotation(J,Q={}){let Z=`${Ap}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+_C}};var qJ1=v6(bY6(),1);function UN(J,Q,{target:Z="stdout",...X}={}){if(!qJ1.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (​${Q}​)`}return GJ1.link(J,Q)}UN.isSupported=qJ1.default.stdout;UN.stderr=(J,Q,Z={})=>UN(J,Q,{target:"stderr",...Z});UN.stderr.isSupported=qJ1.default.stderr;G0();cX();class wp{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.1761681682-g5b9199"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await fa(Q,this.configService)}catch(Q){u.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 UJ1}from"node:child_process";import{platform as Xh1}from"node:os";import{promisify as qZ9}from"node:util";var zJ1=qZ9(UJ1),zZ9=(J)=>`\x1B]52;c;${J}\x1B\\`,UZ9="\x1B]52;c;?\x1B\\",WZ9="\x1B]52;p;?\x1B\\";class yY6{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 zJ1("which",[J]),!0}catch{return!1}}async writeToPbcopy(J){try{let Q=UJ1("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=UJ1("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=UJ1("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(UZ9)}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 zJ1("pbpaste");return J}catch{return null}}async readFromWlPaste(J){try{let Q=["--no-newline"];if(J==="primary")Q.push("--primary");let{stdout:Z}=await zJ1("wl-paste",Q);return Z}catch{return null}}async readFromXclip(J){try{let{stdout:Q}=await zJ1("xclip",["-selection",J,"-o"]);return Q}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(WZ9)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if(Xh1()==="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(Xh1()==="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=zZ9(Z);process.stdout.write(X);return}if(Xh1()==="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 OY=new yY6;G0();class z2{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function WJ1(J){if(J instanceof z2)return{title:"Info",description:J.message,type:"info"};return u.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 VN=null,VG9={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(VN)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(() => (x51(),Lf1)),G=await K({worker:J.worker},J.configService,{clientId:J.clientId,onUserDisconnect:()=>{VN=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});VN=G,G.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((M)=>{VN=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(() => v6(vp(),1))).toString(W,{type:"utf8",margin:2,color:{dark:"#000000",light:"#FFFFFF"}})}catch(M){u.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 z2(`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(!VN)return new z2("Not connected to Amp web interface");try{VN.disconnect();let Z=VN.clientID;return VN=null,J.connectedClientsService.sendStatus({connected:!1,enabled:!1,errorMessage:void 0}),new z2(`Disconnected from Amp web interface
6392
6392
  Client ID: ${Z}
6393
6393
  Server will clean up automatically within 60 seconds`)}catch(Z){return Error(`Failed to disconnect: ${Z.message}`)}}}};class oh1{configService;commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=$S(),Q){this.configService=Q;this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Z)=>this.latestCustom=Z),this.telemetrySubmitter=new wp(async()=>{try{return(await this.configService.getLatest()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}},this.configService),this.configService.config.pipe(b0((Z)=>NZ(Z.settings)),J8()).subscribe((Z)=>{this._initBaseCommands(Z.length>1)})}_initBaseCommands(J){if(this.commands={...NG9},process.env.AMP_CONNECT==="1")Object.assign(this.commands,VG9);if(J)Object.assign(this.commands,LG9)}async execute(J,Q,Z=[],X){this.telemetrySubmitter.submit(J).catch((q)=>{u.debug("Failed to submit command telemetry",q)});let Y=this.commands[J];if(Y)return Y.execute(Q,Z);let K=this.latestCustom.find((q)=>q.name===J),G=await Vp(J,Z,this.customRegistry,{signal:X});if(G.success)if(K?.kind==="markdown"){Q.editorDispatch({type:"set-input",input:G.output});return}else{Q.submitMessage(G.output);return}return Error(G.error??`Command '${J}' failed`)}query(J,Q,Z){let X=Object.values(this.commands).filter((K)=>{if(!Q||!K.isVisible)return!0;return K.isVisible(Q,Z)}),Y=this.latestCustom.filter((K)=>K.available).map((K)=>({name:K.name,description:"Custom command",requiresArgs:K.kind==="executable",execute:(G,q)=>this.execute(K.name,G,q??[])}));return[...X,...Y]}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??[])}}getCustomCommand(J){return this.latestCustom.find((Q)=>Q.name===J)}}var NG9={"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=fZ(Z.settings),K=J.getInMemoryAgentModeOverride()??X;J.worker.handle({type:"user:message",message:{content:[{type:"text",text:ga}],agentMode:K}});return}},editor:{name:"editor",description:"Open $EDITOR to write a prompt",launchesWindow:!0,execute:async(J,Q)=>{return J.openInEditor("")}},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 LZ("dangerouslyAllowAll",!1),new z2("Amp is now following permissions rules for this session")}catch(K){return u.error("Failed to set dangerously allow all setting",K),Error("Failed to enable permissions for this session")}case"off":try{return LZ("dangerouslyAllowAll",!0),new z2("Permissions disabled for this session - you will NOT be asked for confirmation before Amp runs a command.")}catch(K){return u.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 GW();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 u.error("editPermissions exited with status",K),Error(X)},settingsFile:J.settingsFilePath,resolveEditor:GW};await vC(Y);return}catch(Y){u.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 u.error("Failed to start new thread",Z),Error("Failed to start new thread")}},isVisible:(J)=>J.messages.length!==0},handoff:{name:"handoff",description:"Draft a new thread with relevant context from current thread: /handoff <your goal>",requiresArgs:!0,execute:async()=>{return},isVisible:(J)=>J.messages.length!==0},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 z2(`Switched to existing thread: ${Z}`)}await J.pickAndContinueThread();return}catch(Z){return u.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((q)=>q.type==="text").map((q)=>q.text).join("").trim()}).filter(Boolean).join(`
6394
6394
  `).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=sW(new URL(Y),Z.id).toString(),q=`Thread URL: ${UN(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_unlisted"};break;default:return Error(`Invalid visibility option: ${z}. Use: private, workspace, group, or public`)}try{return await X.updateThreadMeta(Z.id,U),new z2(`${q}
@@ -6604,7 +6604,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
6604
6604
  `),J.stdout.write(`Thread: ${H}
6605
6605
  `),J.stdout.write(`Continue this thread with: amp threads continue ${W}
6606
6606
  `)}}function hp1(J){return J==="smart"?I1.rgb(3,197,97):J==="free"?I1.rgb(0,184,255):NB9(J)}function NB9(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 I1.index(Z[X])}Vg1();if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){XG.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
6607
- `)}var mp1=gp1.join(Di1||gp1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function OB9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),G=Z||"Warning",q=!1;J.warn(K,{name:G,code:X})}}function oq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")LZ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new k9("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${W8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")LZ("experimental.agentMode",Q.agentMode)}async function pp1(J){try{await AB9(gp1.dirname(mp1),{recursive:!0}),await wB9(mp1,J,"utf-8")}catch(Q){u.debug("Failed to save last thread ID",Q)}}async function jB9(){try{return(await YH6(mp1,"utf-8")).trim()}catch(J){return null}}function $B9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return gS("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 QH6=[{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??FZ,description:`Custom settings file path (overrides the default location ${FZ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(u).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${zf1})`},{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:nK(),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:wc}],ZH6=(J)=>("deprecated"in J)&&J.deprecated===!0,EB9=(J)=>("hidden"in J)&&J.hidden===!0,IB9=(J)=>("default"in J),PB9=(J)=>("default"in J)?J.default:void 0;function TB9(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((q)=>Z.includes(q)||q.includes(Z)),G="Run amp --help for a list of available commands.";if(K.length>0)G=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new k9(iK.unknownCommand(Z),1,G)}}var KH6=null;function W94(){return KH6}function QZ1(J){return{...J,getThreadEnvironment:T51,vfs:w70({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new a_(J.fileSystem),generateThreadTitle:kz0,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var dp1=$0.file(RB9.homedir()),GH6=process.env.XDG_CONFIG_HOME?$0.file(process.env.XDG_CONFIG_HOME):y0.joinPath(dp1,".config");async function tq(J,Q){Oa1("0.0.1761681406-gc27eeb");let Z=UY1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:t1.of([$0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:dp1,userConfigDir:GH6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (eQ1(),tQ1));X(Z);let Y=await Z.getLatest();u.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let K=Jr(fO({configService:Z})),G=s40({configService:Z,toolService:K}),q=Yj0(K,E2,h11).catch((O)=>{u.warn("Toolbox registration failed, continuing anyway:",O)}),z=G.initialized.catch((O)=>{u.warn("MCP service initialization failed, continuing anyway:",O)});if(J.executeMode)await Promise.all([z,q]);if(Q.jetbrains)mO("JetBrains");else if(Q.ide&&BX6())mO("VS Code");else if(Q.ide&&DX6())mO("Neovim");if(J.executeMode)ja1(!0);W46(K,{configService:Z});let U,W=v7.status.pipe(b0((O)=>Boolean(O.connected&&O.authenticated)),J8()).subscribe((O)=>{if(O){if(!U)U=K.registerTool(Xo)}else U?.dispose(),U=void 0}),F;if(!J.executeMode)F=new d51(process.cwd(),{},!0);else F=new class extends d51{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(e2.write(`No API key found. Starting login flow...
6607
+ `)}var mp1=gp1.join(Di1||gp1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function OB9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),G=Z||"Warning",q=!1;J.warn(K,{name:G,code:X})}}function oq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")LZ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new k9("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${W8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")LZ("experimental.agentMode",Q.agentMode)}async function pp1(J){try{await AB9(gp1.dirname(mp1),{recursive:!0}),await wB9(mp1,J,"utf-8")}catch(Q){u.debug("Failed to save last thread ID",Q)}}async function jB9(){try{return(await YH6(mp1,"utf-8")).trim()}catch(J){return null}}function $B9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return gS("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 QH6=[{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??FZ,description:`Custom settings file path (overrides the default location ${FZ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(u).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${zf1})`},{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:nK(),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:wc}],ZH6=(J)=>("deprecated"in J)&&J.deprecated===!0,EB9=(J)=>("hidden"in J)&&J.hidden===!0,IB9=(J)=>("default"in J),PB9=(J)=>("default"in J)?J.default:void 0;function TB9(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((q)=>Z.includes(q)||q.includes(Z)),G="Run amp --help for a list of available commands.";if(K.length>0)G=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new k9(iK.unknownCommand(Z),1,G)}}var KH6=null;function W94(){return KH6}function QZ1(J){return{...J,getThreadEnvironment:T51,vfs:w70({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new a_(J.fileSystem),generateThreadTitle:kz0,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var dp1=$0.file(RB9.homedir()),GH6=process.env.XDG_CONFIG_HOME?$0.file(process.env.XDG_CONFIG_HOME):y0.joinPath(dp1,".config");async function tq(J,Q){Oa1("0.0.1761681682-g5b9199");let Z=UY1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:t1.of([$0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:dp1,userConfigDir:GH6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (eQ1(),tQ1));X(Z);let Y=await Z.getLatest();u.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let K=Jr(fO({configService:Z})),G=s40({configService:Z,toolService:K}),q=Yj0(K,E2,h11).catch((O)=>{u.warn("Toolbox registration failed, continuing anyway:",O)}),z=G.initialized.catch((O)=>{u.warn("MCP service initialization failed, continuing anyway:",O)});if(J.executeMode)await Promise.all([z,q]);if(Q.jetbrains)mO("JetBrains");else if(Q.ide&&BX6())mO("VS Code");else if(Q.ide&&DX6())mO("Neovim");if(J.executeMode)ja1(!0);W46(K,{configService:Z});let U,W=v7.status.pipe(b0((O)=>Boolean(O.connected&&O.authenticated)),J8()).subscribe((O)=>{if(O){if(!U)U=K.registerTool(Xo)}else U?.dispose(),U=void 0}),F;if(!J.executeMode)F=new d51(process.cwd(),{},!0);else F=new class extends d51{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(e2.write(`No API key found. Starting login flow...
6608
6608
  `),!await CB9(J))await OR(),process.exit(1)}let H=await I70({isDevelopment:!1}),B=new WN1(H),M=new sB1(H,Z,{lazy:!0}),V=Q.notifications!==void 0?Q.notifications:!J.executeMode,N=H46({playNotificationSound:async(O)=>{if(V){F46(O);let j=Dg1(),$=Mg1();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});u.info("Starting Amp background services");let L=vz0({threadService:B,threadHistoryService:M,configService:Z,isExtensionDevelopment:!1}),A;v7.status.subscribe((O)=>{A=O});let R={codebaseContextService:new ZX1({workspaceRoots:[$0.file(process.cwd())],getCurrentFile:()=>{if(!A?.openFile)return;try{return $0.parse(A.openFile)}catch(O){u.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((j)=>j!==O).map((j)=>{try{return $0.parse(j)}catch($){return u.warn("Failed to parse visible file URI",{uri:j,error:$}),null}}).filter((j)=>j!==null)}}),configService:Z,toolService:K,mcpService:G,threadService:B,threadHistoryService:M,threadSyncService:L,threadStorage:H,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:F,notificationService:N,fileSystem:Q.jetbrains||Q.ide?N70:E2};return{...R,async asyncDispose(){await R.mcpService.dispose(),await R.threadService.asyncDispose(),R.configService.unsubscribe(),R.toolService.dispose(),R.fuzzyServer.dispose(),R.threadSyncService.dispose(),R.settingsStorage[Symbol.dispose](),W.unsubscribe(),U?.dispose()}}}async function CB9(J){if(!J.executeMode){if(!await cf1("Would you like to log in to Amp? [(y)es, (n)o]: "))return e2.write(`Login cancelled. Run the command again to retry.
6609
6609
  `),!1}return await qH6(J)}async function qH6(J){let Q=LB9(32).toString("hex"),Z=await df1(J.ampURL,Q),X=new AbortController;RY(Z,X.signal).catch((K)=>{u.error("Error opening browser",{err:K})});let Y=await df1(J.ampURL,Q,!1);e2.write(`If your browser does not open automatically, visit:
6610
6610
 
@@ -6614,13 +6614,13 @@ ${W8.blue.bold(Y)}
6614
6614
  Login successful! You can now use the Amp CLI.
6615
6615
  `),!0}catch(K){return u.error("Login failed",{error:K}),XG.write(`
6616
6616
  Login failed: ${K instanceof Error?K.message:String(K)}
6617
- `),!1}}function SB9(){let J=new Su().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((U)=>{if(U.code==="commander.help"||U.code==="commander.version"||U.exitCode===0)$R(),process.exit(0);let W=U.originalError??U;DZ6(W)}),J.option("-V, --version","output the version number",()=>{e2.write(`0.0.1761681406-gc27eeb (released 2025-10-28T20:01:47.590Z)
6617
+ `),!1}}function SB9(){let J=new Su().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((U)=>{if(U.code==="commander.help"||U.code==="commander.version"||U.exitCode===0)$R(),process.exit(0);let W=U.originalError??U;DZ6(W)}),J.option("-V, --version","output the version number",()=>{e2.write(`0.0.1761681682-g5b9199 (released 2025-10-28T20:06:37.290Z)
6618
6618
  `),process.exit(0)}),J.addHelpText("after",WX6()),J.configureHelp({formatHelp:FX6}),J.command("logout").description("Log out by removing stored API key").action(async(U,W)=>{let F=W.optsWithGlobals(),H=await jX(F);await xB9(H)}),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(U,W)=>{let F=W.optsWithGlobals(),H=await jX(F);await _B9(H,await vf1(F,H.settings))});let Q=async(U,W,F)=>{UY1({storage:W.settings,secretStorage:W.secrets,workspaceRoots:t1.of([$0.file(process.cwd())]),defaultAmpURL:W.ampURL,homeDir:dp1,userConfigDir:GH6});let H={...W,executeMode:!1};await up1(H,{...U,startWithPicker:!0},F)},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(U,W)=>{let F=W.optsWithGlobals(),H=await jX(F);await XH6(F,H,W)});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(U,W)=>{let F=W.optsWithGlobals(),H=await jX(F);await mB9(F,H,W)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, shows an interactive picker with the most recently used thread at the top. Use --last to continue the last thread directly without the picker.").option("--last","Continue the last thread directly without showing the picker").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(U,W,F)=>{let H=F.optsWithGlobals(),B=await jX(H);if(W.pick)XG.write(`${W8.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
6619
6619
  `);if(W.last||U||B.executeMode)await gB9(H,B,U,F);else await Q(H,B,F)}),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(U,W,F)=>{let H=F.optsWithGlobals(),B=await jX(H);await hB9(H,B,U,F)}),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(U,W)=>{let F=W.optsWithGlobals(),H=await jX(F);await XH6(F,H,W)}),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(U,W,F)=>{let H=F.optsWithGlobals(),B=await jX(H);await fB9(H,B,U,F,W.support)}),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(U,W,F,H)=>{let B=H.optsWithGlobals(),M=await jX(B);await bB9(B,M,U,W,H)}),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(U,W,F)=>{let H=F.optsWithGlobals(),B=await jX(H);await yB9(H,B,U,F)}),DY6(J,async(U,W)=>{let F=await jX(W);oq(U,W);let H=await tq(F,W);return{context:F,mcpService:H.mcpService,toolService:H.toolService,configService:H.configService,cleanupTerminal:$R,asyncDispose:H.asyncDispose.bind(H)}}),dX6(J),bX6(J,async(U)=>{let W=await jX(U);return{settings:W.settings,getThreadDeps:async(F)=>{oq(F,U);let H=await tq(W,U);return{mcpService:H.mcpService,asyncDispose:H.asyncDispose.bind(H)}}}}),J.command("connect").description("Connect CLI to web interface for multi-thread management").action(async(U,W)=>{let F=W.optsWithGlobals(),H=await jX(F);oq(W,F);let B=await tq(H,F);try{await Nf1(B,B.configService,{})}finally{await B.asyncDispose(),await $R()}});function X(U,W,F){let B=typeof U.description==="string"?U.description:F===void 0?U.description(!0):U.description(F),M=new rV(W,B),V=PB9(U);if(V)M.default(V);if(M.hidden=EB9(U)||ZH6(U),"choices"in U)M.choices([...U.choices]);return M}for(let U of QH6)switch(U.type){case"flag":{J.addOption(X(U,`--${U.long}`)),J.addOption(X(U,`--no-${U.long}`,!1));break}case"switch":{J.addOption(X(U,`--${U.long}`,!0));break}default:{J.addOption(X(U,`--${U.long} <value>`));break}}let Y=new rV("-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(Y);let K=new rV("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(K);let G=new rV("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1);J.addOption(G);let q=new rV("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(q);let z=new rV("--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 U=new rV("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(U)}return J.action(async(U,W)=>{let F=U,H=await jX(F);if(Object.keys(F).forEach((B)=>{let M=QH6.find((V)=>V.name===B);if(M&&ZH6(M)&&!IB9(M))XG.write(W8.yellow(`Warning: '--${B}' flag is deprecated
6620
6620
  `))}),W.args.length>0)TB9(H,W);await up1(H,F,W)}),CX6(J),J}async function JZ1(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??Fz(),K=QZ1(J);if(Z)await J.threadStorage.set(Y,Z);let G=await DJ.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,QJ1(X));let q=J.threadService.observe(Y).subscribe(async(z)=>{if(t7(z,"assistant"))await pp1(Y),q.unsubscribe()});return await G.resume(),G}async function up1(J,Q,Z){let X=JJ1(Q);if(X instanceof Error)ZG(X.message);let Y,K=null;if(Q.streamJsonInput)Y="";else if(typeof Q.execute==="string"){Y=Q.execute;let O=(await if1()).trimEnd();if(O)K=O}else Y=(await if1()).trimEnd();if(Q.remote&&!J.executeMode)throw new k9("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new k9("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new k9("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new k9("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 k9(`Execute mode is not permitted with --agent-mode '${Q.agentMode}'`,1);if(Q.stats&&!J.executeMode)throw new k9("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 k9("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 k9("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"
6621
6621
  Or pipe via stdin: echo "your message" | amp --execute`);oq(Z,Q);let G=await tq(J,Q);KH6=G;let q=QZ1(G),z=async(O)=>{let j=await YH6(O,"utf-8"),$=JSON.parse(j);if(!MG($.id))throw new k9(iK.invalidThreadId);return JZ1(G,{visibility:X,thread:$})},U=async(O)=>{if(!MG(O))throw new k9(iK.invalidThreadId);let j=await G.threadService.get(O)??void 0;if(u.info(`[fetchAndStartThread] Loaded thread ${O}, agentMode: ${j?.agentMode??"undefined"}`),j?.agentMode)u.info(`[fetchAndStartThread] Setting runtime override for agentMode to: ${j.agentMode}`),LZ("experimental.agentMode",j.agentMode);else u.info("[fetchAndStartThread] No agentMode on thread, not setting override");return JZ1(G,{visibility:X,thread:j})},W=async()=>{try{if(Q.threadId)return U(Q.threadId);else return JZ1(G,{visibility:X})}catch(O){if(O instanceof k9)throw O;throw await b51(O,Q.threadId),Error("handleError should have called process.exit()")}},F=async()=>{return JZ1(G,{visibility:X})};if(Q.format==="jsonl")XG.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
6622
- `),await OR(),process.exit(1);if(J.executeMode&&Q.remote)await cX6(Y,K,G.configService),await G.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await PZ6(H,H.threadID,Y,K,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let B=!1,M=!1;if(Q.jetbrains||Q.ide){await hs1();let O=await pB({jetbrainsOnly:Q.jetbrains});if(O.length===0){if(Q.jetbrains)M=!await G.configService.get("jetbrains.skipInstall")}else if(O.length===1){let j=O[0];if(j)v7.selectConfig(j)}else B=!0}let V=uf1("0.0.1761681406-gc27eeb",G.settingsStorage),N=new rB1(G.threadStorage),L=t1.of([$0.file(process.cwd())]),A=$S(void 0,L);if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let w;try{w=await qJ.getUserFreeTierStatus({},{config:G.configService})}catch(O){w={ok:!1,error:O}}u.info("User free tier status:",w);let R=await aX6();u.info("Loaded session state:",R),await JH6({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new Of1,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadSyncService:G.threadSyncService,threadID:H.threadID,threadFuzzyIndexer:N,worker:H,workerDeps:q,configService:G.configService,internalAPIClient:qJ,ampURL:J.ampURL,startNewThread:F,pickAndContinueThread:async()=>{u.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:v7,connectedClientsService:new nc,commandRegistry:A,showJetBrainsInstaller:M,showIdePicker:B,startWithPicker:Q.startWithPicker,updateService:V,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:R,freeTierStatus:w.ok?w.result:void 0}),await G.asyncDispose(),process.exit(0)}async function jX(J){if(J.interactive)XG.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6623
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await aZ6({...J,getHook:process.env.AMP_URL?(G,q)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let G=await yX6(J.mcpConfig);X=$B9(X,G)}let Y=await X.get("url","global");if(!Y)Y=AZ;if(!IB(Y))u.info("Targeting custom Amp server",{ampURL:Y});if(X=mi1(X),await X.get("debug.httpLogging"))vi1();return{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:lX6(await vf1(J,X))}}function vB9(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,(q,z)=>z.toUpperCase()),G=J[Z+1];if(G&&!G.startsWith("--"))Q[K]=G,Z++}}return Q}async function kB9(){let J=vB9(process.argv);if(sQ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),OB9(u),u.info("Starting Amp CLI.",{version:"0.0.1761681406-gc27eeb",buildTimestamp:"2025-10-28T20:01:47.590Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new k9(iK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await SB9().parseAsync(process.argv)}kB9().catch(b51);async function _B9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),e2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6622
+ `),await OR(),process.exit(1);if(J.executeMode&&Q.remote)await cX6(Y,K,G.configService),await G.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await PZ6(H,H.threadID,Y,K,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let B=!1,M=!1;if(Q.jetbrains||Q.ide){await hs1();let O=await pB({jetbrainsOnly:Q.jetbrains});if(O.length===0){if(Q.jetbrains)M=!await G.configService.get("jetbrains.skipInstall")}else if(O.length===1){let j=O[0];if(j)v7.selectConfig(j)}else B=!0}let V=uf1("0.0.1761681682-g5b9199",G.settingsStorage),N=new rB1(G.threadStorage),L=t1.of([$0.file(process.cwd())]),A=$S(void 0,L);if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let w;try{w=await qJ.getUserFreeTierStatus({},{config:G.configService})}catch(O){w={ok:!1,error:O}}u.info("User free tier status:",w);let R=await aX6();u.info("Loaded session state:",R),await JH6({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new Of1,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadSyncService:G.threadSyncService,threadID:H.threadID,threadFuzzyIndexer:N,worker:H,workerDeps:q,configService:G.configService,internalAPIClient:qJ,ampURL:J.ampURL,startNewThread:F,pickAndContinueThread:async()=>{u.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:v7,connectedClientsService:new nc,commandRegistry:A,showJetBrainsInstaller:M,showIdePicker:B,startWithPicker:Q.startWithPicker,updateService:V,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:R,freeTierStatus:w.ok?w.result:void 0}),await G.asyncDispose(),process.exit(0)}async function jX(J){if(J.interactive)XG.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6623
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await aZ6({...J,getHook:process.env.AMP_URL?(G,q)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let G=await yX6(J.mcpConfig);X=$B9(X,G)}let Y=await X.get("url","global");if(!Y)Y=AZ;if(!IB(Y))u.info("Targeting custom Amp server",{ampURL:Y});if(X=mi1(X),await X.get("debug.httpLogging"))vi1();return{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:lX6(await vf1(J,X))}}function vB9(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,(q,z)=>z.toUpperCase()),G=J[Z+1];if(G&&!G.startsWith("--"))Q[K]=G,Z++}}return Q}async function kB9(){let J=vB9(process.argv);if(sQ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),OB9(u),u.info("Starting Amp CLI.",{version:"0.0.1761681682-g5b9199",buildTimestamp:"2025-10-28T20:06:37.290Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new k9(iK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await SB9().parseAsync(process.argv)}kB9().catch(b51);async function _B9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),e2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6624
6624
  `);else if(!IB(J.ampURL))e2.write(`Logging in to ${new URL(J.ampURL).hostname}
6625
6625
  `);let Z=process.env.AMP_API_KEY;if(Z)e2.write(`API key found in environment variable, storing...
6626
6626
  `),await Q.set("apiKey",Z,J.ampURL),e2.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1761681406-gc27eeb",
3
+ "version": "0.0.1761681682-g5b9199",
4
4
  "description": "CLI for Amp, the frontier coding agent from Sourcegraph.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {