@sourcegraph/amp 0.0.1761696104-g382fd7 → 0.0.1761710698-g945ae7

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
@@ -6038,11 +6038,11 @@ Actual: ${Y}`)}async function qJ9(J,Q,Z){let{execSync:X}=await import("node:ch
6038
6038
  ${B}`;if(Y==="pnpm"&&B.includes("Unable to find the global bin directory"))M+=`
6039
6039
 
6040
6040
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
6041
- 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 KJ1(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=HJ9(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 HJ9(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 sf1(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 d_(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 KJ1(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let U=await YJ1();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 Ap(z.latestVersion,U);let W=await qN(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 d_(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as GW}from"node:process";function dX6(J){let Q=new DR().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 nf1(X.force||!1,X.verbose||!1,"0.0.1761696104-g382fd7"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new DR("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 BJ9(X.version)});J.addCommand(Z)}async function BJ9(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")GW.write(W8.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6041
+ 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 KJ1(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=HJ9(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 HJ9(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 sf1(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 d_(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 KJ1(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let U=await YJ1();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 Ap(z.latestVersion,U);let W=await qN(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 d_(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as GW}from"node:process";function dX6(J){let Q=new DR().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 nf1(X.force||!1,X.verbose||!1,"0.0.1761710698-g945ae7"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new DR("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 BJ9(X.version)});J.addCommand(Z)}async function BJ9(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")GW.write(W8.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6042
6042
 
6043
6043
  `));try{if(!J){GW.write(W8.blue(`Checking for updates...
6044
- `));let{hasUpdate:Z,latestVersion:X}=await KJ1("0.0.1761696104-g382fd7");if(!Z){GW.write(W8.green(`✓ Amp CLI is already up to date.
6045
- `));let Y=await qN("0.0.1761696104-g382fd7");if(Y.warning)GW.write(`
6044
+ `));let{hasUpdate:Z,latestVersion:X}=await KJ1("0.0.1761710698-g945ae7");if(!Z){GW.write(W8.green(`✓ Amp CLI is already up to date.
6045
+ `));let Y=await qN("0.0.1761710698-g945ae7");if(Y.warning)GW.write(`
6046
6046
  `+W8.yellow(Y.warning)+`
6047
6047
  `);process.exit(0)}if(!X)GW.write(W8.yellow("[WARN] could not find latest version")),process.exit(0);J=X}GW.write(W8.blue(`Updating to version ${J}...
6048
6048
  `)),await Ap(J,void 0,(Z)=>{GW.write(W8.dim(`Running: ${Z}
@@ -6462,7 +6462,7 @@ See https://ampcode.com/manual#toolboxes`);return Q[0]||MO}function CY6(J,Q){let
6462
6462
  `);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(PY6()){let F=[];for await(let H of process.stdin)F.push(H);W=Buffer.concat(F).toString("utf-8").trim()}await EY6({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 vB9}from"node:crypto";import{homedir as kB9}from"node:os";import kd from"node:path";v0();G0();var SY6=120000,vY6=180000;function Xh1(J,Q=Date.now()){return Q-J<vY6}function Yh1(J,Q,Z=()=>!0,X){let Y=null,K=[],G=5;return uN(t1.of(void 0),Qc(SY6).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();G$();U2();YD();t9();_L();z8();k6();function kY6(J){let Q=J.trim();if(Q==="quit"||Q==="exit")return"/quit";return J}function _Y6(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();YD();import fQ9 from"node:fs";import xY6 from"node:path";function bY6(J){let Q=J.trim().replace(/^["']|["']$/g,"");if(Q=Q.replace(/\\(.)/g,"$1"),!/\.(png|jpe?g|gif|webp)$/i.test(Q))return null;if(!xY6.isAbsolute(Q))return null;return u.debug("Extracted image path",{original:J,extracted:Q}),Q}function yY6(J){try{let Q=xY6.extname(J).toLowerCase(),Z=w00(Q);if(!Z)return u.warn("Unsupported image file extension",{ext:Q}),null;try{let X=fQ9.readFileSync(J);return hQ9(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 hQ9(J,Q){if(J.length===0)return u.warn("Image file is empty (0 bytes)"),null;if(J.length>gW)return u.warn(`Image file too large: ${J.length} bytes (max: ${gW})`),null;return{type:"image",source:{type:"base64",data:J.toString("base64"),mediaType:Q}}}import{execSync as kG9}from"node:child_process";Ej();G0();import{spawn as gQ9}from"node:child_process";import{promises as mQ9}from"node:fs";function fY6(J){return J.kind==="executable"}function hY6(J){return J.kind==="markdown"}var ZB=50000,gY6=300000;async function Op(J,Q,Z,X={}){let{timeoutMs:Y=gY6,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}),hY6(G))return await uQ9(G,Q);else if(fY6(G))return await pQ9(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 uQ9(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await mQ9.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>ZB?Z.slice(0,ZB)+`
6463
6463
  ... (output truncated at ${ZB} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function pQ9(J,Q,Z=gY6,X){return new Promise((Y)=>{let[K,G]=dQ9(J,Q);u.debug("Spawning command",{spawnCommand:K,spawnArgs:G.slice(0,10),filePath:J.filePath,timeoutMs:Z});let q=B00(X),z=!1,U=setTimeout(()=>{z=!0,q.abort(),u.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),W=gQ9(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<=ZB)F.push(V);else{let N=ZB-(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<=ZB)H.push(V);else{let N=ZB-(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?`
6464
6464
  ${L}`:L;if(B>ZB)A+=`
6465
- ... (output truncated at ${ZB} 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 dQ9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return lQ9(Z,X?[...X]:null,Y,Q);else return cQ9(Z,X?[...X]:null,Y,Q)}function cQ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function lQ9(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();G$();U2();EW();iX();Pz();k6();v0();var HJ1={};j6(HJ1,{scrollUp:()=>FZ9,scrollDown:()=>HZ9,link:()=>LZ9,image:()=>AZ9,iTerm:()=>wZ9,exitAlternativeScreen:()=>VZ9,eraseUp:()=>WZ9,eraseStartLine:()=>zZ9,eraseScreen:()=>Kh1,eraseLines:()=>GZ9,eraseLine:()=>dY6,eraseEndLine:()=>qZ9,eraseDown:()=>UZ9,enterAlternativeScreen:()=>MZ9,cursorUp:()=>uY6,cursorTo:()=>aQ9,cursorShow:()=>KZ9,cursorSavePosition:()=>eQ9,cursorRestorePosition:()=>JZ9,cursorPrevLine:()=>XZ9,cursorNextLine:()=>ZZ9,cursorMove:()=>rQ9,cursorLeft:()=>pY6,cursorHide:()=>YZ9,cursorGetPosition:()=>QZ9,cursorForward:()=>oQ9,cursorDown:()=>sQ9,cursorBackward:()=>tQ9,clearTerminal:()=>DZ9,clearScreen:()=>BZ9,beep:()=>NZ9});import Gh1 from"node:process";var FJ1=globalThis.window?.document!==void 0,Mj2=globalThis.process?.versions?.node!==void 0,Vj2=globalThis.process?.versions?.bun!==void 0,Nj2=globalThis.Deno?.version?.deno!==void 0,Lj2=globalThis.process?.versions?.electron!==void 0,Aj2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,wj2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,Rj2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,Oj2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,jj2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,jp=globalThis.navigator?.userAgentData?.platform,$j2=jp==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",Ej2=jp==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",Ij2=jp==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",Pj2=jp==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),Tj2=jp==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var O2="\x1B[",Ep="\x1B]",fC="\x07",$p=";",mY6=!FJ1&&Gh1.env.TERM_PROGRAM==="Apple_Terminal",iQ9=!FJ1&&Gh1.platform==="win32",nQ9=FJ1?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Gh1.cwd,aQ9=(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)+$p+(J+1)+"H"},rQ9=(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},uY6=(J=1)=>O2+J+"A",sQ9=(J=1)=>O2+J+"B",oQ9=(J=1)=>O2+J+"C",tQ9=(J=1)=>O2+J+"D",pY6=O2+"G",eQ9=mY6?"\x1B7":O2+"s",JZ9=mY6?"\x1B8":O2+"u",QZ9=O2+"6n",ZZ9=O2+"E",XZ9=O2+"F",YZ9=O2+"?25l",KZ9=O2+"?25h",GZ9=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=dY6+(Z<J-1?uY6():"");if(J)Q+=pY6;return Q},qZ9=O2+"K",zZ9=O2+"1K",dY6=O2+"2K",UZ9=O2+"J",WZ9=O2+"1J",Kh1=O2+"2J",FZ9=O2+"S",HZ9=O2+"T",BZ9="\x1Bc",DZ9=iQ9?`${Kh1}${O2}0f`:`${Kh1}${O2}3J${O2}H`,MZ9=O2+"?1049h",VZ9=O2+"?1049l",NZ9=fC,LZ9=(J,Q)=>[Ep,"8",$p,$p,Q,fC,J,Ep,"8",$p,$p,fC].join(""),AZ9=(J,Q={})=>{let Z=`${Ep}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")+fC},wZ9={setCwd:(J=nQ9())=>`${Ep}50;CurrentDir=${J}${fC}`,annotation(J,Q={}){let Z=`${Ep}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+fC}};var BJ1=v6(sY6(),1);function WN(J,Q,{target:Z="stdout",...X}={}){if(!BJ1.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (​${Q}​)`}return HJ1.link(J,Q)}WN.isSupported=BJ1.default.stdout;WN.stderr=(J,Q,Z={})=>WN(J,Q,{target:"stderr",...Z});WN.stderr.isSupported=BJ1.default.stderr;G0();iX();class Ip{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.1761696104-g382fd7"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await da(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 MJ1}from"node:child_process";import{platform as Fh1}from"node:os";import{promisify as $Z9}from"node:util";var DJ1=$Z9(MJ1),EZ9=(J)=>`\x1B]52;c;${J}\x1B\\`,IZ9="\x1B]52;c;?\x1B\\",PZ9="\x1B]52;p;?\x1B\\";class oY6{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 DJ1("which",[J]),!0}catch{return!1}}async writeToPbcopy(J){try{let Q=MJ1("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=MJ1("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=MJ1("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(IZ9)}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 DJ1("pbpaste");return J}catch{return null}}async readFromWlPaste(J){try{let Q=["--no-newline"];if(J==="primary")Q.push("--primary");let{stdout:Z}=await DJ1("wl-paste",Q);return Z}catch{return null}}async readFromXclip(J){try{let{stdout:Q}=await DJ1("xclip",["-selection",J,"-o"]);return Q}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(PZ9)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if(Fh1()==="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(Fh1()==="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=EZ9(Z);process.stdout.write(X);return}if(Fh1()==="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 jY=new oY6;G0();class z2{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function VJ1(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 NN=null,_G9={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(NN)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(() => (m51(),Pf1)),G=await K({worker:J.worker},J.configService,{clientId:J.clientId,onUserDisconnect:()=>{NN=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});NN=G,G.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((M)=>{NN=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(fp(),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(!NN)return new z2("Not connected to Amp web interface");try{NN.disconnect();let Z=NN.clientID;return NN=null,J.connectedClientsService.sendStatus({connected:!1,enabled:!1,errorMessage:void 0}),new z2(`Disconnected from Amp web interface
6465
+ ... (output truncated at ${ZB} 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 dQ9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return lQ9(Z,X?[...X]:null,Y,Q);else return cQ9(Z,X?[...X]:null,Y,Q)}function cQ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function lQ9(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();G$();U2();EW();iX();Pz();k6();v0();var HJ1={};j6(HJ1,{scrollUp:()=>FZ9,scrollDown:()=>HZ9,link:()=>LZ9,image:()=>AZ9,iTerm:()=>wZ9,exitAlternativeScreen:()=>VZ9,eraseUp:()=>WZ9,eraseStartLine:()=>zZ9,eraseScreen:()=>Kh1,eraseLines:()=>GZ9,eraseLine:()=>dY6,eraseEndLine:()=>qZ9,eraseDown:()=>UZ9,enterAlternativeScreen:()=>MZ9,cursorUp:()=>uY6,cursorTo:()=>aQ9,cursorShow:()=>KZ9,cursorSavePosition:()=>eQ9,cursorRestorePosition:()=>JZ9,cursorPrevLine:()=>XZ9,cursorNextLine:()=>ZZ9,cursorMove:()=>rQ9,cursorLeft:()=>pY6,cursorHide:()=>YZ9,cursorGetPosition:()=>QZ9,cursorForward:()=>oQ9,cursorDown:()=>sQ9,cursorBackward:()=>tQ9,clearTerminal:()=>DZ9,clearScreen:()=>BZ9,beep:()=>NZ9});import Gh1 from"node:process";var FJ1=globalThis.window?.document!==void 0,Mj2=globalThis.process?.versions?.node!==void 0,Vj2=globalThis.process?.versions?.bun!==void 0,Nj2=globalThis.Deno?.version?.deno!==void 0,Lj2=globalThis.process?.versions?.electron!==void 0,Aj2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,wj2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,Rj2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,Oj2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,jj2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,jp=globalThis.navigator?.userAgentData?.platform,$j2=jp==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",Ej2=jp==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",Ij2=jp==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",Pj2=jp==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),Tj2=jp==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var O2="\x1B[",Ep="\x1B]",fC="\x07",$p=";",mY6=!FJ1&&Gh1.env.TERM_PROGRAM==="Apple_Terminal",iQ9=!FJ1&&Gh1.platform==="win32",nQ9=FJ1?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Gh1.cwd,aQ9=(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)+$p+(J+1)+"H"},rQ9=(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},uY6=(J=1)=>O2+J+"A",sQ9=(J=1)=>O2+J+"B",oQ9=(J=1)=>O2+J+"C",tQ9=(J=1)=>O2+J+"D",pY6=O2+"G",eQ9=mY6?"\x1B7":O2+"s",JZ9=mY6?"\x1B8":O2+"u",QZ9=O2+"6n",ZZ9=O2+"E",XZ9=O2+"F",YZ9=O2+"?25l",KZ9=O2+"?25h",GZ9=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=dY6+(Z<J-1?uY6():"");if(J)Q+=pY6;return Q},qZ9=O2+"K",zZ9=O2+"1K",dY6=O2+"2K",UZ9=O2+"J",WZ9=O2+"1J",Kh1=O2+"2J",FZ9=O2+"S",HZ9=O2+"T",BZ9="\x1Bc",DZ9=iQ9?`${Kh1}${O2}0f`:`${Kh1}${O2}3J${O2}H`,MZ9=O2+"?1049h",VZ9=O2+"?1049l",NZ9=fC,LZ9=(J,Q)=>[Ep,"8",$p,$p,Q,fC,J,Ep,"8",$p,$p,fC].join(""),AZ9=(J,Q={})=>{let Z=`${Ep}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")+fC},wZ9={setCwd:(J=nQ9())=>`${Ep}50;CurrentDir=${J}${fC}`,annotation(J,Q={}){let Z=`${Ep}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+fC}};var BJ1=v6(sY6(),1);function WN(J,Q,{target:Z="stdout",...X}={}){if(!BJ1.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (​${Q}​)`}return HJ1.link(J,Q)}WN.isSupported=BJ1.default.stdout;WN.stderr=(J,Q,Z={})=>WN(J,Q,{target:"stderr",...Z});WN.stderr.isSupported=BJ1.default.stderr;G0();iX();class Ip{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.1761710698-g945ae7"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await da(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 MJ1}from"node:child_process";import{platform as Fh1}from"node:os";import{promisify as $Z9}from"node:util";var DJ1=$Z9(MJ1),EZ9=(J)=>`\x1B]52;c;${J}\x1B\\`,IZ9="\x1B]52;c;?\x1B\\",PZ9="\x1B]52;p;?\x1B\\";class oY6{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 DJ1("which",[J]),!0}catch{return!1}}async writeToPbcopy(J){try{let Q=MJ1("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=MJ1("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=MJ1("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(IZ9)}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 DJ1("pbpaste");return J}catch{return null}}async readFromWlPaste(J){try{let Q=["--no-newline"];if(J==="primary")Q.push("--primary");let{stdout:Z}=await DJ1("wl-paste",Q);return Z}catch{return null}}async readFromXclip(J){try{let{stdout:Q}=await DJ1("xclip",["-selection",J,"-o"]);return Q}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(PZ9)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if(Fh1()==="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(Fh1()==="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=EZ9(Z);process.stdout.write(X);return}if(Fh1()==="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 jY=new oY6;G0();class z2{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function VJ1(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 NN=null,_G9={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(NN)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(() => (m51(),Pf1)),G=await K({worker:J.worker},J.configService,{clientId:J.clientId,onUserDisconnect:()=>{NN=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});NN=G,G.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((M)=>{NN=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(fp(),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(!NN)return new z2("Not connected to Amp web interface");try{NN.disconnect();let Z=NN.clientID;return NN=null,J.connectedClientsService.sendStatus({connected:!1,enabled:!1,errorMessage:void 0}),new z2(`Disconnected from Amp web interface
6466
6466
  Client ID: ${Z}
6467
6467
  Server will clean up automatically within 60 seconds`)}catch(Z){return Error(`Failed to disconnect: ${Z.message}`)}}}};class Kg1{configService;commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=CS(),Q){this.configService=Q;this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Z)=>this.latestCustom=Z),this.telemetrySubmitter=new Ip(async()=>{try{return(await this.configService.getLatest()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}},this.configService),this.configService.config.pipe(b0((Z)=>wZ(Z.settings)),J8()).subscribe((Z)=>{this._initBaseCommands(Z.length>1)})}_initBaseCommands(J){if(this.commands={...xG9},process.env.AMP_CONNECT==="1")Object.assign(this.commands,_G9);if(J)Object.assign(this.commands,bG9)}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 Op(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 xG9={"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=mZ(Z.settings),K=J.getInMemoryAgentModeOverride()??X;J.worker.handle({type:"user:message",message:{content:[{type:"text",text:la}],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 RZ("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 RZ("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 qW();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:qW};await bC(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(`
6468
6468
  `).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=tW(new URL(Y),Z.id).toString(),q=`Thread URL: ${WN(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}
@@ -6678,7 +6678,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
6678
6678
  `),J.stdout.write(`Thread: ${H}
6679
6679
  `),J.stdout.write(`Continue this thread with: amp threads continue ${W}
6680
6680
  `)}}function ip1(J){return J==="smart"?I1.rgb(3,197,97):J==="free"?I1.rgb(0,184,255):xB9(J)}function xB9(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])}$g1();if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){YG.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
6681
- `)}var ap1=np1.join(Oi1||np1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function gB9(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")RZ("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")RZ("experimental.agentMode",Q.agentMode)}async function sp1(J){try{await yB9(np1.dirname(ap1),{recursive:!0}),await fB9(ap1,J,"utf-8")}catch(Q){u.debug("Failed to save last thread ID",Q)}}async function mB9(){try{return(await AH6(ap1,"utf-8")).trim()}catch(J){return null}}function uB9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return cS("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 VH6=[{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??DZ,description:`Custom settings file path (overrides the default location ${DZ})`},{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 ${Nf1})`},{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:LQ(),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:Ec}],NH6=(J)=>("deprecated"in J)&&J.deprecated===!0,pB9=(J)=>("hidden"in J)&&J.hidden===!0,dB9=(J)=>("default"in J),cB9=(J)=>("default"in J)?J.default:void 0;function lB9(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(aK.unknownCommand(Z),1,G)}}var wH6=null;function z24(){return wH6}function qZ1(J){return{...J,getThreadEnvironment:x51,vfs:x70({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new Qx(J.fileSystem),generateThreadTitle:iz0,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var op1=$0.file(hB9.homedir()),RH6=process.env.XDG_CONFIG_HOME?$0.file(process.env.XDG_CONFIG_HOME):y0.joinPath(op1,".config");async function tq(J,Q){Sa1("0.0.1761696104-g382fd7");let Z=VY1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:t1.of([$0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:op1,userConfigDir:RH6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (KZ1(),YZ1));X(Z);let Y=await Z.getLatest();u.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let K=Gr(mO({configService:Z})),G=new Map,q=()=>G.clear(),z=W70({configService:Z,toolService:K,secretStorage:J.secrets,createOAuthProvider:async(E)=>{let I=G.get(E);if(I)return u.debug("Reusing existing OAuth provider for server",{serverName:E}),I;u.debug("Creating OAuth provider for server",{serverName:E});let T=(async()=>{let S=new P3(J.secrets),_=await S.getClientInfo(E),h=new gW1({storage:S,serverName:E,clientId:_?.clientId,clientSecret:_?.clientSecret,scopes:_?.scopes});return u.debug("OAuth provider created",{serverName:E,hasManualClientId:!!_?.clientId,willUseDCR:!_?.clientId}),h})();return G.set(E,T),T}}),U=Lj0(K,E2,c11).catch((E)=>{u.warn("Toolbox registration failed, continuing anyway:",E)}),W=z.initialized.catch((E)=>{u.warn("MCP service initialization failed, continuing anyway:",E)}),F=Promise.all([W,U]).then(()=>{});if(Q.jetbrains)dO("JetBrains");else if(Q.ide&&PX6())dO("VS Code");else if(Q.ide&&TX6())dO("Neovim");if(J.executeMode)va1(!0);$46(K,{configService:Z});let H,B=v7.status.pipe(b0((E)=>Boolean(E.connected&&E.authenticated)),J8()).subscribe((E)=>{if(E){if(!H)H=K.registerTool(Uo)}else H?.dispose(),H=void 0}),M;if(!J.executeMode)M=new r51(process.cwd(),{},!0);else M=new class extends r51{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...
6681
+ `)}var ap1=np1.join(Oi1||np1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function gB9(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")RZ("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")RZ("experimental.agentMode",Q.agentMode)}async function sp1(J){try{await yB9(np1.dirname(ap1),{recursive:!0}),await fB9(ap1,J,"utf-8")}catch(Q){u.debug("Failed to save last thread ID",Q)}}async function mB9(){try{return(await AH6(ap1,"utf-8")).trim()}catch(J){return null}}function uB9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return cS("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 VH6=[{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??DZ,description:`Custom settings file path (overrides the default location ${DZ})`},{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 ${Nf1})`},{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:LQ(),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:Ec}],NH6=(J)=>("deprecated"in J)&&J.deprecated===!0,pB9=(J)=>("hidden"in J)&&J.hidden===!0,dB9=(J)=>("default"in J),cB9=(J)=>("default"in J)?J.default:void 0;function lB9(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(aK.unknownCommand(Z),1,G)}}var wH6=null;function z24(){return wH6}function qZ1(J){return{...J,getThreadEnvironment:x51,vfs:x70({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new Qx(J.fileSystem),generateThreadTitle:iz0,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var op1=$0.file(hB9.homedir()),RH6=process.env.XDG_CONFIG_HOME?$0.file(process.env.XDG_CONFIG_HOME):y0.joinPath(op1,".config");async function tq(J,Q){Sa1("0.0.1761710698-g945ae7");let Z=VY1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:t1.of([$0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:op1,userConfigDir:RH6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (KZ1(),YZ1));X(Z);let Y=await Z.getLatest();u.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let K=Gr(mO({configService:Z})),G=new Map,q=()=>G.clear(),z=W70({configService:Z,toolService:K,secretStorage:J.secrets,createOAuthProvider:async(E)=>{let I=G.get(E);if(I)return u.debug("Reusing existing OAuth provider for server",{serverName:E}),I;u.debug("Creating OAuth provider for server",{serverName:E});let T=(async()=>{let S=new P3(J.secrets),_=await S.getClientInfo(E),h=new gW1({storage:S,serverName:E,clientId:_?.clientId,clientSecret:_?.clientSecret,scopes:_?.scopes});return u.debug("OAuth provider created",{serverName:E,hasManualClientId:!!_?.clientId,willUseDCR:!_?.clientId}),h})();return G.set(E,T),T}}),U=Lj0(K,E2,c11).catch((E)=>{u.warn("Toolbox registration failed, continuing anyway:",E)}),W=z.initialized.catch((E)=>{u.warn("MCP service initialization failed, continuing anyway:",E)}),F=Promise.all([W,U]).then(()=>{});if(Q.jetbrains)dO("JetBrains");else if(Q.ide&&PX6())dO("VS Code");else if(Q.ide&&TX6())dO("Neovim");if(J.executeMode)va1(!0);$46(K,{configService:Z});let H,B=v7.status.pipe(b0((E)=>Boolean(E.connected&&E.authenticated)),J8()).subscribe((E)=>{if(E){if(!H)H=K.registerTool(Uo)}else H?.dispose(),H=void 0}),M;if(!J.executeMode)M=new r51(process.cwd(),{},!0);else M=new class extends r51{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...
6682
6682
  `),!await iB9(J))await ER(),process.exit(1)}let V=await m70({isDevelopment:!1}),N=new AN1(V),L=new KD1(V,Z,{lazy:!0}),A=Q.notifications!==void 0?Q.notifications:!J.executeMode,w=I46({playNotificationSound:async(E)=>{if(A){E46(E);let I=Og1(),T=jg1();if((!I||T)&&Y.settings["notifications.system.enabled"]!==!1){if(E==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(E==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:N,configService:Z});u.info("Starting Amp background services");let R=lz0({threadService:N,threadHistoryService:L,configService:Z,isExtensionDevelopment:!1}),O;v7.status.subscribe((E)=>{O=E});let j={codebaseContextService:new zX1({workspaceRoots:[$0.file(process.cwd())],getCurrentFile:()=>{if(!O?.openFile)return;try{return $0.parse(O.openFile)}catch(E){u.warn("Failed to parse current file URI",{uri:O.openFile,error:E});return}},getOpenFiles:()=>{if(!O?.visibleFiles?.length)return[];let E=O.openFile;return O.visibleFiles.filter((I)=>I!==E).map((I)=>{try{return $0.parse(I)}catch(T){return u.warn("Failed to parse visible file URI",{uri:I,error:T}),null}}).filter((I)=>I!==null)}}),configService:Z,toolService:K,mcpService:z,threadService:N,threadHistoryService:L,threadSyncService:R,threadStorage:V,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:M,notificationService:w,backgroundInit:F,fileSystem:Q.jetbrains||Q.ide?v70:E2};return{...j,async asyncDispose(){await j.mcpService.dispose(),q(),await j.threadService.asyncDispose(),j.configService.unsubscribe(),j.toolService.dispose(),j.fuzzyServer.dispose(),j.threadSyncService.dispose(),j.settingsStorage[Symbol.dispose](),B.unsubscribe(),H?.dispose()}}}async function iB9(J){if(!J.executeMode){if(!await tf1("Would you like to log in to Amp? [(y)es, (n)o]: "))return e2.write(`Login cancelled. Run the command again to retry.
6683
6683
  `),!1}return await OH6(J)}async function OH6(J){let Q=bB9(32).toString("hex"),Z=await of1(J.ampURL,Q),X=new AbortController;try{await PQ(Z,X.signal)}catch(K){u.error("Error opening browser",{error:K})}let Y=await of1(J.ampURL,Q,!1);e2.write(`If your browser does not open automatically, visit:
6684
6684
 
@@ -6688,13 +6688,13 @@ ${W8.blue.bold(Y)}
6688
6688
  Login successful! You can now use the Amp CLI.
6689
6689
  `),!0}catch(K){return u.error("Login failed",{error:K}),YG.write(`
6690
6690
  Login failed: ${K instanceof Error?K.message:String(K)}
6691
- `),!1}}function nB9(){let J=new DR().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)PR(),process.exit(0);let W=U.originalError??U;TZ6(W)}),J.option("-V, --version","output the version number",()=>{e2.write(`0.0.1761696104-g382fd7 (released 2025-10-29T00:06:40.621Z)
6691
+ `),!1}}function nB9(){let J=new DR().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)PR(),process.exit(0);let W=U.originalError??U;TZ6(W)}),J.option("-V, --version","output the version number",()=>{e2.write(`0.0.1761710698-g945ae7 (released 2025-10-29T04:10:04.215Z)
6692
6692
  `),process.exit(0)}),J.addHelpText("after",$X6()),J.configureHelp({formatHelp:EX6}),J.command("logout").description("Log out by removing stored API key").action(async(U,W)=>{let F=W.optsWithGlobals(),H=await IX(F);await oB9(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 IX(F);await sB9(H,await mf1(F,H.settings))});let Q=async(U,W,F)=>{VY1({storage:W.settings,secretStorage:W.secrets,workspaceRoots:t1.of([$0.file(process.cwd())]),defaultAmpURL:W.ampURL,homeDir:op1,userConfigDir:RH6});let H={...W,executeMode:!1};await rp1(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 IX(F);await LH6(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 IX(F);await XD9(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 IX(H);if(W.pick)YG.write(`${W8.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
6693
6693
  `);if(W.last||U||B.executeMode)await ZD9(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 IX(H);await QD9(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 IX(F);await LH6(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 IX(H);await JD9(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 IX(B);await tB9(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 IX(H);await eB9(H,B,U,F)}),CY6(J,async(U,W)=>{let F=await IX(W);oq(U,W);let H=await tq(F,W);return{context:F,mcpService:H.mcpService,toolService:H.toolService,configService:H.configService,cleanupTerminal:PR,asyncDispose:H.asyncDispose.bind(H)}}),YY6(J),sX6(J,async(U)=>{let W=await IX(U);return{settings:W.settings,secretStorage:W.secrets,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 IX(F);oq(W,F);let B=await tq(H,F);try{await If1(B,B.configService,{})}finally{await B.asyncDispose(),await PR()}});function X(U,W,F){let B=typeof U.description==="string"?U.description:F===void 0?U.description(!0):U.description(F),M=new oV(W,B),V=cB9(U);if(V)M.default(V);if(M.hidden=pB9(U)||NH6(U),"choices"in U)M.choices([...U.choices]);return M}for(let U of VH6)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 oV("-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 oV("-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 oV("--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 oV("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(q);let z=new oV("--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 oV("--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 IX(F);if(Object.keys(F).forEach((B)=>{let M=VH6.find((V)=>V.name===B);if(M&&NH6(M)&&!dB9(M))YG.write(W8.yellow(`Warning: '--${B}' flag is deprecated
6694
6694
  `))}),W.args.length>0)lB9(H,W);await rp1(H,F,W)}),dX6(J),J}async function GZ1(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 VJ.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 sp1(Y),q.unsubscribe()});return await G.resume(),G}async function rp1(J,Q,Z){let X=GJ1(Q);if(X instanceof Error)XG(X.message);let Y,K=null;if(Q.streamJsonInput)Y="";else if(typeof Q.execute==="string"){Y=Q.execute;let O=(await Jh1()).trimEnd();if(O)K=O}else Y=(await Jh1()).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"
6695
6695
  Or pipe via stdin: echo "your message" | amp --execute`);oq(Z,Q);let G=await tq(J,Q);if(J.executeMode||Q.threadId)await G.backgroundInit;wH6=G;let q=qZ1(G),z=async(O)=>{let $=await AH6(O,"utf-8"),j=JSON.parse($);if(!MG(j.id))throw new k9(aK.invalidThreadId);return GZ1(G,{visibility:X,thread:j})},U=async(O)=>{if(!MG(O))throw new k9(aK.invalidThreadId);let $=await G.threadService.get(O)??void 0;if(u.info(`[fetchAndStartThread] Loaded thread ${O}, agentMode: ${$?.agentMode??"undefined"}`),$?.agentMode)u.info(`[fetchAndStartThread] Setting runtime override for agentMode to: ${$.agentMode}`),RZ("experimental.agentMode",$.agentMode);else u.info("[fetchAndStartThread] No agentMode on thread, not setting override");return GZ1(G,{visibility:X,thread:$})},W=async()=>{try{if(Q.threadId)return U(Q.threadId);else return GZ1(G,{visibility:X})}catch(O){if(O instanceof k9)throw O;throw await u51(O,Q.threadId),Error("handleError should have called process.exit()")}},F=async()=>{return GZ1(G,{visibility:X})};if(Q.format==="jsonl")YG.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
6696
- `),await ER(),process.exit(1);if(J.executeMode&&Q.remote)await KY6(Y,K,G.configService),await G.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await uZ6(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 is1();let O=await cB({jetbrainsOnly:Q.jetbrains});if(O.length===0){if(Q.jetbrains)M=!await G.configService.get("jetbrains.skipInstall")}else if(O.length===1){let $=O[0];if($)v7.selectConfig($)}else B=!0}let V=sf1("0.0.1761696104-g382fd7",G.settingsStorage),N=new YD1(G.threadStorage),L=t1.of([$0.file(process.cwd())]),A=CS(void 0,L);if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let w;try{w=await UJ.getUserFreeTierStatus({},{config:G.configService,signal:AbortSignal.timeout(5000)})}catch(O){w={ok:!1,error:O}}u.info("User free tier status:",w);let R=await UY6();u.info("Loaded session state:",R),await MH6({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new vf1,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:UJ,ampURL:J.ampURL,startNewThread:F,pickAndContinueThread:async()=>{u.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:v7,connectedClientsService:new tc,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 IX(J){if(J.interactive)YG.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6697
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await zX6({...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 oX6(J.mcpConfig);X=uB9(X,G)}let Y=await X.get("url","global");if(!Y)Y=OZ;if(!TB(Y))u.info("Targeting custom Amp server",{ampURL:Y});if(X=ai1(X),await X.get("debug.httpLogging"))gi1();return{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:GY6(await mf1(J,X))}}function aB9(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 rB9(){let J=aB9(process.argv);if(WZ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),gB9(u),u.info("Starting Amp CLI.",{version:"0.0.1761696104-g382fd7",buildTimestamp:"2025-10-29T00:06:40.621Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new k9(aK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await nB9().parseAsync(process.argv)}rB9().catch(u51);async function sB9(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}
6696
+ `),await ER(),process.exit(1);if(J.executeMode&&Q.remote)await KY6(Y,K,G.configService),await G.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await uZ6(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 is1();let O=await cB({jetbrainsOnly:Q.jetbrains});if(O.length===0){if(Q.jetbrains)M=!await G.configService.get("jetbrains.skipInstall")}else if(O.length===1){let $=O[0];if($)v7.selectConfig($)}else B=!0}let V=sf1("0.0.1761710698-g945ae7",G.settingsStorage),N=new YD1(G.threadStorage),L=t1.of([$0.file(process.cwd())]),A=CS(void 0,L);if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let w;try{w=await UJ.getUserFreeTierStatus({},{config:G.configService,signal:AbortSignal.timeout(5000)})}catch(O){w={ok:!1,error:O}}u.info("User free tier status:",w);let R=await UY6();u.info("Loaded session state:",R),await MH6({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new vf1,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:UJ,ampURL:J.ampURL,startNewThread:F,pickAndContinueThread:async()=>{u.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:v7,connectedClientsService:new tc,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 IX(J){if(J.interactive)YG.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6697
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await zX6({...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 oX6(J.mcpConfig);X=uB9(X,G)}let Y=await X.get("url","global");if(!Y)Y=OZ;if(!TB(Y))u.info("Targeting custom Amp server",{ampURL:Y});if(X=ai1(X),await X.get("debug.httpLogging"))gi1();return{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:GY6(await mf1(J,X))}}function aB9(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 rB9(){let J=aB9(process.argv);if(WZ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),gB9(u),u.info("Starting Amp CLI.",{version:"0.0.1761710698-g945ae7",buildTimestamp:"2025-10-29T04:10:04.215Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new k9(aK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await nB9().parseAsync(process.argv)}rB9().catch(u51);async function sB9(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}
6698
6698
  `);else if(!TB(J.ampURL))e2.write(`Logging in to ${new URL(J.ampURL).hostname}
6699
6699
  `);let Z=process.env.AMP_API_KEY;if(Z)e2.write(`API key found in environment variable, storing...
6700
6700
  `),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.1761696104-g382fd7",
3
+ "version": "0.0.1761710698-g945ae7",
4
4
  "description": "CLI for Amp, the frontier coding agent from Sourcegraph.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {