@sourcegraph/amp 0.0.1774897010-g0ac150 → 0.0.1774901365-g0ac150

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
@@ -6200,11 +6200,11 @@ ${H}`))}},error:(U)=>{if(!W)W=!0,G(Error(`Failed to spawn brew: ${U.message}`))}
6200
6200
  ${H}`;if(X==="pnpm"&&H.includes("Unable to find the global bin directory"))D+=`
6201
6201
 
6202
6202
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
6203
- npm install -g @sourcegraph/amp`;G(Error(D))}},error:(U)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}m0();m0();gM();async function uY0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let G=await fetch(X,{signal:K.signal});if(!G.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let z=await G.json(),F=z.version??z["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=MP4(J,F),W=q<0,U,H;if(z.time){let D=z.time[J],B=z.time[F],N=Date.now();if(D)U=Math.floor((N-new Date(D).getTime())/3600000);if(B)H=Math.floor((N-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:U,latestVersionAge:H}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:U,latestVersionAge:H,source:"npm"}}catch(G){return P.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var eZ3="https://static.ampcode.com/cli/cli-version.txt";async function bY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${eZ3}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let K=MP4(J,X),V=K<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return P.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var $Q3=604800000;function EP4(J){if(!J)return null;let Z=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Z))return null;let Q=Date.now()-Z;if(Q>$Q3)return{ageMs:Q};return null}function MP4(J,Z){let Q=(V)=>{let[G,z]=V.split("-");return{parts:G?.split(".").map(Number)||[],label:z}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let G=Y.parts[V]||0,z=X.parts[V]||0;if(G<z)return-1;if(G>z)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function ma0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?MF(Q):void 0;return{sha:Y,age:X}}catch{return null}}O1();function pa0(J,Z,Q={}){let Y=new Y4,X=Y.pipe(d6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new Tz().scoped("update"),V=Q.startDelayMs??0;if(V>0)await JF(V);let G=X.subscribe({next:(z)=>{K.debug("emit new state",z)}});try{let z=process.env.AMP_TEST_UPDATE_STATUS;if(z){K.debug("using fake update status for testing",{status:z}),await JF(500),Y.next(z);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){K.debug("checking disabled");return}let q=await fY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await bY0(J):await uY0(J,Oj());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let H=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let D=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(D)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:D}),!0}return!1};if(!F)F=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:F});if(q==="brew"){if(!H())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==xa0()){if(K.debug("non-standard binary path, showing warning"),!H())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!H())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Y.next("update-available");return}try{await Ti(U.latestVersion,q);let D=await ww(U.latestVersion),B={from:U.currentVersion,to:U.latestVersion,...D};if(D.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(D){Y.next("update-error")}}catch(z){K.debug("check failed",{error:z})}finally{await JF(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}gM();import{stderr as SG}from"node:process";function AP4(J){let Z=new uN().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(Y)=>{await Sa0(Y.force||!1,Y.verbose||!1,"0.0.1774897010-g0ac150"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new uN("update").alias("up").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("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await JQ3(Y.targetVersion)});J.addCommand(Q)}async function JQ3(J){let Z=process.platform==="win32"&&xY0(),Q=Z?{currentExecutablePath:process.execPath}:void 0;if(process.env.AMP_SKIP_UPDATE_CHECK==="1")SG.write(o0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6203
+ npm install -g @sourcegraph/amp`;G(Error(D))}},error:(U)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}m0();m0();gM();async function uY0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let G=await fetch(X,{signal:K.signal});if(!G.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let z=await G.json(),F=z.version??z["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=MP4(J,F),W=q<0,U,H;if(z.time){let D=z.time[J],B=z.time[F],N=Date.now();if(D)U=Math.floor((N-new Date(D).getTime())/3600000);if(B)H=Math.floor((N-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:U,latestVersionAge:H}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:U,latestVersionAge:H,source:"npm"}}catch(G){return P.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var eZ3="https://static.ampcode.com/cli/cli-version.txt";async function bY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${eZ3}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let K=MP4(J,X),V=K<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return P.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var $Q3=604800000;function EP4(J){if(!J)return null;let Z=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Z))return null;let Q=Date.now()-Z;if(Q>$Q3)return{ageMs:Q};return null}function MP4(J,Z){let Q=(V)=>{let[G,z]=V.split("-");return{parts:G?.split(".").map(Number)||[],label:z}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let G=Y.parts[V]||0,z=X.parts[V]||0;if(G<z)return-1;if(G>z)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function ma0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?MF(Q):void 0;return{sha:Y,age:X}}catch{return null}}O1();function pa0(J,Z,Q={}){let Y=new Y4,X=Y.pipe(d6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new Tz().scoped("update"),V=Q.startDelayMs??0;if(V>0)await JF(V);let G=X.subscribe({next:(z)=>{K.debug("emit new state",z)}});try{let z=process.env.AMP_TEST_UPDATE_STATUS;if(z){K.debug("using fake update status for testing",{status:z}),await JF(500),Y.next(z);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){K.debug("checking disabled");return}let q=await fY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await bY0(J):await uY0(J,Oj());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let H=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let D=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(D)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:D}),!0}return!1};if(!F)F=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:F});if(q==="brew"){if(!H())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==xa0()){if(K.debug("non-standard binary path, showing warning"),!H())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!H())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Y.next("update-available");return}try{await Ti(U.latestVersion,q);let D=await ww(U.latestVersion),B={from:U.currentVersion,to:U.latestVersion,...D};if(D.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(D){Y.next("update-error")}}catch(z){K.debug("check failed",{error:z})}finally{await JF(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}gM();import{stderr as SG}from"node:process";function AP4(J){let Z=new uN().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(Y)=>{await Sa0(Y.force||!1,Y.verbose||!1,"0.0.1774901365-g0ac150"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new uN("update").alias("up").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("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await JQ3(Y.targetVersion)});J.addCommand(Q)}async function JQ3(J){let Z=process.platform==="win32"&&xY0(),Q=Z?{currentExecutablePath:process.execPath}:void 0;if(process.env.AMP_SKIP_UPDATE_CHECK==="1")SG.write(o0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6204
6204
 
6205
6205
  `));try{if(!J){SG.write(o0.blue(`Checking for updates...
6206
- `));let{hasUpdate:K,latestVersion:V}=xY0()?await bY0("0.0.1774897010-g0ac150"):await uY0("0.0.1774897010-g0ac150",Oj());if(!K){let G=ma0("0.0.1774897010-g0ac150"),z=G?.age?`released ${G.age} ago`:`built ${MF(new Date("2026-03-30T19:00:10.483Z"))} ago`;SG.write(o0.green(`✓ Amp is already up to date on version ${"0.0.1774897010-g0ac150"} (${z})
6207
- `));let F=await ww("0.0.1774897010-g0ac150",Q);if(F.warning)SG.write(`
6206
+ `));let{hasUpdate:K,latestVersion:V}=xY0()?await bY0("0.0.1774901365-g0ac150"):await uY0("0.0.1774901365-g0ac150",Oj());if(!K){let G=ma0("0.0.1774901365-g0ac150"),z=G?.age?`released ${G.age} ago`:`built ${MF(new Date("2026-03-30T20:13:20.449Z"))} ago`;SG.write(o0.green(`✓ Amp is already up to date on version ${"0.0.1774901365-g0ac150"} (${z})
6207
+ `));let F=await ww("0.0.1774901365-g0ac150",Q);if(F.warning)SG.write(`
6208
6208
  `+o0.yellow(F.warning)+`
6209
6209
  `);process.exit(0)}if(!V)SG.write(o0.yellow("[WARN] could not find latest version")),process.exit(0);J=V}SG.write(o0.blue(`Updating to version ${J}...
6210
6210
  `)),await Ti(J,void 0,(K)=>{SG.write(o0.dim(`Running: ${K}
@@ -7376,7 +7376,7 @@ Ctrl-X, Y, Z to unlock`;if(U){let f=F.text.replace(/`([^`]+)`/g,"$1")+`
7376
7376
  `),K=[];for(let V=0;V<X.length;V++){let F=X[V].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let q of F)if(q.startsWith("\x00")&&q.endsWith("\x01"))K.push(new C(q.slice(1,-1),new g({color:Y.app.keybind,bold:!0})));else K.push(new C(q,new g({color:Q.colorScheme.foreground})));if(V<X.length-1)K.push(new C(`
7377
7377
  `))}return new d0({decoration:{color:Q.colorScheme.background,border:c1.all(new g1(Y.app.keybind,1,"rounded"))},child:new n0({padding:C0.symmetric(0,1),child:new e({text:new C(void 0,void 0,K)})})})}}class K01 extends x${chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=RG0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new Y01({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(J){let Z=J;Z.chartData=this.chartData,Z.highlightIndex=this.highlightIndex,Z.showAxes=this.showAxes,Z.colors=this.colors,Z.markNeedsLayout()}}function Ah4(J,Z,Q,Y,X,K,V){if(K<=0)return null;switch(J){case"horizontal-bar":{let G=Q;return G>=0&&G<K?G:null}case"bar":case"stacked-bar":{let G=V?v9:0,z=Y-G;if(z<=0)return null;let F=Z-G;if(F<0||F>=z)return null;let q=Math.max(1,Math.floor(z/K)),W=Math.floor(F/q);return W>=0&&W<K?W:null}case"line":case"sparkline":case"stacked-area":{let G=V?v9:0,z=Y-G;if(z<=0)return null;let F=Math.max(0,Math.min(z-1,Z-G));if(K===1)return 0;let q=z/(K-1),W=Math.round(F/q);return Math.max(0,Math.min(K-1,W))}default:return null}}function nR3(J,Z,Q,Y,X,K,V,G){if(X<=0||Z<0||Z>=X)return null;let z=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let F=K?v9:0,q=Q-F,W=Y-(K?z:0);if(q<=0||W<=0)return null;let U=Math.max(1,Math.floor(q/X)),H=F+Z*U+Math.floor(U/2),D=G>0?V/G:0,B=Math.round((1-D)*(W-1));return{x:H,y:B}}case"line":case"sparkline":case"stacked-area":{let F=K?v9:0,q=Q-F,W=Y-(K?z:0);if(q<=0||W<=0)return null;let U=X>1?F+Math.round(Z/(X-1)*(q-1)):F+Math.floor(q/2),H=G>0?V/G:0,D=Math.round((1-H)*(W-1));return{x:U,y:D}}default:return null}}function aR3(J){let Z=0;for(let Q of J)for(let Y of Q.points)if(Y.value>Z)Z=Y.value;return Z||1}function oR3(J,Z,Q,Y,X){if(Q.length<=1){let G=Y(J.value),z=J.meta?` (${J.meta})`:"";return J.label.length+2+G.length+z.length}let K=J.label.length,V=0;for(let G of Q){let z=G.points[Z];if(!z)continue;V+=z.value;let F=2+G.name.length+2+Y(z.value).length;K=Math.max(K,F)}if(X){let G=9+Y(V).length;K=Math.max(K,G)}return K}function rR3(J,Z,Q,Y,X,K,V){let G;try{let D=x1.of(J),B=f0.of(J);G={foreground:D.colorScheme.foreground,background:D.colorScheme.background,border:B.app.keybind}}catch{G={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let z=new g({color:G.foreground,bold:!0}),F=new g({color:G.foreground}),q=new g({color:G.foreground,dim:!0}),W=[],U=new g({color:G.foreground,underline:!0}),H=(D,B)=>new C(B,U,void 0,nY0(D),()=>{u3(J,D)});if(Y.length<=1){if(W.push(new C(`${Z.label}: `,z)),Z.link)W.push(H(Z.link,K(Z.value)));else W.push(new C(K(Z.value),F));if(Z.meta)W.push(new C(` (${Z.meta})`,q))}else{let D=V==="stacked-bar"||V==="stacked-area";W.push(new C(`${Z.label}
7378
7378
  `,z));let B=0;for(let N=0;N<Y.length;N++){let w=Y[N],L=w.points[Q];if(!L)continue;B+=L.value;let O=w.color??X[N%X.length]??G.foreground;if(W.push(new C("● ",new g({color:O}))),W.push(new C(`${w.name}: `,q)),L.link)W.push(H(L.link,K(L.value)));else W.push(new C(K(L.value),F));if(N<Y.length-1||D)W.push(new C(`
7379
- `))}if(D)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),F))}return new d0({decoration:{color:G.background,border:c1.all(new g1(G.border,1,"rounded"))},child:new e({text:new C(void 0,void 0,W)})})}tO();m0();_7();YE();N$();y3();_2();Nd();CX();O$();rJ();ZQ();wA();d4();ug();SP();O1();m0();O$();class V01{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Z){this.enabled=J;this.configService=Z;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(([Z,Q])=>({feature:"cli.command",action:Z,source:{client:"cli",clientVersion:"0.0.1774897010-g0ac150"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await H40(Z,this.configService)}catch(Z){P.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class VL extends l0{props;constructor(J){super();this.props=J}createState(){return new jh4}}class jh4 extends p0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class Rh4 extends p0{controller=new r7;focusNode=new z6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=c1.all(new g1(Q.foreground,1,"solid")),z=new IZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(H)=>{let D=H.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new W1({children:[new d0({decoration:{color:Q.background},child:new e({text:new C(">",new g({color:Q.foreground}))})}),new y1({child:z})]}),q=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new C("Enter",new g({color:Y.keybind}))),W.push(new C(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new C("Esc",new g({color:Y.keybind}))),W.push(new C(" to cancel",new g({color:Q.foreground,dim:!0})));let U=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,W)})});return new d0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new R0({height:1}),F,new f3,U]})})}}class Ma extends l0{props;constructor(J){super();this.props=J}createState(){return new Rh4}}ZQ();import{mkdtemp as eR3,readFile as $I3,rmdir as JI3,unlink as ZI3,writeFile as QI3}from"node:fs/promises";import{tmpdir as YI3}from"node:os";import vh4 from"node:path";m0();m0();class Ih4{_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 Z of J)try{Z()}catch(Q){}}dispose(){this._disposed=!0,this._listeners.clear()}get disposed(){return this._disposed}get hasListeners(){return this._listeners.size>0}}class BR extends Ih4{_value;constructor(J){super();this._value=J}get value(){return this._value}set value(J){let Z=typeof J==="object"||this._value!==J;if(this._value=J,Z)this.notifyListeners()}}function Ph4(J,Z){let Q=()=>{Z()};return J.addListener(Q),{dispose:()=>J.removeListener(Q)}}class G01{builder;maintainState;_overlayState;_needsBuild=!0;constructor(J,Z=!1){this.builder=J;this.maintainState=Z}get mounted(){return this._overlayState!==void 0}remove(){if(this._overlayState)this._overlayState.remove(this)}markNeedsBuild(){if(this._needsBuild=!0,this._overlayState)this._overlayState._markNeedsRebuild()}_setOverlayState(J){this._overlayState=J}_needsRebuild(){return this._needsBuild}_clearNeedsRebuild(){this._needsBuild=!1}}class z01 extends n3{link;showWhenUnlinked;offset;constructor({key:J,link:Z,showWhenUnlinked:Q=!0,offset:Y={x:0,y:0},child:X}){super({key:J,child:X});this.link=Z,this.showWhenUnlinked=Q,this.offset=Y}createElement(){return new Bq(this)}createRenderObject(){return new Ch4(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class Ch4 extends u4{_link;_showWhenUnlinked;_followerOffset;_cachedPosition=null;constructor(J,Z,Q){super();this._link=J,this._showWhenUnlinked=Z,this._followerOffset=Q}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(Z6(!!J,"performLayout called without constraints"),!this.shouldShow()){this.setSize(0,0),super.performLayout();return}let Z=this.calculatePosition();if(this._cachedPosition=Z,Z)this.setOffset(Z.x,Z.y);if(this.children.length>0){let Q=this.children[0];Q.layout(J);let Y=Q.size;this.setSize(Y.width,Y.height)}else this.setSize(0,0);super.performLayout()}getCurrentPosition(){return this._cachedPosition}setOffset(J,Z){super.setOffset(J,Z)}paint(J,Z=0,Q=0){super.paint(J,Z,Q)}}m0();var sR3=500;class F01{_state;_textController=null;_lastText="";_triggers=[];_optionsBuilder=null;_onSelected=null;_pendingBuildTimer=null;_disposed=!1;constructor(){let J={trigger:null,options:[],selectedIndex:-1,isActive:!1,generationId:0};this._state=new BR(J)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:J,triggers:Z,optionsBuilder:Q,onSelected:Y}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=J,this._lastText=J.text,this._triggers=Z,this._optionsBuilder=Q,this._onSelected=Y||null,this._textController.addListener(this._handleTextChange)}selectNext(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex<J.options.length-1?J.selectedIndex+1:0;this._updateState({selectedIndex:Z})}selectPrevious(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex>0?J.selectedIndex-1:J.options.length-1;this._updateState({selectedIndex:Z})}acceptSelected(){let J=this.currentState;if(!J.isActive||J.selectedIndex<0||J.selectedIndex>=J.options.length)return;let Z=J.options[J.selectedIndex];if(!Z)return;if(this.dismiss(),this._onSelected)this._onSelected(Z)}dismiss(){this._clearPendingBuildTimer(),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.currentState.trigger,Z=this._textController.text,Q=Z!==this._lastText;if(this._lastText=Z,!Q&&!this.currentState.isActive)return;let Y=this._textController.cursorPosition,X=null;for(let G of this._triggers){let z=G.detect(Z,Y);if(z&&(!X||z.start>X.start))X=z}if(!this.currentState.isActive&&X&&X.query.length>0){let G=f6(Z),z=Y,F=z;while(F<G.length){let q=G[F];if(q&&/[\s)\]}@]/.test(q))break;F++}if(F>z){let W=[...G.slice(0,z),...G.slice(F)].join("");this._textController.text=W,this._textController.cursorPosition=Y;return}}if(!X){if(this.currentState.isActive)this.dismiss();else this._clearPendingBuildTimer();return}let K=Q&&this._shouldDebounceBuild(J,X),V=this.currentState.generationId+1;if(this._updateState({trigger:X,generationId:V,options:K?[]:this.currentState.options,isActive:!K,selectedIndex:-1}),K){this._scheduleDebouncedBuild(X.query,V);return}this._clearPendingBuildTimer(),this._buildOptions(X.query,V)};async _buildOptions(J,Z){if(!this._optionsBuilder)return;try{let Q=await this._optionsBuilder(J);if(this.currentState.generationId===Z&&!this._disposed)this._updateState({options:Q,selectedIndex:Q.length>0?0:-1,isActive:Q.length>0})}catch(Q){if(P.error("Error building autocomplete options:",Q),this.currentState.generationId===Z&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_scheduleDebouncedBuild(J,Z){this._clearPendingBuildTimer(),this._pendingBuildTimer=setTimeout(()=>{this._pendingBuildTimer=null,this._buildOptions(J,Z)},sR3)}_shouldDebounceBuild(J,Z){if(!J)return!1;if(J.trigger!==Z.trigger||J.start!==Z.start)return!1;return Z.query.length<J.query.length}_clearPendingBuildTimer(){if(this._pendingBuildTimer)clearTimeout(this._pendingBuildTimer),this._pendingBuildTimer=null}_updateState(J){if(this._disposed)return;this._state.value={...this.currentState,...J}}_cleanup(){if(this._clearPendingBuildTimer(),this._textController)this._textController.removeListener(this._handleTextChange)}}class Aa{}class ja{}class Ra{}class PG0{}class CG0 extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Th4(this.props)}}class Th4 extends p0{props;controller;stateListener=null;overlayEntry=null;layerLink=new wa;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new z6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new F01,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=Ph4(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.handle)this.props.handle.dismiss=()=>this.controller.dismiss();if(this.props.autofocus??!0)C6.instance.addPostFrameCallback(()=>{this._effectiveFocusNode.requestFocus()})}didUpdateWidget(J){super.didUpdateWidget(J);let Z=J.props,Q=this.widget.props;if(this.props=Q,Z.controller!==Q.controller||Z.triggers!==Q.triggers||Z.optionsBuilder!==Q.optionsBuilder||Z.textFieldProps!==Q.textFieldProps||Z.onSelected!==Q.onSelected)this.controller.initialize({textController:Q.controller,triggers:Q.triggers,optionsBuilder:Q.optionsBuilder,onSelected:Q.onSelected});if(Z.handle!==Q.handle){if(Q.handle)Q.handle.dismiss=()=>this.controller.dismiss()}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 Aa)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof ja)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Ra)return this.controller.acceptSelected(),"handled";if(J instanceof PG0)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let J=this.controller.currentState;if(!J.isActive||J.selectedIndex<0)return;let Z=J.selectedIndex,Q=J.options.length,Y=this._cachedMaxVisibleOptions||Q;if(Y>=Q){this.scrollOffset=0;return}let X=Z-this.scrollOffset,K=1,V=this.scrollOffset;if(X>=Y-K)V=Math.max(0,Z-(Y-K-1));if(X<K)V=Math.max(0,Z-K);let G=Math.max(0,Q-Y);V=Math.min(V,G),this.scrollOffset=V}build(J){let Z=new IZ({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Q=new m$({shortcuts:new Map([[new D4("ArrowDown"),new Aa],[new D4("ArrowUp"),new ja],[new D4("n",{ctrl:!0}),new Aa],[new D4("p",{ctrl:!0}),new ja],[new D4("Enter"),new Ra],[new D4("Escape"),new PG0],[new D4("Tab"),new Ra]]),focusNode:this._effectiveFocusNode,child:Z}),Y=new M7({actions:new Map([[Aa,new D6(this.invoke)],[ja,new D6(this.invoke)],[Ra,new D6(this.invoke)],[PG0,new D6(this.invoke)]]),child:Q});return new Na({link:this.layerLink,child:Y})}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 G01((J)=>{let Z=this.controller.currentState;return this.buildOverlayContent(J,Z)});try{UR.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}buildOverlayHints(J,Z){if(this.props.overlayHint!==void 0){if(this.props.overlayHint===null)return[];let{prefix:Q,suffix:Y}=this.props.overlayHint,X=[];if(Q)X.push(new C(Q,new g({color:f0.of(J).app.command})),new C(" ",new g({color:Z})));return X.push(new C(Y,new g({color:Z}))),[{child:new e({text:new C(" ",new g({dim:!0}),X)}),position:"top",alignment:"center"}]}return[]}buildOverlayContent(J,Z){let Q=x1.maybeOf(J),Y=Q?.colorScheme.background??M0.default(),X=this.props.overlayBorderColor??Q?.colorScheme.border??M0.default(),K=Z.options.length,V=V4.sizeOf(J).height,G=0;try{let R=this.layerLink.getTargetTransform();if(R)G=R.position.y}catch{}let z=this.props.autoOverlayPosition?G<V/3:!1,F=2,q;if(z){let R=this.props.controller.getCursorVisualRow(),_=G+R+1;q=V-_-F}else q=G-F;K=Math.min(K,Math.max(1,q)),this._cachedMaxVisibleOptions=K,this.updateScrollPosition();let W=this.scrollOffset,U=Math.min(Z.options.length,W+K),H=[],D=0;for(let R=W;R<U;R++){let _=Z.options[R];if(!_)continue;let T=R===Z.selectedIndex,u,m;if(this.props.optionViewBuilder){u=this.props.optionViewBuilder(J,_,T);let f=this.props.displayStringForOption?.(_)??String(_),d="",p=f,h=_;if(h&&typeof h==="object"&&"type"in h)switch(h.type){case"file":d="@",p=h.path||f;break;case"artifact":d="",p=h.label||f;break}m=d+p}else{let f=this.props.displayStringForOption?.(_)??String(_),d=Q?.colorScheme.selection??M0.default(),p=Q?.colorScheme.foreground??M0.default();u=new e({text:new C(f,new g({color:p,backgroundColor:T?d:void 0}))}),m=f}let y=V4.of(J),k=x5(m,y.supportsEmojiWidth);D=Math.max(D,k),H.push(u)}let B=V4.sizeOf(J).width,N=D+4,w=Math.floor(B*0.9),L=Math.max(Math.min(N,w),Math.min(30,w)),M=H.length+2,A;if(z)A=this.props.controller.getCursorVisualRow()+1;else A=-M;let j=new R0({width:L,child:new d0({height:M,decoration:new $6(Y),child:new s8({decoration:{border:c1.all(new g1(X,1,"rounded"))},padding:C0.symmetric(1,0),overlays:this.buildOverlayHints(J,X),child:new x0({crossAxisAlignment:"start",children:H})})})});return new z01({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:A},child:j})}}function _h4(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 Sh4(J){switch(J.type){case"file":return J.path;case"hint":return`${tR3(J.kind)} ${J.message}`;case"commit":return`${J.shortHash} ${J.message} (${J.relativeDate})`}}function kh4(J){switch(J.type){case"file":return;case"hint":return;case"commit":return}}function tR3(J){switch(J){case"commit":return"@:";case"thread":return"@@"}}class yq{detect(J,Z){if(!J||Z<1)return null;let Q=f6(J);if(Z>Q.length)return null;let Y=this.findWordStart(Q,Z);if(Y>=Q.length||Q[Y]!=="@")return null;let X=Q.slice(Y+1,Z).join("");if(X.includes(" ")||X.includes("\t")||X.includes(`
7379
+ `))}if(D)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),F))}return new d0({decoration:{color:G.background,border:c1.all(new g1(G.border,1,"rounded"))},child:new e({text:new C(void 0,void 0,W)})})}tO();m0();_7();YE();N$();y3();_2();Nd();CX();O$();rJ();ZQ();wA();d4();ug();SP();O1();m0();O$();class V01{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Z){this.enabled=J;this.configService=Z;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(([Z,Q])=>({feature:"cli.command",action:Z,source:{client:"cli",clientVersion:"0.0.1774901365-g0ac150"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await H40(Z,this.configService)}catch(Z){P.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class VL extends l0{props;constructor(J){super();this.props=J}createState(){return new jh4}}class jh4 extends p0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class Rh4 extends p0{controller=new r7;focusNode=new z6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=c1.all(new g1(Q.foreground,1,"solid")),z=new IZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(H)=>{let D=H.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new W1({children:[new d0({decoration:{color:Q.background},child:new e({text:new C(">",new g({color:Q.foreground}))})}),new y1({child:z})]}),q=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new C("Enter",new g({color:Y.keybind}))),W.push(new C(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new C("Esc",new g({color:Y.keybind}))),W.push(new C(" to cancel",new g({color:Q.foreground,dim:!0})));let U=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,W)})});return new d0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new R0({height:1}),F,new f3,U]})})}}class Ma extends l0{props;constructor(J){super();this.props=J}createState(){return new Rh4}}ZQ();import{mkdtemp as eR3,readFile as $I3,rmdir as JI3,unlink as ZI3,writeFile as QI3}from"node:fs/promises";import{tmpdir as YI3}from"node:os";import vh4 from"node:path";m0();m0();class Ih4{_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 Z of J)try{Z()}catch(Q){}}dispose(){this._disposed=!0,this._listeners.clear()}get disposed(){return this._disposed}get hasListeners(){return this._listeners.size>0}}class BR extends Ih4{_value;constructor(J){super();this._value=J}get value(){return this._value}set value(J){let Z=typeof J==="object"||this._value!==J;if(this._value=J,Z)this.notifyListeners()}}function Ph4(J,Z){let Q=()=>{Z()};return J.addListener(Q),{dispose:()=>J.removeListener(Q)}}class G01{builder;maintainState;_overlayState;_needsBuild=!0;constructor(J,Z=!1){this.builder=J;this.maintainState=Z}get mounted(){return this._overlayState!==void 0}remove(){if(this._overlayState)this._overlayState.remove(this)}markNeedsBuild(){if(this._needsBuild=!0,this._overlayState)this._overlayState._markNeedsRebuild()}_setOverlayState(J){this._overlayState=J}_needsRebuild(){return this._needsBuild}_clearNeedsRebuild(){this._needsBuild=!1}}class z01 extends n3{link;showWhenUnlinked;offset;constructor({key:J,link:Z,showWhenUnlinked:Q=!0,offset:Y={x:0,y:0},child:X}){super({key:J,child:X});this.link=Z,this.showWhenUnlinked=Q,this.offset=Y}createElement(){return new Bq(this)}createRenderObject(){return new Ch4(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class Ch4 extends u4{_link;_showWhenUnlinked;_followerOffset;_cachedPosition=null;constructor(J,Z,Q){super();this._link=J,this._showWhenUnlinked=Z,this._followerOffset=Q}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(Z6(!!J,"performLayout called without constraints"),!this.shouldShow()){this.setSize(0,0),super.performLayout();return}let Z=this.calculatePosition();if(this._cachedPosition=Z,Z)this.setOffset(Z.x,Z.y);if(this.children.length>0){let Q=this.children[0];Q.layout(J);let Y=Q.size;this.setSize(Y.width,Y.height)}else this.setSize(0,0);super.performLayout()}getCurrentPosition(){return this._cachedPosition}setOffset(J,Z){super.setOffset(J,Z)}paint(J,Z=0,Q=0){super.paint(J,Z,Q)}}m0();var sR3=500;class F01{_state;_textController=null;_lastText="";_triggers=[];_optionsBuilder=null;_onSelected=null;_pendingBuildTimer=null;_disposed=!1;constructor(){let J={trigger:null,options:[],selectedIndex:-1,isActive:!1,generationId:0};this._state=new BR(J)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:J,triggers:Z,optionsBuilder:Q,onSelected:Y}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=J,this._lastText=J.text,this._triggers=Z,this._optionsBuilder=Q,this._onSelected=Y||null,this._textController.addListener(this._handleTextChange)}selectNext(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex<J.options.length-1?J.selectedIndex+1:0;this._updateState({selectedIndex:Z})}selectPrevious(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex>0?J.selectedIndex-1:J.options.length-1;this._updateState({selectedIndex:Z})}acceptSelected(){let J=this.currentState;if(!J.isActive||J.selectedIndex<0||J.selectedIndex>=J.options.length)return;let Z=J.options[J.selectedIndex];if(!Z)return;if(this.dismiss(),this._onSelected)this._onSelected(Z)}dismiss(){this._clearPendingBuildTimer(),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.currentState.trigger,Z=this._textController.text,Q=Z!==this._lastText;if(this._lastText=Z,!Q&&!this.currentState.isActive)return;let Y=this._textController.cursorPosition,X=null;for(let G of this._triggers){let z=G.detect(Z,Y);if(z&&(!X||z.start>X.start))X=z}if(!this.currentState.isActive&&X&&X.query.length>0){let G=f6(Z),z=Y,F=z;while(F<G.length){let q=G[F];if(q&&/[\s)\]}@]/.test(q))break;F++}if(F>z){let W=[...G.slice(0,z),...G.slice(F)].join("");this._textController.text=W,this._textController.cursorPosition=Y;return}}if(!X){if(this.currentState.isActive)this.dismiss();else this._clearPendingBuildTimer();return}let K=Q&&this._shouldDebounceBuild(J,X),V=this.currentState.generationId+1;if(this._updateState({trigger:X,generationId:V,options:K?[]:this.currentState.options,isActive:!K,selectedIndex:-1}),K){this._scheduleDebouncedBuild(X.query,V);return}this._clearPendingBuildTimer(),this._buildOptions(X.query,V)};async _buildOptions(J,Z){if(!this._optionsBuilder)return;try{let Q=await this._optionsBuilder(J);if(this.currentState.generationId===Z&&!this._disposed)this._updateState({options:Q,selectedIndex:Q.length>0?0:-1,isActive:Q.length>0})}catch(Q){if(P.error("Error building autocomplete options:",Q),this.currentState.generationId===Z&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_scheduleDebouncedBuild(J,Z){this._clearPendingBuildTimer(),this._pendingBuildTimer=setTimeout(()=>{this._pendingBuildTimer=null,this._buildOptions(J,Z)},sR3)}_shouldDebounceBuild(J,Z){if(!J)return!1;if(J.trigger!==Z.trigger||J.start!==Z.start)return!1;return Z.query.length<J.query.length}_clearPendingBuildTimer(){if(this._pendingBuildTimer)clearTimeout(this._pendingBuildTimer),this._pendingBuildTimer=null}_updateState(J){if(this._disposed)return;this._state.value={...this.currentState,...J}}_cleanup(){if(this._clearPendingBuildTimer(),this._textController)this._textController.removeListener(this._handleTextChange)}}class Aa{}class ja{}class Ra{}class PG0{}class CG0 extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Th4(this.props)}}class Th4 extends p0{props;controller;stateListener=null;overlayEntry=null;layerLink=new wa;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new z6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new F01,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=Ph4(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.handle)this.props.handle.dismiss=()=>this.controller.dismiss();if(this.props.autofocus??!0)C6.instance.addPostFrameCallback(()=>{this._effectiveFocusNode.requestFocus()})}didUpdateWidget(J){super.didUpdateWidget(J);let Z=J.props,Q=this.widget.props;if(this.props=Q,Z.controller!==Q.controller||Z.triggers!==Q.triggers||Z.optionsBuilder!==Q.optionsBuilder||Z.textFieldProps!==Q.textFieldProps||Z.onSelected!==Q.onSelected)this.controller.initialize({textController:Q.controller,triggers:Q.triggers,optionsBuilder:Q.optionsBuilder,onSelected:Q.onSelected});if(Z.handle!==Q.handle){if(Q.handle)Q.handle.dismiss=()=>this.controller.dismiss()}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 Aa)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof ja)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Ra)return this.controller.acceptSelected(),"handled";if(J instanceof PG0)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let J=this.controller.currentState;if(!J.isActive||J.selectedIndex<0)return;let Z=J.selectedIndex,Q=J.options.length,Y=this._cachedMaxVisibleOptions||Q;if(Y>=Q){this.scrollOffset=0;return}let X=Z-this.scrollOffset,K=1,V=this.scrollOffset;if(X>=Y-K)V=Math.max(0,Z-(Y-K-1));if(X<K)V=Math.max(0,Z-K);let G=Math.max(0,Q-Y);V=Math.min(V,G),this.scrollOffset=V}build(J){let Z=new IZ({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Q=new m$({shortcuts:new Map([[new D4("ArrowDown"),new Aa],[new D4("ArrowUp"),new ja],[new D4("n",{ctrl:!0}),new Aa],[new D4("p",{ctrl:!0}),new ja],[new D4("Enter"),new Ra],[new D4("Escape"),new PG0],[new D4("Tab"),new Ra]]),focusNode:this._effectiveFocusNode,child:Z}),Y=new M7({actions:new Map([[Aa,new D6(this.invoke)],[ja,new D6(this.invoke)],[Ra,new D6(this.invoke)],[PG0,new D6(this.invoke)]]),child:Q});return new Na({link:this.layerLink,child:Y})}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 G01((J)=>{let Z=this.controller.currentState;return this.buildOverlayContent(J,Z)});try{UR.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}buildOverlayHints(J,Z){if(this.props.overlayHint!==void 0){if(this.props.overlayHint===null)return[];let{prefix:Q,suffix:Y}=this.props.overlayHint,X=[];if(Q)X.push(new C(Q,new g({color:f0.of(J).app.command})),new C(" ",new g({color:Z})));return X.push(new C(Y,new g({color:Z}))),[{child:new e({text:new C(" ",new g({dim:!0}),X)}),position:"top",alignment:"center"}]}return[]}buildOverlayContent(J,Z){let Q=x1.maybeOf(J),Y=Q?.colorScheme.background??M0.default(),X=this.props.overlayBorderColor??Q?.colorScheme.border??M0.default(),K=Z.options.length,V=V4.sizeOf(J).height,G=0;try{let R=this.layerLink.getTargetTransform();if(R)G=R.position.y}catch{}let z=this.props.autoOverlayPosition?G<V/3:!1,F=2,q;if(z){let R=this.props.controller.getCursorVisualRow(),_=G+R+1;q=V-_-F}else q=G-F;K=Math.min(K,Math.max(1,q)),this._cachedMaxVisibleOptions=K,this.updateScrollPosition();let W=this.scrollOffset,U=Math.min(Z.options.length,W+K),H=[],D=0;for(let R=W;R<U;R++){let _=Z.options[R];if(!_)continue;let T=R===Z.selectedIndex,u,m;if(this.props.optionViewBuilder){u=this.props.optionViewBuilder(J,_,T);let f=this.props.displayStringForOption?.(_)??String(_),d="",p=f,h=_;if(h&&typeof h==="object"&&"type"in h)switch(h.type){case"file":d="@",p=h.path||f;break;case"artifact":d="",p=h.label||f;break}m=d+p}else{let f=this.props.displayStringForOption?.(_)??String(_),d=Q?.colorScheme.selection??M0.default(),p=Q?.colorScheme.foreground??M0.default();u=new e({text:new C(f,new g({color:p,backgroundColor:T?d:void 0}))}),m=f}let y=V4.of(J),k=x5(m,y.supportsEmojiWidth);D=Math.max(D,k),H.push(u)}let B=V4.sizeOf(J).width,N=D+4,w=Math.floor(B*0.9),L=Math.max(Math.min(N,w),Math.min(30,w)),M=H.length+2,A;if(z)A=this.props.controller.getCursorVisualRow()+1;else A=-M;let j=new R0({width:L,child:new d0({height:M,decoration:new $6(Y),child:new s8({decoration:{border:c1.all(new g1(X,1,"rounded"))},padding:C0.symmetric(1,0),overlays:this.buildOverlayHints(J,X),child:new x0({crossAxisAlignment:"start",children:H})})})});return new z01({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:A},child:j})}}function _h4(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 Sh4(J){switch(J.type){case"file":return J.path;case"hint":return`${tR3(J.kind)} ${J.message}`;case"commit":return`${J.shortHash} ${J.message} (${J.relativeDate})`}}function kh4(J){switch(J.type){case"file":return;case"hint":return;case"commit":return}}function tR3(J){switch(J){case"commit":return"@:";case"thread":return"@@"}}class yq{detect(J,Z){if(!J||Z<1)return null;let Q=f6(J);if(Z>Q.length)return null;let Y=this.findWordStart(Q,Z);if(Y>=Q.length||Q[Y]!=="@")return null;let X=Q.slice(Y+1,Z).join("");if(X.includes(" ")||X.includes("\t")||X.includes(`
7380
7380
  `))return null;return{start:Y,end:Z,query:X,trigger:"@"}}findWordStart(J,Z){let Q=Z;for(let Y=Z-1;Y>=0;Y--){let X=J[Y];if(!X||/[\s([{]/.test(X)){Q=Y+1;break}if(Y===0)Q=0}return Q}}class NR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new yh4(this.props)}}var XI3=":";class yh4 extends p0{props;_effectiveFocusNode;_textChangeListener=null;_isCommitMode=!1;_imageUploadSpinner=new V3;_imageUploadSpinnerInterval=null;constructor(J){super();this.props=J}buildOptions=async(J)=>{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=new yq().detect(Z,Q);if(X&&this.props.completionBuilder){if(X.query==="@"&&this.props.onDoubleAtTrigger)return this.props.onDoubleAtTrigger(this.props.controller),[];let G=X.query.toLowerCase().startsWith(XI3);if(G!==this._isCommitMode)this._isCommitMode=G,this.setState();return await this.props.completionBuilder.buildOptions(X)}if(this._isCommitMode)this._isCommitMode=!1,this.setState();return[]};defaultOnOptionSelected=(J)=>{switch(J.type){case"hint":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),G=J.kind==="commit"?"@:":"@@",z=K+G+V;this.props.controller.clear(),this.props.controller.insertText(z),this.props.controller.cursorPosition=X+G.length}return}case"file":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),G=K+`@${J.path} `+V;this.props.controller.clear(),this.props.controller.insertText(G),this.props.controller.cursorPosition=X+1+J.path.length+1}break}case"commit":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),G=`git-commit(${J.hash})`,z=K+G+" "+V;this.props.controller.clear(),this.props.controller.insertText(z),this.props.controller.cursorPosition=X+G.length+1}break}}};initState(){super.initState(),this._effectiveFocusNode=this.props.focusNode||new z6({debugLabel:"PromptEditorFocus"}),this._textChangeListener=()=>{this.setState()},this.props.controller.addListener(this._textChangeListener),this.props.controller.onInsertText=(J,Z)=>{if(J.length<=3)return!0;let Q=jb4(J);if(Q.length===0)return!0;if(this.props.onInsertImage){for(let Y of Q)this.props.onInsertImage(Y);return!1}return!0},this.syncImageUploadSpinner()}didUpdateWidget(J){super.didUpdateWidget(J),this.props=this.widget.props,this.syncImageUploadSpinner()}dispose(){if(this._imageUploadSpinnerInterval)clearInterval(this._imageUploadSpinnerInterval),this._imageUploadSpinnerInterval=null;if(this._textChangeListener)this.props.controller.removeListener(this._textChangeListener),this._textChangeListener=null;if(!this.props.focusNode)this._effectiveFocusNode.dispose();super.dispose()}syncImageUploadSpinner(){if(this.props.showImageUploadSpinner===!0){if(!this._imageUploadSpinnerInterval)this._imageUploadSpinnerInterval=setInterval(()=>{this._imageUploadSpinner.step(),this.setState()},120);return}if(this._imageUploadSpinnerInterval)clearInterval(this._imageUploadSpinnerInterval),this._imageUploadSpinnerInterval=null}_handleOpenInEditor=async(J)=>{try{let Z=await eR3(vh4.join(YI3(),"amp-edit-")),Q=vh4.join(Z,"message.amp.md");await QI3(Q,J,"utf-8"),await hK(Q);try{let Y=await $I3(Q,"utf-8");this.props.controller.text=Y}catch(Y){if(Y?.code!=="ENOENT")P.error("Failed to read temporary file",Y)}try{await ZI3(Q),await JI3(Z)}catch(Y){P.warn("Failed to clean up temporary file",Y)}}catch(Z){P.error("Error opening editor:",Z)}};_handleBackspaceAtStart=()=>{if(this.props.imageAttachments.length>0&&this.props.popImage)return this.props.popImage(),!0;if((this.props.pendingSkills??[]).length>0&&this.props.popSkill)return this.props.popSkill(),!0;return!1};_handleSubmitted=(J)=>{if(this.props.previousThreadId&&J.trim()===""){this.props.onPreviousThreadHintAccepted?.();return}this.props.onSubmitted?.(J)};build(J){let Z=this.props.theme,Q=this.props.pendingSkills??[],Y=this.props.imageAttachments.length>0,X=Q.length>0?new W1({mainAxisSize:"min",children:[new e({text:new C("Skills: ",new g({color:Z.foreground,dim:!0}))}),...Q.flatMap((z,F)=>{let q=new Q4({onClick:()=>{this.props.onSkillClick?.(F)},cursor:"pointer",child:new e({text:new C(z.name,new g({color:Z.success,underline:!0}))})});if(F<Q.length-1)return[q,new e({text:new C(" ")})];return[q]})]}):null,K=Y?new W1({mainAxisSize:"min",children:[new e({text:new C("Images: ",new g({color:Z.foreground,dim:!0}))}),...this.props.imageAttachments.flatMap((z,F)=>{let q=this.props.onImageClick!==void 0,W=new Q4({onClick:q?()=>{this.props.onImageClick?.(F)}:void 0,cursor:q?"pointer":void 0,child:new e({text:new C(`[Image ${F+1}]`,new g({color:Z.success,underline:!0}))})});if(F<this.props.imageAttachments.length-1)return[W,new e({text:new C(" ")})];return[W]}),...this.props.showImageUploadSpinner?[new e({text:new C(" ")}),new e({text:new C(this._imageUploadSpinner.toBraille(),new g({color:Z.foreground,dim:!0}))})]:[]]}):null,V=new CG0({controller:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.buildOptions,onSelected:this.props.onOptionSelected??this.defaultOnOptionSelected,displayStringForOption:(z)=>Sh4(z),overlayBorderColor:Z.border,focusNode:this._effectiveFocusNode,autofocus:this.props.autofocus??!0,autoOverlayPosition:this.props.autoOverlayPosition,handle:this.props.autocompleteHandle,textFieldProps:{placeholder:this.props.placeholder,wrap:!0,minLines:this.props.minLines??3,maxLines:null,expands:!0,autofocus:!1,enabled:this.props.enabled??!0,onSubmitted:this._handleSubmitted,onOpenInEditor:this._handleOpenInEditor,submitKey:this.props.submitKey??{character:"Enter"},prompts:this.props.shellPromptRules,style:{backgroundColor:Z.background,border:null,padding:C0.all(0),textColor:this.props.textColor??Z.foreground,cursorColor:Z.cursor,placeholderColor:Z.mutedForeground,selectionBackgroundColor:Z.selection},clipboard:this.props.clipboard,onCopy:this.props.onCopy,copyOnSelectionEnabled:!0,onBackspaceWhenEmpty:this._handleBackspaceAtStart},optionViewBuilder:(z,F,q)=>{let W=q?Z.selection:void 0,U=Z.secondary,H=Z.foreground,D=Z.foreground,B=Z.warning;if(F.type==="commit")return new d0({decoration:new $6(W),child:new W1({children:[new y1({child:new e({text:new C("",void 0,[new C(F.shortHash,new g({color:Z.secondary})),new C(" ",new g({})),new C(F.message,new g({color:H}))]),maxLines:1,overflow:"ellipsis"})}),new e({text:new C(` ${F.relativeDate}`,new g({color:D,dim:!0}))})]})});let N=[];switch(F.type){case"file":N.push(new C("@",new g({color:U}))),N.push(new C(F.path,new g({color:H})));break;case"hint":N.push(new C(F.kind==="commit"?"@:":"@@",new g({color:B}))),N.push(new C(" ",new g({}))),N.push(new C(F.message,new g({color:B})));break}let w=kh4(F);if(w)N.push(new C(" - ",new g({color:D,dim:!0}))),N.push(new C(w,new g({color:D,dim:!0})));return new d0({decoration:new $6(W),child:new e({text:new C("",void 0,N),maxLines:1,overflow:"ellipsis"})})}}),G=[];if(this.props.topWidget)G.push(this.props.topWidget);if(X||K){let z=[];if(X)z.push(X);if(X&&K)z.push(new e({text:new C(" ")}));if(K)z.push(K);let F=new d0({padding:C0.only({bottom:1}),child:new W1({mainAxisSize:"min",children:z})});G.push(F)}if(G.push(new y1({child:V})),this.props.bottomWidget)G.push(this.props.bottomWidget);return new x0({crossAxisAlignment:"start",children:G})}requestFocus(){this._effectiveFocusNode.requestFocus()}}class xh4 extends p0{controller=new r7;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new z6({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=async(J)=>{if(this.imageAttachments.length>=PV)return!1;let Z=await ZL(J);if(typeof Z==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z],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 Z=f0.of(J),{colors:Q,app:Y}=Z,K=V4.of(J).size.height,V=Math.max(Math.floor(K*0.5),10),G=new NR({controller:this.controller,triggers:[new yq],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(H)=>{this.widget.props.onSubmit(H.trim(),this.imageAttachments)},theme:Q,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:t4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),z=new s4({focusNode:this.focusNode,child:G}),F=new d0({constraints:new I1({maxHeight:V}),padding:C0.symmetric(1,0),child:z}),q=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=new d0({padding:C0.symmetric(1,0),child:new e({text:this.isConfirmingClearInput?new C("",void 0,[new C("Esc",new g({color:Y.keybind})),new C(" again to clear input",new g({color:Q.foreground,dim:!0}))]):new C("",void 0,[new C("Press ",new g({color:Q.foreground,dim:!0})),new C("Enter",new g({color:Y.keybind})),new C(" to submit, ",new g({color:Q.foreground,dim:!0})),new C("Esc",new g({color:Y.keybind})),new C(" to clear",new g({color:Q.foreground,dim:!0}))])})}),U=[q,new R0({height:1}),new y1({child:F}),new R0({height:1}),W];return new d0({decoration:{border:c1.all(new g1(Q.foreground,1,"solid")),color:Q.background},padding:C0.all(1),child:new x0({children:U})})}}class q01 extends l0{props;constructor(J){super();this.props=J}createState(){return new xh4}}import{isDeepStrictEqual as W01}from"node:util";var KI3=/[\\/_ +.#"@[({&]/,VI3=/[\\/_ +.#"@[({&]/g,GI3=/[\s-]/,fh4=/[\s-]/g;function _G0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let G=`${X},${K}`;if(V[G]!==void 0)return V[G];let z=Y.charAt(K),F=Q.indexOf(z,X),q=0,W,U,H,D;while(F>=0){if(W=_G0(J,Z,Q,Y,F+1,K+1,V),W>q){if(F===X)W*=1;else if(GI3.test(J.charAt(F-1))){if(W*=0.9,D=J.slice(X,F-1).match(fh4),D&&X>0)W*=0.999**D.length}else if(KI3.test(J.charAt(F-1))){if(W*=0.8,H=J.slice(X,F-1).match(VI3),H&&X>0)W*=0.999**H.length}else if(W*=0.3,X>0)W*=0.999**(F-X);if(J.charAt(F)!==Z.charAt(K))W*=0.9999}if(W<0.1&&(Q.charAt(F-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(F-1)!==Y.charAt(K))){if(U=_G0(J,Z,Q,Y,F+1,K+2,V),U*0.1>W)W=U*0.1}if(W>q)q=W;F=Q.indexOf(z,F+1)}return V[G]=q,q}function TG0(J){return J.toLowerCase().replace(fh4," ")}function uh4(J,Z){let Q=_G0(J,Z,TG0(J),TG0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let G of Y){let z=_G0(J,G,TG0(J),TG0(G),0,0,{});if(z===0)return Q;X+=z,K+=G.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class Hy{}class Dy{}class SG0{}class kG0{}class bh4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new hh4}}class hh4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function zI3(J,Z){if(J==="")return{matches:!0,score:1};let Q=uh4(Z,J);return{matches:Q>0.15,score:Q}}class $7 extends l0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new gh4}}class gh4 extends p0{textController;focusNode;scrollController=new j5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new r7(this.widget.props.controller?.query??""),this.focusNode=new z6({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>W01(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!W01(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>W01(Q,this.widget.props.controller?.selectedItem));if(Z>=0)this.selectedIndex=Z}this.clampSelectedIndex(),this.ensureSelectedItemVisible(),this.syncSelection()}}dispose(){this.widget.props.onSelectionChange?.(null),this.textController.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof Hy){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof Dy){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof SG0){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length){let Q=Z[this.selectedIndex];if(Q){if(!(this.widget.props.isItemDisabled?.(Q)??!1))this.widget.props.onAccept(Q,{hasUserInteracted:this.hasUserInteracted})}}return"handled"}if(J instanceof kG0)return this.widget.props.onDismiss?.(),"handled";return"ignored"};syncSelection(){let Z=this.cachedFiltered[this.selectedIndex]??null;if(this.widget.props.controller)this.widget.props.controller.selectedItem=Z;this.widget.props.onSelectionChange?.(Z)}clampSelectedIndex(){let J=this.cachedFiltered.length-1;if(J<0){this.selectedIndex=0;return}this.selectedIndex=Math.max(0,Math.min(this.selectedIndex,J))}recomputeFilteredItems(){let J=this.textController.text,Z=this.widget.props.items,Q=this.widget.props.normalizeQuery?.(J)??J,Y=Z.filter((X)=>!this.widget.props.filterItem||this.widget.props.filterItem(X,J)).map((X)=>({item:X,...zI3(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,K)=>this.widget.props.sortItems(X,K,J):(X,K)=>K.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Z=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Z)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;Gy(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=c1.all(new g1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,G=new IZ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:V,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),z=new m$({shortcuts:new Map([[new D4("ArrowDown"),new Hy],[new D4("ArrowUp"),new Dy],[new D4("Tab"),new Hy],[new D4("Tab",{shift:!0}),new Dy],[new D4("n",{ctrl:!0}),new Hy],[new D4("p",{ctrl:!0}),new Dy],[new D4("Enter"),new SG0],[new D4("Escape"),new kG0]]),focusNode:this.focusNode,child:G}),F=new M7({actions:new Map([[Hy,new D6(this.invoke)],[Dy,new D6(this.invoke)],[SG0,new D6(this.invoke)],[kG0,new D6(this.invoke)]]),child:z}),q=new W1({children:[new d0({decoration:{color:Q.background},child:new e({text:new C(">",new g({color:Q.foreground}))})}),new y1({child:F})]});this.itemContexts=[];let W;if(this.widget.props.isLoading){let N=this.widget.props.loadingText??"Loading...";W=new R0({height:10,child:new X4({child:new e({text:new C(N,new g({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)W=new y1({child:new X4({child:new e({text:new C(this.widget.props.emptyStateText,new g({color:Q.foreground,dim:!0}))})})});else{let N=Y.map((w,L)=>{let O=L===this.selectedIndex,E=this.widget.props.isItemDisabled?.(w)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(w,O,E,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new d0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C(this.widget.props.getLabel(w),new g({color:j,dim:E}))})})}return new bh4(new Q4({onClick:(A)=>this.handleItemClick(L,A.clickCount),child:M}),(A)=>{this.itemContexts[L]=A})});W=new x0({children:N,crossAxisAlignment:"start"})}let U=new Q4({onScroll:this.handleScroll,opaque:!1,child:new T6({controller:this.scrollController,autofocus:!1,child:W})}),H=[];if(this.widget.props.title){let N=new d0({padding:C0.symmetric(1,0),child:new e({text:new C(this.widget.props.title,new g({color:Z.app.command,bold:!0}))})});H.push(N)}if(!K)H.push(q,new R0({height:1}));if(this.textController.text!==""){let N=Y.length>0?Y[this.selectedIndex]:void 0,w=N&&this.widget.props.buildDisabledReasonWidget?.(N,J);H.push(new y1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new y1({child:U}),new d0({padding:C0.only({top:1}),child:new X4({child:w??new R0({height:1})})})]})}))}else H.push(new y1({child:U}));if(this.widget.props.footer)H.push(this.widget.props.footer);return new d0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:H})})}}function mh4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),K=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(K<7)return`${K}d ago`;return J.toLocaleDateString()}class U01 extends J4{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,K)=>K.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>mh4(X.pubDate).length));return new $7({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,K,V,G)=>{let z=f0.of(G),{colors:F}=z,q=z.app,W=K?q.selectionBackground:void 0,U=K?q.selectionForeground:F.foreground,H=F.mutedForeground,D=(B,N)=>new R0({width:N,child:W1.end([new e({text:new C(B,new g({color:H}))})])});return new d0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new W1({children:[new y1({child:new e({text:new C(X.title,new g({color:U})),overflow:"ellipsis",maxLines:1})}),new R0({width:2}),D(mh4(X.pubDate),Q)]})})}})}}hP();class H01 extends l0{createState(){return new ph4}}class ph4 extends p0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new e({text:new C("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function FI3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let G=V.relationships.find((z)=>z.role==="child"&&Z.has(z.threadID)&&(z.type==="fork"||z.type==="handoff"));if(G){Y.set(V.id,G.type);let z=G.threadID,F=Q.get(z)||[];F.push(V),Q.set(z,F)}else X.push(V)}return QV0.flatten(X,(V)=>Q.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function D01(J,Z,Q){return new e({text:new C(`${J}${Z}`,new g({color:Q})),maxLines:1})}function qI3(J,Z,Q,Y){return[D01("+",J,Y.success),f3.horizontal(1),D01("~",Z,Y.warning),f3.horizontal(1),D01("-",Q,Y.destructive)]}function WI3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class vG0 extends l0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new dh4}}class dh4 extends p0{spinner=new V3;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,K=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((L)=>L.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((L)=>L.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],G=new Set(V),z=Z.currentThreadID,F=[...K].sort((L,O)=>{if(z){if(L.id===z)return-1;if(O.id===z)return 1}let E=V.indexOf(L.id),M=V.indexOf(O.id);if(E!==-1&&M!==-1)return E-M;if(E!==-1)return-1;if(M!==-1)return 1;return 0}),q=FI3(F),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),U=f0.of(J),H=new n0({padding:C0.symmetric(0,1),child:new X4({child:new e({text:new C("",new g({color:U.colors.foreground,dim:!0}),[new C("Alt+W/Ctrl+T",new g({color:U.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:U.colors.foreground,dim:!0}))])})})}),D="",B=null,N=(L)=>{if(L!==D)D=L,B=H$(L);return B};return new $7({items:q,getLabel:(L)=>`${L.title} ${L.id}`,filterItem:(L,O)=>{let E=N(O);if(E)return L.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(L)=>N(L)?"":L,onAccept:async(L,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(L.id,O);if(!WI3(E))return;this.setSwitchingThread(!0);try{await E}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(L)=>{if(Z.previewController){if(L)Z.previewController.select(L.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:H,renderItem:(L,O,E,M)=>{let A=f0.of(M),{app:j,colors:R}=A,_=O?j.selectionBackground:void 0,T=O?j.selectionForeground:R.foreground,u=R.mutedForeground,m=(a,W0)=>new R0({width:W0,child:W1.end([new e({text:new C(a,new g({color:u}))})])}),y=Z.threadViewStates[L.id],k=[],f=L.relationshipType==="handoff",d=new on({connectorColor:R.mutedForeground});if(L.depth>0){let a=[],W0=L.ancestorsAreLast.slice(1);for(let L0 of W0)a.push(new C(d.getAncestorPrefix(L0),new g({color:d.connectorColor,dim:d.connectorDim})));let r=L.isLast?d.elbow:d.tee,H0=d.getConnectorText(r);a.push(new C(H0,new g({color:d.connectorColor,dim:d.connectorDim}))),k.push(new e({text:new C("",void 0,a)}))}let p=[],h=z===L.id?new C("(current) ",new g({color:R.success})):G.has(L.id)?new C("(visited) ",new g({color:R.foreground,dim:!0})):null;if(h)p.push(new e({text:h}));if(DN(y))p.push(new H01),p.push(new R0({width:1}));let n=L.title;if(L.relationshipType==="fork"){let a=n.match(/^Forked\((\d+)\): /);if(a)n=n.slice(a[0].length);else while(n.startsWith("Forked: "))n=n.slice(8);p.push(new e({text:new C("[fork] ",new g({color:R.primary}))}))}else if(f)p.push(new e({text:new C("[handoff] ",new g({color:R.accent}))}));if(p.push(new y1({child:new e({text:new C(n,new g({color:T})),overflow:"ellipsis",maxLines:1})})),p.push(new R0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let a=O?{success:u,warning:u,destructive:u}:R;p.push(...qI3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,a)),p.push(new R0({width:2}))}return p.push(m(L.description.timeAgo,W)),new d0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new W1({children:[...k,...p]})})}})}}function ch4(J){return 1-(1-J)**3}function lh4(J,Z,Q){return J+(Z-J)*Q}function Ia(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),K=ch4(Y),V=ch4(X);return{x:lh4(J.startOffset.x,J.targetOffset.x,K),y:lh4(J.startOffset.y,J.targetOffset.y,V)}}var UI3={nodeWidth:3,horizontalSpacing:3};class By{options;constructor(J={}){this.options={...UI3,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let K=0,V=(G,z)=>{let F=Z.get(G.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let q={...G,parentID:Q.get(G.id)};if(F.length===0){Y.push({node:q,position:{x:K,y:z}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let W=[];for(let B of F)W.push(V(B,z+1));let U=Math.min(...W),H=Math.max(...W),D=Math.floor((U+H)/2);return Y.push({node:q,position:{x:D,y:z}}),D};for(let G of X)V(G,0);return Y}buildTree(J){let Z=new Set(J.map((K)=>K.id)),Q=[...J].sort((K,V)=>K.id.localeCompare(V.id)),Y=new Map;for(let K of Q){if(!K.parentID||!Z.has(K.parentID)){Y.set(K.id,void 0);continue}let V=!1,G=K.parentID;while(G){if(G===K.id){V=!0;break}G=Y.get(G)}Y.set(K.id,V?void 0:K.parentID)}let X=new Map;for(let K of J){let V=Y.get(K.id);if(!X.has(V))X.set(V,[]);X.get(V).push(K)}return{childrenMap:X,resolvedParent:Y}}}var HI3={nodeWidth:3,nodeHeight:2};class Ny{options;constructor(J={}){this.options={...HI3,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let K=this.calculateConnectorLine(X.position,Y.position);Z.push({points:K,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,K=Z.x+Q,V=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:V});let G=V+1;if(Y.push({x:X,y:G}),X!==K)Y.push({x:K,y:G});let z=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:z}),Y}}var DI3={nodeWidth:3,nodeHeight:2},BI3={x:0,y:0};class xG0{options;constructor(J={}){this.options={...DI3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=BI3,X,K,V,G){let z=G?f0.of(G):null,F=z?.colors,q=z?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new e({text:new C("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),D=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let _=[],T=0;for(let u of R){if(u.position.x>T)_.push(new R0({width:u.position.x-T}));let m=u.node.id===Q,y=V?.(u.node.data)??!1,k=K?.activeFlashOn??!1,f=u.node.id===K?.copyFlashNodeId;_.push(this.renderNode(m,y,k,f,q,F)),T=u.position.x+this.options.nodeWidth}if(N.push(new W1({crossAxisAlignment:"start",children:_})),j>0){let u=J.filter((k)=>k.position.y===j-1),m=R,y=this.renderConnectors(u,m,Z,D,F,q);N.push(...y)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(U+1)*B,M=[new R0({width:D,height:E}),new t6({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,_=L+A.position.x+this.options.nodeWidth+1,T=O+R*B+1,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new t6({left:_,top:T,child:this.renderInfoBox(j,u,F,q)}))}return new d0({padding:C0.horizontal(2),child:new uG(new G5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",G="└─┘",z=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,F=!1;if(Y)z=X?.threadGraphNodeSelected??K?.primary??z,V="┏━┓",G="┗━┛",F=!0;else if(Z&&Q)z=X?.toolSuccess??K?.primary??z,V="┏━┓",G="┗━┛";return new x0({crossAxisAlignment:"start",children:[new e({text:new C(V,new g({color:z,bold:F}))}),new e({text:new C(G,new g({color:z,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),K=Math.min(Z,Math.max(1,...X.map((U)=>U.length))),V=K+2,G="┌"+"─".repeat(V)+"┐",z="└"+"─".repeat(V)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,W=[new e({text:new C(G,new g({color:F}))})];for(let U of X){let H=" ".repeat(K-U.length);W.push(new e({text:new C("│ ",new g({color:F}),[new C(U+H,new g({color:q??F})),new C(" │",new g({color:F}))])}))}return W.push(new e({text:new C(z,new g({color:F}))})),new x0({crossAxisAlignment:"start",children:W})}renderConnectors(J,Z,Q,Y,X,K){let V=[],G=Math.floor(this.options.nodeWidth/2),z=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of Z){let H=U.position.x+G;if(H>=0&&H<Y)F[H]="▲"}V.push(new e({text:new C(F.join(""),new g({color:z}))}));let q=Array(Y).fill(" ");for(let U of J){let H=Z.filter((L)=>L.node.parentID===U.node.id);if(H.length===0)continue;let D=U.position.x+G,B=H.map((L)=>L.position.x+G),N=Math.min(...B),w=Math.max(...B);for(let L=N;L<=w;L++)if(L>=0&&L<Y){if(L===D)if(H.length===1&&B[0]===D)q[L]="│";else if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┬";else if(B.includes(L))if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┴";else if(q[L]===" ")q[L]="─"}}V.push(new e({text:new C(q.join(""),new g({color:z}))}));let W=Array(Y).fill(" ");for(let U of J){if(Z.filter((B)=>B.node.parentID===U.node.id).length===0)continue;let D=U.position.x+G;if(D>=0&&D<Y)W[D]="│"}return V.push(new e({text:new C(W.join(""),new g({color:z}))})),V}}var NI3={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},wI3={x:0,y:0};class B01{options;constructor(J={}){this.options={...NI3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=wI3,X,K,V,G){let z=G?f0.of(G):null,F=z?.colors,q=z?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new e({text:new C("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),D=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let _=[],T=0;for(let u of R){if(u.position.x>T)_.push(new R0({width:u.position.x-T}));let m=u.node.id===Q,y=V?.(u.node.data)??!1,k=K?.activeFlashOn??!1;_.push(this.renderNode(m,y,k,q,F)),T=u.position.x+this.options.nodeWidth}if(N.push(new W1({crossAxisAlignment:"start",children:_})),j>0){let u=J.filter((k)=>k.position.y===j-1),m=R,y=this.renderConnectors(u,m,Z,D,F,q);N.push(...y)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(U+1)*B,M=[new R0({width:D,height:E}),new t6({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,_=L+A.position.x+this.options.nodeWidth+1,T=O+R*B,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new t6({left:_,top:T,child:this.renderInfoBox(j,u,F)}))}return new d0({padding:C0.horizontal(2),child:new uG(new G5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let K=J?this.options.selectedIcon:this.options.nodeIcon,V=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)V=Y?.toolSuccess??X?.primary??V,K="■";return new e({text:new C(K,new g({color:V}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,K=[];for(let V of Y)K.push(new e({text:new C(V,new g({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:K})}renderConnectors(J,Z,Q,Y,X,K){let V=[],G=Math.floor(this.options.nodeWidth/2),z=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let q of J){let W=Z.filter((N)=>N.node.parentID===q.node.id);if(W.length===0)continue;let U=q.position.x+G,H=W.map((N)=>N.position.x+G),D=Math.min(...H),B=Math.max(...H);for(let N=D;N<=B;N++)if(N>=0&&N<Y){let w=N===U,L=H.includes(N);if(w&&L)if(W.length===1)F[N]="│";else if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┼";else if(w)if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┬";else if(L)if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┴";else if(F[N]===" ")F[N]="─"}}return V.push(new e({text:new C(F.join(""),new g({color:z}))})),V}}class Pa extends n3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new ih4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class ih4 extends u4{onWidth;onHeight;constructor(J,Z){super();this.onWidth=J,this.onHeight=Z}performLayout(){let J=this._lastConstraints,Z=Number.isFinite(J.maxWidth)?J.maxWidth:80,Q=Number.isFinite(J.maxHeight)?J.maxHeight:24;this.onWidth(Z),this.onHeight?.(Q);let Y=this.children[0];if(Y)Y.layout(J),this.setSize(Y.size.width,Y.size.height);else this.setSize(J.minWidth,J.minHeight)}paint(J,Z,Q){for(let Y of this.children)Y.paint(J,Z,Q)}}class wR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new oh4}}var nh4=400,ah4=300,LI3=16;class oh4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new By({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new Ny;renderer=new B01;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((z)=>z.id)),Q=new Set(this.widget.props.threads.map((z)=>z.id));if(Z.size!==Q.size||[...Z].some((z)=>!Q.has(z)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,K=this.widget.props.initialSelectedThreadID;if(X!==K&&K){let F=this.widget.props.threads.find((q)=>q.id===K);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((z)=>z.isActive),G=this.widget.props.threads.some((z)=>z.isActive);if(V!==G){if(this.stopActiveFlashTimer(),G)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:nh4,durationY:ah4};let Z=Math.max(nh4,ah4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=Ia(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},LI3)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),K=Math.floor(this.viewportWidth/2)-J-Y,V=Q-Z,G=2,z=Math.floor(this.viewportHeight/2),q=Math.floor(z/2)-V;return{x:K,y:q}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((K)=>K.node.parentID===Q.node.id);if(X.length>0){X.sort((V,G)=>V.position.x-G.position.x);let K=Math.floor(X.length/2);Y=X[K]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x<Q.position.x);if(X.length>0)X.sort((K,V)=>V.position.x-K.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x>Q.position.x);if(X.length>0)X.sort((K,V)=>K.position.x-V.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let q=(this.selectedNodeId?this.positionedNodes.find((W)=>W.node.id===this.selectedNodeId):null)??this.positionedNodes.find((W)=>!W.node.parentID);if(q){let W=Math.max(...this.positionedNodes.map((U)=>U.position.y));this.currentOffset=this.calculateCenterOffset(q.position.x,q.position.y,W)}}let X=this.widget.props.showTitle??!0,K=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+K},G=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),z=new Pa({onWidth:(F)=>{if(this.viewportWidth!==F)this.viewportWidth=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(F)=>{if(this.viewportHeight!==F)this.viewportHeight=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:G});return new s4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:z})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class sh4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new th4}}class th4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var rh4=30,OI3=30;class wy{}class Ly{}class fG0{}class uG0{}class N01 extends l0{props;constructor(J){super();this.props=J}createState(){return new eh4}}class eh4 extends p0{highlightedIndex=0;controller=new r7;focusNode;scrollController=new j5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new z6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;Gy(J,{top:Q,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Z}=this.widget.props;if(!J)this.filteredClusters=[...Z];else this.filteredClusters=Z.filter((Q)=>Q.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof wy){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof Ly){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof fG0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof uG0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,G=V4.of(J).size.width>=OI3+rh4,z=c1.all(new g1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,q=new d0({padding:C0.symmetric(1,0),child:new e({text:new C("Select a cluster",new g({color:X.command,bold:!0}))})}),W=new IZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),U=new m$({shortcuts:new Map([[new D4("ArrowDown"),new wy],[new D4("ArrowUp"),new Ly],[new D4("Tab"),new wy],[new D4("Tab",{shift:!0}),new Ly],[new D4("n",{ctrl:!0}),new wy],[new D4("p",{ctrl:!0}),new Ly],[new D4("Enter"),new fG0],[new D4("Escape"),new uG0]]),focusNode:this.focusNode,child:W}),H=new M7({actions:new Map([[wy,new D6(this.invoke)],[Ly,new D6(this.invoke)],[fG0,new D6(this.invoke)],[uG0,new D6(this.invoke)]]),child:U}),D=new W1({children:[new d0({decoration:{color:Y.background},child:new e({text:new C(">",new g({color:Y.foreground}))})}),new y1({child:H})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,R=Z?M.threads.some((m)=>m.id===Z):!1,_=j?X.selectionBackground:void 0,T=j?X.selectionForeground:Y.foreground,u=[new C(M.label,new g({color:T})),new C(` (${M.threads.length})`,new g({color:T,dim:!0}))];if(R)u.push(new C(" (current)",new g({color:j?X.selectionForeground:Y.success})));return new sh4(new Q4({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new d0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C("",void 0,u)})})}),(m)=>{this.itemContexts[A]=m})}),N=new x0({children:B,crossAxisAlignment:"start"}),w=new y1({child:new Q4({onScroll:this.handleScroll,child:new T6({controller:this.scrollController,autofocus:!1,child:N})})}),L=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],O=F?new d0({padding:C0.all(1),child:new wR({threads:L,autofocus:!1,offsetY:2})}):null,E;if(G){let M=O?new y1({child:O}):new R0({width:rh4});E=new W1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,M]})}else{let M=[new y1({child:new Q4({onScroll:this.handleScroll,child:new T6({controller:this.scrollController,autofocus:!1,child:N})})})];if(O)M.push(new y1({child:O}));E=new x0({crossAxisAlignment:"stretch",children:M})}return new d0({decoration:{border:z,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[q,D,new R0({height:1}),new y1({child:E})]})})}}m0();IX();gM();CX();O$();d4();N4();SP();var L01=B4(eW(),1);import{execSync as LR}from"node:child_process";import{writeFile as Oy}from"node:fs/promises";import EI3 from"node:os";import xq from"node:path";var $g4="c446b2e9b16cdc06df2ec285894d6421",MI3="5ea19563777f4ade8707fc56f7e7a388",AI3="amp-thread-worker",Jg4=[{id:"cli-open",label:"cli: open in pager"},{id:"cloudflare-logs",label:"cloudflare: open logs"},{id:"cloudflare-data-studio",label:"cloudflare: open data studio"}];function jI3(J){return!!J&&typeof J==="object"&&"usesDtw"in J}function zL(J){if(!J||!jI3(J.meta))return!1;return J.meta.usesDtw===!0}function O01(J){let Z=new URL(`https://dash.cloudflare.com/${$g4}/workers/durable-objects/view/${MI3}/studio`);return Z.searchParams.set("name",J),Z.searchParams.set("jurisdiction","none"),Z.toString()}function E01(J){let Z=new URL(`https://dash.cloudflare.com/${$g4}/workers/services/view/${AI3}/production/observability/events`);return Z.searchParams.set("filterCombination",'"and"'),Z.searchParams.set("calculations",'[{"operator":"count"}]'),Z.searchParams.set("orderBy",'{"value":"count","limit":10,"order":"desc"}'),Z.searchParams.set("timeframe","24h"),Z.searchParams.set("conditions","{}"),Z.searchParams.set("conditionCombination",'"and"'),Z.searchParams.set("alertTiming",'{"interval":300,"window":900,"timeBeforeFiring":600,"timeBeforeResolved":600}'),Z.searchParams.set("filters",JSON.stringify([{key:"threadId",operation:"eq",value:J,type:"string"}])),Z.toString()}function RI3(J,Z){if(OV(J))return`amp dtw-curl ${Z}`;return`AMP_URL=${JSON.stringify(J)} pnpm -C cli cli -- dtw-curl ${Z}`}function M01(J,Z){let Q=RI3(Z,J);return[{label:"dtw: get full transcript",command:`${Q} get-transcript`},{label:"dtw: send message via curl",command:`${Q} add-message "<your message here>"`},{label:"dtw: dump full sqlite DB to disk",command:`${Q} dump`},{label:"dtw: fetch Cloudflare logs",command:`./scripts/fetch-cloudflare-logs.ts ${J}`}]}function Ca(J,Z,Q){let Y=`select(.pid == ${Z})`,X=Ta(Q);return`${J==="snapshot"?`tail -n 10000 ${X}`:`tail -f ${X}`} | jq -C '${Y}'`}function Ta(J){return J.path??f9(J.uri)}function Zg4(J,Z,Q){let Y=Ca("snapshot",J,Z);return Q?`${Y} | ${Q}`:Y}function Qg4(J,Z){return M01(J,Z).map(({label:Q,command:Y})=>`# ${Q}
7381
7381
  ${Y}`).join(`
7382
7382
 
@@ -7605,7 +7605,7 @@ ${t.content||""}`:t.content||"",T0=[],e0=t.baseDir.startsWith("file://")?Az0(t.b
7605
7605
  `),process.exit(1)}process.stdout.write(await GS3(z.result.displayText)+`
7606
7606
  `),process.exit(0)})}gM();import{stdout as zS3}from"node:process";function FS3({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${MF(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function ad4(J){zS3.write(`${FS3(J)}
7607
7607
  `)}function od4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{ad4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{ad4(Z),process.exit(0)})}var _x3=iH.join(nZ,"logs","headless.log"),r61=iH.join(Qv,"device-id.json"),Nn4=`cli-tui-${In4(16).toString("hex")}`;async function Sx3(){for(let J of KE)try{if((await J.listConfigs()).length>0)return J}catch(Z){P.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => B4(oy(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){j2.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
7608
- `)}function kx3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",G=!1;J.warn(K,{name:V,code:Y})}}function A2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")aJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")aJ("experimental.agentMode",Z.mode)}function _n4(J,Z){if(J.getOptionValueSourceWithGlobals("sp")==="cli"&&Z.sp)return Z.sp;if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Z.systemPrompt)return Z.systemPrompt;return}async function vx3(J){try{return await Cn4(J,"utf-8")}catch{return J}}async function s61(J,Z,Q){let Y=_n4(J,Z);if(!Y)return;let X=o6(Q)?Q.features:[],K=o6(Q)?Q.user.email:void 0;if(!Z51(X,S2.HARNESS_SYSTEM_PROMPT)&&!Sn4(K))throw new T1("You are not allowed to do this.",1);aJ("systemPrompt",await vx3(Y))}function Sn4(J){return!!(J&&J10(J))}function Z51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function t61(J){return(J.userEmail?dJ(J.userEmail):!1)||Z51(J.features,S2.DTW_TUI)}function wn4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new T1("This TUI mode is not enabled for your user;",1)}function e61(J,Z){if(typeof J==="boolean")return J;if(!o6(Z))return!1;return t61({userEmail:Z.user.email,features:Z.features})}function $51(J){if(!o6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function yx3(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function UF0(J){let Y=yx3(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new T1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function Ln4(J){if(!Y5.write(J))await Ix3(Y5,"drain")}var On4=[{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)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??yK,description:`Custom settings file path (overrides the default location ${yK})`},{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 ${Cn0})`},{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:a7(),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:"mode",long:"mode",short:"m",type:"option",default:fz.SMART.key,description:`Set the agent mode (${uz().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:uz().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"threadActors",long:"thread-actors",type:"switch",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],En4=(J)=>("deprecated"in J)&&J.deprecated===!0,xx3=(J)=>("hidden"in J)&&J.hidden===!0,fx3=(J)=>("default"in J),ux3=(J)=>("default"in J)?J.default:void 0,kn4=[{name:"toggle-skills-count",entryPoint:jo0}];function bx3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((G)=>Q.includes(G)||G.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new T1(E3.unknownCommand(Q),1,V)}}async function Q51(J){return{...J,getThreadEnvironment:uY,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new hV(J.fileSystem),generateThreadTitle:g80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>xX(J.configService),pluginService:J.pluginService}}function vn4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:uY,filesystem:J.fileSystem,threadService:J.threadService}}var HF0=V1.file(Tn4.homedir()),J51=process.env.XDG_CONFIG_HOME?V1.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(HF0,".config");function hx3(J){return qq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){Fq4(Z);let Q=AX0(),Y=ho0();if((!Q||Y||ST4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(LH("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(LH("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(AX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function gx3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function R7(J,Z,Q){let Y=Q?.deferAuth??!1;Qf1("0.0.1774897010-g0ac150");let X=O10({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(V1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:HF0,userConfigDir:J51});_T4(X);let K=await X.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let a=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(a),P.info("API key lookup before login",{found:Boolean(a),ampURL:J.ampURL,deferAuth:Y}),!a)if(Y)P.info("No API key found, continuing startup with deferred auth");else{Y5.write(`No API key found. Starting login flow...
7608
+ `)}function kx3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",G=!1;J.warn(K,{name:V,code:Y})}}function A2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")aJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")aJ("experimental.agentMode",Z.mode)}function _n4(J,Z){if(J.getOptionValueSourceWithGlobals("sp")==="cli"&&Z.sp)return Z.sp;if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Z.systemPrompt)return Z.systemPrompt;return}async function vx3(J){try{return await Cn4(J,"utf-8")}catch{return J}}async function s61(J,Z,Q){let Y=_n4(J,Z);if(!Y)return;let X=o6(Q)?Q.features:[],K=o6(Q)?Q.user.email:void 0;if(!Z51(X,S2.HARNESS_SYSTEM_PROMPT)&&!Sn4(K))throw new T1("You are not allowed to do this.",1);aJ("systemPrompt",await vx3(Y))}function Sn4(J){return!!(J&&J10(J))}function Z51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function t61(J){return(J.userEmail?dJ(J.userEmail):!1)||Z51(J.features,S2.DTW_TUI)}function wn4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new T1("This TUI mode is not enabled for your user;",1)}function e61(J,Z){if(typeof J==="boolean")return J;if(!o6(Z))return!1;return t61({userEmail:Z.user.email,features:Z.features})}function $51(J){if(!o6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function yx3(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function UF0(J){let Y=yx3(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new T1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function Ln4(J){if(!Y5.write(J))await Ix3(Y5,"drain")}var On4=[{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)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??yK,description:`Custom settings file path (overrides the default location ${yK})`},{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 ${Cn0})`},{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:a7(),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:"mode",long:"mode",short:"m",type:"option",default:fz.SMART.key,description:`Set the agent mode (${uz().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:uz().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"threadActors",long:"thread-actors",type:"switch",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],En4=(J)=>("deprecated"in J)&&J.deprecated===!0,xx3=(J)=>("hidden"in J)&&J.hidden===!0,fx3=(J)=>("default"in J),ux3=(J)=>("default"in J)?J.default:void 0,kn4=[{name:"toggle-skills-count",entryPoint:jo0}];function bx3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((G)=>Q.includes(G)||G.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new T1(E3.unknownCommand(Q),1,V)}}async function Q51(J){return{...J,getThreadEnvironment:uY,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new hV(J.fileSystem),generateThreadTitle:g80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>xX(J.configService),pluginService:J.pluginService}}function vn4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:uY,filesystem:J.fileSystem,threadService:J.threadService}}var HF0=V1.file(Tn4.homedir()),J51=process.env.XDG_CONFIG_HOME?V1.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(HF0,".config");function hx3(J){return qq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){Fq4(Z);let Q=AX0(),Y=ho0();if((!Q||Y||ST4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(LH("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(LH("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(AX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function gx3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function R7(J,Z,Q){let Y=Q?.deferAuth??!1;Qf1("0.0.1774901365-g0ac150");let X=O10({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(V1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:HF0,userConfigDir:J51});_T4(X);let K=await X.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let a=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(a),P.info("API key lookup before login",{found:Boolean(a),ampURL:J.ampURL,deferAuth:Y}),!a)if(Y)P.info("No API key found, continuing startup with deferred auth");else{Y5.write(`No API key found. Starting login flow...
7609
7609
  `);let W0=await mx3(J),r=await J.secrets.get("apiKey",J.ampURL);if(P.info("Login flow completed",{success:W0,storedKeyPresent:Boolean(r),ampURL:J.ampURL}),!W0)await GH(),process.exit(1);V=!0}}{let a=await X.getLatest(),W0=a.settings.url,r=a.secrets.isSet?.[W0];P.info("Config secrets state after login",{configURL:W0,apiKeySet:r?.apiKey??!1})}let G=j1(xX(X).pipe(T5((a)=>a!=="pending"))),z=Y?"pending":await G;if(!Y)P.info("Server status resolved",{status:"ready",isAuthenticated:o6(z),isError:hW(z),errorMessage:hW(z)?z.error.message:void 0});let{toolService:F,dispose:q}=Xq4({configService:X}),W=new Map,U=()=>W.clear(),H=new uT0(X,J.settings.getWorkspaceRootPath()),D=Gt1({configService:X,filesystem:n8}),B=Qa1({configService:X,trustStore:H,skillMCPServers:D.skillMCPServers,createOAuthProvider:async(a,W0,r)=>{let H0=`${a}:${W0}`,L0=W.get(H0);if(L0)return P.debug("Reusing existing OAuth provider for server",{serverName:a,serverUrl:W0}),L0;P.debug("Creating OAuth provider for server",{serverName:a,serverUrl:W0});let G0=(async()=>{let J0=new DE(J.secrets),z0=await J0.getClientInfo(a,W0),i=r?.scopes??z0?.scopes,o=ZI4();P.info("OAuth headless mode check",{useHeadless:o,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:Y5.isTTY});let t;if(o)t=J.executeMode?JI4():$I4(a);let $0=new NR0({storage:J0,serverName:a,serverUrl:W0,clientId:r?.clientId??z0?.clientId,clientSecret:r?.clientSecret??z0?.clientSecret,authUrl:r?.authUrl??z0?.authUrl,tokenUrl:r?.tokenUrl??z0?.tokenUrl,scopes:i,headlessAuthHandler:t});return P.debug("OAuth provider created",{serverName:a,serverUrl:W0,hasManualClientId:!!(r?.clientId??z0?.clientId),willUseDCR:!(r?.clientId??z0?.clientId),scopes:i,headlessMode:o,executeMode:J.executeMode}),$0})();return W.set(H0,G0),G0}}),N=bg0({configService:X,filesystem:n8,spawn:P$0}),w;if(J.executeMode){let a=await zG4({toolService:F,providers:[B,N],initialTimeout:15000});w=a.registrations;for(let[W0,r]of a.initErrors)P.warn(`${W0} provider initialization slow or failed:`,r)}else w=hg0({toolService:F,providers:[B,N]});if(Z.jetbrains)JE("JetBrains");else if(Z.ide&&gI4())JE("VS Code");else if(Z.ide&&mI4())JE("Neovim");else if(Z.ide){let a=await Sx3();if(a){let W0=_10(a.ideName);if(W0)JE(W0)}}if(J.executeMode)Yf1(!0);let L,O=w$.status.pipe(D1((a)=>Boolean(a.connected&&a.authenticated&&a.ideName&&if1(a.ideName))),b4()).subscribe((a)=>{if(a){if(!L)L=F.registerTool(GG4)}else L?.dispose(),L=void 0}),E;if(!J.executeMode){let a=await J.settings.get("fuzzy.alwaysIncludePaths")??[];E=new WY0(process.cwd(),{alwaysIncludePaths:a},!0)}else E=new class extends WY0{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let M=await Dt1({isDevelopment:!1}),A=new hS0(M,X,{maxThreads:200});P.info("Starting Amp background services");let j=Z.takeMeBack?!1:void 0,R=e61(j,z),_=Boolean(R||Z.headless);if(_)P.info("DTW mode enabled: thread sync service disabled");let T=_?gx3():yt1({threadService:A,configService:X,isExtensionDevelopment:!1}),u;w$.status.subscribe((a)=>{u=a});let m=new iA0({workspaceRoots:[V1.file(process.cwd())],fileSystem:n8,getCurrentFile:()=>{if(!u?.openFile)return;try{return V1.parse(u.openFile)}catch(a){P.warn("Failed to parse current file URI",{uri:u.openFile,error:a});return}},getOpenFiles:()=>{if(!u?.visibleFiles?.length)return[];let a=u.openFile;return u.visibleFiles.filter((W0)=>W0!==a).map((W0)=>{try{return V1.parse(W0)}catch(r){return P.warn("Failed to parse visible file URI",{uri:W0,error:r}),null}}).filter((W0)=>W0!==null)}}),y=new po0,k=process.env.PLUGINS??"off",f=Z.headless?HT4():void 0,d=f??new NX0({configService:X}),p=d instanceof NX0?d:void 0;if(p)p.pluginExecutorKind=R?"local":"unknown";let h=eT0({configService:X,fileSystem:n8,platform:d,internalPlugins:kn4,pluginFilter:k}),n=sa1({pluginService:h,toolService:F}),c={codebaseContextService:m,configService:X,toolService:F,mcpService:B,skillService:D,toolboxService:N,trustStore:H,threadService:A,threadSyncService:T,threadStorage:M,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:E,fileSystem:n8,terminal:y,pluginService:h,pluginPlatform:p,headlessPluginPlatform:f,serverStatus:z,serverStatusPromise:G,hasAPIKeyAtStartup:V};return{...c,async asyncDispose(){if(c.mcpService.hasAuthenticatingClients())P.info("Waiting for OAuth authentication to complete before exit..."),await c.mcpService.waitForAuthentication();for(let a of w.values())a.dispose();await c.mcpService.dispose(),U(),await c.threadService.asyncDispose(),c.configService.unsubscribe(),q(),c.fuzzyServer.dispose(),c.threadSyncService.dispose(),c.settingsStorage[Symbol.dispose](),O.unsubscribe(),L?.dispose(),n.dispose(),await c.pluginService.dispose()}}}async function mx3(J){if(!J.executeMode){if(!await HX0("Would you like to log in to Amp? [(y)es, (n)o]: "))return Y5.write(`Login cancelled. Run the command again to retry.
7610
7610
  `),!1}return await yn4(J)}async function yn4(J){let Z=In4(32).toString("hex"),Q=await qv(J.ampURL,Z),Y=new AbortController;try{await EV(Q,Y.signal)}catch(K){P.error("Error opening browser",{error:K})}let X=await qv(J.ampURL,Z,!1);Y5.write(`If your browser does not open automatically, visit:
7611
7611
 
@@ -7613,7 +7613,7 @@ ${o0.blue.bold(X)}
7613
7613
 
7614
7614
  `);try{return await nC4(J.ampURL,Z,J.secrets,Y),Y5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(K){return P.error("Login failed",{error:K}),j2.write(`
7615
7615
  Login failed: ${K instanceof Error?K.message:String(K)}
7616
- `),!1}}function Mn4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function px3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new T1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!b9(Y.threadId))throw new T1("Create response did not include a valid thread ID",1);return Y.threadId}function dx3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function cx3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new T1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!dx3(Q))throw new T1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function lx3(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(J)}async function ix3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new T1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function nx3(J){let Z=new uN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Z.exitOverride((B)=>{if(B.code==="commander.help"||B.code==="commander.version"||B.exitCode===0)Hj(),process.exit(0);let N=B.originalError??B;QR4(N)}),od4(Z,{version:"0.0.1774897010-g0ac150",buildTimestamp:"2026-03-30T19:00:10.483Z",buildType:"'release'"}),Z.addHelpText("after",uI4()),Z.configureHelp({formatHelp:bI4}),Z.command("logout").description("Log out by removing stored API key").action(async(B,N)=>{let w=N.optsWithGlobals(),L=await r3(w);await Jf3(L)}),Z.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(B,N)=>{let w=N.optsWithGlobals(),L=await r3(w);await $f3(L,await Ma0(w,L.settings))}),Z.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(B,N,w)=>{let L=w.optsWithGlobals(),O=await r3(L);await SR4(B??"get",O.ampURL,O.secrets),process.exit(process.exitCode??0)}),Z.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(B,N)=>{let w=N.optsWithGlobals(),L=await r3(w);await kR4(L.ampURL,L.secrets),process.exit(process.exitCode??0)}),Z.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
7616
+ `),!1}}function Mn4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function px3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new T1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!b9(Y.threadId))throw new T1("Create response did not include a valid thread ID",1);return Y.threadId}function dx3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function cx3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new T1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!dx3(Q))throw new T1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function lx3(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(J)}async function ix3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new T1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function nx3(J){let Z=new uN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Z.exitOverride((B)=>{if(B.code==="commander.help"||B.code==="commander.version"||B.exitCode===0)Hj(),process.exit(0);let N=B.originalError??B;QR4(N)}),od4(Z,{version:"0.0.1774901365-g0ac150",buildTimestamp:"2026-03-30T20:13:20.449Z",buildType:"'release'"}),Z.addHelpText("after",uI4()),Z.configureHelp({formatHelp:bI4}),Z.command("logout").description("Log out by removing stored API key").action(async(B,N)=>{let w=N.optsWithGlobals(),L=await r3(w);await Jf3(L)}),Z.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(B,N)=>{let w=N.optsWithGlobals(),L=await r3(w);await $f3(L,await Ma0(w,L.settings))}),Z.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(B,N,w)=>{let L=w.optsWithGlobals(),O=await r3(L);await SR4(B??"get",O.ampURL,O.secrets),process.exit(process.exitCode??0)}),Z.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(B,N)=>{let w=N.optsWithGlobals(),L=await r3(w);await kR4(L.ampURL,L.secrets),process.exit(process.exitCode??0)}),Z.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
7617
7617
  Actions:
7618
7618
  create Create a new DTW thread and print its ID
7619
7619
  add-message <message> Send a user message and wait for message_added
@@ -7677,8 +7677,8 @@ ${M}
7677
7677
 
7678
7678
  This thread belongs to a different user and cannot be continued for security reasons. Set AMP_RESUME_OTHER_USER_THREADS_INSECURE=1 to bypass this check.`)}}async function ax3(J){P.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new rn({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,clientID:J.clientID,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized]).then(()=>{return}),toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:uY,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new hV(J.fileSystem),ampURL:J.ampURL,useThreadActors:J.useThreadActors});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw P.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function ox3(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await Bv()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await Bv()).trimEnd(),stdinInput:null}}function rx3(J,Z,Q){if(J.remote&&!Z)throw new T1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new T1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new T1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new T1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new T1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new T1("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(J.streamJsonInput&&typeof J.execute==="string"&&J.execute.trim()!=="")throw new T1("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"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Z&&Q===""&&!J.streamJsonInput&&!J.headless)throw new T1("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"
7679
7679
  Or pipe via stdin: echo "your message" | amp --execute`)}async function DF0(J,Z,Q,Y){let X=process.hrtime.bigint(),K=(G0,J0)=>{let z0=Number(process.hrtime.bigint()-J0)/1e6,i=XO4();P.info("Startup phase",{phase:G0,phaseMs:Math.round(z0),sinceMainMs:i===null?void 0:Math.round(i)})},{userInput:V,stdinInput:G}=await ox3(Z),z=!!Z.streamJson||!!Z.streamJsonThinking;rx3({...Z,streamJson:z},J.executeMode,V),A2(Q,Z);let F=process.hrtime.bigint(),q=Boolean(await J.secrets.get("apiKey",J.ampURL)),W=!J.executeMode&&!Z.headless&&!Z.threadActors&&q;P.info("Interactive auth startup mode",{deferInteractiveAuth:W,hasAPIKeyAtStartup:q,executeMode:J.executeMode,headless:Boolean(Z.headless)});let U=await R7(J,Z,{deferAuth:W});K("runMainThread:createThreadDependencies",F),F=process.hrtime.bigint();let H=await Q51(U);K("runMainThread:createWorkerDeps",F);let{serverStatus:D}=U;if(!W&&hW(D)){let G0=ak(Error(D.error.message));if(G0.message===E3.networkOffline||G0.message===E3.networkTimeout)throw UF0(J.ampURL);throw new T1(E3.invalidAPIKey,1)}let B=o6(D)?D:null,N=B?.user.email,w=Sn4(N),L=t61({userEmail:N,features:B?.features}),O=Z.takeMeBack?!1:void 0,E=B!==null&&e61(O,B);if(!W)await s61(Q,Z,D);let M=$51(D),A=M?.features??[],j=M?.team??null,R=DX0(Z,M);if(R instanceof Error)s3(R.message);if((J.executeMode||z)&&N8(Z.mode)&&!w)throw new T1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(B&&!QE(Z.mode,N))throw new T1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await NT4(V,G,U.configService),await U.asyncDispose(),process.exit(0);if(Z.headless){if(!N||!dJ(N))throw new T1("Headless DTW mode is only available for Amp employees",1);let G0=await U.secretStorage.get("apiKey",J.ampURL);if(!G0)throw new T1("API key required for headless mode. Please run `amp login` first.",1);let J0=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if(J0&&!b9(J0))throw new T1(`Invalid thread ID: ${J0}`,1);let z0=J0?void 0:await zf3({dependencies:U,visibility:R??void 0,usesThreadActors:Z.threadActors?!0:void 0}),i=J0??z0?.threadId;if(!i)throw new T1("Failed to resolve headless thread ID",1);let o=await KI4(i);if(o.status==="already-running")await U.asyncDispose(),await GH(),process.exit(0);try{await eR4({ampURL:J.ampURL,apiKey:G0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:i,ownerUserId:z0?.ownerUserId,threadVersion:z0?.threadVersion,agentMode:z0?.agentMode,initialToolDiscovery:Promise.all([U.mcpService.initialized,U.toolboxService.initialized]).then(()=>{return}),configService:U.configService,mcpService:U.mcpService,toolService:U.toolService,skillService:U.skillService,fileSystem:U.fileSystem,pluginService:U.pluginService,pluginPlatform:U.headlessPluginPlatform,useThreadActors:Z.threadActors?!0:void 0})}finally{await o.release(),await U.asyncDispose()}await GH(),process.exit(0)}let _=J.executeMode?void 0:async(G0)=>Lo(G0,"interactive"),T={threadService:U.threadService,workerDeps:H,createThread:async()=>{let G0=W?await U.serverStatusPromise:D,J0=await sQ0(J.settings,process.cwd(),$51(G0),R);if(J0 instanceof Error)s3(J0.message);return Ze0(H,{threadMeta:J0?yG(J0):void 0,agentMode:Z.mode,onFirstAssistantMessage:_})},validateThreadOwnership:async(G0,J0)=>{if(J0?.nonBlockingOwnershipCheck){An4(G0,U.configService).catch((z0)=>{if(z0 instanceof T1){if(J0.onOwnershipError){J0.onOwnershipError(z0,G0);return}zH(z0,G0);return}P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:z0})});return}try{await An4(G0,U.configService)}catch(z0){if(z0 instanceof T1)throw z0;P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:z0})}},switchThreadVisibility:R,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:_,handleError:zH},u=async(G0)=>{try{if(G0==="dtw")return ax3({ampURL:J.ampURL,configService:U.configService,threadService:U.threadService,mcpService:U.mcpService,clientID:Nn4,toolboxService:U.toolboxService,toolService:U.toolService,skillService:U.skillService,fileSystem:U.fileSystem,threadId:Z.threadId,useThreadActors:Z.threadActors?!0:void 0});return jf4(T,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(J0){if(J0 instanceof T1)throw J0;throw await zH(J0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")j2.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
7680
- `),await GH(),process.exit(1);let m=(async()=>{if(W){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let G0=await U.configService.getLatest(),J0=ou(G0),z0=await c6.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(J0)});if(z0.ok)return P.info("User free tier status:",z0),z0.result;return}catch(G0){P.error("Failed to fetch free tier status:",G0);return}})(),k=!J.executeMode?new st0:null,f,d=null;if(k)f=k,d=(async()=>{let G0=W?await U.serverStatusPromise:U.serverStatus;await s61(Q,Z,G0);let J0=process.hrtime.bigint(),z0=e61(O,G0),i=o6(G0)?t61({userEmail:G0.user.email,features:G0.features}):!1;wn4({dtwEnabled:z0,hasV2TUIAccess:i});let o=await u(z0?"dtw":"worker");if(K("runMainThread:createThreadPool",J0),k.attach(o),V){let t=await j1(o.threadHandles$);if(!t)throw new T1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(G0)=>{let J0=G0 instanceof Error?G0:Error(String(G0));k.setInitError(J0),await zH(G0,Z.threadId)});else F=process.hrtime.bigint(),wn4({dtwEnabled:E,hasV2TUIAccess:L}),f=await u(E?"dtw":"worker"),K("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let h=await U.configService.getLatest();if(K("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),hx3({configService:U.configService,threadService:U.threadService,config:h,useNotificationsForService:p,threadViewStates$:()=>f.threadHandles$.pipe(H4((G0)=>{if(!G0)return k0.of({});return D5(G0.thread$,G0.threadViewState$).pipe(D1(([J0,z0])=>({[J0.id]:z0})))}))}),K("runMainThread:createCliNotificationService",F),J.executeMode){XT4(U.mcpService,J.settings);let G0={userInput:V,stdinInput:G,dependencies:U,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},J0=await HR4({threadPool:f,...G0});if(await Lo(J0,"execute"),Z.archive)await c6.archiveThread({thread:J0,archived:!0},{config:U.configService});await U.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Z.jetbrains||Z.ide){await tf1();let G0=await GE({jetbrainsOnly:Z.jetbrains});if(G0.length===0){if(Z.jetbrains)n=!await U.configService.get("jetbrains.skipInstall")}else if(G0.length===1){let J0=G0[0];if(J0)w$.selectConfig(J0)}else c=!0}F=process.hrtime.bigint();let a=pa0("0.0.1774897010-g0ac150",U.settingsStorage,{startDelayMs:3000});K("runMainThread:createUpdateService",F),F=process.hrtime.bigint();let W0=new Ao0(U.mcpService,J.settings.getWorkspaceRootPath());if(K("runMainThread:createMcpTrustHandler",F),V&&J.executeMode){let G0=await j1(f.threadHandles$);if(!G0)throw new T1("No active thread is available yet.",1);await G0.sendMessage({content:[{type:"text",text:V}]})}F=process.hrtime.bigint();let r=await LX0();K("runMainThread:loadSessionState",F),P.info("Loaded session state:",r);let H0={...r,launchCount:r.launchCount+1};Ij((G0)=>({...G0,launchCount:G0.launchCount+1}));let L0=Z.threadId&&b9(Z.threadId)?Z.threadId:void 0;try{if(F=process.hrtime.bigint(),await Uu4({codebaseContextService:U.codebaseContextService,history:new Ya0,fuzzyServer:U.fuzzyServer,settingsStorage:U.settingsStorage,threadService:U.threadService,skillService:U.skillService,configService:U.configService,secretStorage:U.secretStorage,internalAPIClient:c6,threadPool:f,createSystemPromptDeps:async()=>vn4(U),ideClient:w$,mcpService:U.mcpService,toolboxService:U.toolboxService,mcpTrustHandler:W0,updateService:a,pluginPlatform:U.pluginPlatform,pluginService:U.pluginService},{initialServerStatus:U.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:U.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:L0,showJetBrainsInstaller:n,showIdePickerHint:c,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Nn4,logFile:{path:Y},sessionState:H0,freeTierStatusPromise:m,workspace:j??null,features:A,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-30T19:00:10.483Z"},(G0)=>new De0({...G0,threadPool:G0.threadPool},(J0)=>new M41({...J0,threadState:J0.threadState}))),K("runMainThread:mountApp-returned",F),d)await d}finally{}await U.asyncDispose(),K("runMainThread:dependencies.asyncDispose",X),process.exit(0)}async function r3(J){if(P.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)j2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7681
- `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Ga1({get:async(G)=>{if(G!==rh)return;try{let z=await Cn4(r61,"utf-8");return JSON.parse(z).installationID}catch{return}},set:async(G,z)=>{if(G!==rh)return;await Pn4(iH.dirname(r61),{recursive:!0}),await Px3(r61,JSON.stringify({installationID:z},null,2),{mode:384})}},{clientType:"cli",platform:yz()});Xf1(Y);let X=await LI4({...J,workspaceTrust:{current:!0,changes:su},getHook:process.env.AMP_URL?(G,z)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return z()}:void 0});if(J.mcpConfig){let G=await QT4(J.mcpConfig);X=YT4(X,G)}let K=iH.dirname(X.getSettingsFilePath());zq4(Qv,K);let V=await X.get("url","global");if(!V)V=z7;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!OV(V))P.info("Targeting custom Amp server",{ampURL:V});return X=ox1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:MT4(await Ma0(J,X))}}function sx3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(G,z)=>z.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function tx3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=iH.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?_x3:Cn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function ex3(){YO4();let J=sx3(process.argv),Z=tx3(process.argv,J),Q=Hj4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)o0.level=0;if(kx3(P),P.info("Starting Amp CLI.",{version:"0.0.1774897010-g0ac150",buildTimestamp:"2026-03-30T19:00:10.483Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new T1(E3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await nx3(Q).parseAsync(process.argv)}Vq4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await ex3().catch(zH)});async function $f3(J,Z){let Q=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Q)await J.settings.set("url",process.env.AMP_URL,"global"),Y5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7680
+ `),await GH(),process.exit(1);let m=(async()=>{if(W){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let G0=await U.configService.getLatest(),J0=ou(G0),z0=await c6.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout(J0)});if(z0.ok)return P.info("User free tier status:",z0),z0.result;return}catch(G0){P.error("Failed to fetch free tier status:",G0);return}})(),k=!J.executeMode?new st0:null,f,d=null;if(k)f=k,d=(async()=>{let G0=W?await U.serverStatusPromise:U.serverStatus;await s61(Q,Z,G0);let J0=process.hrtime.bigint(),z0=e61(O,G0),i=o6(G0)?t61({userEmail:G0.user.email,features:G0.features}):!1;wn4({dtwEnabled:z0,hasV2TUIAccess:i});let o=await u(z0?"dtw":"worker");if(K("runMainThread:createThreadPool",J0),k.attach(o),V){let t=await j1(o.threadHandles$);if(!t)throw new T1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(G0)=>{let J0=G0 instanceof Error?G0:Error(String(G0));k.setInitError(J0),await zH(G0,Z.threadId)});else F=process.hrtime.bigint(),wn4({dtwEnabled:E,hasV2TUIAccess:L}),f=await u(E?"dtw":"worker"),K("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let h=await U.configService.getLatest();if(K("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),hx3({configService:U.configService,threadService:U.threadService,config:h,useNotificationsForService:p,threadViewStates$:()=>f.threadHandles$.pipe(H4((G0)=>{if(!G0)return k0.of({});return D5(G0.thread$,G0.threadViewState$).pipe(D1(([J0,z0])=>({[J0.id]:z0})))}))}),K("runMainThread:createCliNotificationService",F),J.executeMode){XT4(U.mcpService,J.settings);let G0={userInput:V,stdinInput:G,dependencies:U,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},J0=await HR4({threadPool:f,...G0});if(await Lo(J0,"execute"),Z.archive)await c6.archiveThread({thread:J0,archived:!0},{config:U.configService});await U.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Z.jetbrains||Z.ide){await tf1();let G0=await GE({jetbrainsOnly:Z.jetbrains});if(G0.length===0){if(Z.jetbrains)n=!await U.configService.get("jetbrains.skipInstall")}else if(G0.length===1){let J0=G0[0];if(J0)w$.selectConfig(J0)}else c=!0}F=process.hrtime.bigint();let a=pa0("0.0.1774901365-g0ac150",U.settingsStorage,{startDelayMs:3000});K("runMainThread:createUpdateService",F),F=process.hrtime.bigint();let W0=new Ao0(U.mcpService,J.settings.getWorkspaceRootPath());if(K("runMainThread:createMcpTrustHandler",F),V&&J.executeMode){let G0=await j1(f.threadHandles$);if(!G0)throw new T1("No active thread is available yet.",1);await G0.sendMessage({content:[{type:"text",text:V}]})}F=process.hrtime.bigint();let r=await LX0();K("runMainThread:loadSessionState",F),P.info("Loaded session state:",r);let H0={...r,launchCount:r.launchCount+1};Ij((G0)=>({...G0,launchCount:G0.launchCount+1}));let L0=Z.threadId&&b9(Z.threadId)?Z.threadId:void 0;try{if(F=process.hrtime.bigint(),await Uu4({codebaseContextService:U.codebaseContextService,history:new Ya0,fuzzyServer:U.fuzzyServer,settingsStorage:U.settingsStorage,threadService:U.threadService,skillService:U.skillService,configService:U.configService,secretStorage:U.secretStorage,internalAPIClient:c6,threadPool:f,createSystemPromptDeps:async()=>vn4(U),ideClient:w$,mcpService:U.mcpService,toolboxService:U.toolboxService,mcpTrustHandler:W0,updateService:a,pluginPlatform:U.pluginPlatform,pluginService:U.pluginService},{initialServerStatus:U.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:U.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:L0,showJetBrainsInstaller:n,showIdePickerHint:c,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Nn4,logFile:{path:Y},sessionState:H0,freeTierStatusPromise:m,workspace:j??null,features:A,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-30T20:13:20.449Z"},(G0)=>new De0({...G0,threadPool:G0.threadPool},(J0)=>new M41({...J0,threadState:J0.threadState}))),K("runMainThread:mountApp-returned",F),d)await d}finally{}await U.asyncDispose(),K("runMainThread:dependencies.asyncDispose",X),process.exit(0)}async function r3(J){if(P.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)j2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7681
+ `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Ga1({get:async(G)=>{if(G!==rh)return;try{let z=await Cn4(r61,"utf-8");return JSON.parse(z).installationID}catch{return}},set:async(G,z)=>{if(G!==rh)return;await Pn4(iH.dirname(r61),{recursive:!0}),await Px3(r61,JSON.stringify({installationID:z},null,2),{mode:384})}},{clientType:"cli",platform:yz()});Xf1(Y);let X=await LI4({...J,workspaceTrust:{current:!0,changes:su},getHook:process.env.AMP_URL?(G,z)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return z()}:void 0});if(J.mcpConfig){let G=await QT4(J.mcpConfig);X=YT4(X,G)}let K=iH.dirname(X.getSettingsFilePath());zq4(Qv,K);let V=await X.get("url","global");if(!V)V=z7;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!OV(V))P.info("Targeting custom Amp server",{ampURL:V});return X=ox1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:MT4(await Ma0(J,X))}}function sx3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(G,z)=>z.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function tx3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=iH.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?_x3:Cn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function ex3(){YO4();let J=sx3(process.argv),Z=tx3(process.argv,J),Q=Hj4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)o0.level=0;if(kx3(P),P.info("Starting Amp CLI.",{version:"0.0.1774901365-g0ac150",buildTimestamp:"2026-03-30T20:13:20.449Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new T1(E3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await nx3(Q).parseAsync(process.argv)}Vq4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await ex3().catch(zH)});async function $f3(J,Z){let Q=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Q)await J.settings.set("url",process.env.AMP_URL,"global"),Y5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7682
7682
  `);else if(!OV(J.ampURL))Y5.write(`Logging in to ${new URL(J.ampURL).hostname}
7683
7683
  `);let Y=process.env.AMP_API_KEY;if(Y)Y5.write(`API key found in environment variable, storing...
7684
7684
  `),await Z.set("apiKey",Y,J.ampURL),Y5.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1774897010-g0ac150",
3
+ "version": "0.0.1774901365-g0ac150",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {