@sourcegraph/amp 0.0.1762214500-ge4fc77 → 0.0.1762228891-ge4fc77

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +8 -8
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -6503,11 +6503,11 @@ Actual: ${Y}`)}async function n29(J,Q,Z){let{execSync:X}=await import("node:ch
6503
6503
  ${B}`;if(Y==="pnpm"&&B.includes("Unable to find the global bin directory"))M+=`
6504
6504
 
6505
6505
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
6506
- npm install -g @sourcegraph/amp`;G(Error(M))}},error:(F)=>{if(!W)W=!0,G(Error(`Failed to spawn ${Y}: ${F.message}`))},complete:()=>{if(!W)W=!0,q()}})})}q0();q0();async function S51(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(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=e29(J,q),z=G<0,U,W;if(K.time){let H=K.time[J],F=K.time[q],B=Date.now();if(H)U=Math.floor((B-new Date(H).getTime())/3600000);if(F)W=Math.floor((B-new Date(F).getTime())/3600000)}return u.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:G,hasUpdate:z,currentVersionAge:U,latestVersionAge:W}),{hasUpdate:z,latestVersion:q,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 e29(J,Q){let Z=(q)=>{let[G,z]=q.split("-");return{parts:G?.split(".").map(Number)||[],label:z}},X=Z(J),Y=Z(Q),K=Math.max(X.parts.length,Y.parts.length);for(let q=0;q<K;q++){let G=X.parts[q]||0,z=Y.parts[q]||0;if(G<z)return-1;if(G>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}I0();function Uf1(J,Q){let Z=new w8,X=Z.pipe(M9({shouldCountRefs:!1}));return setImmediate(async()=>{let Y=new eG().scoped("update"),K=X.subscribe({next:(q)=>{Y.debug("emit new state",q)}});try{let q=process.env.AMP_TEST_UPDATE_STATUS;if(q){Y.debug("using fake update status for testing",{status:q}),await Xx(500),Z.next(q);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){Y.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let G=await Q.get("updates.mode");if(G==="disabled"){Y.debug("checking disabled");return}Y.debug("checking",{currentVersion:J,mode:G});let z=await S51(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let U=await C51();if(!G)G=U==="pnpm"?"warn":"auto",Y.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:G});if(G==="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 Wp(z.latestVersion,U);let W=await qN(z.latestVersion),H={from:z.currentVersion,to:z.latestVersion,...W};if(W.status==="same")Y.info("success",H),Z.next("updated");else Y.warn("success with warning",H),Z.next("updated-with-warning")}catch(W){Z.next("update-error")}}catch(q){Y.debug("check failed",{error:q})}finally{await Xx(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as tU}from"node:process";function hZ6(J){let Q=new KR().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 qf1(X.force||!1,X.verbose||!1,"0.0.1762214500-ge4fc77"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new KR("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 J49(X.version)});J.addCommand(Z)}async function J49(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")tU.write(Z8.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6506
+ npm install -g @sourcegraph/amp`;G(Error(M))}},error:(F)=>{if(!W)W=!0,G(Error(`Failed to spawn ${Y}: ${F.message}`))},complete:()=>{if(!W)W=!0,q()}})})}q0();q0();async function S51(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(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=e29(J,q),z=G<0,U,W;if(K.time){let H=K.time[J],F=K.time[q],B=Date.now();if(H)U=Math.floor((B-new Date(H).getTime())/3600000);if(F)W=Math.floor((B-new Date(F).getTime())/3600000)}return u.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:G,hasUpdate:z,currentVersionAge:U,latestVersionAge:W}),{hasUpdate:z,latestVersion:q,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 e29(J,Q){let Z=(q)=>{let[G,z]=q.split("-");return{parts:G?.split(".").map(Number)||[],label:z}},X=Z(J),Y=Z(Q),K=Math.max(X.parts.length,Y.parts.length);for(let q=0;q<K;q++){let G=X.parts[q]||0,z=Y.parts[q]||0;if(G<z)return-1;if(G>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}I0();function Uf1(J,Q){let Z=new w8,X=Z.pipe(M9({shouldCountRefs:!1}));return setImmediate(async()=>{let Y=new eG().scoped("update"),K=X.subscribe({next:(q)=>{Y.debug("emit new state",q)}});try{let q=process.env.AMP_TEST_UPDATE_STATUS;if(q){Y.debug("using fake update status for testing",{status:q}),await Xx(500),Z.next(q);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){Y.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let G=await Q.get("updates.mode");if(G==="disabled"){Y.debug("checking disabled");return}Y.debug("checking",{currentVersion:J,mode:G});let z=await S51(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let U=await C51();if(!G)G=U==="pnpm"?"warn":"auto",Y.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:G});if(G==="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 Wp(z.latestVersion,U);let W=await qN(z.latestVersion),H={from:z.currentVersion,to:z.latestVersion,...W};if(W.status==="same")Y.info("success",H),Z.next("updated");else Y.warn("success with warning",H),Z.next("updated-with-warning")}catch(W){Z.next("update-error")}}catch(q){Y.debug("check failed",{error:q})}finally{await Xx(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as tU}from"node:process";function hZ6(J){let Q=new KR().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 qf1(X.force||!1,X.verbose||!1,"0.0.1762228891-ge4fc77"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new KR("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 J49(X.version)});J.addCommand(Z)}async function J49(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")tU.write(Z8.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6507
6507
 
6508
6508
  `));try{if(!J){tU.write(Z8.blue(`Checking for updates...
6509
- `));let{hasUpdate:Z,latestVersion:X}=await S51("0.0.1762214500-ge4fc77");if(!Z){tU.write(Z8.green(`✓ Amp CLI is already up to date.
6510
- `));let Y=await qN("0.0.1762214500-ge4fc77");if(Y.warning)tU.write(`
6509
+ `));let{hasUpdate:Z,latestVersion:X}=await S51("0.0.1762228891-ge4fc77");if(!Z){tU.write(Z8.green(`✓ Amp CLI is already up to date.
6510
+ `));let Y=await qN("0.0.1762228891-ge4fc77");if(Y.warning)tU.write(`
6511
6511
  `+Z8.yellow(Y.warning)+`
6512
6512
  `);process.exit(0)}if(!X)tU.write(Z8.yellow("[WARN] could not find latest version")),process.exit(0);J=X}tU.write(Z8.blue(`Updating to version ${J}...
6513
6513
  `)),await Wp(J,void 0,(Z)=>{tU.write(Z8.dim(`Running: ${Z}
@@ -7078,7 +7078,7 @@ exit code: ${G}`,new R1({color:X.foreground,dim:!0,italic:!0})));if(z)U.push(new
7078
7078
  `,B),...M],N=new f0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new p1({text:new D1("",void 0,V)})]}),L="high";if(this.agentMode==="fast")L="fast";else if(this.agentMode==="free")L="free";return k9.child(new h0({constraints:new R6(40,120,0,1/0),child:new s6({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[new V8({flex:1,child:new Nh1({width:40,height:40,colorMode:L,fps:q==="fast"?60:q==="slow"?15:0,...q==="disabled"&&{seed:42,t:3}})}),new G0({width:1}),new V8({flex:2,child:N})]})}))}}p8();class ZQ1 extends p0{props;constructor(J){super({key:J.key});this.props=J;this.props.enabled??=!0}createState(){return new hG6}}class hG6 extends u0{build(J){let Z=M6.of(J).colors,{todos:X,title:Y="TODOs",enabled:K=!0}=this.widget.props;if(!Array.isArray(X)||X.length===0)return new G0({width:0,height:0});let q=K?Z.foreground:Z.mutedForeground,G=X.map((z)=>this.buildTodoItem(z,Z,K));return new h0({child:new T6({padding:V0.symmetric(1,0),child:new f0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new p1({text:new D1(Y,new R1({bold:!0,color:q}))}),...G]})})})}buildTodoItem(J,Q,Z){let X=this.getStatusIcon(J.status),Y=Z?Q.foreground:Q.mutedForeground,K=new R1({bold:J.status==="in-progress",color:Y}),q=new R1({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Y});return new s6({crossAxisAlignment:"start",children:[new p1({text:new D1(X,K)}),new G0({width:1}),new V8({child:new p1({text:new D1(J.content,q)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class Lm1 extends B6{ad;onDismiss;onButtonClick;constructor({key:J,ad:Q,onDismiss:Z,onButtonClick:X}){super({key:J});this.ad=Q,this.onDismiss=Z,this.onButtonClick=X}build(J){let Q=M6.of(J),Z=Q.colors.primary,X=Q.colors.foreground;return new h0({decoration:new q9(void 0,new b8(new j8(Z,1,"rounded"),new j8(Z,1,"rounded"),void 0,new j8(Z,1,"rounded"))),child:new T6({padding:V0.horizontal(1),child:new f0({children:[new s6({crossAxisAlignment:"start",children:[new V8({child:new p1({text:new D1(this.ad.content,new R1({color:X}))})}),new G0({width:4}),new MQ({uri:"https://ampcode.com/free",text:"Ad",style:new R1({color:X,dim:!0}),onError:(Y)=>{}})]}),new s6({crossAxisAlignment:"start",children:[new ef1({text:this.ad.buttonLabel,onPressed:()=>this.onButtonClick?.(),padding:V0.horizontal(1),color:Z,reverse:!0}),new G0({width:2}),new p1({text:new D1(this.ad.destinationUrlHostname,new R1({color:X,dim:!0}))})]})]})})})}}K9();p8();class Am1 extends p0{props;constructor(J){super();this.props=J}createState(){return new gG6(this.props.autofocus??!0)}}class gG6 extends u0{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=(G)=>{if(G.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(G.ctrlKey&&G.key==="c"||G.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},Z=_8.sizeOf(J),X=Math.min(60,Z.width-4),Y=Z.height-4,K=[];if(this.widget.props.title)K.push(new p1({text:new D1(this.widget.props.title,new R1({bold:!0,color:$1.blue}))}),new G0({height:1}));if(this.widget.props.message)K.push(new p1({text:new D1(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)K.push(new G0({height:1}));let q=[];if(this.widget.props.showCopyOption)q.push(new p1({text:new D1("Enter to copy",new R1({dim:!0}))}));return q.push(new p1({text:new D1("Escape to close",new R1({dim:!0}))})),K.push(new s6({children:q.flatMap((G,z)=>z<q.length-1?[G,new G0({width:1}),new p1({text:new D1("•",new R1({dim:!0}))}),new G0({width:1})]:[G]),mainAxisSize:"min"})),new k9({child:new h0({constraints:new R6(X,X,0,Y),decoration:new q9($1.default(),new b8(new j8($1.blue,1,"rounded"),new j8($1.blue,1,"rounded"),new j8($1.blue,1,"rounded"),new j8($1.blue,1,"rounded"))),padding:new V0(2,2,2,2),child:new o8({autofocus:this.autofocus,onKey:Q,child:new f0({children:K,mainAxisSize:"min"})})})})}}function wm1(J){let Q=J.match(/"([^"]*)"|'([^']*)'|([^\s"']+)/g);if(!Q)return[];return Q.map((Z)=>{if(Z.startsWith('"')&&Z.endsWith('"')||Z.startsWith("'")&&Z.endsWith("'"))return Z.slice(1,-1);return Z})}uB();q0();import{spawn as DY9}from"node:child_process";import{promises as MY9}from"node:fs";function mG6(J){return J.kind==="executable"}function uG6(J){return J.kind==="markdown"}var zB=50000,pG6=300000;async function Rm1(J,Q,Z,X={}){let{timeoutMs:Y=pG6,signal:K}=X;try{let q=await Z.getCommand(J);if(!q)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:q.filePath,args:Q}),uG6(q))return await VY9(q,Q);else if(mG6(q))return await NY9(q,Q,Y,K);else return{success:!1,output:"",error:"Unsupported command type"}}catch(q){return u.error("Failed to execute command",{commandName:J,error:q}),{success:!1,output:"",error:q instanceof Error?q.message:"Unknown error occurred"}}}async function VY9(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await MY9.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>zB?Z.slice(0,zB)+`
7079
7079
  ... (output truncated at ${zB} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function NY9(J,Q,Z=pG6,X){return new Promise((Y)=>{let[K,q]=LY9(J,Q);u.debug("Spawning command",{spawnCommand:K,spawnArgs:q.slice(0,10),filePath:J.filePath,timeoutMs:Z});let G=Xr1(X),z=!1,U=setTimeout(()=>{z=!0,G.abort(),u.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),W=DY9(K,q,{stdio:["pipe","pipe","pipe"],signal:G.signal,detached:!0}),H=[],F=[],B=0;W.stdout?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=zB)H.push(V);else{let N=zB-(B-V.length);if(N>0)H.push(V.slice(0,N))}}),W.stderr?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=zB)F.push(V);else{let N=zB-(B-V.length);if(N>0)F.push(V.slice(0,N))}}),W.on("close",(M)=>{if(clearTimeout(U),z){Y({success:!1,output:H.join(""),error:`Command timed out after ${Z}ms`,exitCode:void 0});return}if(G.signal.aborted){Y({success:!1,output:H.join(""),error:"The command was aborted",exitCode:M??void 0});return}let V=M===0||M===1,N=H.join(""),L=F.join(""),A=N;if(!V&&!N.trim()&&L.trim())A=L;else if(L.trim())A+=N?`
7080
7080
  ${L}`:L;if(B>zB)A+=`
7081
- ... (output truncated at ${zB} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:H.join(""),error:V})})})}function LY9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return wY9(Z,X?[...X]:null,Y,Q);else return AY9(Z,X?[...X]:null,Y,Q)}function AY9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function wY9(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]}}q0();h2();MW();tY();zz();zH();zS();import{writeFile as RY9}from"fs/promises";import jY9 from"path";q0();tY();class jm1{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.1762214500-ge4fc77"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Vr(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}}var OY9={EMPTY_THREAD:"Thread is empty",THREAD_HAS_MESSAGES:"Can only change mode for new threads",NOT_PROCESSING:"Agent must be processing to queue prompts",NO_QUEUED_MESSAGES:"No queued messages",NO_TEXT_TO_CLEAR:"No prompt to clear",NO_TEXT_SELECTED:"No text selected",INSUFFICIENT_MODES:"Multiple agent modes required",ALREADY_IN_MODE:"Already in this mode",DEV_ONLY:"Only available in development"};function $Y9(J){return J.startsWith("custom-command-")}function dG6(J){return J.startsWith("agent-mode-")}function EY9(J){return J.replace(/^custom-command-/,"")}class Om1{configService;registry;onExecute;onExecutionComplete;commands=new Map;latestCustom=[];telemetrySubmitter;constructor(J,Q,Z,X){this.configService=J;this.registry=Q;this.onExecute=Z;this.onExecutionComplete=X;this.configService.config.subscribe((Y)=>{this.commands.clear(),this.registerCommands(Y)}),this.registry.commands.subscribe((Y)=>this.latestCustom=Y),this.telemetrySubmitter=new jm1(async()=>{try{return(await this.configService.getLatest()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}},this.configService)}async execute(J,Q,Z=[]){this.telemetrySubmitter.submit(J).catch((W)=>{u.debug("Failed to submit command telemetry",W)});let X=new AbortController,Y=Date.now(),K=`command-${Y}-${Math.random().toString(36).substring(7)}`,q=this.commands.get(J);if(q){this.onExecute({id:K,name:q.id,startTime:Y,abortController:X});let W=await q.execute(Q,Z);return this.onExecutionComplete(),W}let G=EY9(J),z=this.latestCustom.find((W)=>W.name===G);if(!z)return;this.onExecute({id:K,name:z.name,startTime:Y,abortController:X});let U=await Rm1(G,Z,this.registry,{signal:X.signal});if(this.onExecutionComplete(),U.success){let W=Q.editorState.text,F=W.trim()&&!W.endsWith(`
7081
+ ... (output truncated at ${zB} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:H.join(""),error:V})})})}function LY9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return wY9(Z,X?[...X]:null,Y,Q);else return AY9(Z,X?[...X]:null,Y,Q)}function AY9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function wY9(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]}}q0();h2();MW();tY();zz();zH();zS();import{writeFile as RY9}from"fs/promises";import jY9 from"path";q0();tY();class jm1{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.1762228891-ge4fc77"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Vr(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}}var OY9={EMPTY_THREAD:"Thread is empty",THREAD_HAS_MESSAGES:"Can only change mode for new threads",NOT_PROCESSING:"Agent must be processing to queue prompts",NO_QUEUED_MESSAGES:"No queued messages",NO_TEXT_TO_CLEAR:"No prompt to clear",NO_TEXT_SELECTED:"No text selected",INSUFFICIENT_MODES:"Multiple agent modes required",ALREADY_IN_MODE:"Already in this mode",DEV_ONLY:"Only available in development"};function $Y9(J){return J.startsWith("custom-command-")}function dG6(J){return J.startsWith("agent-mode-")}function EY9(J){return J.replace(/^custom-command-/,"")}class Om1{configService;registry;onExecute;onExecutionComplete;commands=new Map;latestCustom=[];telemetrySubmitter;constructor(J,Q,Z,X){this.configService=J;this.registry=Q;this.onExecute=Z;this.onExecutionComplete=X;this.configService.config.subscribe((Y)=>{this.commands.clear(),this.registerCommands(Y)}),this.registry.commands.subscribe((Y)=>this.latestCustom=Y),this.telemetrySubmitter=new jm1(async()=>{try{return(await this.configService.getLatest()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}},this.configService)}async execute(J,Q,Z=[]){this.telemetrySubmitter.submit(J).catch((W)=>{u.debug("Failed to submit command telemetry",W)});let X=new AbortController,Y=Date.now(),K=`command-${Y}-${Math.random().toString(36).substring(7)}`,q=this.commands.get(J);if(q){this.onExecute({id:K,name:q.id,startTime:Y,abortController:X});let W=await q.execute(Q,Z);return this.onExecutionComplete(),W}let G=EY9(J),z=this.latestCustom.find((W)=>W.name===G);if(!z)return;this.onExecute({id:K,name:z.name,startTime:Y,abortController:X});let U=await Rm1(G,Z,this.registry,{signal:X.signal});if(this.onExecutionComplete(),U.success){let W=Q.editorState.text,F=W.trim()&&!W.endsWith(`
7082
7082
 
7083
7083
  `)?`
7084
7084
  ${U.output}`:U.output;Q.editorDispatch({type:"insert-text",text:F});return}return Error(U.error??`Command '${J}' failed`)}getPriority(J,Q){if($Y9(J))return 4;if(Q.editorState.hasSelection)switch(J){case"copy-selection":return 60}if(this.isThreadEmpty(Q)){if(dG6(J))return 59;switch(J){case"set-agent-mode":return 58;case"toggle-agent-mode":return 57}}if(this.hasPromptText(Q)&&Q.isProcessing)switch(J){case"queue":return 39;case"dequeue":return 37}if(Q.isProcessing)switch(J){case"queue":return 29;case"dequeue":return 27}if(this.hasPromptText(Q))switch(J){case"handoff":return 19;case"editor":return 18;case"clear":return 17}if(dG6(J))return 0;switch(J){case"help":return 10;case"continue":return 9;case"new":return 8;case"handoff":return 7;case"editor":return 6;case"browser":case"url":case"visibility":case"toggle-thinking-blocks":case"queue":case"clear":case"copy-selection":case"dequeue":case"generate-agent-file":case"agent-files":case"connect":case"disconnect":case"settings":case"permissions":case"permissions-enable":case"permissions-disable":case"ide":case"toggle-agent-mode":case"set-agent-mode":case"show-costs":case"refresh":case"execute-plan":case"edit-plan":case"debug-thread-json":return 1;case"quit":return 0}}getCommandFollows(J){switch(J){case"handoff":return["new"];case"quit":return["queue","dequeue"];case"set-agent-mode":case"toggle-agent-mode":return gF().map(({mode:Q})=>`agent-mode-${Q}`);default:return[]}}registerCommands(J){this.register({id:"new",noun:"thread",verb:"new",description:"Start new thread",aliases:["start"],execute:async(Z)=>{await Z.startNewThread()},isEnabled:(Z)=>this.isThreadEmpty(Z)?"Cannot use thread: new from an empty thread":!0}),this.register({id:"continue",noun:"thread",verb:"switch",description:"Switch to existing thread",aliases:["continue"],gatherArguments:async(Z,X)=>{return await X.launchThreadPicker()},execute:async(Z,X)=>{await Z.switchToThread(X)},isEnabled:()=>!0}),this.register({id:"handoff",noun:"thread",verb:"handoff",description:"Draft a new thread based on current thread",gatherArguments:async(Z,X)=>{if(this.hasPromptText(Z))return{text:Z.editorState.text,images:Z.takeImageAttachments()};return await X.launchMultilinePrompt("handoff","Describe a prompt to hand off...")},execute:async(Z,X)=>{return Z.handleHandoff(X.text,X.images)},isEnabled:(Z)=>this.isThreadEmpty(Z)?"Cannot use thread: handoff from an empty thread":!0,getPromptText:(Z)=>{if(this.hasPromptText(Z))return this.truncatedPromptText(Z)},nonBlocking:!0}),this.register({id:"execute-plan",noun:"plan",verb:"Execute plan",description:"Create execution thread from plan",execute:async(Z)=>{return Z.handleExecutePlan()},isVisible:(Z)=>Z.thread.agentMode==="plan",nonBlocking:!0}),this.register({id:"edit-plan",noun:"plan",verb:"Edit plan in editor",description:"Open plan in $EDITOR with live sync",execute:async(Z)=>{try{let X=process.env.EDITOR||process.env.VISUAL||"nano",{filePath:Y}=await Z.planFileManager.ensureSync(Z.thread.id);H2.instance.tuiInstance.suspend();let{execSync:K}=await import("child_process");return K(`${X} "${Y}"`,{stdio:"inherit"}),H2.instance.tuiInstance.resume(),new OY("Plan editing session closed")}catch(X){return u.error("Failed to edit plan",X),Error("Failed to edit plan")}},isVisible:(Z)=>Z.thread.agentMode==="plan"}),this.register({id:"browser",noun:"thread",verb:"open in browser",description:"Open thread in browser",execute:async({thread:Z,ampURL:X})=>{let Y=Kx(new URL(X),Z.id).toString();try{await $X(Y)}catch(K){u.error("Failed to open browser",{error:K})}},isEnabled:(Z)=>this.isThreadEmpty(Z)?"Cannot use thread: open in browser from an empty thread":!0}),this.register({id:"url",noun:"thread",verb:"copy URL",description:"Copy thread URL",execute:async(Z)=>{let X=Kx(new URL(Z.ampURL),Z.thread.id).toString();try{return await H2.instance.tuiInstance.clipboard.writeText(X),new OY(`Thread URL: ${X}
@@ -7138,7 +7138,7 @@ Trust all current and future MCP servers in this workspace?`}getOptions(){return
7138
7138
  `),J.stdout.write(`Thread: ${F}
7139
7139
  `),J.stdout.write(`Continue this thread with: amp threads continue ${W}
7140
7140
  `)}}function Du1(J){return J==="smart"?$1.rgb(3,197,97):J==="free"?$1.rgb(0,184,255):aK9(J)}function aK9(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 $1.index(Z[X])}mf1();if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){Xq.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
7141
- `)}var Vu1=Mu1.join(uc1||Mu1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function tK9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),q=Z||"Warning",G=!1;J.warn(K,{name:q,code:X})}}function KW(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")Gq("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new b9("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")Gq("experimental.agentMode",Q.agentMode)}async function Lu1(J){try{await rK9(Mu1.dirname(Vu1),{recursive:!0}),await sK9(Vu1,J,"utf-8")}catch(Q){u.debug("Failed to save last thread ID",Q)}}async function eK9(){try{return(await zU6(Vu1,"utf-8")).trim()}catch(J){return null}}var KU6=[{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??qZ,description:`Custom settings file path (overrides the default location ${qZ})`},{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 ${hy1})`},{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:r5(),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:dw}],qU6=(J)=>("deprecated"in J)&&J.deprecated===!0,Jq9=(J)=>("hidden"in J)&&J.hidden===!0,Qq9=(J)=>("default"in J),Zq9=(J)=>("default"in J)?J.default:void 0;function Xq9(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((G)=>Z.includes(G)||G.includes(Z)),q="Run amp --help for a list of available commands.";if(K.length>0)q=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new b9(nK.unknownCommand(Z),1,q)}}var UU6=null;function qt2(){return UU6}function vQ1(J){return{...J,getThreadEnvironment:W51,vfs:Pr1({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new bm(J.fileSystem),generateThreadTitle:$16,deleteThread:(Q)=>J.threadService.delete(Q)}}var Au1=A0.file(oK9.homedir()),WU6=process.env.XDG_CONFIG_HOME?A0.file(process.env.XDG_CONFIG_HOME):y0.joinPath(Au1,".config");async function qW(J,Q){pi1("0.0.1762214500-ge4fc77");let Z=ev1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:t1.of([A0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:Au1,userConfigDir:WU6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (TQ1(),PQ1));X(Z);let Y=await Z.getLatest();u.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let K=new cw({configService:Z}),q=new Map,G=()=>q.clear(),z=new T_1(Z,J.settings.getWorkspaceRootPath()),U=ae0({configService:Z,toolServices:K,trustStore:z,createOAuthProvider:async(T)=>{let S=q.get(T);if(S)return u.debug("Reusing existing OAuth provider for server",{serverName:T}),S;u.debug("Creating OAuth provider for server",{serverName:T});let _=(async()=>{let h=new sw(J.secrets),v=await h.getClientInfo(T),x=new F_1({storage:h,serverName:T,clientId:v?.clientId,clientSecret:v?.clientSecret,scopes:v?.scopes});return u.debug("OAuth provider created",{serverName:T,hasManualClientId:!!v?.clientId,willUseDCR:!v?.clientId}),x})();return q.set(T,_),_}}),W=T26(K,T2,k71).catch((T)=>{u.warn("Toolbox registration failed, continuing anyway:",{error:T})}),H=U.initialized.catch((T)=>{u.warn("MCP service initialization failed, continuing anyway:",{error:T})}),F=Promise.all([H,W]).then(()=>{});if(Q.jetbrains)_j("JetBrains");else if(Q.ide&&jZ6())_j("VS Code");else if(Q.ide&&OZ6())_j("Neovim");if(J.executeMode)di1(!0);let B,M=h7.status.pipe(k0((T)=>Boolean(T.connected&&T.authenticated)),G8()).subscribe((T)=>{if(T){if(!B)B=K.registerTool(VE)}else B?.dispose(),B=void 0}),V;if(!J.executeMode)V=new w51(process.cwd(),{},!0);else V=new class extends w51{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(J4.write(`No API key found. Starting login flow...
7141
+ `)}var Vu1=Mu1.join(uc1||Mu1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function tK9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),q=Z||"Warning",G=!1;J.warn(K,{name:q,code:X})}}function KW(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")Gq("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new b9("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")Gq("experimental.agentMode",Q.agentMode)}async function Lu1(J){try{await rK9(Mu1.dirname(Vu1),{recursive:!0}),await sK9(Vu1,J,"utf-8")}catch(Q){u.debug("Failed to save last thread ID",Q)}}async function eK9(){try{return(await zU6(Vu1,"utf-8")).trim()}catch(J){return null}}var KU6=[{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??qZ,description:`Custom settings file path (overrides the default location ${qZ})`},{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 ${hy1})`},{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:r5(),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:dw}],qU6=(J)=>("deprecated"in J)&&J.deprecated===!0,Jq9=(J)=>("hidden"in J)&&J.hidden===!0,Qq9=(J)=>("default"in J),Zq9=(J)=>("default"in J)?J.default:void 0;function Xq9(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((G)=>Z.includes(G)||G.includes(Z)),q="Run amp --help for a list of available commands.";if(K.length>0)q=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new b9(nK.unknownCommand(Z),1,q)}}var UU6=null;function qt2(){return UU6}function vQ1(J){return{...J,getThreadEnvironment:W51,vfs:Pr1({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new bm(J.fileSystem),generateThreadTitle:$16,deleteThread:(Q)=>J.threadService.delete(Q)}}var Au1=A0.file(oK9.homedir()),WU6=process.env.XDG_CONFIG_HOME?A0.file(process.env.XDG_CONFIG_HOME):y0.joinPath(Au1,".config");async function qW(J,Q){pi1("0.0.1762228891-ge4fc77");let Z=ev1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:t1.of([A0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:Au1,userConfigDir:WU6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (TQ1(),PQ1));X(Z);let Y=await Z.getLatest();u.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let K=new cw({configService:Z}),q=new Map,G=()=>q.clear(),z=new T_1(Z,J.settings.getWorkspaceRootPath()),U=ae0({configService:Z,toolServices:K,trustStore:z,createOAuthProvider:async(T)=>{let S=q.get(T);if(S)return u.debug("Reusing existing OAuth provider for server",{serverName:T}),S;u.debug("Creating OAuth provider for server",{serverName:T});let _=(async()=>{let h=new sw(J.secrets),v=await h.getClientInfo(T),x=new F_1({storage:h,serverName:T,clientId:v?.clientId,clientSecret:v?.clientSecret,scopes:v?.scopes});return u.debug("OAuth provider created",{serverName:T,hasManualClientId:!!v?.clientId,willUseDCR:!v?.clientId}),x})();return q.set(T,_),_}}),W=T26(K,T2,k71).catch((T)=>{u.warn("Toolbox registration failed, continuing anyway:",{error:T})}),H=U.initialized.catch((T)=>{u.warn("MCP service initialization failed, continuing anyway:",{error:T})}),F=Promise.all([H,W]).then(()=>{});if(Q.jetbrains)_j("JetBrains");else if(Q.ide&&jZ6())_j("VS Code");else if(Q.ide&&OZ6())_j("Neovim");if(J.executeMode)di1(!0);let B,M=h7.status.pipe(k0((T)=>Boolean(T.connected&&T.authenticated)),G8()).subscribe((T)=>{if(T){if(!B)B=K.registerTool(VE)}else B?.dispose(),B=void 0}),V;if(!J.executeMode)V=new w51(process.cwd(),{},!0);else V=new class extends w51{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(J4.write(`No API key found. Starting login flow...
7142
7142
  `),!await Yq9(J))await VR(),process.exit(1)}let N=await D16({isDevelopment:!1}),L=new f_1(N,Z),A=new x_1(N,{lazy:!0}),w=new C_1(L,(T,S)=>{let _=a5.get(T);if(_)_.handle(S).catch((h)=>{u.error("Failed to apply artifact delta",h)})}),R=Q.notifications!==void 0?Q.notifications:!J.executeMode,j=S26({playNotificationSound:async(T)=>{if(R){C26(T);let S=hf1(),_=gf1();if((!S||_)&&Y.settings["notifications.system.enabled"]!==!1){if(T==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(T==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:L,configService:Z});u.info("Starting Amp background services");let $=O16({threadService:L,threadHistoryService:A,configService:Z,isExtensionDevelopment:!1}),O;h7.status.subscribe((T)=>{O=T});let I={codebaseContextService:new _Z1({workspaceRoots:[A0.file(process.cwd())],getCurrentFile:()=>{if(!O?.openFile)return;try{return A0.parse(O.openFile)}catch(T){u.warn("Failed to parse current file URI",{uri:O.openFile,error:T});return}},getOpenFiles:()=>{if(!O?.visibleFiles?.length)return[];let T=O.openFile;return O.visibleFiles.filter((S)=>S!==T).map((S)=>{try{return A0.parse(S)}catch(_){return u.warn("Failed to parse visible file URI",{uri:S,error:_}),null}}).filter((S)=>S!==null)}}),configService:Z,toolServices:K,mcpService:U,trustStore:z,threadService:L,threadHistoryService:A,threadSyncService:$,planFileManager:w,threadStorage:N,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:V,notificationService:j,backgroundInit:F,fileSystem:Q.jetbrains||Q.ide?z16:T2};return{...I,async asyncDispose(){await I.mcpService.dispose(),G(),await I.threadService.asyncDispose(),I.configService.unsubscribe(),I.toolServices.dispose(),I.fuzzyServer.dispose(),I.threadSyncService.dispose(),I.settingsStorage[Symbol.dispose](),M.unsubscribe(),B?.dispose()}}}async function Yq9(J){if(!J.executeMode){if(!await Hf1("Would you like to log in to Amp? [(y)es, (n)o]: "))return J4.write(`Login cancelled. Run the command again to retry.
7143
7143
  `),!1}return await HU6(J)}async function HU6(J){let Q=nK9(32).toString("hex"),Z=await Wf1(J.ampURL,Q),X=new AbortController;try{await $X(Z,X.signal)}catch(K){u.error("Error opening browser",{error:K})}let Y=await Wf1(J.ampURL,Q,!1);J4.write(`If your browser does not open automatically, visit:
7144
7144
 
@@ -7148,13 +7148,13 @@ ${Z8.blue.bold(Y)}
7148
7148
  Login successful! You can now use the Amp CLI.
7149
7149
  `),!0}catch(K){return u.error("Login failed",{error:K}),Xq.write(`
7150
7150
  Login failed: ${K instanceof Error?K.message:String(K)}
7151
- `),!1}}function Kq9(){let J=new KR().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((W)=>{if(W.code==="commander.help"||W.code==="commander.version"||W.exitCode===0)IC(),process.exit(0);let H=W.originalError??W;jQ6(H)}),J.option("-V, --version","output the version number",()=>{J4.write(`0.0.1762214500-ge4fc77 (released 2025-11-04T00:07:11.075Z)
7151
+ `),!1}}function Kq9(){let J=new KR().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((W)=>{if(W.code==="commander.help"||W.code==="commander.version"||W.exitCode===0)IC(),process.exit(0);let H=W.originalError??W;jQ6(H)}),J.option("-V, --version","output the version number",()=>{J4.write(`0.0.1762228891-ge4fc77 (released 2025-11-04T04:06:46.423Z)
7152
7152
  `),process.exit(0)}),J.addHelpText("after",AZ6()),J.configureHelp({formatHelp:wZ6}),J.command("logout").description("Log out by removing stored API key").action(async(W,H)=>{let F=H.optsWithGlobals(),B=await IY(F);await Uq9(B)}),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(W,H)=>{let F=H.optsWithGlobals(),B=await IY(F);await zq9(B,await ey1(F,B.settings))});let Q=async(W,H,F)=>{ev1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:t1.of([A0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:Au1,userConfigDir:WU6});let B={...H,executeMode:!1};await Nu1(B,{...W,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(W,H)=>{let F=H.optsWithGlobals(),B=await IY(F);await GU6(F,B,H)});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(W,H)=>{let F=H.optsWithGlobals(),B=await IY(F);await Mq9(F,B,H)}),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(W,H,F)=>{let B=F.optsWithGlobals(),M=await IY(B);if(H.pick)Xq.write(`${Z8.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
7153
7153
  `);if(H.last||W||M.executeMode)await Dq9(B,M,W,F);else await Q(B,M,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(W,H,F)=>{let B=F.optsWithGlobals(),M=await IY(B);await Bq9(B,M,W,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(W,H)=>{let F=H.optsWithGlobals(),B=await IY(F);await GU6(F,B,H)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, unlisted, 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, unlisted, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(W,H,F)=>{let B=F.optsWithGlobals(),M=await IY(B);await Fq9(B,M,W,F,H.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(W,H,F,B)=>{let M=B.optsWithGlobals(),V=await IY(M);await Wq9(M,V,W,H,B)}),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(W,H,F)=>{let B=F.optsWithGlobals(),M=await IY(B);await Hq9(B,M,W,F)}),TX6(J,async(W,H)=>{let F=await IY(H);KW(W,H);let B=await qW(F,H);return{context:F,mcpService:B.mcpService,toolService:B.toolServices,toolServices:B.toolServices,configService:B.configService,cleanupTerminal:IC,asyncDispose:B.asyncDispose.bind(B)}}),ZX6(J),iZ6(J,async(W)=>{let H=await IY(W);return{settings:H.settings,secretStorage:H.secrets,getThreadDeps:async(F)=>{KW(F,W);let B=await qW(H,W);return{mcpService:B.mcpService,settings:H.settings,asyncDispose:B.asyncDispose.bind(B)}}}});function Y(W,H,F){let M=typeof W.description==="string"?W.description:F===void 0?W.description(!0):W.description(F),V=new oV(H,M),N=Zq9(W);if(N)V.default(N);if(V.hidden=Jq9(W)||qU6(W),"choices"in W)V.choices([...W.choices]);return V}for(let W of KU6)switch(W.type){case"flag":{J.addOption(Y(W,`--${W.long}`)),J.addOption(Y(W,`--no-${W.long}`,!1));break}case"switch":{J.addOption(Y(W,`--${W.long}`,!0));break}default:{J.addOption(Y(W,`--${W.long} <value>`));break}}let K=new oV("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);J.addOption(K);let q=new oV("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(q);let G=new oV("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1);J.addOption(G);let z=new oV("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(z);let U=new oV("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(U),process.env.AMP_CONNECT==="1"){let W=new oV("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(W)}return J.action(async(W,H)=>{let F=W,B=await IY(F);if(Object.keys(F).forEach((M)=>{let V=KU6.find((N)=>N.name===M);if(V&&qU6(V)&&!Qq9(V))Xq.write(Z8.yellow(`Warning: '--${M}' flag is deprecated
7154
7154
  `))}),H.args.length>0)Xq9(B,H);await Nu1(B,F,H)}),hZ6(J),J}async function SQ1(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??Dq(),K=vQ1(J);if(Z)await J.threadStorage.set(Y,Z);let q=await a5.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,k51(X));let G=J.threadService.observe(Y).subscribe(async(z)=>{if(KJ(z,"assistant"))await Lu1(Y),G.unsubscribe()});return await q.resume(),q}async function Nu1(J,Q,Z){let X=v51(Q);if(X instanceof Error)Zq(X.message);let Y,K=null;if(Q.streamJsonInput)Y="";else if(typeof Q.execute==="string"){Y=Q.execute;let O=(await Df1()).trimEnd();if(O)K=O}else Y=(await Df1()).trimEnd();if(Q.remote&&!J.executeMode)throw new b9("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new b9("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new b9("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new b9("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 b9(`Execute mode is not permitted with --agent-mode '${Q.agentMode}'`,1);if(Q.stats&&!J.executeMode)throw new b9("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 b9("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 b9("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"
7155
7155
  Or pipe via stdin: echo "your message" | amp --execute`);KW(Z,Q);let q=await qW(J,Q);if(J.executeMode||Q.threadId)await q.backgroundInit;UU6=q;let G=vQ1(q),z=async(O)=>{let E=await zU6(O,"utf-8"),I=JSON.parse(E);if(!Mq(I.id))throw new b9(nK.invalidThreadId);return SQ1(q,{visibility:X,thread:I})},U=async(O)=>{if(!Mq(O))throw new b9(nK.invalidThreadId);let E=await q.threadService.get(O)??void 0;if(u.info(`[fetchAndStartThread] Loaded thread ${O}, agentMode: ${E?.agentMode??"undefined"}`),E?.agentMode)u.info(`[fetchAndStartThread] Setting runtime override for agentMode to: ${E.agentMode}`),Gq("experimental.agentMode",E.agentMode);else u.info("[fetchAndStartThread] No agentMode on thread, not setting override");return SQ1(q,{visibility:X,thread:E})},W=async()=>{try{if(Q.threadId)return U(Q.threadId);else return SQ1(q,{visibility:X})}catch(O){if(O instanceof b9)throw O;throw await H51(O,Q.threadId),Error("handleError should have called process.exit()")}},H=async()=>{return SQ1(q,{visibility:X})};if(Q.format==="jsonl")Xq.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
7156
- `),await VR(),process.exit(1);if(J.executeMode&&Q.remote)await XX6(Y,K,q.configService),await q.asyncDispose(),process.exit(0);let F=await W();if(J.executeMode)rZ6(q.mcpService,J.settings),await bQ6(F,F.threadID,Y,K,q,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await q.asyncDispose(),process.exit(0);let B=!1,M=!1;if(Q.jetbrains||Q.ide){await lK0();let O=ME({jetbrainsOnly:Q.jetbrains});if(O.length===0){if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall")}else if(O.length===1){let E=O[0];if(E)h7.selectConfig(E)}else B=!0}let V=Uf1("0.0.1762214500-ge4fc77",q.settingsStorage),N=new __1(q.threadStorage),L=t1.of([A0.file(process.cwd())]),A=ec1(void 0,L),w=new Ff1(q.mcpService,J.settings.getWorkspaceRootPath());if(Y)F.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let R;try{R=await G5.getUserFreeTierStatus({},{config:q.configService,signal:AbortSignal.timeout(5000)})}catch(O){R={ok:!1,error:O}}u.info("User free tier status:",R);let j=null;try{let O=await G5.getUserInfo({},{config:q.configService});if(O.ok&&O.result.team)j=O.result.team}catch(O){u.debug("Failed to fetch user workspace info:",O)}let $=await GX6();u.info("Loaded session state:",$),await YU6({codebaseContextService:q.codebaseContextService,stdout:process.stdout,history:new dy1,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadSyncService:q.threadSyncService,planFileManager:q.planFileManager,threadID:F.threadID,threadFuzzyIndexer:N,worker:F,workerDeps:G,configService:q.configService,internalAPIClient:G5,ampURL:J.ampURL,startNewThread:H,pickAndContinueThread:async()=>{u.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:h7,connectedClientsService:new Zk1,commandRegistry:A,mcpTrustHandler:w,showJetBrainsInstaller:M,showIdePicker:B,startWithPicker:Q.startWithPicker,updateService:V,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:$,freeTierStatus:R.ok?R.result:void 0,workspace:j,threadDependencies:q}),await q.asyncDispose(),process.exit(0)}async function IY(J){if(J.interactive)Xq.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7157
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await XZ6({...J,workspaceTrust:{current:!0,changes:VS},getHook:process.env.AMP_URL?(K,q)=>{if(K==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let K=await aZ6(J.mcpConfig);X=nZ6(X,K)}let Y=await X.get("url","global");if(!Y)Y=HZ;if(!RB(Y))u.info("Targeting custom Amp server",{ampURL:Y});return X=zl1(X),{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:YX6(await ey1(J,X))}}function qq9(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,(G,z)=>z.toUpperCase()),q=J[Z+1];if(q&&!q.startsWith("--"))Q[K]=q,Z++}}return Q}async function Gq9(){let J=qq9(process.argv);if(DQ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),tK9(u),u.info("Starting Amp CLI.",{version:"0.0.1762214500-ge4fc77",buildTimestamp:"2025-11-04T00:07:11.075Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new b9(nK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Kq9().parseAsync(process.argv)}Gq9().catch(H51);async function zq9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),J4.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7156
+ `),await VR(),process.exit(1);if(J.executeMode&&Q.remote)await XX6(Y,K,q.configService),await q.asyncDispose(),process.exit(0);let F=await W();if(J.executeMode)rZ6(q.mcpService,J.settings),await bQ6(F,F.threadID,Y,K,q,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await q.asyncDispose(),process.exit(0);let B=!1,M=!1;if(Q.jetbrains||Q.ide){await lK0();let O=ME({jetbrainsOnly:Q.jetbrains});if(O.length===0){if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall")}else if(O.length===1){let E=O[0];if(E)h7.selectConfig(E)}else B=!0}let V=Uf1("0.0.1762228891-ge4fc77",q.settingsStorage),N=new __1(q.threadStorage),L=t1.of([A0.file(process.cwd())]),A=ec1(void 0,L),w=new Ff1(q.mcpService,J.settings.getWorkspaceRootPath());if(Y)F.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let R;try{R=await G5.getUserFreeTierStatus({},{config:q.configService,signal:AbortSignal.timeout(5000)})}catch(O){R={ok:!1,error:O}}u.info("User free tier status:",R);let j=null;try{let O=await G5.getUserInfo({},{config:q.configService});if(O.ok&&O.result.team)j=O.result.team}catch(O){u.debug("Failed to fetch user workspace info:",O)}let $=await GX6();u.info("Loaded session state:",$),await YU6({codebaseContextService:q.codebaseContextService,stdout:process.stdout,history:new dy1,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadSyncService:q.threadSyncService,planFileManager:q.planFileManager,threadID:F.threadID,threadFuzzyIndexer:N,worker:F,workerDeps:G,configService:q.configService,internalAPIClient:G5,ampURL:J.ampURL,startNewThread:H,pickAndContinueThread:async()=>{u.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:h7,connectedClientsService:new Zk1,commandRegistry:A,mcpTrustHandler:w,showJetBrainsInstaller:M,showIdePicker:B,startWithPicker:Q.startWithPicker,updateService:V,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:$,freeTierStatus:R.ok?R.result:void 0,workspace:j,threadDependencies:q}),await q.asyncDispose(),process.exit(0)}async function IY(J){if(J.interactive)Xq.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7157
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await XZ6({...J,workspaceTrust:{current:!0,changes:VS},getHook:process.env.AMP_URL?(K,q)=>{if(K==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let K=await aZ6(J.mcpConfig);X=nZ6(X,K)}let Y=await X.get("url","global");if(!Y)Y=HZ;if(!RB(Y))u.info("Targeting custom Amp server",{ampURL:Y});return X=zl1(X),{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:YX6(await ey1(J,X))}}function qq9(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,(G,z)=>z.toUpperCase()),q=J[Z+1];if(q&&!q.startsWith("--"))Q[K]=q,Z++}}return Q}async function Gq9(){let J=qq9(process.argv);if(DQ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),tK9(u),u.info("Starting Amp CLI.",{version:"0.0.1762228891-ge4fc77",buildTimestamp:"2025-11-04T04:06:46.423Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new b9(nK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Kq9().parseAsync(process.argv)}Gq9().catch(H51);async function zq9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),J4.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7158
7158
  `);else if(!RB(J.ampURL))J4.write(`Logging in to ${new URL(J.ampURL).hostname}
7159
7159
  `);let Z=process.env.AMP_API_KEY;if(Z)J4.write(`API key found in environment variable, storing...
7160
7160
  `),await Q.set("apiKey",Z,J.ampURL),J4.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1762214500-ge4fc77",
3
+ "version": "0.0.1762228891-ge4fc77",
4
4
  "description": "CLI for Amp, the frontier coding agent from Sourcegraph.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {