@sourcegraph/amp 0.0.1761379287-ge22fe5 → 0.0.1761393687-gf965ca
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
|
@@ -5906,11 +5906,11 @@ Actual: ${Y}`)}async function e79(J,Q,Z){let{execSync:X}=await import("node:ch
|
|
|
5906
5906
|
${B}`;if(Y==="pnpm"&&B.includes("Unable to find the global bin directory"))M+=`
|
|
5907
5907
|
|
|
5908
5908
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
5909
|
-
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 b51(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=Y59(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 Y59(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 Qf1(J,Q){let Z=new b8,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 E_(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 b51(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let U=await x51();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 Zp(z.latestVersion,U);let W=await eV(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 E_(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as JW}from"node:process";function iZ6(J){let Q=new Bu().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 ty1(X.force||!1,X.verbose||!1,"0.0.
|
|
5909
|
+
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 b51(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=Y59(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 Y59(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 Qf1(J,Q){let Z=new b8,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 E_(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 b51(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let U=await x51();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 Zp(z.latestVersion,U);let W=await eV(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 E_(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as JW}from"node:process";function iZ6(J){let Q=new Bu().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 ty1(X.force||!1,X.verbose||!1,"0.0.1761393687-gf965ca"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new Bu("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 K59(X.version)});J.addCommand(Z)}async function K59(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")JW.write(z8.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
5910
5910
|
|
|
5911
5911
|
`));try{if(!J){JW.write(z8.blue(`Checking for updates...
|
|
5912
|
-
`));let{hasUpdate:Z,latestVersion:X}=await b51("0.0.
|
|
5913
|
-
`));let Y=await eV("0.0.
|
|
5912
|
+
`));let{hasUpdate:Z,latestVersion:X}=await b51("0.0.1761393687-gf965ca");if(!Z){JW.write(z8.green(`✓ Amp CLI is already up to date.
|
|
5913
|
+
`));let Y=await eV("0.0.1761393687-gf965ca");if(Y.warning)JW.write(`
|
|
5914
5914
|
`+z8.yellow(Y.warning)+`
|
|
5915
5915
|
`);process.exit(0)}if(!X)JW.write(z8.yellow("[WARN] could not find latest version")),process.exit(0);J=X}JW.write(z8.blue(`Updating to version ${J}...
|
|
5916
5916
|
`)),await Zp(J,void 0,(Z)=>{JW.write(z8.dim(`Running: ${Z}
|
|
@@ -6282,7 +6282,7 @@ See https://ampcode.com/manual#toolboxes`);return Q[0]||ZO}function vX6(J,Q){let
|
|
|
6282
6282
|
`);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(CX6()){let F=[];for await(let H of process.stdin)F.push(H);W=Buffer.concat(F).toString("utf-8").trim()}await PX6({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 PH9}from"node:crypto";import{homedir as TH9}from"node:os";import Dd from"node:path";C0();G0();var kX6=120000,_X6=180000;function Uf1(J,Q=Date.now()){return Q-J<_X6}function Wf1(J,Q,Z=()=>!0,X){let Y=null,K=[],G=5;return fd(kX6).pipe(v2(void 0),q8(()=>d6(async(q)=>{if(!Z())return u.debug("[Ads] Skipping ad fetch (user inactive or ad already fetched)"),Y;let z=await X?.getContext();u.debug("[Ads] Fetching ad from server",{hasContext:!!z});let U=await J.getCurrentAd({context:z,excludeAdIds:K},{config:Q,signal:q});if(!U.ok)throw u.error("[Ads] Failed to fetch ad",{error:U.error.message}),Error(U.error.message);if(U.result){if(Y=U.result,K.length>=G)K.shift();K.push(Y.id),u.debug("[Ads] Received ad from server",{adTitle:Y.title,matchType:Y.matchType,matchedPatterns:Y.matchedPatterns,candidateAdPoolCount:Y.candidateAdPoolCount,recentlyShownCount:K.length})}else u.debug("[Ads] No ad available from server");return Y})),J8((q,z)=>q?.id===z?.id))}G0();lj();W2();JD();M2();$L();N8();b6();function xX6(J){let Q=J.trim();if(Q==="quit"||Q==="exit")return"/quit";return J}function bX6(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();JD();import kJ9 from"node:fs";import yX6 from"node:path";function fX6(J){let Q=J.trim().replace(/^["']|["']$/g,"");if(Q=Q.replace(/\\(.)/g,"$1"),!/\.(png|jpe?g|gif|webp)$/i.test(Q))return null;if(!yX6.isAbsolute(Q))return null;return u.debug("Extracted image path",{original:J,extracted:Q}),Q}function hX6(J){try{let Q=yX6.extname(J).toLowerCase(),Z=M10(Q);if(!Z)return u.warn("Unsupported image file extension",{ext:Q}),null;try{let X=kJ9.readFileSync(J);return _J9(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 _J9(J,Q){if(J.length>_W)return u.warn(`Image file too large: ${J.length} bytes (max: ${_W})`),null;return{type:"image",source:{type:"base64",data:J.toString("base64"),mediaType:Q}}}import{execSync as PK9}from"node:child_process";Fj();G0();import{spawn as xJ9}from"node:child_process";import{promises as bJ9}from"node:fs";function gX6(J){return J.kind==="executable"}function mX6(J){return J.kind==="markdown"}var JB=50000,uX6=300000;async function Kp(J,Q,Z,X={}){let{timeoutMs:Y=uX6,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}),mX6(G))return await yJ9(G,Q);else if(gX6(G))return await fJ9(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 yJ9(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await bJ9.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>JB?Z.slice(0,JB)+`
|
|
6283
6283
|
... (output truncated at ${JB} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function fJ9(J,Q,Z=uX6,X){return new Promise((Y)=>{let[K,G]=hJ9(J,Q);u.debug("Spawning command",{spawnCommand:K,spawnArgs:G.slice(0,10),filePath:J.filePath,timeoutMs:Z});let q=z10(X),z=!1,U=setTimeout(()=>{z=!0,q.abort(),u.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),W=xJ9(K,G,{stdio:["pipe","pipe","pipe"],signal:q.signal,detached:!0}),F=[],H=[],B=0;W.stdout?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=JB)F.push(V);else{let N=JB-(B-V.length);if(N>0)F.push(V.slice(0,N))}}),W.stderr?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=JB)H.push(V);else{let N=JB-(B-V.length);if(N>0)H.push(V.slice(0,N))}}),W.on("close",(M)=>{if(clearTimeout(U),z){Y({success:!1,output:F.join(""),error:`Command timed out after ${Z}ms`,exitCode:void 0});return}if(q.signal.aborted){Y({success:!1,output:F.join(""),error:"The command was aborted",exitCode:M??void 0});return}let V=M===0||M===1,N=F.join(""),L=H.join(""),A=N;if(!V&&!N.trim()&&L.trim())A=L;else if(L.trim())A+=N?`
|
|
6284
6284
|
${L}`:L;if(B>JB)A+=`
|
|
6285
|
-
... (output truncated at ${JB} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:F.join(""),error:V})})})}function hJ9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return mJ9(Z,X?[...X]:null,Y,Q);else return gJ9(Z,X?[...X]:null,Y,Q)}function gJ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function mJ9(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();lj();W2();bB();fX();Oz();b6();C0();var p51={};R6(p51,{scrollUp:()=>GQ9,scrollDown:()=>qQ9,link:()=>BQ9,image:()=>DQ9,iTerm:()=>MQ9,exitAlternativeScreen:()=>FQ9,eraseUp:()=>KQ9,eraseStartLine:()=>XQ9,eraseScreen:()=>Ff1,eraseLines:()=>QQ9,eraseLine:()=>lX6,eraseEndLine:()=>ZQ9,eraseDown:()=>YQ9,enterAlternativeScreen:()=>WQ9,cursorUp:()=>dX6,cursorTo:()=>dJ9,cursorShow:()=>JQ9,cursorSavePosition:()=>aJ9,cursorRestorePosition:()=>rJ9,cursorPrevLine:()=>tJ9,cursorNextLine:()=>oJ9,cursorMove:()=>cJ9,cursorLeft:()=>cX6,cursorHide:()=>eJ9,cursorGetPosition:()=>sJ9,cursorForward:()=>iJ9,cursorDown:()=>lJ9,cursorBackward:()=>nJ9,clearTerminal:()=>UQ9,clearScreen:()=>zQ9,beep:()=>HQ9});import Hf1 from"node:process";var u51=globalThis.window?.document!==void 0,gw2=globalThis.process?.versions?.node!==void 0,mw2=globalThis.process?.versions?.bun!==void 0,uw2=globalThis.Deno?.version?.deno!==void 0,pw2=globalThis.process?.versions?.electron!==void 0,dw2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,cw2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,lw2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,iw2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,nw2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,Gp=globalThis.navigator?.userAgentData?.platform,aw2=Gp==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",rw2=Gp==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",sw2=Gp==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",ow2=Gp==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),tw2=Gp==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var j2="\x1B[",zp="\x1B]",IC="\x07",qp=";",pX6=!u51&&Hf1.env.TERM_PROGRAM==="Apple_Terminal",uJ9=!u51&&Hf1.platform==="win32",pJ9=u51?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Hf1.cwd,dJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return j2+(J+1)+"G";return j2+(Q+1)+qp+(J+1)+"H"},cJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=j2+-J+"D";else if(J>0)Z+=j2+J+"C";if(Q<0)Z+=j2+-Q+"A";else if(Q>0)Z+=j2+Q+"B";return Z},dX6=(J=1)=>j2+J+"A",lJ9=(J=1)=>j2+J+"B",iJ9=(J=1)=>j2+J+"C",nJ9=(J=1)=>j2+J+"D",cX6=j2+"G",aJ9=pX6?"\x1B7":j2+"s",rJ9=pX6?"\x1B8":j2+"u",sJ9=j2+"6n",oJ9=j2+"E",tJ9=j2+"F",eJ9=j2+"?25l",JQ9=j2+"?25h",QQ9=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=lX6+(Z<J-1?dX6():"");if(J)Q+=cX6;return Q},ZQ9=j2+"K",XQ9=j2+"1K",lX6=j2+"2K",YQ9=j2+"J",KQ9=j2+"1J",Ff1=j2+"2J",GQ9=j2+"S",qQ9=j2+"T",zQ9="\x1Bc",UQ9=uJ9?`${Ff1}${j2}0f`:`${Ff1}${j2}3J${j2}H`,WQ9=j2+"?1049h",FQ9=j2+"?1049l",HQ9=IC,BQ9=(J,Q)=>[zp,"8",qp,qp,Q,IC,J,zp,"8",qp,qp,IC].join(""),DQ9=(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")+IC},MQ9={setCwd:(J=pJ9())=>`${zp}50;CurrentDir=${J}${IC}`,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+IC}};var d51=C6(tX6(),1);function ZN(J,Q,{target:Z="stdout",...X}={}){if(!d51.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (${Q})`}return p51.link(J,Q)}ZN.isSupported=d51.default.stdout;ZN.stderr=(J,Q,Z={})=>ZN(J,Q,{target:"stderr",...Z});ZN.stderr.isSupported=d51.default.stderr;G0();fX();class Up{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.1761379287-ge22fe5"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await $a(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 l51}from"node:child_process";import{platform as Nf1}from"node:os";import{promisify as AQ9}from"node:util";var c51=AQ9(l51),wQ9=(J)=>`\x1B]52;c;${J}\x1B\\`,RQ9="\x1B]52;c;?\x1B\\",OQ9="\x1B]52;p;?\x1B\\";class eX6{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 c51("which",[J]),!0}catch{return!1}}async writeToPbcopy(J){try{let Q=l51("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=l51("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=l51("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(RQ9)}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 c51("pbpaste");return J}catch{return null}}async readFromWlPaste(J){try{let Q=["--no-newline"];if(J==="primary")Q.push("--primary");let{stdout:Z}=await c51("wl-paste",Q);return Z}catch{return null}}async readFromXclip(J){try{let{stdout:Q}=await c51("xclip",["-selection",J,"-o"]);return Q}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(OQ9)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if(Nf1()==="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(Nf1()==="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=wQ9(Z);process.stdout.write(X);return}if(Nf1()==="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 NY=new eX6;G0();class e9{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function i51(J){if(J instanceof e9)return{title:"Info",description:J.message,type:"info"};return u.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var UN=null,TK9={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(UN)return Error("Already connected. Use /disconnect first to reconnect.");let{connectedClientsService:Z}=J;await Z.start({clientId:J.clientId,currentThreadID:J.worker.thread.id});let Y=Z.getCurrentStatus().clientID||"unknown",{connectBackground:K}=await Promise.resolve().then(() => (M51(),Py1)),G=await K({worker:J.worker},J.configService,{clientId:J.clientId,onUserDisconnect:()=>{UN=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});UN=G,G.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((M)=>{UN=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(() => C6(wp(),1))).toString(W,{type:"utf8",margin:2,color:{dark:"#000000",light:"#FFFFFF"}})}catch(M){u.error("Failed to generate QR code:",M)}if((process.stdout.rows||24)>=30&&H&&J.onShowQRCodeOverlay)J.onShowQRCodeOverlay({url:F,qrCode:H});else return new e9(`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(!UN)return new e9("Not connected to Amp web interface");try{UN.disconnect();let Z=UN.clientID;return UN=null,J.connectedClientsService.sendStatus({connected:!1,enabled:!1,errorMessage:void 0}),new e9(`Disconnected from Amp web interface
|
|
6285
|
+
... (output truncated at ${JB} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:F.join(""),error:V})})})}function hJ9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return mJ9(Z,X?[...X]:null,Y,Q);else return gJ9(Z,X?[...X]:null,Y,Q)}function gJ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function mJ9(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();lj();W2();bB();fX();Oz();b6();C0();var p51={};R6(p51,{scrollUp:()=>GQ9,scrollDown:()=>qQ9,link:()=>BQ9,image:()=>DQ9,iTerm:()=>MQ9,exitAlternativeScreen:()=>FQ9,eraseUp:()=>KQ9,eraseStartLine:()=>XQ9,eraseScreen:()=>Ff1,eraseLines:()=>QQ9,eraseLine:()=>lX6,eraseEndLine:()=>ZQ9,eraseDown:()=>YQ9,enterAlternativeScreen:()=>WQ9,cursorUp:()=>dX6,cursorTo:()=>dJ9,cursorShow:()=>JQ9,cursorSavePosition:()=>aJ9,cursorRestorePosition:()=>rJ9,cursorPrevLine:()=>tJ9,cursorNextLine:()=>oJ9,cursorMove:()=>cJ9,cursorLeft:()=>cX6,cursorHide:()=>eJ9,cursorGetPosition:()=>sJ9,cursorForward:()=>iJ9,cursorDown:()=>lJ9,cursorBackward:()=>nJ9,clearTerminal:()=>UQ9,clearScreen:()=>zQ9,beep:()=>HQ9});import Hf1 from"node:process";var u51=globalThis.window?.document!==void 0,gw2=globalThis.process?.versions?.node!==void 0,mw2=globalThis.process?.versions?.bun!==void 0,uw2=globalThis.Deno?.version?.deno!==void 0,pw2=globalThis.process?.versions?.electron!==void 0,dw2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,cw2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,lw2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,iw2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,nw2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,Gp=globalThis.navigator?.userAgentData?.platform,aw2=Gp==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",rw2=Gp==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",sw2=Gp==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",ow2=Gp==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),tw2=Gp==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var j2="\x1B[",zp="\x1B]",IC="\x07",qp=";",pX6=!u51&&Hf1.env.TERM_PROGRAM==="Apple_Terminal",uJ9=!u51&&Hf1.platform==="win32",pJ9=u51?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Hf1.cwd,dJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return j2+(J+1)+"G";return j2+(Q+1)+qp+(J+1)+"H"},cJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=j2+-J+"D";else if(J>0)Z+=j2+J+"C";if(Q<0)Z+=j2+-Q+"A";else if(Q>0)Z+=j2+Q+"B";return Z},dX6=(J=1)=>j2+J+"A",lJ9=(J=1)=>j2+J+"B",iJ9=(J=1)=>j2+J+"C",nJ9=(J=1)=>j2+J+"D",cX6=j2+"G",aJ9=pX6?"\x1B7":j2+"s",rJ9=pX6?"\x1B8":j2+"u",sJ9=j2+"6n",oJ9=j2+"E",tJ9=j2+"F",eJ9=j2+"?25l",JQ9=j2+"?25h",QQ9=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=lX6+(Z<J-1?dX6():"");if(J)Q+=cX6;return Q},ZQ9=j2+"K",XQ9=j2+"1K",lX6=j2+"2K",YQ9=j2+"J",KQ9=j2+"1J",Ff1=j2+"2J",GQ9=j2+"S",qQ9=j2+"T",zQ9="\x1Bc",UQ9=uJ9?`${Ff1}${j2}0f`:`${Ff1}${j2}3J${j2}H`,WQ9=j2+"?1049h",FQ9=j2+"?1049l",HQ9=IC,BQ9=(J,Q)=>[zp,"8",qp,qp,Q,IC,J,zp,"8",qp,qp,IC].join(""),DQ9=(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")+IC},MQ9={setCwd:(J=pJ9())=>`${zp}50;CurrentDir=${J}${IC}`,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+IC}};var d51=C6(tX6(),1);function ZN(J,Q,{target:Z="stdout",...X}={}){if(!d51.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (${Q})`}return p51.link(J,Q)}ZN.isSupported=d51.default.stdout;ZN.stderr=(J,Q,Z={})=>ZN(J,Q,{target:"stderr",...Z});ZN.stderr.isSupported=d51.default.stderr;G0();fX();class Up{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.1761393687-gf965ca"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await $a(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 l51}from"node:child_process";import{platform as Nf1}from"node:os";import{promisify as AQ9}from"node:util";var c51=AQ9(l51),wQ9=(J)=>`\x1B]52;c;${J}\x1B\\`,RQ9="\x1B]52;c;?\x1B\\",OQ9="\x1B]52;p;?\x1B\\";class eX6{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 c51("which",[J]),!0}catch{return!1}}async writeToPbcopy(J){try{let Q=l51("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=l51("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=l51("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(RQ9)}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 c51("pbpaste");return J}catch{return null}}async readFromWlPaste(J){try{let Q=["--no-newline"];if(J==="primary")Q.push("--primary");let{stdout:Z}=await c51("wl-paste",Q);return Z}catch{return null}}async readFromXclip(J){try{let{stdout:Q}=await c51("xclip",["-selection",J,"-o"]);return Q}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(OQ9)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if(Nf1()==="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(Nf1()==="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=wQ9(Z);process.stdout.write(X);return}if(Nf1()==="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 NY=new eX6;G0();class e9{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function i51(J){if(J instanceof e9)return{title:"Info",description:J.message,type:"info"};return u.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var UN=null,TK9={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(UN)return Error("Already connected. Use /disconnect first to reconnect.");let{connectedClientsService:Z}=J;await Z.start({clientId:J.clientId,currentThreadID:J.worker.thread.id});let Y=Z.getCurrentStatus().clientID||"unknown",{connectBackground:K}=await Promise.resolve().then(() => (M51(),Py1)),G=await K({worker:J.worker},J.configService,{clientId:J.clientId,onUserDisconnect:()=>{UN=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});UN=G,G.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((M)=>{UN=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(() => C6(wp(),1))).toString(W,{type:"utf8",margin:2,color:{dark:"#000000",light:"#FFFFFF"}})}catch(M){u.error("Failed to generate QR code:",M)}if((process.stdout.rows||24)>=30&&H&&J.onShowQRCodeOverlay)J.onShowQRCodeOverlay({url:F,qrCode:H});else return new e9(`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(!UN)return new e9("Not connected to Amp web interface");try{UN.disconnect();let Z=UN.clientID;return UN=null,J.connectedClientsService.sendStatus({connected:!1,enabled:!1,errorMessage:void 0}),new e9(`Disconnected from Amp web interface
|
|
6286
6286
|
Client ID: ${Z}
|
|
6287
6287
|
Server will clean up automatically within 60 seconds`)}catch(Z){return Error(`Failed to disconnect: ${Z.message}`)}}}};class Fh1{configService;commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=AS(),Q){this.configService=Q;this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Z)=>this.latestCustom=Z),this.telemetrySubmitter=new Up(async()=>{try{return(await this.configService.getLatest()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}},this.configService),this.configService.config.pipe(k0((Z)=>EY(Z.settings)),J8()).subscribe((Z)=>{this._initBaseCommands(Z.length>1)})}_initBaseCommands(J){if(this.commands={...CK9},process.env.AMP_CONNECT==="1")Object.assign(this.commands,TK9);if(J)Object.assign(this.commands,SK9)}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 Kp(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 CK9={"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=kQ(Z.settings),K=J.getInMemoryAgentModeOverride()??X;J.worker.handle({type:"user:message",message:{content:[{type:"text",text:Ia}],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 BZ("dangerouslyAllowAll",!1),new e9("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 BZ("dangerouslyAllowAll",!0),new e9("Permissions disabled for this session - you will NOT be asked for confirmation before Amp runs a command.")}catch(K){return u.error("Failed to set dangerously allow all setting",K),Error("Failed to disable permissions for this session")}case"edit":break;default:return Error(`Invalid option: ${Y}. Use: on, off, or edit (or no argument for edit)`)}}let Z=await QW();if(Z===null)return Error("No editor found, please set $EDITOR to edit permissions");let X="";try{let Y={stdin:process.stdin,stdout:process.stdout,stderr:{write:(K)=>{return X=K.toString(),!0}},exit:(K)=>{if(K!==0)throw u.error("editPermissions exited with status",K),Error(X)},settingsFile:J.settingsFilePath,resolveEditor:QW};await $C(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 e9(`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(`
|
|
6288
6288
|
`).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=nW(new URL(Y),Z.id).toString(),q=`Thread URL: ${ZN(K,K,{fallback:()=>K})}`,z=Q[0]?.trim().toLowerCase(),U;switch(z){case"private":U={visibility:"private",sharedGroupIDs:[]};break;case"workspace":U={visibility:"thread_workspace_shared"};break;case"group":U={visibility:"private",sharedGroupIDs:[],shareWithAllCreatorGroups:!0};break;case"public":U={visibility:"public"};break;default:return Error(`Invalid visibility option: ${z}. Use: private, workspace, group, or public`)}try{return await X.updateThreadMeta(Z.id,U),new e9(`${q}
|
|
@@ -6497,7 +6497,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
|
|
|
6497
6497
|
`),J.stdout.write(`Thread: ${H}
|
|
6498
6498
|
`),J.stdout.write(`Continue this thread with: amp threads continue ${W}
|
|
6499
6499
|
`)}}function Jp1(J){return J==="smart"?E1.rgb(3,197,97):J==="free"?E1.rgb(0,184,255):SH9(J)}function SH9(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])}Sh1();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}
|
|
6500
|
-
`)}var Zp1=Qp1.join(Tl1||Qp1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function bH9(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")BZ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new c9("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")BZ("experimental.agentMode",Q.agentMode)}async function Yp1(J){try{await kH9(Qp1.dirname(Zp1),{recursive:!0}),await _H9(Zp1,J,"utf-8")}catch(Q){u.debug("Failed to save last thread ID",Q)}}async function yH9(){try{return(await OF6(Zp1,"utf-8")).trim()}catch(J){return null}}function fH9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return PS("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 AF6=[{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??DX,description:`Custom settings file path (overrides the default location ${DX})`},{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 ${Ny1})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:nK(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration."},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection."},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:GO}],wF6=(J)=>("deprecated"in J)&&J.deprecated===!0,hH9=(J)=>("hidden"in J)&&J.hidden===!0,gH9=(J)=>("default"in J),mH9=(J)=>("default"in J)?J.default:void 0;function uH9(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 c9(iK.unknownCommand(Z),1,G)}}var jF6=null;function Y64(){return jF6}function yQ1(J){return{...J,getThreadEnvironment:U51,vfs:b40({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new f_(J.fileSystem),generateThreadTitle:Bs,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var Kp1=w0.file(xH9.homedir()),$F6=process.env.XDG_CONFIG_HOME?w0.file(process.env.XDG_CONFIG_HOME):b0.joinPath(Kp1,".config");async function lq(J,Q){vn1("0.0.
|
|
6500
|
+
`)}var Zp1=Qp1.join(Tl1||Qp1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function bH9(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")BZ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new c9("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")BZ("experimental.agentMode",Q.agentMode)}async function Yp1(J){try{await kH9(Qp1.dirname(Zp1),{recursive:!0}),await _H9(Zp1,J,"utf-8")}catch(Q){u.debug("Failed to save last thread ID",Q)}}async function yH9(){try{return(await OF6(Zp1,"utf-8")).trim()}catch(J){return null}}function fH9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return PS("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 AF6=[{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??DX,description:`Custom settings file path (overrides the default location ${DX})`},{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 ${Ny1})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:nK(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration."},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection."},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:GO}],wF6=(J)=>("deprecated"in J)&&J.deprecated===!0,hH9=(J)=>("hidden"in J)&&J.hidden===!0,gH9=(J)=>("default"in J),mH9=(J)=>("default"in J)?J.default:void 0;function uH9(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 c9(iK.unknownCommand(Z),1,G)}}var jF6=null;function Y64(){return jF6}function yQ1(J){return{...J,getThreadEnvironment:U51,vfs:b40({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new f_(J.fileSystem),generateThreadTitle:Bs,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var Kp1=w0.file(xH9.homedir()),$F6=process.env.XDG_CONFIG_HOME?w0.file(process.env.XDG_CONFIG_HOME):b0.joinPath(Kp1,".config");async function lq(J,Q){vn1("0.0.1761393687-gf965ca");let Z=hX1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:e1.of([w0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:Kp1,userConfigDir:$F6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (xQ1(),_Q1));X(Z);let Y=await Z.getLatest();u.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let K=pa(IO({configService:Z})),G=F40({configService:Z,toolService:K}),q=VO0(K,k9,A11).catch((O)=>{u.warn("Toolbox registration failed, continuing anyway:",O)}),z=G.initialized.catch((O)=>{u.warn("MCP service initialization failed, continuing anyway:",O)});if(J.executeMode)await Promise.all([z,q]);if(Q.jetbrains)CO("JetBrains");else if(Q.ide&&SZ6())CO("VS Code");else if(Q.ide&&vZ6())CO("Neovim");if(J.executeMode)kn1(!0);O26(K,{configService:Z});let U,W=T7.status.pipe(k0((O)=>Boolean(O.connected&&O.authenticated)),J8()).subscribe((O)=>{if(O){if(!U)U=K.registerTool(ms)}else U?.dispose(),U=void 0}),F;if(!J.executeMode)F=new $51(process.cwd(),{},!0);else F=new class extends $51{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(e2.write(`No API key found. Starting login flow...
|
|
6501
6501
|
`),!await pH9(J))await BR(),process.exit(1)}let H=await m40({isDevelopment:!1}),B=new vV1(H),M=new LB1(H,Z,{lazy:!0}),V=Q.notifications!==void 0?Q.notifications:!J.executeMode,N=$26({playNotificationSound:async(O)=>{if(V){j26(O);let j=Th1(),$=Ch1();if((!j||$)&&Y.settings["notifications.system.enabled"]!==!1){if(O==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(O==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:B,configService:Z});u.info("Starting Amp background services");let L=lq0({threadService:B,threadHistoryService:M,configService:Z,isExtensionDevelopment:!1}),A;T7.status.subscribe((O)=>{A=O});let R={codebaseContextService:new fZ1({workspaceRoots:[w0.file(process.cwd())],getCurrentFile:()=>{if(!A?.openFile)return;try{return w0.parse(A.openFile)}catch(O){u.warn("Failed to parse current file URI",{uri:A.openFile,error:O});return}},getOpenFiles:()=>{if(!A?.visibleFiles?.length)return[];let O=A.openFile;return A.visibleFiles.filter((j)=>j!==O).map((j)=>{try{return w0.parse(j)}catch($){return u.warn("Failed to parse visible file URI",{uri:j,error:$}),null}}).filter((j)=>j!==null)}}),configService:Z,toolService:K,mcpService:G,threadService:B,threadHistoryService:M,threadSyncService:L,threadStorage:H,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:F,notificationService:N,fileSystem:Q.jetbrains||Q.ide?k40:k9};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 pH9(J){if(!J.executeMode){if(!await Yf1("Would you like to log in to Amp? [(y)es, (n)o]: "))return e2.write(`Login cancelled. Run the command again to retry.
|
|
6502
6502
|
`),!1}return await EF6(J)}async function EF6(J){let Q=vH9(32).toString("hex"),Z=await Xf1(J.ampURL,Q);try{await VY(Z)}catch(Y){u.error("Failed to open browser",{error:Y})}let X=await Xf1(J.ampURL,Q,!1);e2.write(`If your browser did not open automatically, visit:
|
|
6503
6503
|
|
|
@@ -6507,13 +6507,13 @@ ${z8.blue.bold(X)}
|
|
|
6507
6507
|
Login successful! You can now use the Amp CLI.
|
|
6508
6508
|
`),!0}catch(Y){return u.error("Login failed",{error:Y}),QG.write(`
|
|
6509
6509
|
Login failed: ${Y instanceof Error?Y.message:String(Y)}
|
|
6510
|
-
`),!1}}function dH9(){let J=new Bu().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)VR(),process.exit(0);let W=U.originalError??U;IQ6(W)}),J.option("-V, --version","output the version number",()=>{e2.write(`0.0.
|
|
6510
|
+
`),!1}}function dH9(){let J=new Bu().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)VR(),process.exit(0);let W=U.originalError??U;IQ6(W)}),J.option("-V, --version","output the version number",()=>{e2.write(`0.0.1761393687-gf965ca (released 2025-10-25T12:06:31.092Z)
|
|
6511
6511
|
`),process.exit(0)}),J.addHelpText("after",PZ6()),J.configureHelp({formatHelp:TZ6}),J.command("logout").description("Log out by removing stored API key").action(async(U,W)=>{let F=W.optsWithGlobals(),H=await NX(F);await nH9(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 NX(F);await iH9(H,await ly1(F,H.settings))});let Q=async(U,W,F)=>{hX1({storage:W.settings,secretStorage:W.secrets,workspaceRoots:e1.of([w0.file(process.cwd())]),defaultAmpURL:W.ampURL,homeDir:Kp1,userConfigDir:$F6});let H={...W,executeMode:!1};await Xp1(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 NX(F);await RF6(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 NX(F);await eH9(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 NX(H);if(W.pick)QG.write(`${z8.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
|
|
6512
6512
|
`);if(W.last||U||B.executeMode)await tH9(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 NX(H);await oH9(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 NX(F);await RF6(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 NX(H);await sH9(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 NX(B);await aH9(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 NX(H);await rH9(H,B,U,F)}),vX6(J,async(U,W)=>{let F=await NX(W);cq(U,W);let H=await lq(F,W);return{context:F,mcpService:H.mcpService,toolService:H.toolService,configService:H.configService,cleanupTerminal:VR,asyncDispose:H.asyncDispose.bind(H)}}),GX6(J),tZ6(J,async(U)=>{let W=await NX(U);return{settings:W.settings,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 NX(F);cq(W,F);let B=await lq(H,F);try{await Iy1(B,B.configService,{})}finally{await B.asyncDispose(),await VR()}});function X(U,W,F){let B=typeof U.description==="string"?U.description:F===void 0?U.description(!0):U.description(F),M=new dV(W,B),V=mH9(U);if(V)M.default(V);if(M.hidden=hH9(U)||wF6(U),"choices"in U)M.choices([...U.choices]);return M}for(let U of AF6)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 dV("-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 dV("-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 dV("--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 dV("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(q);let z=new dV("--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 dV("--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 NX(F);if(Object.keys(F).forEach((B)=>{let M=AF6.find((V)=>V.name===B);if(M&&wF6(M)&&!gH9(M))QG.write(z8.yellow(`Warning: '--${B}' flag is deprecated
|
|
6513
6513
|
`))}),W.args.length>0)uH9(H,W);await Xp1(H,F,W)}),iZ6(J),J}async function bQ1(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??Kz(),K=yQ1(J);if(Z)await J.threadStorage.set(Y,Z);let G=await WJ.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,f51(X));let q=J.threadService.observe(Y).subscribe(async(z)=>{if(o7(z,"assistant"))await Yp1(Y),q.unsubscribe()});return await G.resume(),G}async function Xp1(J,Q,Z){let X=y51(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 Gf1()).trimEnd();if(R)K=R}else Y=(await Gf1()).trimEnd();if(Q.remote&&!J.executeMode)throw new c9("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new c9("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new c9("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new c9("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 c9(`Execute mode is not permitted with --agent-mode '${Q.agentMode}'`,1);if(Q.stats&&!J.executeMode)throw new c9("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 c9("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 c9("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"
|
|
6514
6514
|
Or pipe via stdin: echo "your message" | amp --execute`);cq(Z,Q);let G=await lq(J,Q);jF6=G;let q=yQ1(G),z=async(R)=>{let O=await OF6(R,"utf-8"),j=JSON.parse(O);if(!AW(j.id))throw new c9(iK.invalidThreadId);return bQ1(G,{visibility:X,thread:j})},U=async(R)=>{if(!AW(R))throw new c9(iK.invalidThreadId);let O=await G.threadService.get(R)??void 0;if(u.info(`[fetchAndStartThread] Loaded thread ${R}, agentMode: ${O?.agentMode??"undefined"}`),O?.agentMode)u.info(`[fetchAndStartThread] Setting runtime override for agentMode to: ${O.agentMode}`),BZ("experimental.agentMode",O.agentMode);else u.info("[fetchAndStartThread] No agentMode on thread, not setting override");return bQ1(G,{visibility:X,thread:O})},W=async()=>{try{if(Q.threadId)return U(Q.threadId);else return bQ1(G,{visibility:X})}catch(R){if(R instanceof c9)throw R;throw await V51(R,Q.threadId),Error("handleError should have called process.exit()")}},F=async()=>{return bQ1(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.
|
|
6515
|
-
`),await BR(),process.exit(1);if(J.executeMode&&Q.remote)await qX6(Y,K,G.configService),await G.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await gQ6(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 nr1();let R=await uB({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)T7.selectConfig(O)}else B=!0}let V=Qf1("0.0.
|
|
6516
|
-
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await FZ6({...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 eZ6(J.mcpConfig);X=fH9(X,G)}let Y=await X.get("url","global");if(!Y)Y=DZ;if(!PB(Y))u.info("Targeting custom Amp server",{ampURL:Y});if(X=al1(X),await X.get("debug.httpLogging"))ll1();return{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:zX6(await ly1(J,X))}}function cH9(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 lH9(){let J=cH9(process.argv);if(zQ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),bH9(u),u.info("Starting Amp CLI.",{version:"0.0.
|
|
6515
|
+
`),await BR(),process.exit(1);if(J.executeMode&&Q.remote)await qX6(Y,K,G.configService),await G.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await gQ6(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 nr1();let R=await uB({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)T7.selectConfig(O)}else B=!0}let V=Qf1("0.0.1761393687-gf965ca",G.settingsStorage),N=e1.of([w0.file(process.cwd())]),L=AS(void 0,N);if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let A;try{A=await YJ.getUserFreeTierStatus({},{config:G.configService})}catch(R){A={ok:!1,error:R}}u.info("User free tier status:",A);let w=await FX6();u.info("Loaded session state:",w),await LF6({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new vy1,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadSyncService:G.threadSyncService,threadID:H.threadID,worker:H,workerDeps:q,configService:G.configService,internalAPIClient:YJ,ampURL:J.ampURL,startNewThread:F,pickAndContinueThread:async()=>{u.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:T7,connectedClientsService:new vc,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 NX(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.
|
|
6516
|
+
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await FZ6({...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 eZ6(J.mcpConfig);X=fH9(X,G)}let Y=await X.get("url","global");if(!Y)Y=DZ;if(!PB(Y))u.info("Targeting custom Amp server",{ampURL:Y});if(X=al1(X),await X.get("debug.httpLogging"))ll1();return{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:zX6(await ly1(J,X))}}function cH9(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 lH9(){let J=cH9(process.argv);if(zQ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),bH9(u),u.info("Starting Amp CLI.",{version:"0.0.1761393687-gf965ca",buildTimestamp:"2025-10-25T12:06:31.092Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new c9(iK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await dH9().parseAsync(process.argv)}lH9().catch(V51);async function iH9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),e2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
6517
6517
|
`);else if(!PB(J.ampURL))e2.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
6518
6518
|
`);let Z=process.env.AMP_API_KEY;if(Z)e2.write(`API key found in environment variable, storing...
|
|
6519
6519
|
`),await Q.set("apiKey",Z,J.ampURL),e2.write(`API key successfully stored.
|
package/package.json
CHANGED