@sourcegraph/amp 0.0.1762561694-g1226c3 → 0.0.1762574482-gae4ec1

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
@@ -7002,11 +7002,11 @@ Actual: ${Y}`)}async function Og4(J,Q,Z){let{execSync:X}=await import("node:ch
7002
7002
  ${B}`;if(Y==="pnpm"&&B.includes("Unable to find the global bin directory"))V+=`
7003
7003
 
7004
7004
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
7005
- npm install -g @sourcegraph/amp`;q(Error(V))}},error:(H)=>{if(!U)U=!0,q(Error(`Failed to spawn ${Y}: ${H.message}`))},complete:()=>{if(!U)U=!0,G()}})})}G0();G0();async function HF1(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=Pg4(J,G),z=q<0,W,U;if(K.time){let F=K.time[J],H=K.time[G],B=Date.now();if(F)W=Math.floor((B-new Date(F).getTime())/3600000);if(H)U=Math.floor((B-new Date(H).getTime())/3600000)}return p.info("NPM version comparison",{currentVersion:J,latestVersion:G,compareResult:q,hasUpdate:z,currentVersionAge:W,latestVersionAge:U}),{hasUpdate:z,latestVersion:G,currentVersion:J,currentVersionAge:W,latestVersionAge:U,source:"npm"}}catch(Z){return p.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function Pg4(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}$0();function b60(J,Q){let Z=new E8,X=Z.pipe(r9({shouldCountRefs:!1}));return setImmediate(async()=>{let Y=new mU().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 NN(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 HF1(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let W=await FF1();if(!q)q=W==="pnpm"?"warn":"auto",Y.debug("no configured update mode; selected default based on package manager",{packageManager:W,mode:q});if(q==="warn"){Z.next("update-available");return}if(!W){Y.debug("auto-update not supported, falling back to warn mode"),Z.next("update-available");return}try{await ws(z.latestVersion,W);let U=await sA(z.latestVersion),F={from:z.currentVersion,to:z.latestVersion,...U};if(U.status==="same")Y.info("success",F),Z.next("updated");else Y.warn("success with warning",F),Z.next("updated-with-warning")}catch(U){Z.next("update-error")}}catch(G){Y.debug("check failed",{error:G})}finally{await NN(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as lH}from"node:process";function _58(J){let Q=new sE().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 _60(X.force||!1,X.verbose||!1,"0.0.1762561694-g1226c3"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new sE("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 jg4(X.version)});J.addCommand(Z)}async function jg4(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")lH.write(F8.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
7005
+ npm install -g @sourcegraph/amp`;q(Error(V))}},error:(H)=>{if(!U)U=!0,q(Error(`Failed to spawn ${Y}: ${H.message}`))},complete:()=>{if(!U)U=!0,G()}})})}G0();G0();async function HF1(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=Pg4(J,G),z=q<0,W,U;if(K.time){let F=K.time[J],H=K.time[G],B=Date.now();if(F)W=Math.floor((B-new Date(F).getTime())/3600000);if(H)U=Math.floor((B-new Date(H).getTime())/3600000)}return p.info("NPM version comparison",{currentVersion:J,latestVersion:G,compareResult:q,hasUpdate:z,currentVersionAge:W,latestVersionAge:U}),{hasUpdate:z,latestVersion:G,currentVersion:J,currentVersionAge:W,latestVersionAge:U,source:"npm"}}catch(Z){return p.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function Pg4(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}$0();function b60(J,Q){let Z=new E8,X=Z.pipe(r9({shouldCountRefs:!1}));return setImmediate(async()=>{let Y=new mU().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 NN(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 HF1(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let W=await FF1();if(!q)q=W==="pnpm"?"warn":"auto",Y.debug("no configured update mode; selected default based on package manager",{packageManager:W,mode:q});if(q==="warn"){Z.next("update-available");return}if(!W){Y.debug("auto-update not supported, falling back to warn mode"),Z.next("update-available");return}try{await ws(z.latestVersion,W);let U=await sA(z.latestVersion),F={from:z.currentVersion,to:z.latestVersion,...U};if(U.status==="same")Y.info("success",F),Z.next("updated");else Y.warn("success with warning",F),Z.next("updated-with-warning")}catch(U){Z.next("update-error")}}catch(G){Y.debug("check failed",{error:G})}finally{await NN(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as lH}from"node:process";function _58(J){let Q=new sE().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 _60(X.force||!1,X.verbose||!1,"0.0.1762574482-gae4ec1"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new sE("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 jg4(X.version)});J.addCommand(Z)}async function jg4(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")lH.write(F8.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
7006
7006
 
7007
7007
  `));try{if(!J){lH.write(F8.blue(`Checking for updates...
7008
- `));let{hasUpdate:Z,latestVersion:X}=await HF1("0.0.1762561694-g1226c3");if(!Z){lH.write(F8.green(`✓ Amp CLI is already up to date.
7009
- `));let Y=await sA("0.0.1762561694-g1226c3");if(Y.warning)lH.write(`
7008
+ `));let{hasUpdate:Z,latestVersion:X}=await HF1("0.0.1762574482-gae4ec1");if(!Z){lH.write(F8.green(`✓ Amp CLI is already up to date.
7009
+ `));let Y=await sA("0.0.1762574482-gae4ec1");if(Y.warning)lH.write(`
7010
7010
  `+F8.yellow(Y.warning)+`
7011
7011
  `);process.exit(0)}if(!X)lH.write(F8.yellow("[WARN] could not find latest version")),process.exit(0);J=X}lH.write(F8.blue(`Updating to version ${J}...
7012
7012
  `)),await ws(J,void 0,(Z)=>{lH.write(F8.dim(`Running: ${Z}
@@ -7585,7 +7585,7 @@ exit code: ${q}`,new $1({color:X.foreground,dim:!0,italic:!0})));if(z)W.push(new
7585
7585
  `,B),...V],N=new x0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new l1({text:new D1("",void 0,M)})]});return W9.child(new g0({constraints:new j6(40,120,0,1/0),child:new n6({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[new e6({flex:1,child:new r80({width:40,height:40,agentMode:this.agentMode,fps:G==="fast"?60:G==="slow"?15:0,...G==="disabled"&&{seed:42,t:3}})}),new U0({width:1}),new e6({flex:2,child:N})]})}))}}i8();class o40 extends f0{props;constructor(J){super({key:J.key});this.props=J;this.props.enabled??=!0}createState(){return new mZ8}}class mZ8 extends b0{build(J){let Z=N6.of(J).colors,{todos:X,title:Y="TODOs",enabled:K=!0}=this.widget.props;if(!Array.isArray(X)||X.length===0)return new U0({width:0,height:0});let G=K?Z.foreground:Z.mutedForeground,q=X.map((z)=>this.buildTodoItem(z,Z,K));return new g0({child:new S6({padding:M0.symmetric(1,0),child:new x0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new l1({text:new D1(Y,new $1({bold:!0,color:G}))}),...q]})})})}buildTodoItem(J,Q,Z){let X=this.getStatusIcon(J.status),Y=Z?Q.foreground:Q.mutedForeground,K=new $1({bold:J.status==="in-progress",color:Y}),G=new $1({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Y});return new n6({crossAxisAlignment:"start",children:[new l1({text:new D1(X,K)}),new U0({width:1}),new e6({child:new l1({text:new D1(J.content,G)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class t40 extends M6{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=N6.of(J),Z=Q.colors.primary,X=Q.colors.foreground;return new g0({decoration:new U9(void 0,new f8(new $8(Z,1,"rounded"),new $8(Z,1,"rounded"),void 0,new $8(Z,1,"rounded"))),child:new S6({padding:M0.horizontal(1),child:new x0({children:[new n6({crossAxisAlignment:"start",children:[new e6({child:new l1({text:new D1(this.ad.content,new $1({color:X}))})}),new U0({width:4}),new $Z({uri:"https://ampcode.com/free",text:"Ad",style:new $1({color:X,dim:!0}),onError:(Y)=>{}})]}),new n6({crossAxisAlignment:"start",children:[new T80({text:this.ad.buttonLabel,onPressed:()=>this.onButtonClick?.(),padding:M0.horizontal(1),color:Z,reverse:!0}),new U0({width:2}),new l1({text:new D1(this.ad.destinationUrlHostname,new $1({color:X,dim:!0}))})]})]})})})}}O9();i8();class e40 extends f0{props;constructor(J){super();this.props=J}createState(){return new pZ8(this.props.autofocus??!0)}}class pZ8 extends b0{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=(q)=>{if(q.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(q.ctrlKey&&q.key==="c"||q.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},Z=r8.sizeOf(J),X=Math.min(60,Z.width-4),Y=Z.height-4,K=[];if(this.widget.props.title)K.push(new l1({text:new D1(this.widget.props.title,new $1({bold:!0,color:P1.blue}))}),new U0({height:1}));if(this.widget.props.message)K.push(new l1({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 U0({height:1}));let G=[];if(this.widget.props.showCopyOption)G.push(new l1({text:new D1("Enter to copy",new $1({dim:!0}))}));return G.push(new l1({text:new D1("Escape to close",new $1({dim:!0}))})),K.push(new n6({children:G.flatMap((q,z)=>z<G.length-1?[q,new U0({width:1}),new l1({text:new D1("•",new $1({dim:!0}))}),new U0({width:1})]:[q]),mainAxisSize:"min"})),new W9({child:new g0({constraints:new j6(X,X,0,Y),decoration:new U9(P1.default(),new f8(new $8(P1.blue,1,"rounded"),new $8(P1.blue,1,"rounded"),new $8(P1.blue,1,"rounded"),new $8(P1.blue,1,"rounded"))),padding:new M0(2,2,2,2),child:new V9({autofocus:this.autofocus,onKey:Q,child:new x0({children:K,mainAxisSize:"min"})})})})}}class Bo extends Error{constructor(J="Command timed out"){super(J);this.name="CommandTimeoutError",Object.setPrototypeOf(this,Bo.prototype)}}class cH1 extends Error{constructor(J){let Q=`${J.noun}: ${J.verb} command cancelled`;super(Q);this.name="CommandCancelledError",Object.setPrototypeOf(this,cH1.prototype)}}function J50(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})}PM();G0();import{spawn as ti4}from"node:child_process";import{promises as ei4}from"node:fs";function dZ8(J){return J.kind==="executable"}function cZ8(J){return J.kind==="markdown"}var P3=50000,lZ8=300000;async function Q50(J,Q,Z,X={}){let{timeoutMs:Y=lZ8,signal:K}=X;try{let G=await Z.getCommand(J);if(!G)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Z.isCommandAvailable(J))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(p.debug("Executing command",{commandName:J,filePath:G.filePath,args:Q}),cZ8(G))return await Jn4(G,Q);else if(dZ8(G))return await Qn4(G,Q,Y,K);else return{success:!1,output:"",error:"Unsupported command type"}}catch(G){return p.error("Failed to execute command",{commandName:J,error:G}),{success:!1,output:"",error:G instanceof Error?G.message:"Unknown error occurred"}}}async function Jn4(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await ei4.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>P3?Z.slice(0,P3)+`
7586
7586
  ... (output truncated at ${P3} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function Qn4(J,Q,Z=lZ8,X){return new Promise((Y)=>{let[K,G]=Zn4(J,Q);p.debug("Spawning command",{spawnCommand:K,spawnArgs:G.slice(0,10),filePath:J.filePath,timeoutMs:Z});let q=Mp0(X),z=!1,W=setTimeout(()=>{z=!0,q.abort(),p.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),U=ti4(K,G,{stdio:["pipe","pipe","pipe"],signal:q.signal,detached:!0}),F=[],H=[],B=0;U.stdout?.on("data",(V)=>{let M=V.toString();if(B+=M.length,B<=P3)F.push(M);else{let N=P3-(B-M.length);if(N>0)F.push(M.slice(0,N))}}),U.stderr?.on("data",(V)=>{let M=V.toString();if(B+=M.length,B<=P3)H.push(M);else{let N=P3-(B-M.length);if(N>0)H.push(M.slice(0,N))}}),U.on("close",(V)=>{if(clearTimeout(W),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:V??void 0});return}let M=V===0||V===1,N=F.join(""),L=H.join(""),A=N;if(!M&&!N.trim()&&L.trim())A=L;else if(L.trim())A+=N?`
7587
7587
  ${L}`:L;if(B>P3)A+=`
7588
- ... (output truncated at ${P3} characters)`;Y({success:M,output:A.trim(),error:!M?L.trim()||"Command failed":void 0,exitCode:V??void 0})}),U.on("error",(V)=>{clearTimeout(W);let M=V.message;if(z)M=`Command timed out after ${Z}ms`;else if(V.message.includes("operation was aborted")||V.name==="AbortError")M="The command was aborted";Y({success:!1,output:F.join(""),error:M})})})}function Zn4(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return Yn4(Z,X?[...X]:null,Y,Q);else return Xn4(Z,X?[...X]:null,Y,Q)}function Xn4(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function Yn4(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();jD();W5();jB();TK();sU();$D();zh();import{writeFile as Gn4}from"fs/promises";import qn4 from"path";G0();TK();class Z50{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.1762561694-g1226c3"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await i51(Q,this.configService)}catch(Q){p.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}i8();class X50 extends f0{props;constructor(J){super();this.props=J}createState(){return new iZ8}}class iZ8 extends b0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Z)=>{this.setState(()=>{this._state=Z(this._state)})};return this.widget.props.builder(J,Q,this._state)}}i8();i8();class nZ8 extends b0{controller=new Zz;focusNode=new Y9({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});initState(){this.focusNode.requestFocus()}dispose(){this.focusNode.dispose()}build(J){let Q=N6.of(J),{colors:Z}=Q,X=f8.all(new $8(Z.foreground,1,"solid")),Y=new O3({controller:this.controller,focusNode:this.focusNode,placeholder:"Enter command argument...",onSubmitted:(q)=>{this.widget.props.onSubmit(q.trim())},autofocus:!0,style:{textColor:Z.foreground,border:null},maxLines:1}),K=new n6({children:[new g0({decoration:{color:P1.default()},child:new l1({text:new D1(">",new $1({color:Z.foreground}))})}),new e6({child:Y})]}),G=new g0({padding:M0.symmetric(1,0),child:new l1({text:new D1("",void 0,[new D1("Command: ",new $1({color:Z.foreground})),new D1(this.widget.props.commandName,new $1({color:P1.yellow,bold:!0}))])})});return new g0({decoration:{border:X,color:P1.default()},padding:M0.all(1),child:new x0({children:[G,new U0({height:1}),K]})})}}class Y50 extends f0{props;constructor(J){super();this.props=J}createState(){return new nZ8}}sU();G0();i8();G0();class aZ8{_listeners=new Set;_disposed=!1;addListener(J){if(this._disposed)throw Error("Cannot add listener to disposed ChangeNotifier");this._listeners.add(J)}removeListener(J){this._listeners.delete(J)}notifyListeners(){if(this._disposed)return;let J=Array.from(this._listeners);for(let Q of J)try{Q()}catch(Z){}}dispose(){this._disposed=!0,this._listeners.clear()}get disposed(){return this._disposed}get hasListeners(){return this._listeners.size>0}}class SP extends aZ8{_value;constructor(J){super();this._value=J}get value(){return this._value}set value(J){let Q=typeof J==="object"||this._value!==J;if(this._value=J,Q)this.notifyListeners()}}function rZ8(J,Q){let Z=()=>{Q()};return J.addListener(Z),{dispose:()=>J.removeListener(Z)}}i8();s4();O9();class K50 extends t5{link;showWhenUnlinked;offset;constructor({key:J,link:Q,showWhenUnlinked:Z=!0,offset:X={x:0,y:0},child:Y}){super({key:J,child:Y});this.link=Q,this.showWhenUnlinked=Z,this.offset=X}createElement(){return new Jw(this)}createRenderObject(){return new sZ8(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class sZ8 extends H8{_link;_showWhenUnlinked;_followerOffset;_cachedPosition=null;constructor(J,Q,Z){super();this._link=J,this._showWhenUnlinked=Q,this._followerOffset=Z}get link(){return this._link}set link(J){this._link=J,this._cachedPosition=null,this.markNeedsLayout()}get showWhenUnlinked(){return this._showWhenUnlinked}set showWhenUnlinked(J){if(this._showWhenUnlinked!==J)this._showWhenUnlinked=J,this.markNeedsLayout()}setFollowerOffset(J){if(this._followerOffset.x!==J.x||this._followerOffset.y!==J.y)this._followerOffset={...J},this.markNeedsLayout()}calculatePosition(){let J=this._link.getTargetTransform();if(!J)return null;return{x:J.position.x+this._followerOffset.x,y:J.position.y+this._followerOffset.y}}shouldShow(){return this._link.target!==null||this._showWhenUnlinked}performLayout(){let J=this._lastConstraints;if(l6(!!J,"performLayout called without constraints"),!this.shouldShow()){this.setSize(0,0),super.performLayout();return}let Q=this.calculatePosition();if(this._cachedPosition=Q,Q)this.setOffset(Q.x,Q.y);if(this.children.length>0){let Z=this.children[0];Z.layout(J);let X=Z.size;this.setSize(X.width,X.height)}else this.setSize(0,0);super.performLayout()}getCurrentPosition(){return this._cachedPosition}setOffset(J,Q){super.setOffset(J,Q)}paint(J,Q=0,Z=0){super.paint(J,Q,Z)}}s4();O9();class G50 extends t5{link;constructor({key:J,link:Q,child:Z}){super({key:J,child:Z});this.link=Q}createElement(){return new Jw(this)}createRenderObject(){return new oZ8(this.link)}updateRenderObject(J){J.link=this.link}}class oZ8 extends H8{_link;_globalPosition={x:0,y:0};constructor(J){super();this._link=J}get link(){return this._link}set link(J){if(this._link===J)return;this._link._setTarget(null),this._link=J,this._link._setTarget(this)}attach(){super.attach(),this._link._setTarget(this)}detach(){this._link._setTarget(null),super.detach()}getGlobalPosition(){let J=this.offset.x,Q=this.offset.y,Z=this.parent;while(Z&&Z instanceof H8)J+=Z.offset.x,Q+=Z.offset.y,Z=Z.parent;return{x:J,y:Q}}getSize(){let J=this.size;return{width:J.width,height:J.height}}updateGlobalPosition(){let J={...this._globalPosition};if(this._globalPosition=this.getGlobalPosition(),J.x!==this._globalPosition.x||J.y!==this._globalPosition.y)this._link._notifyFollowers()}performLayout(){let J=this._lastConstraints;if(l6(!!J,"performLayout called without constraints"),this.children.length>0){let Q=this.children[0];Q.layout(J);let Z=Q.size;this.setSize(Z.width,Z.height)}else this.setSize(0,0);this.updateGlobalPosition(),super.performLayout()}}G0();class q50{_target=null;_followers=new Set;get target(){return this._target}_setTarget(J){if(this._target===J)return;this._target=J,this._notifyFollowers()}_addFollower(J){this._followers.add(J)}_removeFollower(J){this._followers.delete(J)}_notifyFollowers(){for(let J of this._followers)try{J()}catch(Q){p.error("Error in LayerLink follower callback:",Q)}}getTargetTransform(){if(!this._target)return null;return{position:this._target.getGlobalPosition(),size:this._target.getSize()}}}G0();class z50{_state;_textController=null;_triggers=[];_optionsBuilder=null;_onSelected=null;_disposed=!1;constructor(){let J={trigger:null,options:[],selectedIndex:-1,isActive:!1,generationId:0};this._state=new SP(J)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:J,triggers:Q,optionsBuilder:Z,onSelected:X}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=J,this._triggers=Q,this._optionsBuilder=Z,this._onSelected=X||null,this._textController.addListener(this._handleTextChange)}selectNext(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Q=J.selectedIndex<J.options.length-1?J.selectedIndex+1:0;this._updateState({selectedIndex:Q})}selectPrevious(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Q=J.selectedIndex>0?J.selectedIndex-1:J.options.length-1;this._updateState({selectedIndex:Q})}acceptSelected(){let J=this.currentState;if(!J.isActive||J.selectedIndex<0||J.selectedIndex>=J.options.length)return;let Q=J.options[J.selectedIndex];if(!Q)return;if(this.dismiss(),this._onSelected)this._onSelected(Q)}dismiss(){this._updateState({trigger:null,options:[],selectedIndex:-1,isActive:!1})}dispose(){this._disposed=!0,this._cleanup(),this._state.dispose()}_handleTextChange=()=>{if(!this._textController||!this._optionsBuilder)return;let J=this._textController.text,Q=this._textController.cursorPosition,Z=null;for(let Y of this._triggers){let K=Y.detect(J,Q);if(K&&(!Z||K.start>Z.start))Z=K}if(!Z){if(this.currentState.isActive)this.dismiss();return}let X=this.currentState.generationId+1;this._updateState({trigger:Z,generationId:X,isActive:!0,selectedIndex:-1}),this._buildOptions(Z.query,X)};async _buildOptions(J,Q){if(!this._optionsBuilder)return;try{let Z=await this._optionsBuilder(J);if(this.currentState.generationId===Q&&!this._disposed)this._updateState({options:Z,selectedIndex:Z.length>0?0:-1,isActive:Z.length>0})}catch(Z){if(p.error("Error building autocomplete options:",Z),this.currentState.generationId===Q&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_updateState(J){if(this._disposed)return;this._state.value={...this.currentState,...J}}_cleanup(){if(this._textController)this._textController.removeListener(this._handleTextChange)}}class Do{}class Vo{}class Mo{}class lH1{}class iH1 extends f0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new tZ8(this.props)}}class tZ8 extends b0{props;controller;stateListener=null;overlayEntry=null;layerLink=new q50;scrollOffset=0;_effectiveFocusNode;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new Y9({debugLabel:"AutocompleteFocusOwned"}),this.controller=new z50,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=rZ8(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.autofocus??!0)i9.instance.addPostFrameCallback(()=>{this._effectiveFocusNode.requestFocus()})}didUpdateWidget(J){super.didUpdateWidget(J);let Q=J.props,Z=this.widget.props;if(this.props=Z,Q.controller!==Z.controller||Q.triggers!==Z.triggers||Q.optionsBuilder!==Z.optionsBuilder||Q.textFieldProps!==Z.textFieldProps||Q.onSelected!==Z.onSelected)this.controller.initialize({textController:Z.controller,triggers:Z.triggers,optionsBuilder:Z.optionsBuilder,onSelected:Z.onSelected});this.setState(()=>{})}dispose(){this.removeOverlay(),this.stateListener?.dispose(),this.controller.dispose(),this._effectiveFocusNode.dispose(),super.dispose()}invoke=(J)=>{if(!this.controller.currentState.isActive)return"ignored";if(J instanceof Do)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof Vo)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Mo)return this.controller.acceptSelected(),"handled";if(J instanceof lH1)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let J=this.controller.currentState;if(!J.isActive||J.selectedIndex<0)return;let Q=J.selectedIndex,Z=J.options.length,X=Z;try{let z=this.layerLink.getTargetTransform();if(z){let W=z.position.y,U=2,F=W-2;X=Math.min(Z,Math.max(1,F))}}catch{}if(X>=Z){this.scrollOffset=0;return}let Y=Q-this.scrollOffset,K=1,G=this.scrollOffset;if(Y>=X-K)G=Math.max(0,Q-(X-K-1));if(Y<K)G=Math.max(0,Q-K);let q=Math.max(0,Z-X);G=Math.min(G,q),this.scrollOffset=G}build(J){let Q=new O3({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Z=new UU({shortcuts:new Map([[new g6("ArrowDown"),new Do],[new g6("ArrowUp"),new Vo],[new g6("n",{ctrl:!0}),new Do],[new g6("p",{ctrl:!0}),new Vo],[new g6("Enter"),new Mo],[new g6("Escape"),new lH1],[new g6("Tab"),new Mo]]),focusNode:this._effectiveFocusNode,child:Q}),X=new wX({actions:new Map([[Do,new S9(this.invoke)],[Vo,new S9(this.invoke)],[Mo,new S9(this.invoke)],[lH1,new S9(this.invoke)]]),child:Z});return new G50({link:this.layerLink,child:X})}updateOverlay(){let J=this.controller.currentState;if(J.isActive&&J.options.length>0)if(!this.overlayEntry)this.createOverlay();else this.overlayEntry.markNeedsBuild();else this.removeOverlay()}createOverlay(){if(this.overlayEntry)return;this.overlayEntry=new b80((J)=>{let Q=this.controller.currentState;return this.buildOverlayContent(J,Q)});try{MP.of(this.context).insert(this.overlayEntry)}catch(J){p.error("Failed to insert autocomplete overlay:",J),this.overlayEntry=null}}removeOverlay(){if(this.overlayEntry)this.overlayEntry.remove(),this.overlayEntry=null}buildOverlayContent(J,Q){let Z=J8.maybeOf(J),X=Z?.colorScheme.background??P1.black,Y=this.props.overlayBorderColor??Z?.colorScheme.border??P1.white,K=Q.options.length;try{let w=this.layerLink.getTargetTransform();if(w){let O=w.position.y,$=2,I=O-2;K=Math.min(K,Math.max(1,I))}}catch{}this.updateScrollPosition();let G=this.scrollOffset,q=Math.min(Q.options.length,G+K),z=[],W=0;for(let w=G;w<q;w++){let O=Q.options[w];if(!O)continue;let $=w===Q.selectedIndex,I,R;if(this.props.optionViewBuilder){I=this.props.optionViewBuilder(J,O,$);let j=this.props.displayStringForOption?.(O)??String(O),C="",x=j,y="",P=O;if(P&&typeof P==="object"&&"type"in P)switch(P.type){case"file":C="@",x=P.path||j;break;case"thread":x=P.title||j,y=P.description||"";break}R=C+x+(y?" - "+y:"")}else{let j=this.props.displayStringForOption?.(O)??String(O),C=Z?.colorScheme.selection??P1.index(8),x=Z?.colorScheme.foreground??P1.white;I=new l1({text:new D1(j,new $1({color:x,backgroundColor:$?C:void 0}))}),R=j}let T=r8.of(J),E=XG(R,T.supportsEmojiWidth);W=Math.max(W,E),z.push(I)}let U=r8.sizeOf(J).width,F=W+4,H=Math.floor(U*0.9),B=Math.max(Math.min(F,H),Math.min(30,H)),N=z.length+2,L=this.props.showMenuBelow?1:-N;if(this.props.showMenuBelow){let w=this.props.controller.getCursorLine();if(w>=0)L=w+1}let A=new U0({width:B,child:new g0({height:N,padding:M0.symmetric(1,0),decoration:new U9(X,f8.all(new $8(Y,1,"rounded"))),child:new x0({crossAxisAlignment:"start",children:z})})});return new K50({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:L},child:A})}}function eZ8(J){if(J.kind!=="file"&&J.kind!=="folder")throw Error("Invalid completion item: missing path or kind");return{type:"file",path:J.path,kind:J.kind}}function JX8(J,Q,Z){return{type:"thread",threadId:J,title:Q,description:Z}}function W50(J){switch(J.type){case"file":return J.path;case"thread":return J.title;case"hint":return J.message}}function QX8(J){switch(J.type){case"file":return;case"thread":return J.description||J.title;case"hint":return}}class Bw{detect(J,Q){if(!J||Q<1)return null;let Z=c4(J);if(Q>Z.length)return null;let X=this.findWordStart(Z,Q);if(X>=Z.length||Z[X]!=="@")return null;let Y=Z.slice(X+1,Q).join("");if(Y.includes(" ")||Y.includes("\t")||Y.includes(`
7588
+ ... (output truncated at ${P3} characters)`;Y({success:M,output:A.trim(),error:!M?L.trim()||"Command failed":void 0,exitCode:V??void 0})}),U.on("error",(V)=>{clearTimeout(W);let M=V.message;if(z)M=`Command timed out after ${Z}ms`;else if(V.message.includes("operation was aborted")||V.name==="AbortError")M="The command was aborted";Y({success:!1,output:F.join(""),error:M})})})}function Zn4(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return Yn4(Z,X?[...X]:null,Y,Q);else return Xn4(Z,X?[...X]:null,Y,Q)}function Xn4(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function Yn4(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();jD();W5();jB();TK();sU();$D();zh();import{writeFile as Gn4}from"fs/promises";import qn4 from"path";G0();TK();class Z50{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.1762574482-gae4ec1"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await i51(Q,this.configService)}catch(Q){p.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}i8();class X50 extends f0{props;constructor(J){super();this.props=J}createState(){return new iZ8}}class iZ8 extends b0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Z)=>{this.setState(()=>{this._state=Z(this._state)})};return this.widget.props.builder(J,Q,this._state)}}i8();i8();class nZ8 extends b0{controller=new Zz;focusNode=new Y9({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});initState(){this.focusNode.requestFocus()}dispose(){this.focusNode.dispose()}build(J){let Q=N6.of(J),{colors:Z}=Q,X=f8.all(new $8(Z.foreground,1,"solid")),Y=new O3({controller:this.controller,focusNode:this.focusNode,placeholder:"Enter command argument...",onSubmitted:(q)=>{this.widget.props.onSubmit(q.trim())},autofocus:!0,style:{textColor:Z.foreground,border:null},maxLines:1}),K=new n6({children:[new g0({decoration:{color:P1.default()},child:new l1({text:new D1(">",new $1({color:Z.foreground}))})}),new e6({child:Y})]}),G=new g0({padding:M0.symmetric(1,0),child:new l1({text:new D1("",void 0,[new D1("Command: ",new $1({color:Z.foreground})),new D1(this.widget.props.commandName,new $1({color:P1.yellow,bold:!0}))])})});return new g0({decoration:{border:X,color:P1.default()},padding:M0.all(1),child:new x0({children:[G,new U0({height:1}),K]})})}}class Y50 extends f0{props;constructor(J){super();this.props=J}createState(){return new nZ8}}sU();G0();i8();G0();class aZ8{_listeners=new Set;_disposed=!1;addListener(J){if(this._disposed)throw Error("Cannot add listener to disposed ChangeNotifier");this._listeners.add(J)}removeListener(J){this._listeners.delete(J)}notifyListeners(){if(this._disposed)return;let J=Array.from(this._listeners);for(let Q of J)try{Q()}catch(Z){}}dispose(){this._disposed=!0,this._listeners.clear()}get disposed(){return this._disposed}get hasListeners(){return this._listeners.size>0}}class SP extends aZ8{_value;constructor(J){super();this._value=J}get value(){return this._value}set value(J){let Q=typeof J==="object"||this._value!==J;if(this._value=J,Q)this.notifyListeners()}}function rZ8(J,Q){let Z=()=>{Q()};return J.addListener(Z),{dispose:()=>J.removeListener(Z)}}i8();s4();O9();class K50 extends t5{link;showWhenUnlinked;offset;constructor({key:J,link:Q,showWhenUnlinked:Z=!0,offset:X={x:0,y:0},child:Y}){super({key:J,child:Y});this.link=Q,this.showWhenUnlinked=Z,this.offset=X}createElement(){return new Jw(this)}createRenderObject(){return new sZ8(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class sZ8 extends H8{_link;_showWhenUnlinked;_followerOffset;_cachedPosition=null;constructor(J,Q,Z){super();this._link=J,this._showWhenUnlinked=Q,this._followerOffset=Z}get link(){return this._link}set link(J){this._link=J,this._cachedPosition=null,this.markNeedsLayout()}get showWhenUnlinked(){return this._showWhenUnlinked}set showWhenUnlinked(J){if(this._showWhenUnlinked!==J)this._showWhenUnlinked=J,this.markNeedsLayout()}setFollowerOffset(J){if(this._followerOffset.x!==J.x||this._followerOffset.y!==J.y)this._followerOffset={...J},this.markNeedsLayout()}calculatePosition(){let J=this._link.getTargetTransform();if(!J)return null;return{x:J.position.x+this._followerOffset.x,y:J.position.y+this._followerOffset.y}}shouldShow(){return this._link.target!==null||this._showWhenUnlinked}performLayout(){let J=this._lastConstraints;if(l6(!!J,"performLayout called without constraints"),!this.shouldShow()){this.setSize(0,0),super.performLayout();return}let Q=this.calculatePosition();if(this._cachedPosition=Q,Q)this.setOffset(Q.x,Q.y);if(this.children.length>0){let Z=this.children[0];Z.layout(J);let X=Z.size;this.setSize(X.width,X.height)}else this.setSize(0,0);super.performLayout()}getCurrentPosition(){return this._cachedPosition}setOffset(J,Q){super.setOffset(J,Q)}paint(J,Q=0,Z=0){super.paint(J,Q,Z)}}s4();O9();class G50 extends t5{link;constructor({key:J,link:Q,child:Z}){super({key:J,child:Z});this.link=Q}createElement(){return new Jw(this)}createRenderObject(){return new oZ8(this.link)}updateRenderObject(J){J.link=this.link}}class oZ8 extends H8{_link;_globalPosition={x:0,y:0};constructor(J){super();this._link=J}get link(){return this._link}set link(J){if(this._link===J)return;this._link._setTarget(null),this._link=J,this._link._setTarget(this)}attach(){super.attach(),this._link._setTarget(this)}detach(){this._link._setTarget(null),super.detach()}getGlobalPosition(){let J=this.offset.x,Q=this.offset.y,Z=this.parent;while(Z&&Z instanceof H8)J+=Z.offset.x,Q+=Z.offset.y,Z=Z.parent;return{x:J,y:Q}}getSize(){let J=this.size;return{width:J.width,height:J.height}}updateGlobalPosition(){let J={...this._globalPosition};if(this._globalPosition=this.getGlobalPosition(),J.x!==this._globalPosition.x||J.y!==this._globalPosition.y)this._link._notifyFollowers()}performLayout(){let J=this._lastConstraints;if(l6(!!J,"performLayout called without constraints"),this.children.length>0){let Q=this.children[0];Q.layout(J);let Z=Q.size;this.setSize(Z.width,Z.height)}else this.setSize(0,0);this.updateGlobalPosition(),super.performLayout()}}G0();class q50{_target=null;_followers=new Set;get target(){return this._target}_setTarget(J){if(this._target===J)return;this._target=J,this._notifyFollowers()}_addFollower(J){this._followers.add(J)}_removeFollower(J){this._followers.delete(J)}_notifyFollowers(){for(let J of this._followers)try{J()}catch(Q){p.error("Error in LayerLink follower callback:",Q)}}getTargetTransform(){if(!this._target)return null;return{position:this._target.getGlobalPosition(),size:this._target.getSize()}}}G0();class z50{_state;_textController=null;_triggers=[];_optionsBuilder=null;_onSelected=null;_disposed=!1;constructor(){let J={trigger:null,options:[],selectedIndex:-1,isActive:!1,generationId:0};this._state=new SP(J)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:J,triggers:Q,optionsBuilder:Z,onSelected:X}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=J,this._triggers=Q,this._optionsBuilder=Z,this._onSelected=X||null,this._textController.addListener(this._handleTextChange)}selectNext(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Q=J.selectedIndex<J.options.length-1?J.selectedIndex+1:0;this._updateState({selectedIndex:Q})}selectPrevious(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Q=J.selectedIndex>0?J.selectedIndex-1:J.options.length-1;this._updateState({selectedIndex:Q})}acceptSelected(){let J=this.currentState;if(!J.isActive||J.selectedIndex<0||J.selectedIndex>=J.options.length)return;let Q=J.options[J.selectedIndex];if(!Q)return;if(this.dismiss(),this._onSelected)this._onSelected(Q)}dismiss(){this._updateState({trigger:null,options:[],selectedIndex:-1,isActive:!1})}dispose(){this._disposed=!0,this._cleanup(),this._state.dispose()}_handleTextChange=()=>{if(!this._textController||!this._optionsBuilder)return;let J=this._textController.text,Q=this._textController.cursorPosition,Z=null;for(let Y of this._triggers){let K=Y.detect(J,Q);if(K&&(!Z||K.start>Z.start))Z=K}if(!Z){if(this.currentState.isActive)this.dismiss();return}let X=this.currentState.generationId+1;this._updateState({trigger:Z,generationId:X,isActive:!0,selectedIndex:-1}),this._buildOptions(Z.query,X)};async _buildOptions(J,Q){if(!this._optionsBuilder)return;try{let Z=await this._optionsBuilder(J);if(this.currentState.generationId===Q&&!this._disposed)this._updateState({options:Z,selectedIndex:Z.length>0?0:-1,isActive:Z.length>0})}catch(Z){if(p.error("Error building autocomplete options:",Z),this.currentState.generationId===Q&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_updateState(J){if(this._disposed)return;this._state.value={...this.currentState,...J}}_cleanup(){if(this._textController)this._textController.removeListener(this._handleTextChange)}}class Do{}class Vo{}class Mo{}class lH1{}class iH1 extends f0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new tZ8(this.props)}}class tZ8 extends b0{props;controller;stateListener=null;overlayEntry=null;layerLink=new q50;scrollOffset=0;_effectiveFocusNode;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new Y9({debugLabel:"AutocompleteFocusOwned"}),this.controller=new z50,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=rZ8(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.autofocus??!0)i9.instance.addPostFrameCallback(()=>{this._effectiveFocusNode.requestFocus()})}didUpdateWidget(J){super.didUpdateWidget(J);let Q=J.props,Z=this.widget.props;if(this.props=Z,Q.controller!==Z.controller||Q.triggers!==Z.triggers||Q.optionsBuilder!==Z.optionsBuilder||Q.textFieldProps!==Z.textFieldProps||Q.onSelected!==Z.onSelected)this.controller.initialize({textController:Z.controller,triggers:Z.triggers,optionsBuilder:Z.optionsBuilder,onSelected:Z.onSelected});this.setState(()=>{})}dispose(){this.removeOverlay(),this.stateListener?.dispose(),this.controller.dispose(),this._effectiveFocusNode.dispose(),super.dispose()}invoke=(J)=>{if(!this.controller.currentState.isActive)return"ignored";if(J instanceof Do)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof Vo)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Mo)return this.controller.acceptSelected(),"handled";if(J instanceof lH1)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let J=this.controller.currentState;if(!J.isActive||J.selectedIndex<0)return;let Q=J.selectedIndex,Z=J.options.length,X=Z;try{let z=this.layerLink.getTargetTransform();if(z){let W=z.position.y,U=2,F=W-2;X=Math.min(Z,Math.max(1,F))}}catch{}if(X>=Z){this.scrollOffset=0;return}let Y=Q-this.scrollOffset,K=1,G=this.scrollOffset;if(Y>=X-K)G=Math.max(0,Q-(X-K-1));if(Y<K)G=Math.max(0,Q-K);let q=Math.max(0,Z-X);G=Math.min(G,q),this.scrollOffset=G}build(J){let Q=new O3({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Z=new UU({shortcuts:new Map([[new g6("ArrowDown"),new Do],[new g6("ArrowUp"),new Vo],[new g6("n",{ctrl:!0}),new Do],[new g6("p",{ctrl:!0}),new Vo],[new g6("Enter"),new Mo],[new g6("Escape"),new lH1],[new g6("Tab"),new Mo]]),focusNode:this._effectiveFocusNode,child:Q}),X=new wX({actions:new Map([[Do,new S9(this.invoke)],[Vo,new S9(this.invoke)],[Mo,new S9(this.invoke)],[lH1,new S9(this.invoke)]]),child:Z});return new G50({link:this.layerLink,child:X})}updateOverlay(){let J=this.controller.currentState;if(J.isActive&&J.options.length>0)if(!this.overlayEntry)this.createOverlay();else this.overlayEntry.markNeedsBuild();else this.removeOverlay()}createOverlay(){if(this.overlayEntry)return;this.overlayEntry=new b80((J)=>{let Q=this.controller.currentState;return this.buildOverlayContent(J,Q)});try{MP.of(this.context).insert(this.overlayEntry)}catch(J){p.error("Failed to insert autocomplete overlay:",J),this.overlayEntry=null}}removeOverlay(){if(this.overlayEntry)this.overlayEntry.remove(),this.overlayEntry=null}buildOverlayContent(J,Q){let Z=J8.maybeOf(J),X=Z?.colorScheme.background??P1.black,Y=this.props.overlayBorderColor??Z?.colorScheme.border??P1.white,K=Q.options.length;try{let w=this.layerLink.getTargetTransform();if(w){let O=w.position.y,$=2,I=O-2;K=Math.min(K,Math.max(1,I))}}catch{}this.updateScrollPosition();let G=this.scrollOffset,q=Math.min(Q.options.length,G+K),z=[],W=0;for(let w=G;w<q;w++){let O=Q.options[w];if(!O)continue;let $=w===Q.selectedIndex,I,R;if(this.props.optionViewBuilder){I=this.props.optionViewBuilder(J,O,$);let j=this.props.displayStringForOption?.(O)??String(O),C="",x=j,y="",P=O;if(P&&typeof P==="object"&&"type"in P)switch(P.type){case"file":C="@",x=P.path||j;break;case"thread":x=P.title||j,y=P.description||"";break}R=C+x+(y?" - "+y:"")}else{let j=this.props.displayStringForOption?.(O)??String(O),C=Z?.colorScheme.selection??P1.index(8),x=Z?.colorScheme.foreground??P1.white;I=new l1({text:new D1(j,new $1({color:x,backgroundColor:$?C:void 0}))}),R=j}let T=r8.of(J),E=XG(R,T.supportsEmojiWidth);W=Math.max(W,E),z.push(I)}let U=r8.sizeOf(J).width,F=W+4,H=Math.floor(U*0.9),B=Math.max(Math.min(F,H),Math.min(30,H)),N=z.length+2,L=this.props.showMenuBelow?1:-N;if(this.props.showMenuBelow){let w=this.props.controller.getCursorLine();if(w>=0)L=w+1}let A=new U0({width:B,child:new g0({height:N,padding:M0.symmetric(1,0),decoration:new U9(X,f8.all(new $8(Y,1,"rounded"))),child:new x0({crossAxisAlignment:"start",children:z})})});return new K50({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:L},child:A})}}function eZ8(J){if(J.kind!=="file"&&J.kind!=="folder")throw Error("Invalid completion item: missing path or kind");return{type:"file",path:J.path,kind:J.kind}}function JX8(J,Q,Z){return{type:"thread",threadId:J,title:Q,description:Z}}function W50(J){switch(J.type){case"file":return J.path;case"thread":return J.title;case"hint":return J.message}}function QX8(J){switch(J.type){case"file":return;case"thread":return J.description||J.title;case"hint":return}}class Bw{detect(J,Q){if(!J||Q<1)return null;let Z=c4(J);if(Q>Z.length)return null;let X=this.findWordStart(Z,Q);if(X>=Z.length||Z[X]!=="@")return null;let Y=Z.slice(X+1,Q).join("");if(Y.includes(" ")||Y.includes("\t")||Y.includes(`
7589
7589
  `))return null;return{start:X,end:Q,query:Y,trigger:"@"}}findWordStart(J,Q){let Z=Q;for(let X=Q-1;X>=0;X--){let Y=J[X];if(!Y||/[\s([{]/.test(Y)){Z=X+1;break}if(X===0)Z=0}return Z}}class No extends f0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new ZX8(this.props)}}class ZX8 extends b0{props;_effectiveFocusNode;constructor(J){super();this.props=J}buildOptions=async(J)=>{let Q=this.props.controller.text,Z=this.props.controller.cursorPosition,Y=new Bw().detect(Q,Z);if(Y)return await this.props.completionBuilder.buildOptions(Y);return[]};defaultOnOptionSelected=(J)=>{switch(J.type){case"hint":return;case"file":{let Q=this.props.controller.text,Z=this.props.controller.cursorPosition,Y=Q.slice(0,Z).lastIndexOf("@");if(Y!==-1){let K=Q.slice(0,Y),G=Q.slice(Z),q=K+`@${J.path} `+G;this.props.controller.clear(),this.props.controller.insertText(q),this.props.controller.cursorPosition=Y+1+J.path.length+1}break}case"thread":{let Q=this.props.controller.text,Z=this.props.controller.cursorPosition,X=Q.split(" ");if(X.length>=1&&X[0]==="/continue"){let Y=`/continue ${J.threadId} `;this.props.onSubmitted?.(Y)}else{let K=Q.slice(0,Z).lastIndexOf("@");if(K!==-1){let G=Q.slice(0,K),q=Q.slice(Z),W=`${this.props.ampURL.replace(/\/$/,"")}/threads/${J.threadId}`,U=G+`${W} `+q;this.props.controller.clear(),this.props.controller.insertText(U),this.props.controller.cursorPosition=K+W.length+1}}break}}};initState(){super.initState(),this._effectiveFocusNode=this.props.focusNode||new Y9({debugLabel:"PromptEditorFocus"}),this.props.controller.onInsertText=(J,Q)=>{if(J.length<=3)return!0;let Z=C78(J);if(!Z)return!0;if(this.props.onInsertImage)return this.props.onInsertImage(Z);return!0}}didUpdateWidget(J){super.didUpdateWidget(J),this.props=this.widget.props}dispose(){if(!this.props.focusNode)this._effectiveFocusNode.dispose();super.dispose()}_handleOpenInEditor=async(J)=>{let{mkdtemp:Q,readFile:Z,unlink:X,rmdir:Y,writeFile:K}=await import("node:fs/promises"),{tmpdir:G}=await import("node:os"),q=await import("node:path");try{let z=await Q(q.join(G(),"amp-edit-")),W=q.join(z,"message.amp.md");await K(W,J,"utf-8"),await Zw(W);try{let U=await Z(W,"utf-8");this.props.controller.text=U}catch(U){if(U?.code!=="ENOENT")p.error("Failed to read temporary file",U)}try{await X(W),await Y(z)}catch(U){p.warn("Failed to clean up temporary file",U)}}catch(z){p.error("Error opening editor:",z)}};_handleBackspaceAtStart=()=>{if(this.props.imageAttachments.length>0&&this.props.popImage)return this.props.popImage(),!0;return!1};build(J){let Q=this.props.theme,Z=this.props.imageAttachments.length>0?new g0({padding:M0.only({bottom:1,left:1}),child:new l1({text:new D1("",void 0,[new D1("Images: ",new $1({color:Q.foreground,dim:!0})),...this.props.imageAttachments.flatMap((Y,K)=>[new D1(`[image ${K+1}]`,new $1({color:Q.success})),...K<this.props.imageAttachments.length-1?[new D1(" ")]:[]])])})}):null,X=new iH1({controller:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.buildOptions,onSelected:this.props.onOptionSelected??this.defaultOnOptionSelected,displayStringForOption:(Y)=>W50(Y),overlayBorderColor:Q.border,focusNode:this._effectiveFocusNode,autofocus:this.props.autofocus??!0,showMenuBelow:this.props.showMenuBelow??!1,textFieldProps:{placeholder:this.props.placeholder,wrap:!0,minLines:3,maxLines:null,expands:!0,autofocus:!1,enabled:this.props.enabled??!0,onSubmitted:this.props.onSubmitted,onOpenInEditor:this._handleOpenInEditor,submitKey:{character:"Enter"},prompts:this.props.shellPromptRules,style:{border:null},clipboard:this.props.clipboard,onCopy:this.props.onCopy,copyOnSelectionEnabled:!0,onBackspaceWhenEmpty:this._handleBackspaceAtStart},optionViewBuilder:(Y,K,G)=>{let q=G?Q.selection:void 0,z=K.type==="thread"?Q.warning:Q.secondary,W=Q.foreground,U=Q.foreground,F,H;switch(K.type){case"file":F="@",H=K.path;break;case"thread":F="@",H=K.title;break;case"hint":F="",H=K.message;break;default:F="",H=W50(K);break}let B=QX8(K),V=new D1(F,new $1({color:z})),M=new D1(H,new $1({color:W})),N=[V,M];if(B){let L=new D1(" - ",new $1({color:U,dim:!0})),A=new D1(B,new $1({color:U,dim:!0}));N.push(L,A)}return new g0({decoration:new U9(q),child:new l1({text:new D1("",void 0,N),maxLines:1,overflow:"ellipsis"})})}});if(Z)return new x0({crossAxisAlignment:"start",children:[Z,new e6({child:X})]});return X}requestFocus(){this._effectiveFocusNode.requestFocus()}}O9();i8();class XX8 extends b0{controller=new Zz;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new Y9({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=(J)=>{if(this.imageAttachments.length>=jM)return!1;let Q=ky(J);if(Q)return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Q=N6.of(J),{colors:Z,app:X}=Q,K=r8.of(J).size.height,G=Math.max(Math.floor(K*0.5),10),q=new No({controller:this.controller,triggers:[new Bw],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(B)=>{this.widget.props.onSubmit(B.trim(),this.imageAttachments)},theme:Z,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:y4.instance.tuiInstance.clipboard,showMenuBelow:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),z=new V9({focusNode:this.focusNode,child:q}),W=new g0({constraints:new j6({maxHeight:G}),child:z}),U=new g0({padding:M0.symmetric(1,0),child:new l1({text:new D1("",void 0,[new D1("Command: ",new $1({color:Z.foreground})),new D1(this.widget.props.commandName,new $1({color:P1.yellow,bold:!0}))])})}),F=new g0({padding:M0.symmetric(1,0),child:new l1({text:this.isConfirmingClearInput?new D1("",void 0,[new D1("Esc",new $1({color:X.keybind})),new D1(" again to clear input",new $1({color:Z.foreground,dim:!0}))]):new D1("",void 0,[new D1("Press ",new $1({color:Z.foreground,dim:!0})),new D1("Enter",new $1({color:X.keybind})),new D1(" to submit, ",new $1({color:Z.foreground,dim:!0})),new D1("Esc",new $1({color:X.keybind})),new D1(" to clear",new $1({color:Z.foreground,dim:!0}))])})}),H=[U,new U0({height:1}),new e6({child:W}),new U0({height:1}),F];return new g0({decoration:{border:f8.all(new $8(Z.foreground,1,"solid")),color:P1.default()},padding:M0.all(1),child:new x0({children:H})})}}class Lo extends f0{props;constructor(J){super();this.props=J}createState(){return new XX8}}i8();class kP extends f0{props;constructor(J){super();this.props=J}createState(){return new YX8}}class YX8 extends b0{_spinner=new sH;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Q=N6.of(J),{colors:Z}=Q,X=f8.all(new $8(Z.foreground,1,"solid")),Y=this._spinner.toBraille(),K=new l1({textAlign:"center",text:new D1("",void 0,[new D1(Y,new $1({color:P1.yellow})),new D1(" ",void 0),new D1(this.widget.props.message,new $1({color:Z.foreground}))])}),q=[new e6({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[K]})})];if(this.widget.props.onAbort)q.push(new U0({height:2,child:new g0({padding:M0.symmetric(2,0),child:new l1({text:new D1("",new $1({dim:!0}),[new D1("Press ",new $1({color:Z.foreground})),new D1("Esc",new $1({color:Z.info})),new D1(" to cancel",new $1({color:Z.foreground}))])})})}));let z=new g0({decoration:new U9(P1.default(),X),child:new U0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:q})})});if(this.widget.props.onAbort)return new V9({debugLabel:"LoadingDialog",autofocus:!0,onKey:(W)=>{if(W.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:z});return z}}i8();class Dw extends f0{props;constructor(J){super();this.props=J}createState(){return new KX8}}class KX8 extends b0{dispose(){super.dispose()}isWidgetMessage(J){return J instanceof rs}build(J){let Q=this.widget.props.message,Z=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let W=rF1(Q);return{title:W.title,type:W.type,description:W.description}})(),X=Z.type==="error"?P1.red:P1.yellow,Y=f8.all(new $8(P1.white,1,"solid")),K=new g0({padding:M0.symmetric(1,0),child:new l1({text:new D1(Z.title,new $1({color:X,bold:!0}))})}),G=this.isWidgetMessage(Q)?Q.widget:new l1({text:new D1(Z.description,new $1({color:P1.white})),selectable:!0}),q=new e6({child:new DP({child:new g0({padding:M0.symmetric(1,0),child:G})})}),z=new g0({padding:M0.symmetric(1,0),child:new l1({text:this.widget.props.onRetry?new D1("",void 0,[new D1("Press ",new $1({color:P1.white,dim:!0})),new D1("R",new $1({color:P1.yellow})),new D1(" to retry, ",new $1({color:P1.white,dim:!0})),new D1("Esc",new $1({color:P1.yellow})),new D1(" to cancel",new $1({color:P1.white,dim:!0}))]):new D1("Press any key to close",new $1({color:P1.white,dim:!0,italic:!0}))})});return new V9({onKey:(W)=>{if(this.widget.props.onRetry&&W.key==="r")return this.widget.props.onRetry(),"handled";if(W.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!0,child:new g0({decoration:{border:Y,color:P1.default()},padding:M0.all(1),child:new x0({mainAxisAlignment:"center",children:[K,new U0({height:1}),q,z]})})})}}function GX8(J){if(typeof J==="string")return{text:J,images:[]};let Q=J.filter((X)=>X.type==="text"),Z=J.filter((X)=>X.type==="image");return{text:Q.map((X)=>X.text).join(`
7590
7590
  `),images:Z}}class WX8 extends f0{props;constructor(J){super();this.props=J}createState(){return new UX8}}class UX8 extends b0{isLoading=!0;error=null;initState(){super.initState(),i9.instance.addPostFrameCallback(()=>{this.startHandoff()})}async startHandoff(){try{let J=await this.widget.props.handleHandoff({goal:this.widget.props.text,images:this.widget.props.images});if(J.ok)this.widget.props.onDismiss();else this.setState(()=>{this.isLoading=!1,this.error=J.error})}catch(J){this.setState(()=>{this.isLoading=!1,this.error=J instanceof Error?J:Error(String(J))})}}build(J){let Q=[];if(this.isLoading)Q.push(new kP({message:"Handing off...",onAbort:this.widget.props.onAbort}));else if(this.error)Q.push(new Dw({message:this.error,onDismiss:()=>{this.setState(()=>{this.isLoading=!1,this.error=null}),this.widget.props.onDismiss()}}));return new I7({children:Q,fit:"expand"})}}class FX8 extends f0{props;constructor(J){super();this.props=J}createState(){return new HX8}}class HX8 extends b0{result=void 0;isLoading=!1;build(J){let Q=[];if(this.isLoading)Q.push(new kP({message:"Updating visibility..."}));else if(this.result!==void 0)Q.push(new Dw({message:this.result,onDismiss:()=>{this.widget.props.onDismiss()}}));else{let Z=["private","workspace","unlisted","public"],X=this.widget.props.workspace?.groups&&this.widget.props.workspace.groups.length>0?Z.concat("group"):Z;Q.push(new Kw({items:X,getLabel:(Y)=>{switch(Y){case"private":return"Private - Only you can see this thread";case"workspace":return"Workspace - Visible to workspace members";case"group":return"Group - Visible to group members";case"unlisted":return"Unlisted - Anyone with the link can view";case"public":return"Public - Searchable and on your public profile"}},title:"Select Thread Visibility",onAccept:async(Y)=>{this.setState(()=>{this.isLoading=!0});let K=await this.widget.props.execute(Y);this.setState(()=>{this.isLoading=!1,this.result=K})},onDismiss:this.widget.props.onDismiss}))}return new I7({children:Q,fit:"expand"})}}var qX8={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 zn4(J){return J.startsWith("custom-command-")}function zX8(J){return J.startsWith("agent-mode-")}function Wn4(J){return J.replace(/^custom-command-/,"")}class U50{configService;registry;onExecute;onExecutionComplete;commands=new Map;latestCustom=[];latestConfig=null;telemetrySubmitter;constructor(J,Q,Z,X){this.configService=J;this.registry=Q;this.onExecute=Z;this.onExecutionComplete=X;this.configService.config.subscribe((Y)=>{this.latestConfig=Y,this.commands.clear(),this.registerCommands(Y)}),this.registry.commands.subscribe((Y)=>this.latestCustom=Y),this.telemetrySubmitter=new Z50(async()=>{try{return(await this.configService.getLatest()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}},this.configService)}async execute(J,Q,Z=[],X){this.telemetrySubmitter.submit(J).catch((U)=>{p.debug("Failed to submit command telemetry",U)});let Y=Date.now(),K=`command-${Y}-${Math.random().toString(36).substring(7)}`,G=this.commands.get(J);if(G){this.onExecute({id:K,name:G.id,startTime:Y,abortController:X});try{return await G.execute(Q,X,Z)}finally{this.onExecutionComplete()}}let q=Wn4(J),z=this.latestCustom.find((U)=>U.name===q);if(!z)return;this.onExecute({id:K,name:z.name,startTime:Y,abortController:X});let W=await Q50(q,Z,this.registry,{signal:X.signal});if(this.onExecutionComplete(),W.success){let U=Q.editorState.text,H=U.trim()&&!U.endsWith(`
7591
7591
 
@@ -7640,7 +7640,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
7640
7640
  `),J.stdout.write(`Thread: ${B}
7641
7641
  `),J.stdout.write(`Continue this thread with: amp threads continue ${F}
7642
7642
  `)}}function a50(J){return J==="smart"?P1.rgb(3,197,97):J==="rush"?P1.rgb(228,180,2):eG(J)?P1.rgb(0,184,255):J==="plan"?P1.rgb(153,102,255):Ia4(J)}class UY8 extends f0{props;constructor(J){super();this.props=J}createState(){return new FY8}}class FY8 extends b0{viewportHeight=1;scrollListenerAttached=!1;initState(){if(!this.scrollListenerAttached)this.widget.props.controller.addListener(()=>{this.updateViewportHeight()}),this.scrollListenerAttached=!0}build(J){let{todos:Q,enabled:Z,controller:X,appTheme:Y}=this.widget.props;return new n6({crossAxisAlignment:"stretch",children:[new e6({child:new OX({controller:X,autofocus:!1,child:new o40({todos:Q,enabled:Z})})}),new BU({controller:X,thumbColor:Y.app.scrollbarThumb,trackColor:Y.app.scrollbarTrack,getScrollInfo:()=>{let{maxScrollExtent:K,offset:G}=X,q=this.viewportHeight,z=K+q;return{totalContentHeight:Math.max(z,0),viewportHeight:Math.max(q,1),scrollOffset:Math.max(G,0)}}})]})}updateViewportHeight(){let J=this.getViewportHeight();if(J!==this.viewportHeight)this.viewportHeight=J}getViewportHeight(){let J=this.context.findRenderObject();if(!J)return this.viewportHeight;let Q=(X,Y=0)=>{if(X&&"size"in X&&"children"in X){let K=X.children||[];for(let G of K){if(G&&"size"in G){let z=G.size;if(typeof z?.height==="number"&&z.height>0)return z.height}let q=Q(G,Y+1);if(q>0)return q}}return 0},Z=Q(J);if(Z>0)return Z;if("size"in J){let X=J.size;if(typeof X?.height==="number"&&X.height>0)return X.height}return this.viewportHeight}}class HY8 extends M6{props;constructor(J){super();this.props=J}build(J){return new D9({child:new U0({height:1}),cursor:H5.NS_RESIZE,onDrag:(Q)=>{if(this.props.userHeight===void 0){let X=J.findRenderObject()?.size.height??0;if(X>0){this.props.onInitializeHeight(X);return}}this.props.onDrag(Q)},onRelease:this.props.onRelease})}}function Ia4(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 P1.index(Z[X])}B80();if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){Kz.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
7643
- `)}var s50=r50.join(Bf0||r50.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function Ca4(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 tH(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")Pz("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new s9("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${F8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")Pz("experimental.agentMode",Q.agentMode)}async function t50(J){try{await Pa4(r50.dirname(s50),{recursive:!0}),await ja4(s50,J,"utf-8")}catch(Q){p.debug("Failed to save last thread ID",Q)}}async function Sa4(){try{return(await MY8(s50,"utf-8")).trim()}catch(J){return null}}var BY8=[{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??sq,description:`Custom settings file path (overrides the default location ${sq})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(p).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${H60})`},{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:g2(),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:xE}],DY8=(J)=>("deprecated"in J)&&J.deprecated===!0,ka4=(J)=>("hidden"in J)&&J.hidden===!0,va4=(J)=>("default"in J),_a4=(J)=>("default"in J)?J.default:void 0;function xa4(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 s9(rq.unknownCommand(Z),1,G)}}var NY8=null;function qa7(){return NY8}function DB1(J){return{...J,getThreadEnvironment:aU1,vfs:up0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new da(J.fileSystem),generateThreadTitle:N18,deleteThread:(Q)=>J.threadService.delete(Q)}}var e50=A0.file(Ta4.homedir()),LY8=process.env.XDG_CONFIG_HOME?A0.file(process.env.XDG_CONFIG_HOME):d0.joinPath(e50,".config");async function eH(J,Q){Qu0("0.0.1762561694-g1226c3");let Z=St1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:e1.of([A0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:e50,userConfigDir:LY8}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (FB1(),UB1));X(Z);let Y=await Z.getLatest();p.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let K=new yE({configService:Z}),G=new Map,q=()=>G.clear(),z=new K10(Z,J.settings.getWorkspaceRootPath()),W=me6({configService:Z,toolServices:K,trustStore:z,createOAuthProvider:async(j)=>{let C=G.get(j);if(C)return p.debug("Reusing existing OAuth provider for server",{serverName:j}),C;p.debug("Creating OAuth provider for server",{serverName:j});let x=(async()=>{let y=new aE(J.secrets),P=await y.getClientInfo(j),v=new de1({storage:y,serverName:j,clientId:P?.clientId,clientSecret:P?.clientSecret,scopes:P?.scopes});return p.debug("OAuth provider created",{serverName:j,hasManualClientId:!!P?.clientId,willUseDCR:!P?.clientId}),v})();return G.set(j,x),x}}),U=Ot1(K,r4,Mr).catch((j)=>{p.warn("Toolbox registration failed, continuing anyway:",{error:j})}),F=W.initialized.catch((j)=>{p.warn("MCP service initialization failed, continuing anyway:",{error:j})}),H=Promise.all([F,U]).then(()=>{});if(Q.jetbrains)TT("JetBrains");else if(Q.ide&&N58())TT("VS Code");else if(Q.ide&&L58())TT("Neovim");if(J.executeMode)Zu0(!0);let B,V=P2.status.pipe(m0((j)=>Boolean(j.connected&&j.authenticated)),P8()).subscribe((j)=>{if(j){if(!B)B=K.registerTool(Fk)}else B?.dispose(),B=void 0}),M;if(!J.executeMode)M=new YF1(process.cwd(),{},!0);else M=new class extends YF1{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(j5.write(`No API key found. Starting login flow...
7643
+ `)}var s50=r50.join(Bf0||r50.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function Ca4(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 tH(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")Pz("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new s9("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${F8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")Pz("experimental.agentMode",Q.agentMode)}async function t50(J){try{await Pa4(r50.dirname(s50),{recursive:!0}),await ja4(s50,J,"utf-8")}catch(Q){p.debug("Failed to save last thread ID",Q)}}async function Sa4(){try{return(await MY8(s50,"utf-8")).trim()}catch(J){return null}}var BY8=[{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??sq,description:`Custom settings file path (overrides the default location ${sq})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(p).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${H60})`},{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:g2(),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:xE}],DY8=(J)=>("deprecated"in J)&&J.deprecated===!0,ka4=(J)=>("hidden"in J)&&J.hidden===!0,va4=(J)=>("default"in J),_a4=(J)=>("default"in J)?J.default:void 0;function xa4(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 s9(rq.unknownCommand(Z),1,G)}}var NY8=null;function qa7(){return NY8}function DB1(J){return{...J,getThreadEnvironment:aU1,vfs:up0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new da(J.fileSystem),generateThreadTitle:N18,deleteThread:(Q)=>J.threadService.delete(Q)}}var e50=A0.file(Ta4.homedir()),LY8=process.env.XDG_CONFIG_HOME?A0.file(process.env.XDG_CONFIG_HOME):d0.joinPath(e50,".config");async function eH(J,Q){Qu0("0.0.1762574482-gae4ec1");let Z=St1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:e1.of([A0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:e50,userConfigDir:LY8}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (FB1(),UB1));X(Z);let Y=await Z.getLatest();p.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let K=new yE({configService:Z}),G=new Map,q=()=>G.clear(),z=new K10(Z,J.settings.getWorkspaceRootPath()),W=me6({configService:Z,toolServices:K,trustStore:z,createOAuthProvider:async(j)=>{let C=G.get(j);if(C)return p.debug("Reusing existing OAuth provider for server",{serverName:j}),C;p.debug("Creating OAuth provider for server",{serverName:j});let x=(async()=>{let y=new aE(J.secrets),P=await y.getClientInfo(j),v=new de1({storage:y,serverName:j,clientId:P?.clientId,clientSecret:P?.clientSecret,scopes:P?.scopes});return p.debug("OAuth provider created",{serverName:j,hasManualClientId:!!P?.clientId,willUseDCR:!P?.clientId}),v})();return G.set(j,x),x}}),U=Ot1(K,r4,Mr).catch((j)=>{p.warn("Toolbox registration failed, continuing anyway:",{error:j})}),F=W.initialized.catch((j)=>{p.warn("MCP service initialization failed, continuing anyway:",{error:j})}),H=Promise.all([F,U]).then(()=>{});if(Q.jetbrains)TT("JetBrains");else if(Q.ide&&N58())TT("VS Code");else if(Q.ide&&L58())TT("Neovim");if(J.executeMode)Zu0(!0);let B,V=P2.status.pipe(m0((j)=>Boolean(j.connected&&j.authenticated)),P8()).subscribe((j)=>{if(j){if(!B)B=K.registerTool(Fk)}else B?.dispose(),B=void 0}),M;if(!J.executeMode)M=new YF1(process.cwd(),{},!0);else M=new class extends YF1{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(j5.write(`No API key found. Starting login flow...
7644
7644
  `),!await ya4(J))await zP(),process.exit(1)}let N=await z18({isDevelopment:!1}),L=new D10(N,Z),A=new F10(N,{lazy:!0}),w=new G10(L,(j,C)=>{let x=iJ.get(j);if(x)x.handle(C).catch((y)=>{p.error("Failed to apply artifact delta",y)})}),O=Q.notifications!==void 0?Q.notifications:!J.executeMode,$=A18({playNotificationSound:async(j)=>{if(O){L18(j);let C=F80(),x=H80();if((!C||x)&&Y.settings["notifications.system.enabled"]!==!1){if(j==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(j==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:L,configService:Z});p.info("Starting Amp background services");let I=V18({threadService:L,threadHistoryService:A,configService:Z,isExtensionDevelopment:!1}),R;P2.status.subscribe((j)=>{R=j});let E={codebaseContextService:new Dw1({workspaceRoots:[A0.file(process.cwd())],getCurrentFile:()=>{if(!R?.openFile)return;try{return A0.parse(R.openFile)}catch(j){p.warn("Failed to parse current file URI",{uri:R.openFile,error:j});return}},getOpenFiles:()=>{if(!R?.visibleFiles?.length)return[];let j=R.openFile;return R.visibleFiles.filter((C)=>C!==j).map((C)=>{try{return A0.parse(C)}catch(x){return p.warn("Failed to parse visible file URI",{uri:C,error:x}),null}}).filter((C)=>C!==null)}}),configService:Z,toolServices:K,mcpService:W,trustStore:z,threadService:L,threadHistoryService:A,threadSyncService:I,planFileManager:w,threadStorage:N,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:M,notificationService:$,backgroundInit:H,fileSystem:Q.jetbrains||Q.ide?Z18:r4};return{...E,async asyncDispose(){await E.mcpService.dispose(),q(),await E.threadService.asyncDispose(),E.configService.unsubscribe(),E.toolServices.dispose(),E.fuzzyServer.dispose(),E.threadSyncService.dispose(),E.settingsStorage[Symbol.dispose](),V.unsubscribe(),B?.dispose()}}}async function ya4(J){if(!J.executeMode){if(!await h60("Would you like to log in to Amp? [(y)es, (n)o]: "))return j5.write(`Login cancelled. Run the command again to retry.
7645
7645
  `),!1}return await AY8(J)}async function AY8(J){let Q=Ea4(32).toString("hex"),Z=await f60(J.ampURL,Q),X=new AbortController;try{await _X(Z,X.signal)}catch(K){p.error("Error opening browser",{error:K})}let Y=await f60(J.ampURL,Q,!1);j5.write(`If your browser does not open automatically, visit:
7646
7646
 
@@ -7650,13 +7650,13 @@ ${F8.blue.bold(Y)}
7650
7650
  Login successful! You can now use the Amp CLI.
7651
7651
  `),!0}catch(K){return p.error("Login failed",{error:K}),Kz.write(`
7652
7652
  Login failed: ${K instanceof Error?K.message:String(K)}
7653
- `),!1}}function ba4(){let J=new sE().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)Ay(),process.exit(0);let F=U.originalError??U;D48(F)}),J.option("-V, --version","output the version number",()=>{j5.write(`0.0.1762561694-g1226c3 (released 2025-11-08T00:33:30.534Z)
7653
+ `),!1}}function ba4(){let J=new sE().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)Ay(),process.exit(0);let F=U.originalError??U;D48(F)}),J.option("-V, --version","output the version number",()=>{j5.write(`0.0.1762574482-gae4ec1 (released 2025-11-08T04:06:51.131Z)
7654
7654
  `),process.exit(0)}),J.addHelpText("after",D58()),J.configureHelp({formatHelp:V58}),J.command("logout").description("Log out by removing stored API key").action(async(U,F)=>{let H=F.optsWithGlobals(),B=await cY(H);await ua4(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(U,F)=>{let H=F.optsWithGlobals(),B=await cY(H);await ga4(B,await P60(H,B.settings))});let Q=async(U,F,H)=>{St1({storage:F.settings,secretStorage:F.secrets,workspaceRoots:e1.of([A0.file(process.cwd())]),defaultAmpURL:F.ampURL,homeDir:e50,userConfigDir:LY8});let B={...F,executeMode:!1};await o50(B,{...U,openThreadSwitcher:!0},H)},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,F)=>{let H=F.optsWithGlobals(),B=await cY(H);await VY8(H,B,F)});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,F)=>{let H=F.optsWithGlobals(),B=await cY(H);await ia4(H,B,F)}),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,F,H)=>{let B=H.optsWithGlobals(),V=await cY(B);if(F.pick)Kz.write(`${F8.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
7655
7655
  `);if(F.last||U||V.executeMode)await la4(B,V,U,H);else await Q(B,V,H)}),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,F,H)=>{let B=H.optsWithGlobals(),V=await cY(B);await ca4(B,V,U,H)}),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,F)=>{let H=F.optsWithGlobals(),B=await cY(H);await VY8(H,B,F)}),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(U,F,H)=>{let B=H.optsWithGlobals(),V=await cY(B);await da4(B,V,U,H,F.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,F,H,B)=>{let V=B.optsWithGlobals(),M=await cY(V);await ma4(V,M,U,F,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(U,F,H)=>{let B=H.optsWithGlobals(),V=await cY(B);await pa4(B,V,U,H)}),R78(J,async(U,F)=>{let H=await cY(F);tH(U,F);let B=await eH(H,F);return{context:H,mcpService:B.mcpService,toolService:B.toolServices,toolServices:B.toolServices,configService:B.configService,cleanupTerminal:Ay,asyncDispose:B.asyncDispose.bind(B)}}),o58(J,async(U)=>{let F=U.optsWithGlobals();return await cY(F)}),m58(J,async(U)=>{let F=await cY(U);return{settings:F.settings,secretStorage:F.secrets,getThreadDeps:async(H)=>{tH(H,U);let B=await eH(F,U);return{mcpService:B.mcpService,settings:F.settings,asyncDispose:B.asyncDispose.bind(B)}}}});function Y(U,F,H){let V=typeof U.description==="string"?U.description:H===void 0?U.description(!0):U.description(H),M=new mA(F,V),N=_a4(U);if(N)M.default(N);if(M.hidden=ka4(U)||DY8(U),"choices"in U)M.choices([...U.choices]);return M}for(let U of BY8)switch(U.type){case"flag":{J.addOption(Y(U,`--${U.long}`)),J.addOption(Y(U,`--no-${U.long}`,!1));break}case"switch":{J.addOption(Y(U,`--${U.long}`,!0));break}default:{J.addOption(Y(U,`--${U.long} <value>`));break}}let K=new mA("-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 G=new mA("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(G);let q=new mA("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1);J.addOption(q);let z=new mA("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(z);let W=new mA("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(W),process.env.AMP_CONNECT==="1"){let U=new mA("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(U)}return J.action(async(U,F)=>{let H=U,B=await cY(H);if(Object.keys(H).forEach((V)=>{let M=BY8.find((N)=>N.name===V);if(M&&DY8(M)&&!va4(M))Kz.write(F8.yellow(`Warning: '--${V}' flag is deprecated
7656
7656
  `))}),F.args.length>0)xa4(B,F);await o50(B,H,F)}),_58(J),J}async function BB1(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??vz(),K=DB1(J);if(Z)await J.threadStorage.set(Y,Z);let G=await iJ.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,DF1(X));let q=J.threadService.observe(Y).subscribe(async(z)=>{if(ZQ(z,"assistant"))await t50(Y),q.unsubscribe()});return await G.resume(),G}async function o50(J,Q,Z){let X=BF1(Q);if(X instanceof Error)Yz(X.message);let Y,K=null;if(Q.streamJsonInput)Y="";else if(typeof Q.execute==="string"){Y=Q.execute;let E=(await m60()).trimEnd();if(E)K=E}else Y=(await m60()).trimEnd();if(Q.remote&&!J.executeMode)throw new s9("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new s9("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new s9("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new s9("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 s9(`Execute mode is not permitted with --agent-mode '${Q.agentMode}'`,1);if(Q.stats&&!J.executeMode)throw new s9("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 s9("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 s9("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"
7657
7657
  Or pipe via stdin: echo "your message" | amp --execute`);tH(Z,Q);let G=await eH(J,Q);if(J.executeMode||Q.threadId)await G.backgroundInit;NY8=G;let q=DB1(G),z=async(E)=>{let j=await MY8(E,"utf-8"),C=JSON.parse(j);if(!_z(C.id))throw new s9(rq.invalidThreadId);return BB1(G,{visibility:X,thread:C})},W=async(E)=>{if(!_z(E))throw new s9(rq.invalidThreadId);let j=await G.threadService.get(E)??void 0;if(p.info(`[fetchAndStartThread] Loaded thread ${E}, agentMode: ${j?.agentMode??"undefined"}`),j?.agentMode)p.info(`[fetchAndStartThread] Setting runtime override for agentMode to: ${j.agentMode}`),Pz("experimental.agentMode",j.agentMode);else p.info("[fetchAndStartThread] No agentMode on thread, not setting override");return BB1(G,{visibility:X,thread:j})},U=async()=>{try{if(Q.threadId)return W(Q.threadId);else return BB1(G,{visibility:X})}catch(E){if(E instanceof s9)throw E;throw await rU1(E,Q.threadId),Error("handleError should have called process.exit()")}},F=async()=>{return BB1(G,{visibility:X})};if(Q.format==="jsonl")Kz.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
7658
- `),await zP(),process.exit(1);if(J.executeMode&&Q.remote)await t58(Y,K,G.configService),await G.asyncDispose(),process.exit(0);let H=await U();if(J.executeMode)c58(G.mcpService,J.settings),await j48(H,H.threadID,Y,K,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let B=!1,V=!1;if(Q.jetbrains||Q.ide){await UJ6();let E=Uk({jetbrainsOnly:Q.jetbrains});if(E.length===0){if(Q.jetbrains)V=!await G.configService.get("jetbrains.skipInstall")}else if(E.length===1){let j=E[0];if(j)P2.selectConfig(j)}else B=!0}let M=b60("0.0.1762561694-g1226c3",G.settingsStorage),N=new U10(G.threadStorage),L=e1.of([A0.file(process.cwd())]),A=Kh0(void 0,L),w=new g60(G.mcpService,J.settings.getWorkspaceRootPath());if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let O=(async()=>{try{let E=await S7.getUserFreeTierStatus({},{config:G.configService,signal:AbortSignal.timeout(5000)});if(E.ok)return p.info("User free tier status:",E),E.result}catch(E){p.error("Failed to fetch free tier status:",E)}})(),$=(async()=>{try{let E=await S7.getUserInfo({},{config:G.configService});if(E.ok)return E.result}catch(E){p.debug("Failed to fetch user workspace info:",E)}})(),[I,R]=await Promise.all([O,$]),T=await Z78();p.info("Loaded session state:",T),await WY8({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new N60,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadHistoryService:G.threadHistoryService,threadSyncService:G.threadSyncService,planFileManager:G.planFileManager,threadID:H.threadID,threadFuzzyIndexer:N,worker:H,workerDeps:q,configService:G.configService,internalAPIClient:S7,ampURL:J.ampURL,startNewThread:F,pickAndContinueThread:async()=>{p.info("Thread picker requested - not yet implemented in TUI")},switchToThread:W,ideClient:P2,connectedClientsService:new _t1,commandRegistry:A,mcpTrustHandler:w,showJetBrainsInstaller:V,showIdePicker:B,openThreadSwitcher:Q.openThreadSwitcher,updateService:M,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:T,freeTierStatus:I,workspace:R?.team??null,features:R?.features??[],threadDependencies:G}),await G.asyncDispose(),process.exit(0)}async function cY(J){if(J.interactive)Kz.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7659
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await t48({...J,workspaceTrust:{current:!0,changes:Uh},getHook:process.env.AMP_URL?(K,G)=>{if(K==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let K=await p58(J.mcpConfig);X=d58(X,K)}let Y=await X.get("url","global");if(!Y)Y=xX;if(!qM(Y))p.info("Targeting custom Amp server",{ampURL:Y});return X=Dh0(X),{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:e58(await P60(J,X))}}function fa4(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 ha4(){let J=fa4(process.argv);if(K48({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),Ca4(p),p.info("Starting Amp CLI.",{version:"0.0.1762561694-g1226c3",buildTimestamp:"2025-11-08T00:33:30.534Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new s9(rq.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await ba4().parseAsync(process.argv)}Go1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await ha4().catch(rU1)});async function ga4(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),j5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7658
+ `),await zP(),process.exit(1);if(J.executeMode&&Q.remote)await t58(Y,K,G.configService),await G.asyncDispose(),process.exit(0);let H=await U();if(J.executeMode)c58(G.mcpService,J.settings),await j48(H,H.threadID,Y,K,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let B=!1,V=!1;if(Q.jetbrains||Q.ide){await UJ6();let E=Uk({jetbrainsOnly:Q.jetbrains});if(E.length===0){if(Q.jetbrains)V=!await G.configService.get("jetbrains.skipInstall")}else if(E.length===1){let j=E[0];if(j)P2.selectConfig(j)}else B=!0}let M=b60("0.0.1762574482-gae4ec1",G.settingsStorage),N=new U10(G.threadStorage),L=e1.of([A0.file(process.cwd())]),A=Kh0(void 0,L),w=new g60(G.mcpService,J.settings.getWorkspaceRootPath());if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let O=(async()=>{try{let E=await S7.getUserFreeTierStatus({},{config:G.configService,signal:AbortSignal.timeout(5000)});if(E.ok)return p.info("User free tier status:",E),E.result}catch(E){p.error("Failed to fetch free tier status:",E)}})(),$=(async()=>{try{let E=await S7.getUserInfo({},{config:G.configService});if(E.ok)return E.result}catch(E){p.debug("Failed to fetch user workspace info:",E)}})(),[I,R]=await Promise.all([O,$]),T=await Z78();p.info("Loaded session state:",T),await WY8({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new N60,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadHistoryService:G.threadHistoryService,threadSyncService:G.threadSyncService,planFileManager:G.planFileManager,threadID:H.threadID,threadFuzzyIndexer:N,worker:H,workerDeps:q,configService:G.configService,internalAPIClient:S7,ampURL:J.ampURL,startNewThread:F,pickAndContinueThread:async()=>{p.info("Thread picker requested - not yet implemented in TUI")},switchToThread:W,ideClient:P2,connectedClientsService:new _t1,commandRegistry:A,mcpTrustHandler:w,showJetBrainsInstaller:V,showIdePicker:B,openThreadSwitcher:Q.openThreadSwitcher,updateService:M,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:T,freeTierStatus:I,workspace:R?.team??null,features:R?.features??[],threadDependencies:G}),await G.asyncDispose(),process.exit(0)}async function cY(J){if(J.interactive)Kz.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7659
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await t48({...J,workspaceTrust:{current:!0,changes:Uh},getHook:process.env.AMP_URL?(K,G)=>{if(K==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let K=await p58(J.mcpConfig);X=d58(X,K)}let Y=await X.get("url","global");if(!Y)Y=xX;if(!qM(Y))p.info("Targeting custom Amp server",{ampURL:Y});return X=Dh0(X),{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:e58(await P60(J,X))}}function fa4(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 ha4(){let J=fa4(process.argv);if(K48({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),Ca4(p),p.info("Starting Amp CLI.",{version:"0.0.1762574482-gae4ec1",buildTimestamp:"2025-11-08T04:06:51.131Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new s9(rq.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await ba4().parseAsync(process.argv)}Go1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await ha4().catch(rU1)});async function ga4(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),j5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7660
7660
  `);else if(!qM(J.ampURL))j5.write(`Logging in to ${new URL(J.ampURL).hostname}
7661
7661
  `);let Z=process.env.AMP_API_KEY;if(Z)j5.write(`API key found in environment variable, storing...
7662
7662
  `),await Q.set("apiKey",Z,J.ampURL),j5.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1762561694-g1226c3",
3
+ "version": "0.0.1762574482-gae4ec1",
4
4
  "description": "CLI for Amp, the frontier coding agent from Sourcegraph.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {