@sourcegraph/amp 0.0.1761735780-g26a9fd → 0.0.1761739318-g60349c
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
|
@@ -6031,11 +6031,11 @@ Actual: ${Y}`)}async function F29(J,Q,Z){let{execSync:X}=await import("node:ch
|
|
|
6031
6031
|
${B}`;if(Y==="pnpm"&&B.includes("Unable to find the global bin directory"))M+=`
|
|
6032
6032
|
|
|
6033
6033
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
6034
|
-
npm install -g @sourcegraph/amp`;q(Error(M))}},error:(H)=>{if(!W)W=!0,q(Error(`Failed to spawn ${Y}: ${H.message}`))},complete:()=>{if(!W)W=!0,G()}})})}G0();G0();async function E51(J){try{let Z=new AbortController,X=setTimeout(()=>Z.abort(),5000),Y=await fetch("https://registry.npmjs.org/@sourcegraph/amp",{signal:Z.signal});if(clearTimeout(X),!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await Y.json(),G=K["dist-tags"]?.latest;if(!G)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=V29(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 V29(J,Q){let Z=(G)=>{let[q,z]=G.split("-");return{parts:q?.split(".").map(Number)||[],label:z}},X=Z(J),Y=Z(Q),K=Math.max(X.parts.length,Y.parts.length);for(let G=0;G<K;G++){let q=X.parts[G]||0,z=Y.parts[G]||0;if(q<z)return-1;if(q>z)return 1}if(X.label===Y.label)return 0;if(!X.label&&Y.label)return 1;if(X.label&&!Y.label)return-1;if(X.label&&Y.label)return X.label<Y.label?-1:1;return 0}v0();function Uf1(J,Q){let Z=new k8,X=Z.pipe(M9({shouldCountRefs:!1}));return setImmediate(async()=>{let Y=new rq().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 N_(500),Z.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){Y.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let q=await Q.get("updates.mode");if(q==="disabled"){Y.debug("checking disabled");return}Y.debug("checking",{currentVersion:J,mode:q});let z=await E51(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let U=await $51();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 ru(z.latestVersion,U);let W=await oV(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 N_(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as eU}from"node:process";function XZ6(J){let Q=new ow().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 Gf1(X.force||!1,X.verbose||!1,"0.0.
|
|
6034
|
+
npm install -g @sourcegraph/amp`;q(Error(M))}},error:(H)=>{if(!W)W=!0,q(Error(`Failed to spawn ${Y}: ${H.message}`))},complete:()=>{if(!W)W=!0,G()}})})}G0();G0();async function E51(J){try{let Z=new AbortController,X=setTimeout(()=>Z.abort(),5000),Y=await fetch("https://registry.npmjs.org/@sourcegraph/amp",{signal:Z.signal});if(clearTimeout(X),!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await Y.json(),G=K["dist-tags"]?.latest;if(!G)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=V29(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 V29(J,Q){let Z=(G)=>{let[q,z]=G.split("-");return{parts:q?.split(".").map(Number)||[],label:z}},X=Z(J),Y=Z(Q),K=Math.max(X.parts.length,Y.parts.length);for(let G=0;G<K;G++){let q=X.parts[G]||0,z=Y.parts[G]||0;if(q<z)return-1;if(q>z)return 1}if(X.label===Y.label)return 0;if(!X.label&&Y.label)return 1;if(X.label&&!Y.label)return-1;if(X.label&&Y.label)return X.label<Y.label?-1:1;return 0}v0();function Uf1(J,Q){let Z=new k8,X=Z.pipe(M9({shouldCountRefs:!1}));return setImmediate(async()=>{let Y=new rq().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 N_(500),Z.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){Y.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let q=await Q.get("updates.mode");if(q==="disabled"){Y.debug("checking disabled");return}Y.debug("checking",{currentVersion:J,mode:q});let z=await E51(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let U=await $51();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 ru(z.latestVersion,U);let W=await oV(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 N_(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as eU}from"node:process";function XZ6(J){let Q=new ow().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 Gf1(X.force||!1,X.verbose||!1,"0.0.1761739318-g60349c"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new ow("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 N29(X.version)});J.addCommand(Z)}async function N29(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")eU.write(W8.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
6035
6035
|
|
|
6036
6036
|
`));try{if(!J){eU.write(W8.blue(`Checking for updates...
|
|
6037
|
-
`));let{hasUpdate:Z,latestVersion:X}=await E51("0.0.
|
|
6038
|
-
`));let Y=await oV("0.0.
|
|
6037
|
+
`));let{hasUpdate:Z,latestVersion:X}=await E51("0.0.1761739318-g60349c");if(!Z){eU.write(W8.green(`✓ Amp CLI is already up to date.
|
|
6038
|
+
`));let Y=await oV("0.0.1761739318-g60349c");if(Y.warning)eU.write(`
|
|
6039
6039
|
`+W8.yellow(Y.warning)+`
|
|
6040
6040
|
`);process.exit(0)}if(!X)eU.write(W8.yellow("[WARN] could not find latest version")),process.exit(0);J=X}eU.write(W8.blue(`Updating to version ${J}...
|
|
6041
6041
|
`)),await ru(J,void 0,(Z)=>{eU.write(W8.dim(`Running: ${Z}
|
|
@@ -6455,7 +6455,7 @@ See https://ampcode.com/manual#toolboxes`);return Q[0]||sR}function dZ6(J,Q){let
|
|
|
6455
6455
|
`);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(uZ6()){let F=[];for await(let H of process.stdin)F.push(H);W=Buffer.concat(F).toString("utf-8").trim()}await gZ6({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 SK9}from"node:crypto";import{homedir as vK9}from"node:os";import tp from"node:path";v0();G0();var cZ6=120000,lZ6=180000;function Vf1(J,Q=Date.now()){return Q-J<lZ6}function Nf1(J,Q,Z=()=>!0,X){let Y=null,K=[],G=5;return $N(t1.of(void 0),Rd(cZ6).pipe(T7(()=>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})),e6((q,z)=>q?.id===z?.id))}G0();dj();q2();aB();o9();VL();z8();v6();function iZ6(J){let Q=J.trim();if(Q==="quit"||Q==="exit")return"/quit";return J}function aZ6(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();aB();import u49 from"node:fs";import nZ6 from"node:path";function rZ6(J){let Q=J.trim().replace(/^["']|["']$/g,"");if(Q=Q.replace(/\\(.)/g,"$1"),!/\.(png|jpe?g|gif|webp)$/i.test(Q))return null;if(!nZ6.isAbsolute(Q))return null;return u.debug("Extracted image path",{original:J,extracted:Q}),Q}function sZ6(J){try{let Q=nZ6.extname(J).toLowerCase(),Z=xe1(Q);if(!Z)return u.warn("Unsupported image file extension",{ext:Q}),null;try{let X=u49.readFileSync(J);return p49(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 p49(J,Q){if(J.length===0)return u.warn("Image file is empty (0 bytes)"),null;if(J.length>CW)return u.warn(`Image file too large: ${J.length} bytes (max: ${CW})`),null;return{type:"image",source:{type:"base64",data:J.toString("base64"),mediaType:Q}}}import{execSync as k79}from"node:child_process";zj();G0();import{spawn as d49}from"node:child_process";import{promises as c49}from"node:fs";function oZ6(J){return J.kind==="executable"}function tZ6(J){return J.kind==="markdown"}var iH=50000,eZ6=300000;async function tu(J,Q,Z,X={}){let{timeoutMs:Y=eZ6,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}),tZ6(G))return await l49(G,Q);else if(oZ6(G))return await i49(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 l49(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await c49.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>iH?Z.slice(0,iH)+`
|
|
6456
6456
|
... (output truncated at ${iH} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function i49(J,Q,Z=eZ6,X){return new Promise((Y)=>{let[K,G]=a49(J,Q);u.debug("Spawning command",{spawnCommand:K,spawnArgs:G.slice(0,10),filePath:J.filePath,timeoutMs:Z});let q=Pe1(X),z=!1,U=setTimeout(()=>{z=!0,q.abort(),u.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),W=d49(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<=iH)F.push(V);else{let N=iH-(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<=iH)H.push(V);else{let N=iH-(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?`
|
|
6457
6457
|
${L}`:L;if(B>iH)A+=`
|
|
6458
|
-
... (output truncated at ${iH} 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 a49(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return r49(Z,X?[...X]:null,Y,Q);else return n49(Z,X?[...X]:null,Y,Q)}function n49(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function r49(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();q2();MW();uX();wz();v6();v0();var k51={};E6(k51,{scrollUp:()=>M79,scrollDown:()=>V79,link:()=>O79,image:()=>j79,iTerm:()=>$79,exitAlternativeScreen:()=>w79,eraseUp:()=>D79,eraseStartLine:()=>H79,eraseScreen:()=>Lf1,eraseLines:()=>W79,eraseLine:()=>XX6,eraseEndLine:()=>F79,eraseDown:()=>B79,enterAlternativeScreen:()=>A79,cursorUp:()=>QX6,cursorTo:()=>t49,cursorShow:()=>U79,cursorSavePosition:()=>X79,cursorRestorePosition:()=>Y79,cursorPrevLine:()=>q79,cursorNextLine:()=>G79,cursorMove:()=>e49,cursorLeft:()=>ZX6,cursorHide:()=>z79,cursorGetPosition:()=>K79,cursorForward:()=>Q79,cursorDown:()=>J79,cursorBackward:()=>Z79,clearTerminal:()=>L79,clearScreen:()=>N79,beep:()=>R79});import Af1 from"node:process";var v51=globalThis.window?.document!==void 0,EV2=globalThis.process?.versions?.node!==void 0,IV2=globalThis.process?.versions?.bun!==void 0,PV2=globalThis.Deno?.version?.deno!==void 0,TV2=globalThis.process?.versions?.electron!==void 0,CV2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,SV2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,vV2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,kV2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,_V2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,eu=globalThis.navigator?.userAgentData?.platform,xV2=eu==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",bV2=eu==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",yV2=eu==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",fV2=eu==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),hV2=eu==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var R2="\x1B[",Qp="\x1B]",wC="\x07",Jp=";",JX6=!v51&&Af1.env.TERM_PROGRAM==="Apple_Terminal",s49=!v51&&Af1.platform==="win32",o49=v51?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Af1.cwd,t49=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return R2+(J+1)+"G";return R2+(Q+1)+Jp+(J+1)+"H"},e49=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=R2+-J+"D";else if(J>0)Z+=R2+J+"C";if(Q<0)Z+=R2+-Q+"A";else if(Q>0)Z+=R2+Q+"B";return Z},QX6=(J=1)=>R2+J+"A",J79=(J=1)=>R2+J+"B",Q79=(J=1)=>R2+J+"C",Z79=(J=1)=>R2+J+"D",ZX6=R2+"G",X79=JX6?"\x1B7":R2+"s",Y79=JX6?"\x1B8":R2+"u",K79=R2+"6n",G79=R2+"E",q79=R2+"F",z79=R2+"?25l",U79=R2+"?25h",W79=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=XX6+(Z<J-1?QX6():"");if(J)Q+=ZX6;return Q},F79=R2+"K",H79=R2+"1K",XX6=R2+"2K",B79=R2+"J",D79=R2+"1J",Lf1=R2+"2J",M79=R2+"S",V79=R2+"T",N79="\x1Bc",L79=s49?`${Lf1}${R2}0f`:`${Lf1}${R2}3J${R2}H`,A79=R2+"?1049h",w79=R2+"?1049l",R79=wC,O79=(J,Q)=>[Qp,"8",Jp,Jp,Q,wC,J,Qp,"8",Jp,Jp,wC].join(""),j79=(J,Q={})=>{let Z=`${Qp}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")+wC},$79={setCwd:(J=o49())=>`${Qp}50;CurrentDir=${J}${wC}`,annotation(J,Q={}){let Z=`${Qp}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+wC}};var _51=d6(WX6(),1);function JN(J,Q,{target:Z="stdout",...X}={}){if(!_51.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (${Q})`}return k51.link(J,Q)}JN.isSupported=_51.default.stdout;JN.stderr=(J,Q,Z={})=>JN(J,Q,{target:"stderr",...Z});JN.stderr.isSupported=_51.default.stderr;G0();uX();class Zp{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.1761735780-g26a9fd"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Wn(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 b51}from"node:child_process";import{platform as $f1}from"node:os";import{promisify as T79}from"node:util";var x51=T79(b51),C79=(J)=>`\x1B]52;c;${J}\x1B\\`,S79="\x1B]52;c;?\x1B\\",v79="\x1B]52;p;?\x1B\\";class FX6{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 x51("which",[J]),!0}catch{return!1}}async writeToPbcopy(J){try{let Q=b51("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=b51("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=b51("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(S79)}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 x51("pbpaste");return J}catch{return null}}async readFromWlPaste(J){try{let Q=["--no-newline"];if(J==="primary")Q.push("--primary");let{stdout:Z}=await x51("wl-paste",Q);return Z}catch{return null}}async readFromXclip(J){try{let{stdout:Q}=await x51("xclip",["-selection",J,"-o"]);return Q}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(v79)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if($f1()==="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($f1()==="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=C79(Z);process.stdout.write(X);return}if($f1()==="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 FX6;G0();class y2{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function y51(J){if(J instanceof y2)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"}}class Ef1{configService;commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=XS(),Q){this.configService=Q;this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Z)=>this.latestCustom=Z),this.telemetrySubmitter=new Zp(async()=>{try{return(await this.configService.getLatest()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}},this.configService),this.configService.config.pipe(b0((Z)=>MZ(Z.settings)),e6()).subscribe((Z)=>{this._initBaseCommands(Z.length>1)})}_initBaseCommands(J){if(this.commands={..._79},J)Object.assign(this.commands,x79)}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 tu(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 _79={"generate-agent-file":{name:"generate-agent-file",description:`Generate an ${k5} file in the current workspace`,execute:async(J,Q)=>{let Z=await J.configService.getLatest(),X=bZ(Z.settings),K=J.getInMemoryAgentModeOverride()??X;J.worker.handle({type:"user:message",message:{content:[{type:"text",text:Hn}],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 VZ("dangerouslyAllowAll",!1),new y2("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 VZ("dangerouslyAllowAll",!0),new y2("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 JW();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:JW};await LC(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 y2(`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(`
|
|
6458
|
+
... (output truncated at ${iH} 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 a49(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return r49(Z,X?[...X]:null,Y,Q);else return n49(Z,X?[...X]:null,Y,Q)}function n49(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function r49(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();q2();MW();uX();wz();v6();v0();var k51={};E6(k51,{scrollUp:()=>M79,scrollDown:()=>V79,link:()=>O79,image:()=>j79,iTerm:()=>$79,exitAlternativeScreen:()=>w79,eraseUp:()=>D79,eraseStartLine:()=>H79,eraseScreen:()=>Lf1,eraseLines:()=>W79,eraseLine:()=>XX6,eraseEndLine:()=>F79,eraseDown:()=>B79,enterAlternativeScreen:()=>A79,cursorUp:()=>QX6,cursorTo:()=>t49,cursorShow:()=>U79,cursorSavePosition:()=>X79,cursorRestorePosition:()=>Y79,cursorPrevLine:()=>q79,cursorNextLine:()=>G79,cursorMove:()=>e49,cursorLeft:()=>ZX6,cursorHide:()=>z79,cursorGetPosition:()=>K79,cursorForward:()=>Q79,cursorDown:()=>J79,cursorBackward:()=>Z79,clearTerminal:()=>L79,clearScreen:()=>N79,beep:()=>R79});import Af1 from"node:process";var v51=globalThis.window?.document!==void 0,EV2=globalThis.process?.versions?.node!==void 0,IV2=globalThis.process?.versions?.bun!==void 0,PV2=globalThis.Deno?.version?.deno!==void 0,TV2=globalThis.process?.versions?.electron!==void 0,CV2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,SV2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,vV2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,kV2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,_V2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,eu=globalThis.navigator?.userAgentData?.platform,xV2=eu==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",bV2=eu==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",yV2=eu==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",fV2=eu==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),hV2=eu==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var R2="\x1B[",Qp="\x1B]",wC="\x07",Jp=";",JX6=!v51&&Af1.env.TERM_PROGRAM==="Apple_Terminal",s49=!v51&&Af1.platform==="win32",o49=v51?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Af1.cwd,t49=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return R2+(J+1)+"G";return R2+(Q+1)+Jp+(J+1)+"H"},e49=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=R2+-J+"D";else if(J>0)Z+=R2+J+"C";if(Q<0)Z+=R2+-Q+"A";else if(Q>0)Z+=R2+Q+"B";return Z},QX6=(J=1)=>R2+J+"A",J79=(J=1)=>R2+J+"B",Q79=(J=1)=>R2+J+"C",Z79=(J=1)=>R2+J+"D",ZX6=R2+"G",X79=JX6?"\x1B7":R2+"s",Y79=JX6?"\x1B8":R2+"u",K79=R2+"6n",G79=R2+"E",q79=R2+"F",z79=R2+"?25l",U79=R2+"?25h",W79=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=XX6+(Z<J-1?QX6():"");if(J)Q+=ZX6;return Q},F79=R2+"K",H79=R2+"1K",XX6=R2+"2K",B79=R2+"J",D79=R2+"1J",Lf1=R2+"2J",M79=R2+"S",V79=R2+"T",N79="\x1Bc",L79=s49?`${Lf1}${R2}0f`:`${Lf1}${R2}3J${R2}H`,A79=R2+"?1049h",w79=R2+"?1049l",R79=wC,O79=(J,Q)=>[Qp,"8",Jp,Jp,Q,wC,J,Qp,"8",Jp,Jp,wC].join(""),j79=(J,Q={})=>{let Z=`${Qp}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")+wC},$79={setCwd:(J=o49())=>`${Qp}50;CurrentDir=${J}${wC}`,annotation(J,Q={}){let Z=`${Qp}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+wC}};var _51=d6(WX6(),1);function JN(J,Q,{target:Z="stdout",...X}={}){if(!_51.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (${Q})`}return k51.link(J,Q)}JN.isSupported=_51.default.stdout;JN.stderr=(J,Q,Z={})=>JN(J,Q,{target:"stderr",...Z});JN.stderr.isSupported=_51.default.stderr;G0();uX();class Zp{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.1761739318-g60349c"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Wn(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 b51}from"node:child_process";import{platform as $f1}from"node:os";import{promisify as T79}from"node:util";var x51=T79(b51),C79=(J)=>`\x1B]52;c;${J}\x1B\\`,S79="\x1B]52;c;?\x1B\\",v79="\x1B]52;p;?\x1B\\";class FX6{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 x51("which",[J]),!0}catch{return!1}}async writeToPbcopy(J){try{let Q=b51("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=b51("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=b51("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(S79)}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 x51("pbpaste");return J}catch{return null}}async readFromWlPaste(J){try{let Q=["--no-newline"];if(J==="primary")Q.push("--primary");let{stdout:Z}=await x51("wl-paste",Q);return Z}catch{return null}}async readFromXclip(J){try{let{stdout:Q}=await x51("xclip",["-selection",J,"-o"]);return Q}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(v79)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if($f1()==="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($f1()==="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=C79(Z);process.stdout.write(X);return}if($f1()==="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 FX6;G0();class y2{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function y51(J){if(J instanceof y2)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"}}class Ef1{configService;commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=XS(),Q){this.configService=Q;this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Z)=>this.latestCustom=Z),this.telemetrySubmitter=new Zp(async()=>{try{return(await this.configService.getLatest()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}},this.configService),this.configService.config.pipe(b0((Z)=>MZ(Z.settings)),e6()).subscribe((Z)=>{this._initBaseCommands(Z.length>1)})}_initBaseCommands(J){if(this.commands={..._79},J)Object.assign(this.commands,x79)}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 tu(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 _79={"generate-agent-file":{name:"generate-agent-file",description:`Generate an ${k5} file in the current workspace`,execute:async(J,Q)=>{let Z=await J.configService.getLatest(),X=bZ(Z.settings),K=J.getInMemoryAgentModeOverride()??X;J.worker.handle({type:"user:message",message:{content:[{type:"text",text:Hn}],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 VZ("dangerouslyAllowAll",!1),new y2("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 VZ("dangerouslyAllowAll",!0),new y2("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 JW();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:JW};await LC(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 y2(`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(`
|
|
6459
6459
|
`).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=pW(new URL(Y),Z.id).toString(),q=`Thread URL: ${JN(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 y2(`${q}
|
|
6460
6460
|
|
|
6461
6461
|
This thread's visibility has been updated to: ${z}`)}catch(W){let F=W instanceof Error?W.message:String(W);if(F.includes("no-workspace"))return Error("You are not a member of any workspace.");if(F.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(F.includes("no-groups"))return Error("You are not a member of any groups.");return u.error("Unexpected failure to update thread visibility",W),Error(`Failed to update thread visibility for ${Z.id}`)}}},browser:{name:"browser",description:"Open the current thread in your browser",requiresArgs:!1,execute:async(J,Q)=>{let{thread:Z,ampURL:X}=J,Y=pW(new URL(X),Z.id).toString();try{return await OQ(Y),new y2("Thread opened in browser")}catch(K){u.error("Failed to open browser",{error:K});let G=JN(Y,Y,{fallback:()=>Y});return new y2(`Could not open browser automatically. Thread URL: ${G}`)}},isVisible:(J)=>J.messages.length!==0},url:{name:"url",description:"Display thread URL and copy to clipboard",requiresArgs:!1,execute:async(J,Q)=>{let{thread:Z,ampURL:X}=J,Y=pW(new URL(X),Z.id).toString();try{return await AY.writeText(Y),new y2(`Thread URL: ${Y}
|
|
@@ -6659,7 +6659,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
|
|
|
6659
6659
|
`),J.stdout.write(`Thread: ${H}
|
|
6660
6660
|
`),J.stdout.write(`Continue this thread with: amp threads continue ${W}
|
|
6661
6661
|
`)}}function Fu1(J){return J==="smart"?I1.rgb(3,197,97):J==="free"?I1.rgb(0,184,255):_K9(J)}function _K9(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])}cf1();if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){oK.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
6662
|
-
`)}var Bu1=Hu1.join(hc1||Hu1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function hK9(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 cq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")VZ("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")VZ("experimental.agentMode",Q.agentMode)}async function Mu1(J){try{await bK9(Hu1.dirname(Bu1),{recursive:!0}),await yK9(Bu1,J,"utf-8")}catch(Q){u.debug("Failed to save last thread ID",Q)}}async function gK9(){try{return(await Ez6(Bu1,"utf-8")).trim()}catch(J){return null}}function mK9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return LS("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 Oz6=[{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??WZ,description:`Custom settings file path (overrides the default location ${WZ})`},{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 ${Sy1})`},{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:DQ(),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:ld}],jz6=(J)=>("deprecated"in J)&&J.deprecated===!0,uK9=(J)=>("hidden"in J)&&J.hidden===!0,pK9=(J)=>("default"in J),dK9=(J)=>("default"in J)?J.default:void 0;function cK9(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(pK.unknownCommand(Z),1,G)}}var Iz6=null;function Js2(){return Iz6}function LQ1(J){return{...J,getThreadEnvironment:J51,vfs:n20({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new C_(J.fileSystem),generateThreadTitle:qq0,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var Vu1=$0.file(fK9.homedir()),Pz6=process.env.XDG_CONFIG_HOME?$0.file(process.env.XDG_CONFIG_HOME):y0.joinPath(Vu1,".config");async function lq(J,Q){ii1("0.0.
|
|
6662
|
+
`)}var Bu1=Hu1.join(hc1||Hu1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function hK9(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 cq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")VZ("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")VZ("experimental.agentMode",Q.agentMode)}async function Mu1(J){try{await bK9(Hu1.dirname(Bu1),{recursive:!0}),await yK9(Bu1,J,"utf-8")}catch(Q){u.debug("Failed to save last thread ID",Q)}}async function gK9(){try{return(await Ez6(Bu1,"utf-8")).trim()}catch(J){return null}}function mK9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return LS("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 Oz6=[{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??WZ,description:`Custom settings file path (overrides the default location ${WZ})`},{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 ${Sy1})`},{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:DQ(),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:ld}],jz6=(J)=>("deprecated"in J)&&J.deprecated===!0,uK9=(J)=>("hidden"in J)&&J.hidden===!0,pK9=(J)=>("default"in J),dK9=(J)=>("default"in J)?J.default:void 0;function cK9(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(pK.unknownCommand(Z),1,G)}}var Iz6=null;function Js2(){return Iz6}function LQ1(J){return{...J,getThreadEnvironment:J51,vfs:n20({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new C_(J.fileSystem),generateThreadTitle:qq0,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var Vu1=$0.file(fK9.homedir()),Pz6=process.env.XDG_CONFIG_HOME?$0.file(process.env.XDG_CONFIG_HOME):y0.joinPath(Vu1,".config");async function lq(J,Q){ii1("0.0.1761739318-g60349c");let Z=TX1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:t1.of([$0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:Vu1,userConfigDir:Pz6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (VQ1(),MQ1));X(Z);let Y=await Z.getLatest();u.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let K=Pn(RO({configService:Z})),G=new Map,q=()=>G.clear(),z=$20({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 W3(J.secrets),_=await S.getClientInfo(E),h=new oU1({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=_R0(K,$2,W11).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)$O("JetBrains");else if(Q.ide&&uQ6())$O("VS Code");else if(Q.ide&&pQ6())$O("Neovim");if(J.executeMode)ai1(!0);g96(K,{configService:Z});let H,B=S7.status.pipe(b0((E)=>Boolean(E.connected&&E.authenticated)),e6()).subscribe((E)=>{if(E){if(!H)H=K.registerTool(Cs)}else H?.dispose(),H=void 0}),M;if(!J.executeMode)M=new M51(process.cwd(),{},!0);else M=new class extends M51{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...
|
|
6663
6663
|
`),!await lK9(J))await zR(),process.exit(1)}let V=await J40({isDevelopment:!1}),N=new kV1(V),L=new NB1(V,Z,{lazy:!0}),A=Q.notifications!==void 0?Q.notifications:!J.executeMode,w=u96({playNotificationSound:async(E)=>{if(A){m96(E);let I=pf1(),T=df1();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=Gq0({threadService:N,threadHistoryService:L,configService:Z,isExtensionDevelopment:!1}),O;S7.status.subscribe((E)=>{O=E});let j={codebaseContextService:new wZ1({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?l20:$2};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 lK9(J){if(!J.executeMode){if(!await Ff1("Would you like to log in to Amp? [(y)es, (n)o]: "))return t2.write(`Login cancelled. Run the command again to retry.
|
|
6664
6664
|
`),!1}return await Tz6(J)}async function Tz6(J){let Q=xK9(32).toString("hex"),Z=await Wf1(J.ampURL,Q),X=new AbortController;try{await OQ(Z,X.signal)}catch(K){u.error("Error opening browser",{error:K})}let Y=await Wf1(J.ampURL,Q,!1);t2.write(`If your browser does not open automatically, visit:
|
|
6665
6665
|
|
|
@@ -6669,13 +6669,13 @@ ${W8.blue.bold(Y)}
|
|
|
6669
6669
|
Login successful! You can now use the Amp CLI.
|
|
6670
6670
|
`),!0}catch(K){return u.error("Login failed",{error:K}),oK.write(`
|
|
6671
6671
|
Login failed: ${K instanceof Error?K.message:String(K)}
|
|
6672
|
-
`),!1}}function iK9(){let J=new ow().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)WR(),process.exit(0);let W=U.originalError??U;pJ6(W)}),J.option("-V, --version","output the version number",()=>{t2.write(`0.0.
|
|
6672
|
+
`),!1}}function iK9(){let J=new ow().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)WR(),process.exit(0);let W=U.originalError??U;pJ6(W)}),J.option("-V, --version","output the version number",()=>{t2.write(`0.0.1761739318-g60349c (released 2025-10-29T12:07:08.560Z)
|
|
6673
6673
|
`),process.exit(0)}),J.addHelpText("after",hQ6()),J.configureHelp({formatHelp:gQ6}),J.command("logout").description("Log out by removing stored API key").action(async(U,W)=>{let F=W.optsWithGlobals(),H=await RX(F);await sK9(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 rK9(H,await ey1(F,H.settings))});let Q=async(U,W,F)=>{TX1({storage:W.settings,secretStorage:W.secrets,workspaceRoots:t1.of([$0.file(process.cwd())]),defaultAmpURL:W.ampURL,homeDir:Vu1,userConfigDir:Pz6});let H={...W,executeMode:!1};await Du1(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 $z6(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 ZG9(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)oK.write(`${W8.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
|
|
6674
6674
|
`);if(W.last||U||B.executeMode)await QG9(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 JG9(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 $z6(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 eK9(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 oK9(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 tK9(H,B,U,F)}),dZ6(J,async(U,W)=>{let F=await RX(W);cq(U,W);let H=await lq(F,W);return{context:F,mcpService:H.mcpService,toolService:H.toolService,configService:H.configService,cleanupTerminal:WR,asyncDispose:H.asyncDispose.bind(H)}}),LZ6(J),WZ6(J,async(U)=>{let W=await RX(U);return{settings:W.settings,secretStorage:W.secrets,getThreadDeps:async(F)=>{cq(F,U);let H=await lq(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);cq(W,F);let B=await lq(H,F);try{await gy1(B,B.configService,{})}finally{await B.asyncDispose(),await WR()}});function X(U,W,F){let B=typeof U.description==="string"?U.description:F===void 0?U.description(!0):U.description(F),M=new mV(W,B),V=dK9(U);if(V)M.default(V);if(M.hidden=uK9(U)||jz6(U),"choices"in U)M.choices([...U.choices]);return M}for(let U of Oz6)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 mV("-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 mV("-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 mV("--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 mV("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(q);let z=new mV("--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 mV("--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=Oz6.find((V)=>V.name===B);if(M&&jz6(M)&&!pK9(M))oK.write(W8.yellow(`Warning: '--${B}' flag is deprecated
|
|
6675
6675
|
`))}),W.args.length>0)cK9(H,W);await Du1(H,F,W)}),XZ6(J),J}async function NQ1(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??Yz(),K=LQ1(J);if(Z)await J.threadStorage.set(Y,Z);let G=await HJ.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,P51(X));let q=J.threadService.observe(Y).subscribe(async(z)=>{if(o7(z,"assistant"))await Mu1(Y),q.unsubscribe()});return await G.resume(),G}async function Du1(J,Q,Z){let X=I51(Q);if(X instanceof Error)sK(X.message);let Y,K=null;if(Q.streamJsonInput)Y="";else if(typeof Q.execute==="string"){Y=Q.execute;let O=(await Bf1()).trimEnd();if(O)K=O}else Y=(await Bf1()).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"
|
|
6676
6676
|
Or pipe via stdin: echo "your message" | amp --execute`);cq(Z,Q);let G=await lq(J,Q);if(J.executeMode||Q.threadId)await G.backgroundInit;Iz6=G;let q=LQ1(G),z=async(O)=>{let $=await Ez6(O,"utf-8"),j=JSON.parse($);if(!zG(j.id))throw new k9(pK.invalidThreadId);return NQ1(G,{visibility:X,thread:j})},U=async(O)=>{if(!zG(O))throw new k9(pK.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}`),VZ("experimental.agentMode",$.agentMode);else u.info("[fetchAndStartThread] No agentMode on thread, not setting override");return NQ1(G,{visibility:X,thread:$})},W=async()=>{try{if(Q.threadId)return U(Q.threadId);else return NQ1(G,{visibility:X})}catch(O){if(O instanceof k9)throw O;throw await G51(O,Q.threadId),Error("handleError should have called process.exit()")}},F=async()=>{return NQ1(G,{visibility:X})};if(Q.format==="jsonl")oK.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
6677
|
-
`),await zR(),process.exit(1);if(J.executeMode&&Q.remote)await AZ6(Y,K,G.configService),await G.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await QQ6(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 Gr1();let O=await uO({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($)S7.selectConfig($)}else B=!0}let V=Uf1("0.0.
|
|
6678
|
-
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await OQ6({...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 FZ6(J.mcpConfig);X=mK9(X,G)}let Y=await X.get("url","global");if(!Y)Y=NZ;if(!LB(Y))u.info("Targeting custom Amp server",{ampURL:Y});if(X=Wl1(X),await X.get("debug.httpLogging"))Ql1();return{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:wZ6(await ey1(J,X))}}function aK9(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 nK9(){let J=aK9(process.argv);if(EJ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),hK9(u),u.info("Starting Amp CLI.",{version:"0.0.
|
|
6677
|
+
`),await zR(),process.exit(1);if(J.executeMode&&Q.remote)await AZ6(Y,K,G.configService),await G.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await QQ6(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 Gr1();let O=await uO({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($)S7.selectConfig($)}else B=!0}let V=Uf1("0.0.1761739318-g60349c",G.settingsStorage),N=new VB1(G.threadStorage),L=t1.of([$0.file(process.cwd())]),A=XS(void 0,L);if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let w;try{w=await KJ.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 jZ6();u.info("Loaded session state:",R),await Rz6({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new cy1,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:KJ,ampURL:J.ampURL,startNewThread:F,pickAndContinueThread:async()=>{u.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:S7,connectedClientsService:new vX1,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,threadDependencies:G}),await G.asyncDispose(),process.exit(0)}async function RX(J){if(J.interactive)oK.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
6678
|
+
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await OQ6({...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 FZ6(J.mcpConfig);X=mK9(X,G)}let Y=await X.get("url","global");if(!Y)Y=NZ;if(!LB(Y))u.info("Targeting custom Amp server",{ampURL:Y});if(X=Wl1(X),await X.get("debug.httpLogging"))Ql1();return{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:wZ6(await ey1(J,X))}}function aK9(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 nK9(){let J=aK9(process.argv);if(EJ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),hK9(u),u.info("Starting Amp CLI.",{version:"0.0.1761739318-g60349c",buildTimestamp:"2025-10-29T12:07:08.560Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new k9(pK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await iK9().parseAsync(process.argv)}nK9().catch(G51);async function rK9(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}
|
|
6679
6679
|
`);else if(!LB(J.ampURL))t2.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
6680
6680
|
`);let Z=process.env.AMP_API_KEY;if(Z)t2.write(`API key found in environment variable, storing...
|
|
6681
6681
|
`),await Q.set("apiKey",Z,J.ampURL),t2.write(`API key successfully stored.
|