@sourcegraph/amp 0.0.1761609709-g7e6816 → 0.0.1761624095-g7e6816
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +8 -8
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -6006,11 +6006,11 @@ Actual: ${Y}`)}async function G59(J,Q,Z){let{execSync:X}=await import("node:ch
|
|
|
6006
6006
|
${B}`;if(Y==="pnpm"&&B.includes("Unable to find the global bin directory"))M+=`
|
|
6007
6007
|
|
|
6008
6008
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
6009
|
-
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 v51(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=F59(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 p.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 p.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function F59(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}C0();function oy1(J,Q){let Z=new f8,X=Z.pipe(M9({shouldCountRefs:!1}));return setImmediate(async()=>{let Y=new oq().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 w_(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 v51(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let U=await S51();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 su(z.latestVersion,U);let W=await tV(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 w_(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as ZW}from"node:process";function aZ6(J){let Q=new qu().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 ay1(X.force||!1,X.verbose||!1,"0.0.
|
|
6009
|
+
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 v51(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=F59(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 p.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 p.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function F59(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}C0();function oy1(J,Q){let Z=new f8,X=Z.pipe(M9({shouldCountRefs:!1}));return setImmediate(async()=>{let Y=new oq().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 w_(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 v51(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let U=await S51();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 su(z.latestVersion,U);let W=await tV(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 w_(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as ZW}from"node:process";function aZ6(J){let Q=new qu().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 ay1(X.force||!1,X.verbose||!1,"0.0.1761624095-g7e6816"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new qu("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 H59(X.version)});J.addCommand(Z)}async function H59(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")ZW.write(z8.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
6010
6010
|
|
|
6011
6011
|
`));try{if(!J){ZW.write(z8.blue(`Checking for updates...
|
|
6012
|
-
`));let{hasUpdate:Z,latestVersion:X}=await v51("0.0.
|
|
6013
|
-
`));let Y=await tV("0.0.
|
|
6012
|
+
`));let{hasUpdate:Z,latestVersion:X}=await v51("0.0.1761624095-g7e6816");if(!Z){ZW.write(z8.green(`✓ Amp CLI is already up to date.
|
|
6013
|
+
`));let Y=await tV("0.0.1761624095-g7e6816");if(Y.warning)ZW.write(`
|
|
6014
6014
|
`+z8.yellow(Y.warning)+`
|
|
6015
6015
|
`);process.exit(0)}if(!X)ZW.write(z8.yellow("[WARN] could not find latest version")),process.exit(0);J=X}ZW.write(z8.blue(`Updating to version ${J}...
|
|
6016
6016
|
`)),await su(J,void 0,(Z)=>{ZW.write(z8.dim(`Running: ${Z}
|
|
@@ -6382,7 +6382,7 @@ See https://ampcode.com/manual#toolboxes`);return Q[0]||XO}function _X6(J,Q){let
|
|
|
6382
6382
|
`);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(vX6()){let F=[];for await(let H of process.stdin)F.push(H);W=Buffer.concat(F).toString("utf-8").trim()}await CX6({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 xH9}from"node:crypto";import{homedir as bH9}from"node:os";import zd from"node:path";C0();G0();var xX6=120000,bX6=180000;function Kf1(J,Q=Date.now()){return Q-J<bX6}function Gf1(J,Q,Z=()=>!0,X){let Y=null,K=[],G=5;return kN(e1.of(void 0),vd(xX6).pipe(P7(()=>Z()))).pipe(q8(()=>f6(async(q)=>{let z=await X?.getContext();p.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 p.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),p.debug("[Ads] Received ad from server",{adTitle:Y.title,matchType:Y.matchType,matchedPatterns:Y.matchedPatterns,candidateAdPoolCount:Y.candidateAdPoolCount,recentlyShownCount:K.length})}else p.debug("[Ads] No ad available from server");return Y})),J8((q,z)=>q?.id===z?.id))}G0();dj();U2();eB();t9();jL();W8();b6();function yX6(J){let Q=J.trim();if(Q==="quit"||Q==="exit")return"/quit";return J}function fX6(J,Q,Z){if(J.agentMode)return J.agentMode;if(Q?.agentMode){let X=Q.agentMode;if(X==="free"){if(Z?.canUseAmpFree??!1)return"free";return"smart"}return X}return"smart"}G0();eB();import gJ9 from"node:fs";import hX6 from"node:path";function gX6(J){let Q=J.trim().replace(/^["']|["']$/g,"");if(Q=Q.replace(/\\(.)/g,"$1"),!/\.(png|jpe?g|gif|webp)$/i.test(Q))return null;if(!hX6.isAbsolute(Q))return null;return p.debug("Extracted image path",{original:J,extracted:Q}),Q}function mX6(J){try{let Q=hX6.extname(J).toLowerCase(),Z=D10(Q);if(!Z)return p.warn("Unsupported image file extension",{ext:Q}),null;try{let X=gJ9.readFileSync(J);return mJ9(X,Z)}catch(X){p.error(`Failed to read image file ${J}:`,X)}}catch(Q){p.error("Error handling image file path",{imagePath:J,error:Q})}return null}function mJ9(J,Q){if(J.length>xW)return p.warn(`Image file too large: ${J.length} bytes (max: ${xW})`),null;return{type:"image",source:{type:"base64",data:J.toString("base64"),mediaType:Q}}}import{execSync as xK9}from"node:child_process";Uj();G0();import{spawn as uJ9}from"node:child_process";import{promises as pJ9}from"node:fs";function uX6(J){return J.kind==="executable"}function pX6(J){return J.kind==="markdown"}var eH=50000,dX6=300000;async function eu(J,Q,Z,X={}){let{timeoutMs:Y=dX6,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(p.debug("Executing command",{commandName:J,filePath:G.filePath,args:Q}),pX6(G))return await dJ9(G,Q);else if(uX6(G))return await cJ9(G,Q,Y,K);else return{success:!1,output:"",error:"Unsupported command type"}}catch(G){return p.error("Failed to execute command",{commandName:J,error:G}),{success:!1,output:"",error:G instanceof Error?G.message:"Unknown error occurred"}}}async function dJ9(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await pJ9.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>eH?Z.slice(0,eH)+`
|
|
6383
6383
|
... (output truncated at ${eH} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function cJ9(J,Q,Z=dX6,X){return new Promise((Y)=>{let[K,G]=lJ9(J,Q);p.debug("Spawning command",{spawnCommand:K,spawnArgs:G.slice(0,10),filePath:J.filePath,timeoutMs:Z});let q=q10(X),z=!1,U=setTimeout(()=>{z=!0,q.abort(),p.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),W=uJ9(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<=eH)F.push(V);else{let N=eH-(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<=eH)H.push(V);else{let N=eH-(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?`
|
|
6384
6384
|
${L}`:L;if(B>eH)A+=`
|
|
6385
|
-
... (output truncated at ${eH} 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 lJ9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return nJ9(Z,X?[...X]:null,Y,Q);else return iJ9(Z,X?[...X]:null,Y,Q)}function iJ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function nJ9(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();dj();U2();wW();mX();$z();b6();C0();var h51={};R6(h51,{scrollUp:()=>BQ9,scrollDown:()=>DQ9,link:()=>wQ9,image:()=>RQ9,iTerm:()=>OQ9,exitAlternativeScreen:()=>LQ9,eraseUp:()=>HQ9,eraseStartLine:()=>WQ9,eraseScreen:()=>qf1,eraseLines:()=>zQ9,eraseLine:()=>nX6,eraseEndLine:()=>UQ9,eraseDown:()=>FQ9,enterAlternativeScreen:()=>NQ9,cursorUp:()=>lX6,cursorTo:()=>sJ9,cursorShow:()=>qQ9,cursorSavePosition:()=>QQ9,cursorRestorePosition:()=>ZQ9,cursorPrevLine:()=>KQ9,cursorNextLine:()=>YQ9,cursorMove:()=>oJ9,cursorLeft:()=>iX6,cursorHide:()=>GQ9,cursorGetPosition:()=>XQ9,cursorForward:()=>eJ9,cursorDown:()=>tJ9,cursorBackward:()=>JQ9,clearTerminal:()=>VQ9,clearScreen:()=>MQ9,beep:()=>AQ9});import zf1 from"node:process";var f51=globalThis.window?.document!==void 0,pw2=globalThis.process?.versions?.node!==void 0,dw2=globalThis.process?.versions?.bun!==void 0,cw2=globalThis.Deno?.version?.deno!==void 0,lw2=globalThis.process?.versions?.electron!==void 0,iw2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,nw2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,aw2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,rw2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,sw2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,Jp=globalThis.navigator?.userAgentData?.platform,ow2=Jp==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",tw2=Jp==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",ew2=Jp==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",JR2=Jp==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),QR2=Jp==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var O2="\x1B[",Zp="\x1B]",OC="\x07",Qp=";",cX6=!f51&&zf1.env.TERM_PROGRAM==="Apple_Terminal",aJ9=!f51&&zf1.platform==="win32",rJ9=f51?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:zf1.cwd,sJ9=(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)+Qp+(J+1)+"H"},oJ9=(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},lX6=(J=1)=>O2+J+"A",tJ9=(J=1)=>O2+J+"B",eJ9=(J=1)=>O2+J+"C",JQ9=(J=1)=>O2+J+"D",iX6=O2+"G",QQ9=cX6?"\x1B7":O2+"s",ZQ9=cX6?"\x1B8":O2+"u",XQ9=O2+"6n",YQ9=O2+"E",KQ9=O2+"F",GQ9=O2+"?25l",qQ9=O2+"?25h",zQ9=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=nX6+(Z<J-1?lX6():"");if(J)Q+=iX6;return Q},UQ9=O2+"K",WQ9=O2+"1K",nX6=O2+"2K",FQ9=O2+"J",HQ9=O2+"1J",qf1=O2+"2J",BQ9=O2+"S",DQ9=O2+"T",MQ9="\x1Bc",VQ9=aJ9?`${qf1}${O2}0f`:`${qf1}${O2}3J${O2}H`,NQ9=O2+"?1049h",LQ9=O2+"?1049l",AQ9=OC,wQ9=(J,Q)=>[Zp,"8",Qp,Qp,Q,OC,J,Zp,"8",Qp,Qp,OC].join(""),RQ9=(J,Q={})=>{let Z=`${Zp}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")+OC},OQ9={setCwd:(J=rJ9())=>`${Zp}50;CurrentDir=${J}${OC}`,annotation(J,Q={}){let Z=`${Zp}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+OC}};var g51=S6(JY6(),1);function QN(J,Q,{target:Z="stdout",...X}={}){if(!g51.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (${Q})`}return h51.link(J,Q)}QN.isSupported=g51.default.stdout;QN.stderr=(J,Q,Z={})=>QN(J,Q,{target:"stderr",...Z});QN.stderr.isSupported=g51.default.stderr;G0();mX();class Xp{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.1761609709-g7e6816"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Aa(Q,this.configService)}catch(Q){p.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 u51}from"node:child_process";import{platform as Bf1}from"node:os";import{promisify as IQ9}from"node:util";var m51=IQ9(u51),PQ9=(J)=>`\x1B]52;c;${J}\x1B\\`,TQ9="\x1B]52;c;?\x1B\\",CQ9="\x1B]52;p;?\x1B\\";class QY6{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 m51("which",[J]),!0}catch{return!1}}async writeToPbcopy(J){try{let Q=u51("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=u51("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=u51("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(TQ9)}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 m51("pbpaste");return J}catch{return null}}async readFromWlPaste(J){try{let Q=["--no-newline"];if(J==="primary")Q.push("--primary");let{stdout:Z}=await m51("wl-paste",Q);return Z}catch{return null}}async readFromXclip(J){try{let{stdout:Q}=await m51("xclip",["-selection",J,"-o"]);return Q}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(CQ9)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if(Bf1()==="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(Bf1()==="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=PQ9(Z);process.stdout.write(X);return}if(Bf1()==="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 AY=new QY6;G0();class q2{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function p51(J){if(J instanceof q2)return{title:"Info",description:J.message,type:"info"};return p.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var zN=null,bK9={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(zN)return Error("Already connected. Use /disconnect first to reconnect.");let{connectedClientsService:Z}=J;await Z.start({clientId:J.clientId,currentThreadID:J.worker.thread.id});let Y=Z.getCurrentStatus().clientID||"unknown",{connectBackground:K}=await Promise.resolve().then(() => (F51(),jy1)),G=await K({worker:J.worker},J.configService,{clientId:J.clientId,onUserDisconnect:()=>{zN=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});zN=G,G.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((M)=>{zN=null,Z.sendStatus({connected:!1,errorMessage:M.message})});let z=(await J.configService.getLatest()).settings.url,U=J.worker.thread.id,W=new URL(`/threads/${U}`,z).toString(),F=new URL("/clients",z).toString(),H="";try{H=await(await Promise.resolve().then(() => S6(Dp(),1))).toString(W,{type:"utf8",margin:2,color:{dark:"#000000",light:"#FFFFFF"}})}catch(M){p.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 q2(`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(!zN)return new q2("Not connected to Amp web interface");try{zN.disconnect();let Z=zN.clientID;return zN=null,J.connectedClientsService.sendStatus({connected:!1,enabled:!1,errorMessage:void 0}),new q2(`Disconnected from Amp web interface
|
|
6385
|
+
... (output truncated at ${eH} 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 lJ9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return nJ9(Z,X?[...X]:null,Y,Q);else return iJ9(Z,X?[...X]:null,Y,Q)}function iJ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function nJ9(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();dj();U2();wW();mX();$z();b6();C0();var h51={};R6(h51,{scrollUp:()=>BQ9,scrollDown:()=>DQ9,link:()=>wQ9,image:()=>RQ9,iTerm:()=>OQ9,exitAlternativeScreen:()=>LQ9,eraseUp:()=>HQ9,eraseStartLine:()=>WQ9,eraseScreen:()=>qf1,eraseLines:()=>zQ9,eraseLine:()=>nX6,eraseEndLine:()=>UQ9,eraseDown:()=>FQ9,enterAlternativeScreen:()=>NQ9,cursorUp:()=>lX6,cursorTo:()=>sJ9,cursorShow:()=>qQ9,cursorSavePosition:()=>QQ9,cursorRestorePosition:()=>ZQ9,cursorPrevLine:()=>KQ9,cursorNextLine:()=>YQ9,cursorMove:()=>oJ9,cursorLeft:()=>iX6,cursorHide:()=>GQ9,cursorGetPosition:()=>XQ9,cursorForward:()=>eJ9,cursorDown:()=>tJ9,cursorBackward:()=>JQ9,clearTerminal:()=>VQ9,clearScreen:()=>MQ9,beep:()=>AQ9});import zf1 from"node:process";var f51=globalThis.window?.document!==void 0,pw2=globalThis.process?.versions?.node!==void 0,dw2=globalThis.process?.versions?.bun!==void 0,cw2=globalThis.Deno?.version?.deno!==void 0,lw2=globalThis.process?.versions?.electron!==void 0,iw2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,nw2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,aw2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,rw2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,sw2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,Jp=globalThis.navigator?.userAgentData?.platform,ow2=Jp==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",tw2=Jp==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",ew2=Jp==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",JR2=Jp==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),QR2=Jp==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var O2="\x1B[",Zp="\x1B]",OC="\x07",Qp=";",cX6=!f51&&zf1.env.TERM_PROGRAM==="Apple_Terminal",aJ9=!f51&&zf1.platform==="win32",rJ9=f51?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:zf1.cwd,sJ9=(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)+Qp+(J+1)+"H"},oJ9=(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},lX6=(J=1)=>O2+J+"A",tJ9=(J=1)=>O2+J+"B",eJ9=(J=1)=>O2+J+"C",JQ9=(J=1)=>O2+J+"D",iX6=O2+"G",QQ9=cX6?"\x1B7":O2+"s",ZQ9=cX6?"\x1B8":O2+"u",XQ9=O2+"6n",YQ9=O2+"E",KQ9=O2+"F",GQ9=O2+"?25l",qQ9=O2+"?25h",zQ9=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=nX6+(Z<J-1?lX6():"");if(J)Q+=iX6;return Q},UQ9=O2+"K",WQ9=O2+"1K",nX6=O2+"2K",FQ9=O2+"J",HQ9=O2+"1J",qf1=O2+"2J",BQ9=O2+"S",DQ9=O2+"T",MQ9="\x1Bc",VQ9=aJ9?`${qf1}${O2}0f`:`${qf1}${O2}3J${O2}H`,NQ9=O2+"?1049h",LQ9=O2+"?1049l",AQ9=OC,wQ9=(J,Q)=>[Zp,"8",Qp,Qp,Q,OC,J,Zp,"8",Qp,Qp,OC].join(""),RQ9=(J,Q={})=>{let Z=`${Zp}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")+OC},OQ9={setCwd:(J=rJ9())=>`${Zp}50;CurrentDir=${J}${OC}`,annotation(J,Q={}){let Z=`${Zp}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+OC}};var g51=S6(JY6(),1);function QN(J,Q,{target:Z="stdout",...X}={}){if(!g51.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (${Q})`}return h51.link(J,Q)}QN.isSupported=g51.default.stdout;QN.stderr=(J,Q,Z={})=>QN(J,Q,{target:"stderr",...Z});QN.stderr.isSupported=g51.default.stderr;G0();mX();class Xp{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.1761624095-g7e6816"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Aa(Q,this.configService)}catch(Q){p.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 u51}from"node:child_process";import{platform as Bf1}from"node:os";import{promisify as IQ9}from"node:util";var m51=IQ9(u51),PQ9=(J)=>`\x1B]52;c;${J}\x1B\\`,TQ9="\x1B]52;c;?\x1B\\",CQ9="\x1B]52;p;?\x1B\\";class QY6{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 m51("which",[J]),!0}catch{return!1}}async writeToPbcopy(J){try{let Q=u51("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=u51("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=u51("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(TQ9)}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 m51("pbpaste");return J}catch{return null}}async readFromWlPaste(J){try{let Q=["--no-newline"];if(J==="primary")Q.push("--primary");let{stdout:Z}=await m51("wl-paste",Q);return Z}catch{return null}}async readFromXclip(J){try{let{stdout:Q}=await m51("xclip",["-selection",J,"-o"]);return Q}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(CQ9)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if(Bf1()==="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(Bf1()==="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=PQ9(Z);process.stdout.write(X);return}if(Bf1()==="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 AY=new QY6;G0();class q2{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function p51(J){if(J instanceof q2)return{title:"Info",description:J.message,type:"info"};return p.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var zN=null,bK9={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(zN)return Error("Already connected. Use /disconnect first to reconnect.");let{connectedClientsService:Z}=J;await Z.start({clientId:J.clientId,currentThreadID:J.worker.thread.id});let Y=Z.getCurrentStatus().clientID||"unknown",{connectBackground:K}=await Promise.resolve().then(() => (F51(),jy1)),G=await K({worker:J.worker},J.configService,{clientId:J.clientId,onUserDisconnect:()=>{zN=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});zN=G,G.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((M)=>{zN=null,Z.sendStatus({connected:!1,errorMessage:M.message})});let z=(await J.configService.getLatest()).settings.url,U=J.worker.thread.id,W=new URL(`/threads/${U}`,z).toString(),F=new URL("/clients",z).toString(),H="";try{H=await(await Promise.resolve().then(() => S6(Dp(),1))).toString(W,{type:"utf8",margin:2,color:{dark:"#000000",light:"#FFFFFF"}})}catch(M){p.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 q2(`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(!zN)return new q2("Not connected to Amp web interface");try{zN.disconnect();let Z=zN.clientID;return zN=null,J.connectedClientsService.sendStatus({connected:!1,enabled:!1,errorMessage:void 0}),new q2(`Disconnected from Amp web interface
|
|
6386
6386
|
Client ID: ${Z}
|
|
6387
6387
|
Server will clean up automatically within 60 seconds`)}catch(Z){return Error(`Failed to disconnect: ${Z.message}`)}}}};class qh1{configService;commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=BS(),Q){this.configService=Q;this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Z)=>this.latestCustom=Z),this.telemetrySubmitter=new Xp(async()=>{try{return(await this.configService.getLatest()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}},this.configService),this.configService.config.pipe(x0((Z)=>DZ(Z.settings)),J8()).subscribe((Z)=>{this._initBaseCommands(Z.length>1)})}_initBaseCommands(J){if(this.commands={...yK9},process.env.AMP_CONNECT==="1")Object.assign(this.commands,bK9);if(J)Object.assign(this.commands,fK9)}async execute(J,Q,Z=[],X){this.telemetrySubmitter.submit(J).catch((q)=>{p.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 eu(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 yK9={"generate-agent-file":{name:"generate-agent-file",description:`Generate an ${_5} file in the current workspace`,execute:async(J,Q)=>{let Z=await J.configService.getLatest(),X=xZ(Z.settings),K=J.getInMemoryAgentModeOverride()??X;J.worker.handle({type:"user:message",message:{content:[{type:"text",text:Ra}],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 MZ("dangerouslyAllowAll",!1),new q2("Amp is now following permissions rules for this session")}catch(K){return p.error("Failed to set dangerously allow all setting",K),Error("Failed to enable permissions for this session")}case"off":try{return MZ("dangerouslyAllowAll",!0),new q2("Permissions disabled for this session - you will NOT be asked for confirmation before Amp runs a command.")}catch(K){return p.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 XW();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 p.error("editPermissions exited with status",K),Error(X)},settingsFile:J.settingsFilePath,resolveEditor:XW};await wC(Y);return}catch(Y){p.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 p.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 q2(`Switched to existing thread: ${Z}`)}await J.pickAndContinueThread();return}catch(Z){return p.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(`
|
|
6388
6388
|
`).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=aW(new URL(Y),Z.id).toString(),q=`Thread URL: ${QN(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 q2(`${q}
|
|
@@ -6598,7 +6598,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
|
|
|
6598
6598
|
`),J.stdout.write(`Thread: ${H}
|
|
6599
6599
|
`),J.stdout.write(`Continue this thread with: amp threads continue ${W}
|
|
6600
6600
|
`)}}function ou1(J){return J==="smart"?E1.rgb(3,197,97):J==="free"?E1.rgb(0,184,255):fH9(J)}function fH9(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 E1.index(Z[X])}Ih1();if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){QG.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
6601
|
-
`)}var eu1=tu1.join(Pl1||tu1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function pH9(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 iq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")MZ("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: ${z8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")MZ("experimental.agentMode",Q.agentMode)}async function Qp1(J){try{await gH9(tu1.dirname(eu1),{recursive:!0}),await mH9(eu1,J,"utf-8")}catch(Q){p.debug("Failed to save last thread ID",Q)}}async function dH9(){try{return(await EF6(eu1,"utf-8")).trim()}catch(J){return null}}function cH9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return OS("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 OF6=[{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??NX,description:`Custom settings file path (overrides the default location ${NX})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(p).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${By1})`},{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:lK(),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:Jc}],jF6=(J)=>("deprecated"in J)&&J.deprecated===!0,lH9=(J)=>("hidden"in J)&&J.hidden===!0,iH9=(J)=>("default"in J),nH9=(J)=>("default"in J)?J.default:void 0;function aH9(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(cK.unknownCommand(Z),1,G)}}var IF6=null;function I64(){return IF6}function vQ1(J){return{...J,getThreadEnvironment:K51,vfs:_40({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new S_(J.fileSystem),generateThreadTitle:nq0,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var Zp1=O0.file(uH9.homedir()),PF6=process.env.XDG_CONFIG_HOME?O0.file(process.env.XDG_CONFIG_HOME):b0.joinPath(Zp1,".config");async function nq(J,Q){Sn1("0.0.
|
|
6601
|
+
`)}var eu1=tu1.join(Pl1||tu1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function pH9(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 iq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")MZ("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: ${z8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")MZ("experimental.agentMode",Q.agentMode)}async function Qp1(J){try{await gH9(tu1.dirname(eu1),{recursive:!0}),await mH9(eu1,J,"utf-8")}catch(Q){p.debug("Failed to save last thread ID",Q)}}async function dH9(){try{return(await EF6(eu1,"utf-8")).trim()}catch(J){return null}}function cH9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return OS("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 OF6=[{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??NX,description:`Custom settings file path (overrides the default location ${NX})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(p).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${By1})`},{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:lK(),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:Jc}],jF6=(J)=>("deprecated"in J)&&J.deprecated===!0,lH9=(J)=>("hidden"in J)&&J.hidden===!0,iH9=(J)=>("default"in J),nH9=(J)=>("default"in J)?J.default:void 0;function aH9(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(cK.unknownCommand(Z),1,G)}}var IF6=null;function I64(){return IF6}function vQ1(J){return{...J,getThreadEnvironment:K51,vfs:_40({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new S_(J.fileSystem),generateThreadTitle:nq0,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var Zp1=O0.file(uH9.homedir()),PF6=process.env.XDG_CONFIG_HOME?O0.file(process.env.XDG_CONFIG_HOME):b0.joinPath(Zp1,".config");async function nq(J,Q){Sn1("0.0.1761624095-g7e6816");let Z=_X1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:e1.of([O0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:Zp1,userConfigDir:PF6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (CQ1(),TQ1));X(Z);let Y=await Z.getLatest();p.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let K=fa(EO({configService:Z})),G=U40({configService:Z,toolService:K}),q=LO0(K,j2,M11).catch((O)=>{p.warn("Toolbox registration failed, continuing anyway:",O)}),z=G.initialized.catch((O)=>{p.warn("MCP service initialization failed, continuing anyway:",O)});if(J.executeMode)await Promise.all([z,q]);if(Q.jetbrains)TO("JetBrains");else if(Q.ide&&kZ6())TO("VS Code");else if(Q.ide&&_Z6())TO("Neovim");if(J.executeMode)vn1(!0);$26(K,{configService:Z});let U,W=S7.status.pipe(x0((O)=>Boolean(O.connected&&O.authenticated)),J8()).subscribe((O)=>{if(O){if(!U)U=K.registerTool(ys)}else U?.dispose(),U=void 0}),F;if(!J.executeMode)F=new w51(process.cwd(),{},!0);else F=new class extends w51{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(t2.write(`No API key found. Starting login flow...
|
|
6602
6602
|
`),!await rH9(J))await HR(),process.exit(1)}let H=await g40({isDevelopment:!1}),B=new PV1(H),M=new BB1(H,Z,{lazy:!0}),V=Q.notifications!==void 0?Q.notifications:!J.executeMode,N=I26({playNotificationSound:async(O)=>{if(V){E26(O);let j=$h1(),$=Eh1();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});p.info("Starting Amp background services");let L=iq0({threadService:B,threadHistoryService:M,configService:Z,isExtensionDevelopment:!1}),A;S7.status.subscribe((O)=>{A=O});let R={codebaseContextService:new kZ1({workspaceRoots:[O0.file(process.cwd())],getCurrentFile:()=>{if(!A?.openFile)return;try{return O0.parse(A.openFile)}catch(O){p.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 O0.parse(j)}catch($){return p.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?S40:j2};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 rH9(J){if(!J.executeMode){if(!await Jf1("Would you like to log in to Amp? [(y)es, (n)o]: "))return t2.write(`Login cancelled. Run the command again to retry.
|
|
6603
6603
|
`),!1}return await TF6(J)}async function TF6(J){let Q=hH9(32).toString("hex"),Z=await ey1(J.ampURL,Q);try{await LY(Z)}catch(Y){p.error("Failed to open browser",{error:Y})}let X=await ey1(J.ampURL,Q,!1);t2.write(`If your browser did not open automatically, visit:
|
|
6604
6604
|
|
|
@@ -6608,13 +6608,13 @@ ${z8.blue.bold(X)}
|
|
|
6608
6608
|
Login successful! You can now use the Amp CLI.
|
|
6609
6609
|
`),!0}catch(Y){return p.error("Login failed",{error:Y}),QG.write(`
|
|
6610
6610
|
Login failed: ${Y instanceof Error?Y.message:String(Y)}
|
|
6611
|
-
`),!1}}function sH9(){let J=new qu().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)DR(),process.exit(0);let W=U.originalError??U;TQ6(W)}),J.option("-V, --version","output the version number",()=>{t2.write(`0.0.
|
|
6611
|
+
`),!1}}function sH9(){let J=new qu().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)DR(),process.exit(0);let W=U.originalError??U;TQ6(W)}),J.option("-V, --version","output the version number",()=>{t2.write(`0.0.1761624095-g7e6816 (released 2025-10-28T04:06:50.250Z)
|
|
6612
6612
|
`),process.exit(0)}),J.addHelpText("after",CZ6()),J.configureHelp({formatHelp:SZ6}),J.command("logout").description("Log out by removing stored API key").action(async(U,W)=>{let F=W.optsWithGlobals(),H=await RX(F);await JB9(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 RX(F);await eH9(H,await uy1(F,H.settings))});let Q=async(U,W,F)=>{_X1({storage:W.settings,secretStorage:W.secrets,workspaceRoots:e1.of([O0.file(process.cwd())]),defaultAmpURL:W.ampURL,homeDir:Zp1,userConfigDir:PF6});let H={...W,executeMode:!1};await Jp1(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 RX(F);await $F6(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 RX(F);await GB9(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 RX(H);if(W.pick)QG.write(`${z8.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
|
|
6613
6613
|
`);if(W.last||U||B.executeMode)await KB9(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 RX(H);await YB9(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 RX(F);await $F6(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 RX(H);await XB9(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 RX(B);await QB9(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 RX(H);await ZB9(H,B,U,F)}),_X6(J,async(U,W)=>{let F=await RX(W);iq(U,W);let H=await nq(F,W);return{context:F,mcpService:H.mcpService,toolService:H.toolService,configService:H.configService,cleanupTerminal:DR,asyncDispose:H.asyncDispose.bind(H)}}),zX6(J),JX6(J,async(U)=>{let W=await RX(U);return{settings:W.settings,getThreadDeps:async(F)=>{iq(F,U);let H=await nq(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 RX(F);iq(W,F);let B=await nq(H,F);try{await Oy1(B,B.configService,{})}finally{await B.asyncDispose(),await DR()}});function X(U,W,F){let B=typeof U.description==="string"?U.description:F===void 0?U.description(!0):U.description(F),M=new pV(W,B),V=nH9(U);if(V)M.default(V);if(M.hidden=lH9(U)||jF6(U),"choices"in U)M.choices([...U.choices]);return M}for(let U of OF6)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 pV("-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 pV("-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 pV("--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 pV("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(q);let z=new pV("--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 pV("--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 RX(F);if(Object.keys(F).forEach((B)=>{let M=OF6.find((V)=>V.name===B);if(M&&jF6(M)&&!iH9(M))QG.write(z8.yellow(`Warning: '--${B}' flag is deprecated
|
|
6614
6614
|
`))}),W.args.length>0)aH9(H,W);await Jp1(H,F,W)}),aZ6(J),J}async function SQ1(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??qz(),K=vQ1(J);if(Z)await J.threadStorage.set(Y,Z);let G=await HJ.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,_51(X));let q=J.threadService.observe(Y).subscribe(async(z)=>{if(t7(z,"assistant"))await Qp1(Y),q.unsubscribe()});return await G.resume(),G}async function Jp1(J,Q,Z){let X=k51(Q);if(X instanceof Error)JG(X.message);let Y,K=null;if(Q.streamJsonInput)Y="";else if(typeof Q.execute==="string"){Y=Q.execute;let R=(await Zf1()).trimEnd();if(R)K=R}else Y=(await Zf1()).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"
|
|
6615
6615
|
Or pipe via stdin: echo "your message" | amp --execute`);iq(Z,Q);let G=await nq(J,Q);IF6=G;let q=vQ1(G),z=async(R)=>{let O=await EF6(R,"utf-8"),j=JSON.parse(O);if(!HG(j.id))throw new k9(cK.invalidThreadId);return SQ1(G,{visibility:X,thread:j})},U=async(R)=>{if(!HG(R))throw new k9(cK.invalidThreadId);let O=await G.threadService.get(R)??void 0;if(p.info(`[fetchAndStartThread] Loaded thread ${R}, agentMode: ${O?.agentMode??"undefined"}`),O?.agentMode)p.info(`[fetchAndStartThread] Setting runtime override for agentMode to: ${O.agentMode}`),MZ("experimental.agentMode",O.agentMode);else p.info("[fetchAndStartThread] No agentMode on thread, not setting override");return SQ1(G,{visibility:X,thread:O})},W=async()=>{try{if(Q.threadId)return U(Q.threadId);else return SQ1(G,{visibility:X})}catch(R){if(R instanceof k9)throw R;throw await H51(R,Q.threadId),Error("handleError should have called process.exit()")}},F=async()=>{return SQ1(G,{visibility:X})};if(Q.format==="jsonl")QG.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
6616
|
-
`),await HR(),process.exit(1);if(J.executeMode&&Q.remote)await UX6(Y,K,G.configService),await G.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await uQ6(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 ir1();let R=await gB({jetbrainsOnly:Q.jetbrains});if(R.length===0){if(Q.jetbrains)M=!await G.configService.get("jetbrains.skipInstall")}else if(R.length===1){let O=R[0];if(O)S7.selectConfig(O)}else B=!0}let V=oy1("0.0.
|
|
6617
|
-
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await BZ6({...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 QX6(J.mcpConfig);X=cH9(X,G)}let Y=await X.get("url","global");if(!Y)Y=VZ;if(!EB(Y))p.info("Targeting custom Amp server",{ampURL:Y});if(X=nl1(X),await X.get("debug.httpLogging"))cl1();return{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:WX6(await uy1(J,X))}}function oH9(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 tH9(){let J=oH9(process.argv);if(WQ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),pH9(p),p.info("Starting Amp CLI.",{version:"0.0.
|
|
6616
|
+
`),await HR(),process.exit(1);if(J.executeMode&&Q.remote)await UX6(Y,K,G.configService),await G.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await uQ6(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 ir1();let R=await gB({jetbrainsOnly:Q.jetbrains});if(R.length===0){if(Q.jetbrains)M=!await G.configService.get("jetbrains.skipInstall")}else if(R.length===1){let O=R[0];if(O)S7.selectConfig(O)}else B=!0}let V=oy1("0.0.1761624095-g7e6816",G.settingsStorage),N=e1.of([O0.file(process.cwd())]),L=BS(void 0,N);if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let A;try{A=await GJ.getUserFreeTierStatus({},{config:G.configService})}catch(R){A={ok:!1,error:R}}p.info("User free tier status:",A);let w=await BX6();p.info("Loaded session state:",w),await RF6({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new Py1,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadSyncService:G.threadSyncService,threadID:H.threadID,worker:H,workerDeps:q,configService:G.configService,internalAPIClient:GJ,ampURL:J.ampURL,startNewThread:F,pickAndContinueThread:async()=>{p.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:S7,connectedClientsService:new Tc,commandRegistry:L,showJetBrainsInstaller:M,showIdePicker:B,startWithPicker:Q.startWithPicker,updateService:V,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:w,freeTierStatus:A.ok?A.result:void 0}),await G.asyncDispose(),process.exit(0)}async function RX(J){if(J.interactive)QG.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
6617
|
+
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await BZ6({...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 QX6(J.mcpConfig);X=cH9(X,G)}let Y=await X.get("url","global");if(!Y)Y=VZ;if(!EB(Y))p.info("Targeting custom Amp server",{ampURL:Y});if(X=nl1(X),await X.get("debug.httpLogging"))cl1();return{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:WX6(await uy1(J,X))}}function oH9(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 tH9(){let J=oH9(process.argv);if(WQ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),pH9(p),p.info("Starting Amp CLI.",{version:"0.0.1761624095-g7e6816",buildTimestamp:"2025-10-28T04:06:50.250Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new k9(cK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await sH9().parseAsync(process.argv)}tH9().catch(H51);async function eH9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),t2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
6618
6618
|
`);else if(!EB(J.ampURL))t2.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
6619
6619
|
`);let Z=process.env.AMP_API_KEY;if(Z)t2.write(`API key found in environment variable, storing...
|
|
6620
6620
|
`),await Q.set("apiKey",Z,J.ampURL),t2.write(`API key successfully stored.
|