@sourcegraph/amp 0.0.1773878033-g2f2f23 → 0.0.1773878698-g9a9736

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
@@ -6167,11 +6167,11 @@ ${W}`))}},error:(U)=>{if(!D)D=!0,z(Error(`Failed to spawn brew: ${U.message}`))}
6167
6167
  ${W}`;if(X==="pnpm"&&W.includes("Unable to find the global bin directory"))H+=`
6168
6168
 
6169
6169
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
6170
- npm install -g @sourcegraph/amp`;z(Error(H))}},error:(U)=>{if(!G)G=!0,z(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!G)G=!0,V()}})})}h0();h0();hP();async function x90(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let z=await fetch(X,{signal:K.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let F=await z.json(),q=F.version??F["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=iz4(J,q),D=G<0,U,W;if(F.time){let H=F.time[J],B=F.time[q],w=Date.now();if(H)U=Math.floor((w-new Date(H).getTime())/3600000);if(B)W=Math.floor((w-new Date(B).getTime())/3600000)}return I.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:G,hasUpdate:D,currentVersionAge:U,latestVersionAge:W}),{hasUpdate:D,latestVersion:q,currentVersion:J,currentVersionAge:U,latestVersionAge:W,source:"npm"}}catch(z){return I.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var yC5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function u90(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${yC5}?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=iz4(J,X),V=K<0;return I.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return I.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var xC5=604800000;function lz4(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>xC5)return{ageMs:Q};return null}function iz4(J,Z){let Q=(V)=>{let[z,F]=V.split("-");return{parts:z?.split(".").map(Number)||[],label:F}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let z=Y.parts[V]||0,F=X.parts[V]||0;if(z<F)return-1;if(z>F)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 cf0(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?hW(Q):void 0;return{sha:Y,age:X}}catch{return null}}H1();function lf0(J,Z,Q={}){let Y=new l1,X=Y.pipe(P6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new TV().scoped("update"),V=Q.startDelayMs??0;if(V>0)await Qz(V);let z=X.subscribe({next:(F)=>{K.debug("emit new state",F)}});try{let F=process.env.AMP_TEST_UPDATE_STATUS;if(F){K.debug("using fake update status for testing",{status:F}),await Qz(500),Y.next(F);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let q=await Z.get("updates.mode");if(q==="disabled"){K.debug("checking disabled");return}let G=await y90(),D=G==="binary"||G==="brew";K.debug("checking",{currentVersion:J,mode:q,packageManager:G,isBinaryDistribution:D});let U=D?await u90(J):await x90(J,$L());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let W=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let H=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!q)q=G==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:G,mode:q});if(G==="brew"){if(!W())Y.next("update-available-brew");return}if(G==="binary"&&process.execPath!==bf0()){if(K.debug("non-standard binary path, showing warning"),!W())Y.next("update-available-unrecognized-path");return}if(q==="warn"){if(!W())Y.next("update-available");return}if(!G){if(K.debug("auto-update not supported, falling back to warn mode"),!W())Y.next("update-available");return}if(G==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!W())Y.next("update-available");return}try{await Mm(U.latestVersion,G);let H=await EH(U.latestVersion),B={from:U.currentVersion,to:U.latestVersion,...H};if(H.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(F){K.debug("check failed",{error:F})}finally{await Qz(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}hP();import{stderr as sz}from"node:process";function nz4(J){let Z=new VH().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 yf0(Y.force||!1,Y.verbose||!1,"0.0.1773878033-g2f2f23"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new VH("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 uC5(Y.targetVersion)});J.addCommand(Q)}async function uC5(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")sz.write(J1.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6170
+ npm install -g @sourcegraph/amp`;z(Error(H))}},error:(U)=>{if(!G)G=!0,z(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!G)G=!0,V()}})})}h0();h0();hP();async function x90(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let z=await fetch(X,{signal:K.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let F=await z.json(),q=F.version??F["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=iz4(J,q),D=G<0,U,W;if(F.time){let H=F.time[J],B=F.time[q],w=Date.now();if(H)U=Math.floor((w-new Date(H).getTime())/3600000);if(B)W=Math.floor((w-new Date(B).getTime())/3600000)}return I.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:G,hasUpdate:D,currentVersionAge:U,latestVersionAge:W}),{hasUpdate:D,latestVersion:q,currentVersion:J,currentVersionAge:U,latestVersionAge:W,source:"npm"}}catch(z){return I.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var yC5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function u90(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${yC5}?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=iz4(J,X),V=K<0;return I.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return I.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var xC5=604800000;function lz4(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>xC5)return{ageMs:Q};return null}function iz4(J,Z){let Q=(V)=>{let[z,F]=V.split("-");return{parts:z?.split(".").map(Number)||[],label:F}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let z=Y.parts[V]||0,F=X.parts[V]||0;if(z<F)return-1;if(z>F)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 cf0(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?hW(Q):void 0;return{sha:Y,age:X}}catch{return null}}H1();function lf0(J,Z,Q={}){let Y=new l1,X=Y.pipe(P6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new TV().scoped("update"),V=Q.startDelayMs??0;if(V>0)await Qz(V);let z=X.subscribe({next:(F)=>{K.debug("emit new state",F)}});try{let F=process.env.AMP_TEST_UPDATE_STATUS;if(F){K.debug("using fake update status for testing",{status:F}),await Qz(500),Y.next(F);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let q=await Z.get("updates.mode");if(q==="disabled"){K.debug("checking disabled");return}let G=await y90(),D=G==="binary"||G==="brew";K.debug("checking",{currentVersion:J,mode:q,packageManager:G,isBinaryDistribution:D});let U=D?await u90(J):await x90(J,$L());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let W=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let H=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!q)q=G==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:G,mode:q});if(G==="brew"){if(!W())Y.next("update-available-brew");return}if(G==="binary"&&process.execPath!==bf0()){if(K.debug("non-standard binary path, showing warning"),!W())Y.next("update-available-unrecognized-path");return}if(q==="warn"){if(!W())Y.next("update-available");return}if(!G){if(K.debug("auto-update not supported, falling back to warn mode"),!W())Y.next("update-available");return}if(G==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!W())Y.next("update-available");return}try{await Mm(U.latestVersion,G);let H=await EH(U.latestVersion),B={from:U.currentVersion,to:U.latestVersion,...H};if(H.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(F){K.debug("check failed",{error:F})}finally{await Qz(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}hP();import{stderr as sz}from"node:process";function nz4(J){let Z=new VH().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 yf0(Y.force||!1,Y.verbose||!1,"0.0.1773878698-g9a9736"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new VH("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 uC5(Y.targetVersion)});J.addCommand(Q)}async function uC5(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")sz.write(J1.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6171
6171
 
6172
6172
  `));try{if(!J){sz.write(J1.blue(`Checking for updates...
6173
- `));let{hasUpdate:Y,latestVersion:X}=xf0()?await u90("0.0.1773878033-g2f2f23"):await x90("0.0.1773878033-g2f2f23",$L());if(!Y){let K=cf0("0.0.1773878033-g2f2f23"),V=K?.age?`released ${K.age} ago`:`built ${hW(new Date("2026-03-18T23:57:58.449Z"))} ago`;sz.write(J1.green(`✓ Amp is already up to date on version ${"0.0.1773878033-g2f2f23"} (${V})
6174
- `));let z=await EH("0.0.1773878033-g2f2f23");if(z.warning)sz.write(`
6173
+ `));let{hasUpdate:Y,latestVersion:X}=xf0()?await u90("0.0.1773878698-g9a9736"):await x90("0.0.1773878698-g9a9736",$L());if(!Y){let K=cf0("0.0.1773878698-g9a9736"),V=K?.age?`released ${K.age} ago`:`built ${hW(new Date("2026-03-19T00:09:00.436Z"))} ago`;sz.write(J1.green(`✓ Amp is already up to date on version ${"0.0.1773878698-g9a9736"} (${V})
6174
+ `));let z=await EH("0.0.1773878698-g9a9736");if(z.warning)sz.write(`
6175
6175
  `+J1.yellow(z.warning)+`
6176
6176
  `);process.exit(0)}if(!X)sz.write(J1.yellow("[WARN] could not find latest version")),process.exit(0);J=X}sz.write(J1.blue(`Updating to version ${J}...
6177
6177
  `)),await Mm(J,void 0,(Y)=>{sz.write(J1.dim(`Running: ${Y}
@@ -7338,7 +7338,7 @@ Ctrl-X, Y, Z to unlock`;if(U){let u=q.text.replace(/`([^`]+)`/g,"$1")+`
7338
7338
  `),K=[];for(let V=0;V<X.length;V++){let q=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 G of q)if(G.startsWith("\x00")&&G.endsWith("\x01"))K.push(new C(G.slice(1,-1),new h({color:Y.app.keybind,bold:!0})));else K.push(new C(G,new h({color:Q.colorScheme.foreground})));if(V<X.length-1)K.push(new C(`
7339
7339
  `))}return new c0({decoration:{color:Q.colorScheme.background,border:f1.all(new k1(Y.app.keybind,1,"rounded"))},child:new i0({padding:C0.symmetric(0,1),child:new e({text:new C(void 0,void 0,K)})})})}}class Zd0 extends R7{chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=HJ0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new $d0({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 CO4(J,Z,Q,Y,X,K,V){if(K<=0)return null;switch(J){case"horizontal-bar":{let z=Q;return z>=0&&z<K?z:null}case"bar":case"stacked-bar":{let z=V?a8:0,F=Y-z;if(F<=0)return null;let q=Z-z;if(q<0||q>=F)return null;let G=Math.max(1,Math.floor(F/K)),D=Math.floor(q/G);return D>=0&&D<K?D:null}case"line":case"sparkline":case"stacked-area":{let z=V?a8:0,F=Y-z;if(F<=0)return null;let q=Math.max(0,Math.min(F-1,Z-z));if(K===1)return 0;let G=F/(K-1),D=Math.round(q/G);return Math.max(0,Math.min(K-1,D))}default:return null}}function Ur5(J,Z,Q,Y,X,K,V,z){if(X<=0||Z<0||Z>=X)return null;let F=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let q=K?a8:0,G=Q-q,D=Y-(K?F:0);if(G<=0||D<=0)return null;let U=Math.max(1,Math.floor(G/X)),W=q+Z*U+Math.floor(U/2),H=z>0?V/z:0,B=Math.round((1-H)*(D-1));return{x:W,y:B}}case"line":case"sparkline":case"stacked-area":{let q=K?a8:0,G=Q-q,D=Y-(K?F:0);if(G<=0||D<=0)return null;let U=X>1?q+Math.round(Z/(X-1)*(G-1)):q+Math.floor(G/2),W=z>0?V/z:0,H=Math.round((1-W)*(D-1));return{x:U,y:H}}default:return null}}function Wr5(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 Hr5(J,Z,Q,Y,X){if(Q.length<=1){let z=Y(J.value),F=J.meta?` (${J.meta})`:"";return J.label.length+2+z.length+F.length}let K=J.label.length,V=0;for(let z of Q){let F=z.points[Z];if(!F)continue;V+=F.value;let q=2+z.name.length+2+Y(F.value).length;K=Math.max(K,q)}if(X){let z=9+Y(V).length;K=Math.max(K,z)}return K}function Br5(J,Z,Q,Y,X,K,V){let z;try{let H=j1.of(J),B=u0.of(J);z={foreground:H.colorScheme.foreground,background:H.colorScheme.background,border:B.app.keybind}}catch{z={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let F=new h({color:z.foreground,bold:!0}),q=new h({color:z.foreground}),G=new h({color:z.foreground,dim:!0}),D=[],U=new h({color:z.foreground,underline:!0}),W=(H,B)=>new C(B,U,void 0,$20(H),()=>{E8(J,H)});if(Y.length<=1){if(D.push(new C(`${Z.label}: `,F)),Z.link)D.push(W(Z.link,K(Z.value)));else D.push(new C(K(Z.value),q));if(Z.meta)D.push(new C(` (${Z.meta})`,G))}else{let H=V==="stacked-bar"||V==="stacked-area";D.push(new C(`${Z.label}
7340
7340
  `,F));let B=0;for(let w=0;w<Y.length;w++){let N=Y[w],E=N.points[Q];if(!E)continue;B+=E.value;let O=N.color??X[w%X.length]??z.foreground;if(D.push(new C("● ",new h({color:O}))),D.push(new C(`${N.name}: `,G)),E.link)D.push(W(E.link,K(E.value)));else D.push(new C(K(E.value),q));if(w<Y.length-1||H)D.push(new C(`
7341
- `))}if(H)D.push(new C(" ",G)),D.push(new C("Total: ",G)),D.push(new C(K(B),q))}return new c0({decoration:{color:z.background,border:f1.all(new k1(z.border,1,"rounded"))},child:new e({text:new C(void 0,void 0,D)})})}VN();h0();p9();import{execSync as lr5}from"node:child_process";DN();_2();N3();T2();wh();uX();t7();m$();GY();RO();j4();Tu();Tk();H1();var CL4=W4(vq(),1);import{writeFile as AL4}from"fs/promises";import jL4 from"path";h0();t7();class Qd0{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.1773878033-g2f2f23"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await it(Z,this.configService)}catch(Z){I.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 zB extends d0{props;constructor(J){super();this.props=J}createState(){return new TO4}}class TO4 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 _O4 extends p0{controller=new s2;focusNode=new s4({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=u0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,z=f1.all(new k1(Q.foreground,1,"solid")),F=new GJ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(W)=>{let H=W.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),q=new q1({children:[new c0({decoration:{color:Q.background},child:new e({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:F})]}),G=new c0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,[new C("Command: ",new h({color:Q.foreground})),new C(this.widget.props.commandName,new h({color:Y.command,bold:!0}))])})}),D=[];if(V)D.push(new C("Enter",new h({color:Y.keybind}))),D.push(new C(" to submit, ",new h({color:Q.foreground,dim:!0})));D.push(new C("Esc",new h({color:Y.keybind}))),D.push(new C(" to cancel",new h({color:Q.foreground,dim:!0})));let U=new c0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,D)})});return new c0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new x0({children:[G,new I0({height:1}),q,new q3,U]})})}}class qd extends d0{props;constructor(J){super();this.props=J}createState(){return new _O4}}import{isDeepStrictEqual as Yd0}from"node:util";var wr5=/[\\/_ +.#"@[({&]/,Nr5=/[\\/_ +.#"@[({&]/g,Er5=/[\s-]/,SO4=/[\s-]/g;function NJ0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let z=`${X},${K}`;if(V[z]!==void 0)return V[z];let F=Y.charAt(K),q=Q.indexOf(F,X),G=0,D,U,W,H;while(q>=0){if(D=NJ0(J,Z,Q,Y,q+1,K+1,V),D>G){if(q===X)D*=1;else if(Er5.test(J.charAt(q-1))){if(D*=0.9,H=J.slice(X,q-1).match(SO4),H&&X>0)D*=0.999**H.length}else if(wr5.test(J.charAt(q-1))){if(D*=0.8,W=J.slice(X,q-1).match(Nr5),W&&X>0)D*=0.999**W.length}else if(D*=0.3,X>0)D*=0.999**(q-X);if(J.charAt(q)!==Z.charAt(K))D*=0.9999}if(D<0.1&&(Q.charAt(q-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(q-1)!==Y.charAt(K))){if(U=NJ0(J,Z,Q,Y,q+1,K+2,V),U*0.1>D)D=U*0.1}if(D>G)G=D;q=Q.indexOf(F,q+1)}return V[z]=G,G}function wJ0(J){return J.toLowerCase().replace(SO4," ")}function vO4(J,Z){let Q=NJ0(J,Z,wJ0(J),wJ0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let z of Y){let F=NJ0(J,z,wJ0(J),wJ0(z),0,0,{});if(F===0)return Q;X+=F,K+=z.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class J_{}class Z_{}class EJ0{}class OJ0{}class kO4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new yO4}}class yO4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function Or5(J,Z){if(J==="")return{matches:!0,score:1};let Q=vO4(Z,J);return{matches:Q>0.15,score:Q}}class $2 extends d0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new xO4}}class xO4 extends p0{textController;focusNode;scrollController=new X5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new s2(this.widget.props.controller?.query??""),this.focusNode=new s4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),W6.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)=>Yd0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!Yd0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>Yd0(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 J_){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof Z_){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof EJ0){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 OJ0)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,...Or5(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;oT(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(),W6.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=u0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=f1.all(new k1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,z=new GJ({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}),F=new S7({shortcuts:new Map([[new X4("ArrowDown"),new J_],[new X4("ArrowUp"),new Z_],[new X4("Tab"),new J_],[new X4("Tab",{shift:!0}),new Z_],[new X4("n",{ctrl:!0}),new J_],[new X4("p",{ctrl:!0}),new Z_],[new X4("Enter"),new EJ0],[new X4("Escape"),new OJ0]]),focusNode:this.focusNode,child:z}),q=new k9({actions:new Map([[J_,new t4(this.invoke)],[Z_,new t4(this.invoke)],[EJ0,new t4(this.invoke)],[OJ0,new t4(this.invoke)]]),child:F}),G=new q1({children:[new c0({decoration:{color:Q.background},child:new e({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:q})]});this.itemContexts=[];let D;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";D=new I0({height:10,child:new a1({child:new e({text:new C(w,new h({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)D=new T1({child:new a1({child:new e({text:new C(this.widget.props.emptyStateText,new h({color:Q.foreground,dim:!0}))})})});else{let w=Y.map((N,E)=>{let O=E===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(N,O,L,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new c0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C(this.widget.props.getLabel(N),new h({color:j,dim:L}))})})}return new kO4(new r1({onClick:(A)=>this.handleItemClick(E,A.clickCount),child:M}),(A)=>{this.itemContexts[E]=A})});D=new x0({children:w,crossAxisAlignment:"start"})}let U=new r1({onScroll:this.handleScroll,opaque:!1,child:new R6({controller:this.scrollController,autofocus:!1,child:D})}),W=[];if(this.widget.props.title){let w=new c0({padding:C0.symmetric(1,0),child:new e({text:new C(this.widget.props.title,new h({color:Z.app.command,bold:!0}))})});W.push(w)}if(!K)W.push(G,new I0({height:1}));if(this.textController.text!==""){let w=Y.length>0?Y[this.selectedIndex]:void 0,N=w&&this.widget.props.buildDisabledReasonWidget?.(w,J);W.push(new T1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new T1({child:U}),new c0({padding:C0.only({top:1}),child:new a1({child:N??new I0({height:1})})})]})}))}else W.push(new T1({child:U}));if(this.widget.props.footer)W.push(this.widget.props.footer);return new c0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:W})})}}function uO4(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 Xd0 extends i1{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)=>uO4(X.pubDate).length));return new $2({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,z)=>{let F=u0.of(z),{colors:q}=F,G=F.app,D=K?G.selectionBackground:void 0,U=K?G.selectionForeground:q.foreground,W=q.mutedForeground,H=(B,w)=>new I0({width:w,child:q1.end([new e({text:new C(B,new h({color:W}))})])});return new c0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[new T1({child:new e({text:new C(X.title,new h({color:U})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),H(uO4(X.pubDate),Q)]})})}})}}j4();class Kd0 extends d0{createState(){return new fO4}}class fO4 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=u0.of(J).colors;return new e({text:new C("●",new h({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}var Lr5=/\/threads\/(T-[^/?#\s<>]+)/i;function Mr5(J){let Z=J.trim(),Y=Z.match(Lr5)?.[1];if(Y&&B8(Y))return Y;let X=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(B8(X))return X;return null}function Ar5(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 z=V.relationships.find((F)=>F.role==="child"&&Z.has(F.threadID)&&(F.type==="fork"||F.type==="handoff"));if(z){Y.set(V.id,z.type);let F=z.threadID,q=Q.get(F)||[];q.push(V),Q.set(F,q)}else X.push(V)}return d70.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 Vd0(J,Z,Q){return new e({text:new C(`${J}${Z}`,new h({color:Q})),maxLines:1})}function jr5(J,Z,Q,Y){return[Vd0("+",J,Y.success),q3.horizontal(1),Vd0("~",Z,Y.warning),q3.horizontal(1),Vd0("-",Q,Y.destructive)]}function Ir5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class LJ0 extends d0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new bO4}}class bO4 extends p0{spinner=new o5;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((E)=>E.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((E)=>E.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],z=new Set(V),F=Z.currentThreadID,q=[...K].sort((E,O)=>{if(F){if(E.id===F)return-1;if(O.id===F)return 1}let L=V.indexOf(E.id),M=V.indexOf(O.id);if(L!==-1&&M!==-1)return L-M;if(L!==-1)return-1;if(M!==-1)return 1;return 0}),G=Ar5(q),D=Math.max(0,...G.map((E)=>E.description.timeAgo.length)),U=u0.of(J),W=new i0({padding:C0.symmetric(0,1),child:new a1({child:new e({text:new C("",new h({color:U.colors.foreground,dim:!0}),[new C("Ctrl+T",new h({color:U.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new h({color:U.colors.foreground,dim:!0}))])})})}),H="",B=null,w=(E)=>{if(E!==H)H=E,B=Mr5(E);return B};return new $2({items:G,getLabel:(E)=>`${E.title} ${E.id}`,filterItem:(E,O)=>{let L=w(O);if(L)return E.id.toLowerCase()===L.toLowerCase();return!0},normalizeQuery:(E)=>w(E)?"":E,onAccept:async(E,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let L=Z.onSelect(E.id,O);if(!Ir5(L))return;this.setSwitchingThread(!0);try{await L}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(E)=>{if(Z.previewController){if(E)Z.previewController.select(E.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:W,renderItem:(E,O,L,M)=>{let A=u0.of(M),{app:j,colors:P}=A,_=O?j.selectionBackground:void 0,S=O?j.selectionForeground:P.foreground,y=P.mutedForeground,m=(s,B0)=>new I0({width:B0,child:q1.end([new e({text:new C(s,new h({color:y}))})])}),b=Z.threadViewStates[E.id],v=[],u=E.relationshipType==="handoff",p=new yp({connectorColor:P.mutedForeground});if(E.depth>0){let s=[],B0=E.ancestorsAreLast.slice(1);for(let O0 of B0)s.push(new C(p.getAncestorPrefix(O0),new h({color:p.connectorColor,dim:p.connectorDim})));let o=E.isLast?p.elbow:p.tee,q0=p.getConnectorText(o);s.push(new C(q0,new h({color:p.connectorColor,dim:p.connectorDim}))),v.push(new e({text:new C("",void 0,s)}))}let c=[],f=F===E.id?new C("(current) ",new h({color:P.success})):z.has(E.id)?new C("(visited) ",new h({color:P.foreground,dim:!0})):null;if(f)c.push(new e({text:f}));if(bW(b))c.push(new Kd0),c.push(new I0({width:1}));let a=E.title;if(E.relationshipType==="fork"){let s=a.match(/^Forked\((\d+)\): /);if(s)a=a.slice(s[0].length);else while(a.startsWith("Forked: "))a=a.slice(8);c.push(new e({text:new C("[fork] ",new h({color:P.primary}))}))}else if(u)c.push(new e({text:new C("[handoff] ",new h({color:P.accent}))}));if(c.push(new T1({child:new e({text:new C(a,new h({color:S})),overflow:"ellipsis",maxLines:1})})),c.push(new I0({width:2})),E.diffStats&&(E.diffStats.added>0||E.diffStats.changed>0||E.diffStats.deleted>0)){let s=O?{success:y,warning:y,destructive:y}:P;c.push(...jr5(E.diffStats.added,E.diffStats.changed,E.diffStats.deleted,s)),c.push(new I0({width:2}))}return c.push(m(E.description.timeAgo,D)),new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[...v,...c]})})}})}}function hO4(J){return 1-(1-J)**3}function gO4(J,Z,Q){return J+(Z-J)*Q}function Gd(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=hO4(Y),V=hO4(X);return{x:gO4(J.startOffset.x,J.targetOffset.x,K),y:gO4(J.startOffset.y,J.targetOffset.y,V)}}var Rr5={nodeWidth:3,horizontalSpacing:3};class Q_{options;constructor(J={}){this.options={...Rr5,...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=(z,F)=>{let q=Z.get(z.id)??[];if(this.options.comparator)q.sort(this.options.comparator);let G={...z,parentID:Q.get(z.id)};if(q.length===0){Y.push({node:G,position:{x:K,y:F}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let D=[];for(let B of q)D.push(V(B,F+1));let U=Math.min(...D),W=Math.max(...D),H=Math.floor((U+W)/2);return Y.push({node:G,position:{x:H,y:F}}),H};for(let z of X)V(z,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,z=K.parentID;while(z){if(z===K.id){V=!0;break}z=Y.get(z)}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 Pr5={nodeWidth:3,nodeHeight:2};class Y_{options;constructor(J={}){this.options={...Pr5,...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 z=V+1;if(Y.push({x:X,y:z}),X!==K)Y.push({x:K,y:z});let F=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:F}),Y}}var Cr5={nodeWidth:3,nodeHeight:2},Tr5={x:0,y:0};class AJ0{options;constructor(J={}){this.options={...Cr5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=Tr5,X,K,V,z){let F=z?u0.of(z):null,q=F?.colors,G=F?.app,D=q?.mutedForeground??q?.foreground;if(J.length===0)return new e({text:new C("No nodes",new h({color:D}))});let U=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,w=[];for(let j=U;j>=0;j--){let P=J.filter((y)=>y.position.y===j);P.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new I0({width:y.position.x-S}));let m=y.node.id===Q,b=V?.(y.node.data)??!1,v=K?.activeFlashOn??!1,u=y.node.id===K?.copyFlashNodeId;_.push(this.renderNode(m,b,v,u,G,q)),S=y.position.x+this.options.nodeWidth}if(w.push(new q1({crossAxisAlignment:"start",children:_})),j>0){let y=J.filter((v)=>v.position.y===j-1),m=P,b=this.renderConnectors(y,m,Z,H,q,G);w.push(...b)}}let N=new x0({crossAxisAlignment:"start",children:w}),E=Math.round(Y.x),O=Math.round(Y.y*B),L=(U+1)*B,M=[new I0({width:H,height:L}),new u6({left:E,top:O,child:N})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),P=U-A.position.y,_=E+A.position.x+this.options.nodeWidth+1,S=O+P*B+1,y=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)y=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new u6({left:_,top:S,child:this.renderInfoBox(j,y,q,G)}))}return new c0({padding:C0.horizontal(2),child:new vH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",z="└─┘",F=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,q=!1;if(Y)F=X?.threadGraphNodeSelected??K?.primary??F,V="┏━┓",z="┗━┛",q=!0;else if(Z&&Q)F=X?.toolSuccess??K?.primary??F,V="┏━┓",z="┗━┛";return new x0({crossAxisAlignment:"start",children:[new e({text:new C(V,new h({color:F,bold:q}))}),new e({text:new C(z,new h({color:F,bold:q}))})]})}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,z="┌"+"─".repeat(V)+"┐",F="└"+"─".repeat(V)+"┘",q=Q?.border??Y?.threadGraphConnector??Q?.foreground,G=Q?.foreground,D=[new e({text:new C(z,new h({color:q}))})];for(let U of X){let W=" ".repeat(K-U.length);D.push(new e({text:new C("│ ",new h({color:q}),[new C(U+W,new h({color:G??q})),new C(" │",new h({color:q}))])}))}return D.push(new e({text:new C(F,new h({color:q}))})),new x0({crossAxisAlignment:"start",children:D})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),F=K?.threadGraphConnector??X?.primary??X?.foreground,q=Array(Y).fill(" ");for(let U of Z){let W=U.position.x+z;if(W>=0&&W<Y)q[W]="▲"}V.push(new e({text:new C(q.join(""),new h({color:F}))}));let G=Array(Y).fill(" ");for(let U of J){let W=Z.filter((E)=>E.node.parentID===U.node.id);if(W.length===0)continue;let H=U.position.x+z,B=W.map((E)=>E.position.x+z),w=Math.min(...B),N=Math.max(...B);for(let E=w;E<=N;E++)if(E>=0&&E<Y){if(E===H)if(W.length===1&&B[0]===H)G[E]="│";else if(E===w)G[E]="└";else if(E===N)G[E]="┘";else G[E]="┬";else if(B.includes(E))if(E===w)G[E]="└";else if(E===N)G[E]="┘";else G[E]="┴";else if(G[E]===" ")G[E]="─"}}V.push(new e({text:new C(G.join(""),new h({color:F}))}));let D=Array(Y).fill(" ");for(let U of J){if(Z.filter((B)=>B.node.parentID===U.node.id).length===0)continue;let H=U.position.x+z;if(H>=0&&H<Y)D[H]="│"}return V.push(new e({text:new C(D.join(""),new h({color:F}))})),V}}var _r5={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},Sr5={x:0,y:0};class zd0{options;constructor(J={}){this.options={..._r5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=Sr5,X,K,V,z){let F=z?u0.of(z):null,q=F?.colors,G=F?.app,D=q?.mutedForeground??q?.foreground;if(J.length===0)return new e({text:new C("No nodes",new h({color:D}))});let U=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,w=[];for(let j=U;j>=0;j--){let P=J.filter((y)=>y.position.y===j);P.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new I0({width:y.position.x-S}));let m=y.node.id===Q,b=V?.(y.node.data)??!1,v=K?.activeFlashOn??!1;_.push(this.renderNode(m,b,v,G,q)),S=y.position.x+this.options.nodeWidth}if(w.push(new q1({crossAxisAlignment:"start",children:_})),j>0){let y=J.filter((v)=>v.position.y===j-1),m=P,b=this.renderConnectors(y,m,Z,H,q,G);w.push(...b)}}let N=new x0({crossAxisAlignment:"start",children:w}),E=Math.round(Y.x),O=Math.round(Y.y*B),L=(U+1)*B,M=[new I0({width:H,height:L}),new u6({left:E,top:O,child:N})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),P=U-A.position.y,_=E+A.position.x+this.options.nodeWidth+1,S=O+P*B,y=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)y=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new u6({left:_,top:S,child:this.renderInfoBox(j,y,q)}))}return new c0({padding:C0.horizontal(2),child:new vH(new i6({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 h({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 h({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:K})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),F=K?.threadGraphConnector??X?.primary??X?.foreground,q=Array(Y).fill(" ");for(let G of J){let D=Z.filter((w)=>w.node.parentID===G.node.id);if(D.length===0)continue;let U=G.position.x+z,W=D.map((w)=>w.position.x+z),H=Math.min(...W),B=Math.max(...W);for(let w=H;w<=B;w++)if(w>=0&&w<Y){let N=w===U,E=W.includes(w);if(N&&E)if(D.length===1)q[w]="│";else if(w===H)q[w]="└";else if(w===B)q[w]="┘";else q[w]="┼";else if(N)if(w===H)q[w]="└";else if(w===B)q[w]="┘";else q[w]="┬";else if(E)if(w===H)q[w]="└";else if(w===B)q[w]="┘";else q[w]="┴";else if(q[w]===" ")q[w]="─"}}return V.push(new e({text:new C(q.join(""),new h({color:F}))})),V}}class Dd extends L3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new mO4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class mO4 extends A4{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 oL extends d0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new cO4}}var pO4=400,dO4=300,vr5=16;class cO4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new Q_({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new Y_;renderer=new zd0;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((F)=>F.id)),Q=new Set(this.widget.props.threads.map((F)=>F.id));if(Z.size!==Q.size||[...Z].some((F)=>!Q.has(F)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,K=this.widget.props.initialSelectedThreadID;if(X!==K&&K){let q=this.widget.props.threads.find((G)=>G.id===K);if(q)this.selectedNodeId=q.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((F)=>F.isActive),z=this.widget.props.threads.some((F)=>F.isActive);if(V!==z){if(this.stopActiveFlashTimer(),z)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:pO4,durationY:dO4};let Z=Math.max(pO4,dO4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=Gd(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},vr5)}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,z=2,F=Math.floor(this.viewportHeight/2),G=Math.floor(F/2)-V;return{x:K,y:G}}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,z)=>V.position.x-z.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 G=(this.selectedNodeId?this.positionedNodes.find((D)=>D.node.id===this.selectedNodeId):null)??this.positionedNodes.find((D)=>!D.node.parentID);if(G){let D=Math.max(...this.positionedNodes.map((U)=>U.position.y));this.currentOffset=this.calculateCenterOffset(G.position.x,G.position.y,D)}}let X=this.widget.props.showTitle??!0,K=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+K},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(q)=>q.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(q)=>q.isActive??!1,J),F=new Dd({onWidth:(q)=>{if(this.viewportWidth!==q)this.viewportWidth=q,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(q)=>{if(this.viewportHeight!==q)this.viewportHeight=q,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new x4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:F})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class iO4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new nO4}}class nO4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var lO4=30,kr5=30;class X_{}class K_{}class jJ0{}class IJ0{}class Fd0 extends d0{props;constructor(J){super();this.props=J}createState(){return new aO4}}class aO4 extends p0{highlightedIndex=0;controller=new s2;focusNode;scrollController=new X5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new s4({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),W6.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;oT(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 X_){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof K_){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof jJ0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof IJ0)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(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=u0.of(J),{colors:Y,app:X}=Q,z=e1.of(J).size.width>=kr5+lO4,F=f1.all(new k1(Y.foreground,1,"solid")),q=this.filteredClusters[this.highlightedIndex]??null,G=new c0({padding:C0.symmetric(1,0),child:new e({text:new C("Select a cluster",new h({color:X.command,bold:!0}))})}),D=new GJ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),U=new S7({shortcuts:new Map([[new X4("ArrowDown"),new X_],[new X4("ArrowUp"),new K_],[new X4("Tab"),new X_],[new X4("Tab",{shift:!0}),new K_],[new X4("n",{ctrl:!0}),new X_],[new X4("p",{ctrl:!0}),new K_],[new X4("Enter"),new jJ0],[new X4("Escape"),new IJ0]]),focusNode:this.focusNode,child:D}),W=new k9({actions:new Map([[X_,new t4(this.invoke)],[K_,new t4(this.invoke)],[jJ0,new t4(this.invoke)],[IJ0,new t4(this.invoke)]]),child:U}),H=new q1({children:[new c0({decoration:{color:Y.background},child:new e({text:new C(">",new h({color:Y.foreground}))})}),new T1({child:W})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,P=Z?M.threads.some((m)=>m.id===Z):!1,_=j?X.selectionBackground:void 0,S=j?X.selectionForeground:Y.foreground,y=[new C(M.label,new h({color:S})),new C(` (${M.threads.length})`,new h({color:S,dim:!0}))];if(P)y.push(new C(" (current)",new h({color:j?X.selectionForeground:Y.success})));return new iO4(new r1({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C("",void 0,y)})})}),(m)=>{this.itemContexts[A]=m})}),w=new x0({children:B,crossAxisAlignment:"start"}),N=new T1({child:new r1({onScroll:this.handleScroll,child:new R6({controller:this.scrollController,autofocus:!1,child:w})})}),E=q?q.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],O=q?new c0({padding:C0.all(1),child:new oL({threads:E,autofocus:!1,offsetY:2})}):null,L;if(z){let M=O?new T1({child:O}):new I0({width:lO4});L=new q1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,M]})}else{let M=[new T1({child:new r1({onScroll:this.handleScroll,child:new R6({controller:this.scrollController,autofocus:!1,child:w})})})];if(O)M.push(new T1({child:O}));L=new x0({crossAxisAlignment:"stretch",children:M})}return new c0({decoration:{border:F,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[G,H,new I0({height:1}),new T1({child:L})]})})}}class E${static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!E$._instance)E$._instance=new E$;return E$._instance}get allExpanded(){return this._allExpanded}setAllExpanded(J){if(this._allExpanded===J)return;this._allExpanded=J,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(J){return this._listeners.add(J),()=>this.removeListener(J)}removeListener(J){this._listeners.delete(J)}_notifyListeners(){for(let J of this._listeners)J()}}h0();class oO4 extends p0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){I.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){I.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((K)=>K.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=u0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),K=X.length>0?this.getValidationError(X):null,V=this.getAvailableLabels(),F=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...V];return new $2({title:"Add Label",items:F,getLabel:(q)=>{if("__isCreateMarker"in q)return this.currentQuery.trim().toLowerCase();return q.name},onAccept:(q)=>{if("__isCreateMarker"in q)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(q.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:K||"Type to create a new label",renderItem:(q,G,D,U)=>{let W=G?Q.selectionBackground:void 0,H=G?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in q&&q.__isCreateMarker){let w=this.currentQuery.trim().toLowerCase();return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C("",void 0,[new C("Create new label: ",new h({color:H})),new C(w,new h({color:H,bold:!0}))])})})}return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C(q.name,new h({color:H}))})})},filterItem:(q,G)=>{if(this.currentQuery!==G)this.currentQuery=G,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in q&&q.__isCreateMarker)return this.shouldShowCreateMarker(G);let U=G.trim().toLowerCase();return U.length===0||q.name.includes(U)},sortItems:(q,G,D)=>{let U="__isCreateMarker"in q.item&&q.item.__isCreateMarker,W="__isCreateMarker"in G.item&&G.item.__isCreateMarker;if(U&&!W)return-1;if(!U&&W)return 1;return G.score-q.score}})}}class qd0 extends d0{props;constructor(J){super();this.props=J}createState(){return new oO4}}class iK extends d0{props;constructor(J){super();this.props=J}createState(){return new rO4}}class rO4 extends p0{_spinner=new o5;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Z=u0.of(J),{colors:Q,app:Y}=Z,X=f1.all(new k1(Q.foreground,1,"solid")),K=this._spinner.toBraille(),V=new e({textAlign:"center",text:new C("",void 0,[new C(K,new h({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new h({color:Q.foreground}))])}),F=[new T1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[V]})})];if(this.widget.props.onAbort)F.push(new I0({height:2,child:new c0({padding:C0.symmetric(2,0),child:new e({text:new C("",new h({dim:!0}),[new C("Press ",new h({color:Q.foreground})),new C("Esc",new h({color:Q.info})),new C(" to cancel",new h({color:Q.foreground}))])})})}));let q=new c0({decoration:new y4(Q.background,X),child:new I0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:F})})});if(this.widget.props.onAbort)return new x4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:q});return q}}var Ud={workspace:{label:"Workspace",pathHint:".amp/settings.json",description:"workspace config"},global:{label:"Global",pathHint:"~/.config/amp/settings.json",description:"global config"},flag:{label:"Flag",pathHint:"CLI flags",description:"flag config"},default:{label:"Default",pathHint:"built-in defaults",description:"default config"},external:{label:"External",pathHint:"extensions / external",description:"external source"},skill:{label:"Skills",pathHint:".agents/skills/",description:"skill source"},other:{label:"Other",pathHint:"",description:"other source"}},RJ0=["workspace","global","flag","default","external","skill","other"];function yr5(J){return Array.from(new Set(J))}function sO4(J){return yr5([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function V_(J){if(J.isExternal)return"external";switch(J.spec._target){case"workspace":return"workspace";case"global":return"global";case"flag":return"flag";case"default":return"default"}return sO4(J).length>0?"skill":"other"}function Gd0(J){return V_(J)==="skill"}function tO4(J){let Z=sO4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=V_(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${Ud[Y].description}: ${Q}`}function eO4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}var $L4=process.platform==="win32"?" ":"█",JL4=process.platform==="win32"?"░":"█";class x8 extends d0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=$L4,thumbChar:K=JL4,showTrack:V=!0,thumbColor:z,trackColor:F}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=z,this.trackColor=F}createState(){return new ZL4}}class ZL4 extends p0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),X=this.context.findRenderObject()?.size.height??0;if(X===0||Z<=Q)return!1;let K=this.widget.getScrollInfo(),V=Math.min(1,Q/Z),z=Math.max(1,X*V),F=Math.max(0,Math.min(1,K.scrollOffset/(Z-Q))),q=X-z,G=Math.max(0,q*F),D=G+z;return J>=G&&J<=D}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let V=J.localPosition.y-this._dragStartY,z=Math.min(1,Q/Z),F=Math.max(1,K*z),q=K-F;if(q<=0)return;let G=Z-Q,D=q/G,U=V/D,W=Math.max(0,Math.min(G,this._dragStartOffset+U));this.widget.controller.jumpTo(W)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Q<=Y)return;let z=Math.min(1,Y/Q),F=Math.max(1,V*z),q=Q-Y,G=V-F,D=Math.max(0,Math.min(1,X/(Q-Y))),U=Math.max(0,G*D),W=U+F;if(Z>=U&&Z<=W)return;if(Z<U)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(q,X+Y))};build(J){return new r1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?O5.POINTER:O5.DEFAULT,child:new QL4({controller:this.widget.controller,getScrollInfo:this.widget.getScrollInfo,thickness:this.widget.thickness,trackChar:this.widget.trackChar,thumbChar:this.widget.thumbChar,showTrack:this.widget.showTrack,thumbColor:this.widget.thumbColor,trackColor:this.widget.trackColor})})}}class QL4 extends QT{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=$L4,thumbChar:K=JL4,showTrack:V=!0,thumbColor:z,trackColor:F}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=z,this.trackColor=F}createRenderObject(){return new YL4(this)}updateRenderObject(J){J.updateWidget(this)}}class YL4 extends A4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;b4(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:K}=this._calculateScrollbarMetrics();if(!K)return;let V=this._widget.trackColor,z=this._widget.thumbColor,F=process.platform==="win32",q=Y,G=Y+X;if(!F){let D=["▁","▂","▃","▄","▅","▆","▇","█"];for(let U=0;U<this.size.height;U++){let W="█",H=!0;if(U===Math.floor(q)){let B=1-(q-U),w=Math.floor(B*8);W=D[w]||"█",H=!1}else if(U===Math.floor(G)){let B=1-(G-U),w=Math.floor(B*8);W=D[w]||"█"}else if(U>q&&U<G)H=!1;J.setChar(Z,Q+U,W,{fg:z,bg:V,reverse:H},1)}return}for(let D=0;D<this.size.height;D++){let U=D+0.5,W=U>=q&&U<G,H=W?this._widget.thumbChar:this._widget.trackChar;J.setChar(Z,Q+D,H,{fg:W?z:V,bg:V,reverse:!1},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),K=Math.min(1,Z/J),V=Math.max(1,Y*K),z=Y-V;return{thumbStartFloat:Math.max(0,z*X),thumbSizeFloat:V,showScrollbar:!0}}}class rL extends d0{props;constructor(J){super();this.props=J}createState(){return new XL4}}class XL4 extends p0{scrollController=new X5;scrollAreaKey=new i2("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(J){return J instanceof y7}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=u0.of(J),Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let G=JJ0(Q);return{title:G.title,type:G.type,description:G.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,K=f1.all(new k1(Z.colors.border,1,"solid")),V=new c0({padding:C0.symmetric(1,0),child:new e({text:new C(Y.title,new h({color:X,bold:!0}))})}),z=this.isWidgetMessage(Q)?Q.widget:new e({text:new C(Y.description,new h({color:Z.colors.foreground})),selectable:!0}),F=new T1({child:new v7({child:new c0({padding:C0.symmetric(1,0),child:new q1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new R6({controller:this.scrollController,autofocus:!0,child:z})}),new x8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let G=this.scrollController.maxScrollExtent,D=this.scrollController.offset,U=this.getViewportHeight(),W=G+U;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(D,0)}}})]})})})}),q=new c0({padding:C0.symmetric(1,0),child:new e({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new h({color:Z.colors.foreground,dim:!0})),new C("R",new h({color:Z.app.keybind})),new C(" to retry, ",new h({color:Z.colors.foreground,dim:!0})),new C("Esc",new h({color:Z.app.keybind})),new C(" to cancel",new h({color:Z.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new C("",new h({color:Z.colors.foreground,dim:!0}));if(G==="help"){let D=new h({color:Z.app.keybind}),U=new h({color:Z.colors.foreground,dim:!0});return new C("",U,[new C("Press ",U),new C("Escape",D),new C(" to close • Use ",U),new C("↑↓",D),new C(" or ",U),new C("j/k",D),new C(" to scroll",U)])}return new C("Press any key to close",new h({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new x4({onKey:(G)=>{if(this.widget.props.onRetry&&G.key==="r")return this.widget.props.onRetry(),"handled";if(G.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new c0({decoration:{border:K,color:Z.colors.background},padding:C0.all(1),child:new x0({mainAxisAlignment:"center",children:[V,new I0({height:1}),F,q]})})})}}p9();class KL4 extends d0{props;constructor(J){super();this.props=J}createState(){return new VL4}}class VL4 extends p0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((J)=>{this.plugins=J,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(J){let Z=J.startsWith("file://")?J.slice(7):J,Q=this.widget.props.cwd;if(Z.startsWith(Q))return Z.slice(Q.length+1);return Z}statusIcon(J){let Z=i8.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=u0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new e({text:new C("No plugins found.",new h({dim:!0}))});let Y=[],X=this.plugins.length,K=this.plugins.filter((F)=>F.status==="active").length,V=this.plugins.reduce((F,q)=>F+q.registeredCommands.length,0),z=this.plugins.reduce((F,q)=>F+q.registeredTools.length,0);if(Y.push(new C(`${K}/${X} ${S4(X,"plugin")} active`,new h({bold:!0}))),V>0||z>0)Y.push(new C(` (${V} ${S4(V,"command")}, ${z} ${S4(z,"tool")})`,new h({dim:!0})));Y.push(new C(`
7341
+ `))}if(H)D.push(new C(" ",G)),D.push(new C("Total: ",G)),D.push(new C(K(B),q))}return new c0({decoration:{color:z.background,border:f1.all(new k1(z.border,1,"rounded"))},child:new e({text:new C(void 0,void 0,D)})})}VN();h0();p9();import{execSync as lr5}from"node:child_process";DN();_2();N3();T2();wh();uX();t7();m$();GY();RO();j4();Tu();Tk();H1();var CL4=W4(vq(),1);import{writeFile as AL4}from"fs/promises";import jL4 from"path";h0();t7();class Qd0{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.1773878698-g9a9736"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await it(Z,this.configService)}catch(Z){I.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 zB extends d0{props;constructor(J){super();this.props=J}createState(){return new TO4}}class TO4 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 _O4 extends p0{controller=new s2;focusNode=new s4({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=u0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,z=f1.all(new k1(Q.foreground,1,"solid")),F=new GJ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(W)=>{let H=W.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),q=new q1({children:[new c0({decoration:{color:Q.background},child:new e({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:F})]}),G=new c0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,[new C("Command: ",new h({color:Q.foreground})),new C(this.widget.props.commandName,new h({color:Y.command,bold:!0}))])})}),D=[];if(V)D.push(new C("Enter",new h({color:Y.keybind}))),D.push(new C(" to submit, ",new h({color:Q.foreground,dim:!0})));D.push(new C("Esc",new h({color:Y.keybind}))),D.push(new C(" to cancel",new h({color:Q.foreground,dim:!0})));let U=new c0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,D)})});return new c0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new x0({children:[G,new I0({height:1}),q,new q3,U]})})}}class qd extends d0{props;constructor(J){super();this.props=J}createState(){return new _O4}}import{isDeepStrictEqual as Yd0}from"node:util";var wr5=/[\\/_ +.#"@[({&]/,Nr5=/[\\/_ +.#"@[({&]/g,Er5=/[\s-]/,SO4=/[\s-]/g;function NJ0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let z=`${X},${K}`;if(V[z]!==void 0)return V[z];let F=Y.charAt(K),q=Q.indexOf(F,X),G=0,D,U,W,H;while(q>=0){if(D=NJ0(J,Z,Q,Y,q+1,K+1,V),D>G){if(q===X)D*=1;else if(Er5.test(J.charAt(q-1))){if(D*=0.9,H=J.slice(X,q-1).match(SO4),H&&X>0)D*=0.999**H.length}else if(wr5.test(J.charAt(q-1))){if(D*=0.8,W=J.slice(X,q-1).match(Nr5),W&&X>0)D*=0.999**W.length}else if(D*=0.3,X>0)D*=0.999**(q-X);if(J.charAt(q)!==Z.charAt(K))D*=0.9999}if(D<0.1&&(Q.charAt(q-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(q-1)!==Y.charAt(K))){if(U=NJ0(J,Z,Q,Y,q+1,K+2,V),U*0.1>D)D=U*0.1}if(D>G)G=D;q=Q.indexOf(F,q+1)}return V[z]=G,G}function wJ0(J){return J.toLowerCase().replace(SO4," ")}function vO4(J,Z){let Q=NJ0(J,Z,wJ0(J),wJ0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let z of Y){let F=NJ0(J,z,wJ0(J),wJ0(z),0,0,{});if(F===0)return Q;X+=F,K+=z.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class J_{}class Z_{}class EJ0{}class OJ0{}class kO4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new yO4}}class yO4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function Or5(J,Z){if(J==="")return{matches:!0,score:1};let Q=vO4(Z,J);return{matches:Q>0.15,score:Q}}class $2 extends d0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new xO4}}class xO4 extends p0{textController;focusNode;scrollController=new X5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new s2(this.widget.props.controller?.query??""),this.focusNode=new s4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),W6.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)=>Yd0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!Yd0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>Yd0(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 J_){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof Z_){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof EJ0){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 OJ0)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,...Or5(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;oT(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(),W6.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=u0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=f1.all(new k1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,z=new GJ({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}),F=new S7({shortcuts:new Map([[new X4("ArrowDown"),new J_],[new X4("ArrowUp"),new Z_],[new X4("Tab"),new J_],[new X4("Tab",{shift:!0}),new Z_],[new X4("n",{ctrl:!0}),new J_],[new X4("p",{ctrl:!0}),new Z_],[new X4("Enter"),new EJ0],[new X4("Escape"),new OJ0]]),focusNode:this.focusNode,child:z}),q=new k9({actions:new Map([[J_,new t4(this.invoke)],[Z_,new t4(this.invoke)],[EJ0,new t4(this.invoke)],[OJ0,new t4(this.invoke)]]),child:F}),G=new q1({children:[new c0({decoration:{color:Q.background},child:new e({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:q})]});this.itemContexts=[];let D;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";D=new I0({height:10,child:new a1({child:new e({text:new C(w,new h({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)D=new T1({child:new a1({child:new e({text:new C(this.widget.props.emptyStateText,new h({color:Q.foreground,dim:!0}))})})});else{let w=Y.map((N,E)=>{let O=E===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(N,O,L,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new c0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C(this.widget.props.getLabel(N),new h({color:j,dim:L}))})})}return new kO4(new r1({onClick:(A)=>this.handleItemClick(E,A.clickCount),child:M}),(A)=>{this.itemContexts[E]=A})});D=new x0({children:w,crossAxisAlignment:"start"})}let U=new r1({onScroll:this.handleScroll,opaque:!1,child:new R6({controller:this.scrollController,autofocus:!1,child:D})}),W=[];if(this.widget.props.title){let w=new c0({padding:C0.symmetric(1,0),child:new e({text:new C(this.widget.props.title,new h({color:Z.app.command,bold:!0}))})});W.push(w)}if(!K)W.push(G,new I0({height:1}));if(this.textController.text!==""){let w=Y.length>0?Y[this.selectedIndex]:void 0,N=w&&this.widget.props.buildDisabledReasonWidget?.(w,J);W.push(new T1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new T1({child:U}),new c0({padding:C0.only({top:1}),child:new a1({child:N??new I0({height:1})})})]})}))}else W.push(new T1({child:U}));if(this.widget.props.footer)W.push(this.widget.props.footer);return new c0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:W})})}}function uO4(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 Xd0 extends i1{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)=>uO4(X.pubDate).length));return new $2({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,z)=>{let F=u0.of(z),{colors:q}=F,G=F.app,D=K?G.selectionBackground:void 0,U=K?G.selectionForeground:q.foreground,W=q.mutedForeground,H=(B,w)=>new I0({width:w,child:q1.end([new e({text:new C(B,new h({color:W}))})])});return new c0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[new T1({child:new e({text:new C(X.title,new h({color:U})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),H(uO4(X.pubDate),Q)]})})}})}}j4();class Kd0 extends d0{createState(){return new fO4}}class fO4 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=u0.of(J).colors;return new e({text:new C("●",new h({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}var Lr5=/\/threads\/(T-[^/?#\s<>]+)/i;function Mr5(J){let Z=J.trim(),Y=Z.match(Lr5)?.[1];if(Y&&B8(Y))return Y;let X=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(B8(X))return X;return null}function Ar5(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 z=V.relationships.find((F)=>F.role==="child"&&Z.has(F.threadID)&&(F.type==="fork"||F.type==="handoff"));if(z){Y.set(V.id,z.type);let F=z.threadID,q=Q.get(F)||[];q.push(V),Q.set(F,q)}else X.push(V)}return d70.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 Vd0(J,Z,Q){return new e({text:new C(`${J}${Z}`,new h({color:Q})),maxLines:1})}function jr5(J,Z,Q,Y){return[Vd0("+",J,Y.success),q3.horizontal(1),Vd0("~",Z,Y.warning),q3.horizontal(1),Vd0("-",Q,Y.destructive)]}function Ir5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class LJ0 extends d0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new bO4}}class bO4 extends p0{spinner=new o5;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((E)=>E.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((E)=>E.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],z=new Set(V),F=Z.currentThreadID,q=[...K].sort((E,O)=>{if(F){if(E.id===F)return-1;if(O.id===F)return 1}let L=V.indexOf(E.id),M=V.indexOf(O.id);if(L!==-1&&M!==-1)return L-M;if(L!==-1)return-1;if(M!==-1)return 1;return 0}),G=Ar5(q),D=Math.max(0,...G.map((E)=>E.description.timeAgo.length)),U=u0.of(J),W=new i0({padding:C0.symmetric(0,1),child:new a1({child:new e({text:new C("",new h({color:U.colors.foreground,dim:!0}),[new C("Ctrl+T",new h({color:U.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new h({color:U.colors.foreground,dim:!0}))])})})}),H="",B=null,w=(E)=>{if(E!==H)H=E,B=Mr5(E);return B};return new $2({items:G,getLabel:(E)=>`${E.title} ${E.id}`,filterItem:(E,O)=>{let L=w(O);if(L)return E.id.toLowerCase()===L.toLowerCase();return!0},normalizeQuery:(E)=>w(E)?"":E,onAccept:async(E,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let L=Z.onSelect(E.id,O);if(!Ir5(L))return;this.setSwitchingThread(!0);try{await L}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(E)=>{if(Z.previewController){if(E)Z.previewController.select(E.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:W,renderItem:(E,O,L,M)=>{let A=u0.of(M),{app:j,colors:P}=A,_=O?j.selectionBackground:void 0,S=O?j.selectionForeground:P.foreground,y=P.mutedForeground,m=(s,B0)=>new I0({width:B0,child:q1.end([new e({text:new C(s,new h({color:y}))})])}),b=Z.threadViewStates[E.id],v=[],u=E.relationshipType==="handoff",p=new yp({connectorColor:P.mutedForeground});if(E.depth>0){let s=[],B0=E.ancestorsAreLast.slice(1);for(let O0 of B0)s.push(new C(p.getAncestorPrefix(O0),new h({color:p.connectorColor,dim:p.connectorDim})));let o=E.isLast?p.elbow:p.tee,q0=p.getConnectorText(o);s.push(new C(q0,new h({color:p.connectorColor,dim:p.connectorDim}))),v.push(new e({text:new C("",void 0,s)}))}let c=[],f=F===E.id?new C("(current) ",new h({color:P.success})):z.has(E.id)?new C("(visited) ",new h({color:P.foreground,dim:!0})):null;if(f)c.push(new e({text:f}));if(bW(b))c.push(new Kd0),c.push(new I0({width:1}));let a=E.title;if(E.relationshipType==="fork"){let s=a.match(/^Forked\((\d+)\): /);if(s)a=a.slice(s[0].length);else while(a.startsWith("Forked: "))a=a.slice(8);c.push(new e({text:new C("[fork] ",new h({color:P.primary}))}))}else if(u)c.push(new e({text:new C("[handoff] ",new h({color:P.accent}))}));if(c.push(new T1({child:new e({text:new C(a,new h({color:S})),overflow:"ellipsis",maxLines:1})})),c.push(new I0({width:2})),E.diffStats&&(E.diffStats.added>0||E.diffStats.changed>0||E.diffStats.deleted>0)){let s=O?{success:y,warning:y,destructive:y}:P;c.push(...jr5(E.diffStats.added,E.diffStats.changed,E.diffStats.deleted,s)),c.push(new I0({width:2}))}return c.push(m(E.description.timeAgo,D)),new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[...v,...c]})})}})}}function hO4(J){return 1-(1-J)**3}function gO4(J,Z,Q){return J+(Z-J)*Q}function Gd(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=hO4(Y),V=hO4(X);return{x:gO4(J.startOffset.x,J.targetOffset.x,K),y:gO4(J.startOffset.y,J.targetOffset.y,V)}}var Rr5={nodeWidth:3,horizontalSpacing:3};class Q_{options;constructor(J={}){this.options={...Rr5,...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=(z,F)=>{let q=Z.get(z.id)??[];if(this.options.comparator)q.sort(this.options.comparator);let G={...z,parentID:Q.get(z.id)};if(q.length===0){Y.push({node:G,position:{x:K,y:F}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let D=[];for(let B of q)D.push(V(B,F+1));let U=Math.min(...D),W=Math.max(...D),H=Math.floor((U+W)/2);return Y.push({node:G,position:{x:H,y:F}}),H};for(let z of X)V(z,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,z=K.parentID;while(z){if(z===K.id){V=!0;break}z=Y.get(z)}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 Pr5={nodeWidth:3,nodeHeight:2};class Y_{options;constructor(J={}){this.options={...Pr5,...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 z=V+1;if(Y.push({x:X,y:z}),X!==K)Y.push({x:K,y:z});let F=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:F}),Y}}var Cr5={nodeWidth:3,nodeHeight:2},Tr5={x:0,y:0};class AJ0{options;constructor(J={}){this.options={...Cr5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=Tr5,X,K,V,z){let F=z?u0.of(z):null,q=F?.colors,G=F?.app,D=q?.mutedForeground??q?.foreground;if(J.length===0)return new e({text:new C("No nodes",new h({color:D}))});let U=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,w=[];for(let j=U;j>=0;j--){let P=J.filter((y)=>y.position.y===j);P.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new I0({width:y.position.x-S}));let m=y.node.id===Q,b=V?.(y.node.data)??!1,v=K?.activeFlashOn??!1,u=y.node.id===K?.copyFlashNodeId;_.push(this.renderNode(m,b,v,u,G,q)),S=y.position.x+this.options.nodeWidth}if(w.push(new q1({crossAxisAlignment:"start",children:_})),j>0){let y=J.filter((v)=>v.position.y===j-1),m=P,b=this.renderConnectors(y,m,Z,H,q,G);w.push(...b)}}let N=new x0({crossAxisAlignment:"start",children:w}),E=Math.round(Y.x),O=Math.round(Y.y*B),L=(U+1)*B,M=[new I0({width:H,height:L}),new u6({left:E,top:O,child:N})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),P=U-A.position.y,_=E+A.position.x+this.options.nodeWidth+1,S=O+P*B+1,y=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)y=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new u6({left:_,top:S,child:this.renderInfoBox(j,y,q,G)}))}return new c0({padding:C0.horizontal(2),child:new vH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",z="└─┘",F=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,q=!1;if(Y)F=X?.threadGraphNodeSelected??K?.primary??F,V="┏━┓",z="┗━┛",q=!0;else if(Z&&Q)F=X?.toolSuccess??K?.primary??F,V="┏━┓",z="┗━┛";return new x0({crossAxisAlignment:"start",children:[new e({text:new C(V,new h({color:F,bold:q}))}),new e({text:new C(z,new h({color:F,bold:q}))})]})}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,z="┌"+"─".repeat(V)+"┐",F="└"+"─".repeat(V)+"┘",q=Q?.border??Y?.threadGraphConnector??Q?.foreground,G=Q?.foreground,D=[new e({text:new C(z,new h({color:q}))})];for(let U of X){let W=" ".repeat(K-U.length);D.push(new e({text:new C("│ ",new h({color:q}),[new C(U+W,new h({color:G??q})),new C(" │",new h({color:q}))])}))}return D.push(new e({text:new C(F,new h({color:q}))})),new x0({crossAxisAlignment:"start",children:D})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),F=K?.threadGraphConnector??X?.primary??X?.foreground,q=Array(Y).fill(" ");for(let U of Z){let W=U.position.x+z;if(W>=0&&W<Y)q[W]="▲"}V.push(new e({text:new C(q.join(""),new h({color:F}))}));let G=Array(Y).fill(" ");for(let U of J){let W=Z.filter((E)=>E.node.parentID===U.node.id);if(W.length===0)continue;let H=U.position.x+z,B=W.map((E)=>E.position.x+z),w=Math.min(...B),N=Math.max(...B);for(let E=w;E<=N;E++)if(E>=0&&E<Y){if(E===H)if(W.length===1&&B[0]===H)G[E]="│";else if(E===w)G[E]="└";else if(E===N)G[E]="┘";else G[E]="┬";else if(B.includes(E))if(E===w)G[E]="└";else if(E===N)G[E]="┘";else G[E]="┴";else if(G[E]===" ")G[E]="─"}}V.push(new e({text:new C(G.join(""),new h({color:F}))}));let D=Array(Y).fill(" ");for(let U of J){if(Z.filter((B)=>B.node.parentID===U.node.id).length===0)continue;let H=U.position.x+z;if(H>=0&&H<Y)D[H]="│"}return V.push(new e({text:new C(D.join(""),new h({color:F}))})),V}}var _r5={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},Sr5={x:0,y:0};class zd0{options;constructor(J={}){this.options={..._r5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=Sr5,X,K,V,z){let F=z?u0.of(z):null,q=F?.colors,G=F?.app,D=q?.mutedForeground??q?.foreground;if(J.length===0)return new e({text:new C("No nodes",new h({color:D}))});let U=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,w=[];for(let j=U;j>=0;j--){let P=J.filter((y)=>y.position.y===j);P.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new I0({width:y.position.x-S}));let m=y.node.id===Q,b=V?.(y.node.data)??!1,v=K?.activeFlashOn??!1;_.push(this.renderNode(m,b,v,G,q)),S=y.position.x+this.options.nodeWidth}if(w.push(new q1({crossAxisAlignment:"start",children:_})),j>0){let y=J.filter((v)=>v.position.y===j-1),m=P,b=this.renderConnectors(y,m,Z,H,q,G);w.push(...b)}}let N=new x0({crossAxisAlignment:"start",children:w}),E=Math.round(Y.x),O=Math.round(Y.y*B),L=(U+1)*B,M=[new I0({width:H,height:L}),new u6({left:E,top:O,child:N})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),P=U-A.position.y,_=E+A.position.x+this.options.nodeWidth+1,S=O+P*B,y=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)y=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new u6({left:_,top:S,child:this.renderInfoBox(j,y,q)}))}return new c0({padding:C0.horizontal(2),child:new vH(new i6({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 h({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 h({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:K})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),F=K?.threadGraphConnector??X?.primary??X?.foreground,q=Array(Y).fill(" ");for(let G of J){let D=Z.filter((w)=>w.node.parentID===G.node.id);if(D.length===0)continue;let U=G.position.x+z,W=D.map((w)=>w.position.x+z),H=Math.min(...W),B=Math.max(...W);for(let w=H;w<=B;w++)if(w>=0&&w<Y){let N=w===U,E=W.includes(w);if(N&&E)if(D.length===1)q[w]="│";else if(w===H)q[w]="└";else if(w===B)q[w]="┘";else q[w]="┼";else if(N)if(w===H)q[w]="└";else if(w===B)q[w]="┘";else q[w]="┬";else if(E)if(w===H)q[w]="└";else if(w===B)q[w]="┘";else q[w]="┴";else if(q[w]===" ")q[w]="─"}}return V.push(new e({text:new C(q.join(""),new h({color:F}))})),V}}class Dd extends L3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new mO4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class mO4 extends A4{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 oL extends d0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new cO4}}var pO4=400,dO4=300,vr5=16;class cO4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new Q_({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new Y_;renderer=new zd0;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((F)=>F.id)),Q=new Set(this.widget.props.threads.map((F)=>F.id));if(Z.size!==Q.size||[...Z].some((F)=>!Q.has(F)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,K=this.widget.props.initialSelectedThreadID;if(X!==K&&K){let q=this.widget.props.threads.find((G)=>G.id===K);if(q)this.selectedNodeId=q.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((F)=>F.isActive),z=this.widget.props.threads.some((F)=>F.isActive);if(V!==z){if(this.stopActiveFlashTimer(),z)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:pO4,durationY:dO4};let Z=Math.max(pO4,dO4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=Gd(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},vr5)}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,z=2,F=Math.floor(this.viewportHeight/2),G=Math.floor(F/2)-V;return{x:K,y:G}}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,z)=>V.position.x-z.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 G=(this.selectedNodeId?this.positionedNodes.find((D)=>D.node.id===this.selectedNodeId):null)??this.positionedNodes.find((D)=>!D.node.parentID);if(G){let D=Math.max(...this.positionedNodes.map((U)=>U.position.y));this.currentOffset=this.calculateCenterOffset(G.position.x,G.position.y,D)}}let X=this.widget.props.showTitle??!0,K=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+K},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(q)=>q.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(q)=>q.isActive??!1,J),F=new Dd({onWidth:(q)=>{if(this.viewportWidth!==q)this.viewportWidth=q,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(q)=>{if(this.viewportHeight!==q)this.viewportHeight=q,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new x4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:F})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class iO4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new nO4}}class nO4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var lO4=30,kr5=30;class X_{}class K_{}class jJ0{}class IJ0{}class Fd0 extends d0{props;constructor(J){super();this.props=J}createState(){return new aO4}}class aO4 extends p0{highlightedIndex=0;controller=new s2;focusNode;scrollController=new X5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new s4({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),W6.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;oT(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 X_){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof K_){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof jJ0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof IJ0)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(),W6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=u0.of(J),{colors:Y,app:X}=Q,z=e1.of(J).size.width>=kr5+lO4,F=f1.all(new k1(Y.foreground,1,"solid")),q=this.filteredClusters[this.highlightedIndex]??null,G=new c0({padding:C0.symmetric(1,0),child:new e({text:new C("Select a cluster",new h({color:X.command,bold:!0}))})}),D=new GJ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),U=new S7({shortcuts:new Map([[new X4("ArrowDown"),new X_],[new X4("ArrowUp"),new K_],[new X4("Tab"),new X_],[new X4("Tab",{shift:!0}),new K_],[new X4("n",{ctrl:!0}),new X_],[new X4("p",{ctrl:!0}),new K_],[new X4("Enter"),new jJ0],[new X4("Escape"),new IJ0]]),focusNode:this.focusNode,child:D}),W=new k9({actions:new Map([[X_,new t4(this.invoke)],[K_,new t4(this.invoke)],[jJ0,new t4(this.invoke)],[IJ0,new t4(this.invoke)]]),child:U}),H=new q1({children:[new c0({decoration:{color:Y.background},child:new e({text:new C(">",new h({color:Y.foreground}))})}),new T1({child:W})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,P=Z?M.threads.some((m)=>m.id===Z):!1,_=j?X.selectionBackground:void 0,S=j?X.selectionForeground:Y.foreground,y=[new C(M.label,new h({color:S})),new C(` (${M.threads.length})`,new h({color:S,dim:!0}))];if(P)y.push(new C(" (current)",new h({color:j?X.selectionForeground:Y.success})));return new iO4(new r1({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C("",void 0,y)})})}),(m)=>{this.itemContexts[A]=m})}),w=new x0({children:B,crossAxisAlignment:"start"}),N=new T1({child:new r1({onScroll:this.handleScroll,child:new R6({controller:this.scrollController,autofocus:!1,child:w})})}),E=q?q.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],O=q?new c0({padding:C0.all(1),child:new oL({threads:E,autofocus:!1,offsetY:2})}):null,L;if(z){let M=O?new T1({child:O}):new I0({width:lO4});L=new q1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,M]})}else{let M=[new T1({child:new r1({onScroll:this.handleScroll,child:new R6({controller:this.scrollController,autofocus:!1,child:w})})})];if(O)M.push(new T1({child:O}));L=new x0({crossAxisAlignment:"stretch",children:M})}return new c0({decoration:{border:F,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[G,H,new I0({height:1}),new T1({child:L})]})})}}class E${static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!E$._instance)E$._instance=new E$;return E$._instance}get allExpanded(){return this._allExpanded}setAllExpanded(J){if(this._allExpanded===J)return;this._allExpanded=J,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(J){return this._listeners.add(J),()=>this.removeListener(J)}removeListener(J){this._listeners.delete(J)}_notifyListeners(){for(let J of this._listeners)J()}}h0();class oO4 extends p0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){I.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){I.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((K)=>K.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=u0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),K=X.length>0?this.getValidationError(X):null,V=this.getAvailableLabels(),F=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...V];return new $2({title:"Add Label",items:F,getLabel:(q)=>{if("__isCreateMarker"in q)return this.currentQuery.trim().toLowerCase();return q.name},onAccept:(q)=>{if("__isCreateMarker"in q)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(q.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:K||"Type to create a new label",renderItem:(q,G,D,U)=>{let W=G?Q.selectionBackground:void 0,H=G?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in q&&q.__isCreateMarker){let w=this.currentQuery.trim().toLowerCase();return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C("",void 0,[new C("Create new label: ",new h({color:H})),new C(w,new h({color:H,bold:!0}))])})})}return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C(q.name,new h({color:H}))})})},filterItem:(q,G)=>{if(this.currentQuery!==G)this.currentQuery=G,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in q&&q.__isCreateMarker)return this.shouldShowCreateMarker(G);let U=G.trim().toLowerCase();return U.length===0||q.name.includes(U)},sortItems:(q,G,D)=>{let U="__isCreateMarker"in q.item&&q.item.__isCreateMarker,W="__isCreateMarker"in G.item&&G.item.__isCreateMarker;if(U&&!W)return-1;if(!U&&W)return 1;return G.score-q.score}})}}class qd0 extends d0{props;constructor(J){super();this.props=J}createState(){return new oO4}}class iK extends d0{props;constructor(J){super();this.props=J}createState(){return new rO4}}class rO4 extends p0{_spinner=new o5;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Z=u0.of(J),{colors:Q,app:Y}=Z,X=f1.all(new k1(Q.foreground,1,"solid")),K=this._spinner.toBraille(),V=new e({textAlign:"center",text:new C("",void 0,[new C(K,new h({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new h({color:Q.foreground}))])}),F=[new T1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[V]})})];if(this.widget.props.onAbort)F.push(new I0({height:2,child:new c0({padding:C0.symmetric(2,0),child:new e({text:new C("",new h({dim:!0}),[new C("Press ",new h({color:Q.foreground})),new C("Esc",new h({color:Q.info})),new C(" to cancel",new h({color:Q.foreground}))])})})}));let q=new c0({decoration:new y4(Q.background,X),child:new I0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:F})})});if(this.widget.props.onAbort)return new x4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:q});return q}}var Ud={workspace:{label:"Workspace",pathHint:".amp/settings.json",description:"workspace config"},global:{label:"Global",pathHint:"~/.config/amp/settings.json",description:"global config"},flag:{label:"Flag",pathHint:"CLI flags",description:"flag config"},default:{label:"Default",pathHint:"built-in defaults",description:"default config"},external:{label:"External",pathHint:"extensions / external",description:"external source"},skill:{label:"Skills",pathHint:".agents/skills/",description:"skill source"},other:{label:"Other",pathHint:"",description:"other source"}},RJ0=["workspace","global","flag","default","external","skill","other"];function yr5(J){return Array.from(new Set(J))}function sO4(J){return yr5([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function V_(J){if(J.isExternal)return"external";switch(J.spec._target){case"workspace":return"workspace";case"global":return"global";case"flag":return"flag";case"default":return"default"}return sO4(J).length>0?"skill":"other"}function Gd0(J){return V_(J)==="skill"}function tO4(J){let Z=sO4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=V_(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${Ud[Y].description}: ${Q}`}function eO4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}var $L4=process.platform==="win32"?" ":"█",JL4=process.platform==="win32"?"░":"█";class x8 extends d0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=$L4,thumbChar:K=JL4,showTrack:V=!0,thumbColor:z,trackColor:F}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=z,this.trackColor=F}createState(){return new ZL4}}class ZL4 extends p0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),X=this.context.findRenderObject()?.size.height??0;if(X===0||Z<=Q)return!1;let K=this.widget.getScrollInfo(),V=Math.min(1,Q/Z),z=Math.max(1,X*V),F=Math.max(0,Math.min(1,K.scrollOffset/(Z-Q))),q=X-z,G=Math.max(0,q*F),D=G+z;return J>=G&&J<=D}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let V=J.localPosition.y-this._dragStartY,z=Math.min(1,Q/Z),F=Math.max(1,K*z),q=K-F;if(q<=0)return;let G=Z-Q,D=q/G,U=V/D,W=Math.max(0,Math.min(G,this._dragStartOffset+U));this.widget.controller.jumpTo(W)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Q<=Y)return;let z=Math.min(1,Y/Q),F=Math.max(1,V*z),q=Q-Y,G=V-F,D=Math.max(0,Math.min(1,X/(Q-Y))),U=Math.max(0,G*D),W=U+F;if(Z>=U&&Z<=W)return;if(Z<U)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(q,X+Y))};build(J){return new r1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?O5.POINTER:O5.DEFAULT,child:new QL4({controller:this.widget.controller,getScrollInfo:this.widget.getScrollInfo,thickness:this.widget.thickness,trackChar:this.widget.trackChar,thumbChar:this.widget.thumbChar,showTrack:this.widget.showTrack,thumbColor:this.widget.thumbColor,trackColor:this.widget.trackColor})})}}class QL4 extends QT{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=$L4,thumbChar:K=JL4,showTrack:V=!0,thumbColor:z,trackColor:F}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=z,this.trackColor=F}createRenderObject(){return new YL4(this)}updateRenderObject(J){J.updateWidget(this)}}class YL4 extends A4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;b4(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:K}=this._calculateScrollbarMetrics();if(!K)return;let V=this._widget.trackColor,z=this._widget.thumbColor,F=process.platform==="win32",q=Y,G=Y+X;if(!F){let D=["▁","▂","▃","▄","▅","▆","▇","█"];for(let U=0;U<this.size.height;U++){let W="█",H=!0;if(U===Math.floor(q)){let B=1-(q-U),w=Math.floor(B*8);W=D[w]||"█",H=!1}else if(U===Math.floor(G)){let B=1-(G-U),w=Math.floor(B*8);W=D[w]||"█"}else if(U>q&&U<G)H=!1;J.setChar(Z,Q+U,W,{fg:z,bg:V,reverse:H},1)}return}for(let D=0;D<this.size.height;D++){let U=D+0.5,W=U>=q&&U<G,H=W?this._widget.thumbChar:this._widget.trackChar;J.setChar(Z,Q+D,H,{fg:W?z:V,bg:V,reverse:!1},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),K=Math.min(1,Z/J),V=Math.max(1,Y*K),z=Y-V;return{thumbStartFloat:Math.max(0,z*X),thumbSizeFloat:V,showScrollbar:!0}}}class rL extends d0{props;constructor(J){super();this.props=J}createState(){return new XL4}}class XL4 extends p0{scrollController=new X5;scrollAreaKey=new i2("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(J){return J instanceof y7}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=u0.of(J),Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let G=JJ0(Q);return{title:G.title,type:G.type,description:G.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,K=f1.all(new k1(Z.colors.border,1,"solid")),V=new c0({padding:C0.symmetric(1,0),child:new e({text:new C(Y.title,new h({color:X,bold:!0}))})}),z=this.isWidgetMessage(Q)?Q.widget:new e({text:new C(Y.description,new h({color:Z.colors.foreground})),selectable:!0}),F=new T1({child:new v7({child:new c0({padding:C0.symmetric(1,0),child:new q1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new R6({controller:this.scrollController,autofocus:!0,child:z})}),new x8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let G=this.scrollController.maxScrollExtent,D=this.scrollController.offset,U=this.getViewportHeight(),W=G+U;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(D,0)}}})]})})})}),q=new c0({padding:C0.symmetric(1,0),child:new e({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new h({color:Z.colors.foreground,dim:!0})),new C("R",new h({color:Z.app.keybind})),new C(" to retry, ",new h({color:Z.colors.foreground,dim:!0})),new C("Esc",new h({color:Z.app.keybind})),new C(" to cancel",new h({color:Z.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new C("",new h({color:Z.colors.foreground,dim:!0}));if(G==="help"){let D=new h({color:Z.app.keybind}),U=new h({color:Z.colors.foreground,dim:!0});return new C("",U,[new C("Press ",U),new C("Escape",D),new C(" to close • Use ",U),new C("↑↓",D),new C(" or ",U),new C("j/k",D),new C(" to scroll",U)])}return new C("Press any key to close",new h({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new x4({onKey:(G)=>{if(this.widget.props.onRetry&&G.key==="r")return this.widget.props.onRetry(),"handled";if(G.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new c0({decoration:{border:K,color:Z.colors.background},padding:C0.all(1),child:new x0({mainAxisAlignment:"center",children:[V,new I0({height:1}),F,q]})})})}}p9();class KL4 extends d0{props;constructor(J){super();this.props=J}createState(){return new VL4}}class VL4 extends p0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((J)=>{this.plugins=J,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(J){let Z=J.startsWith("file://")?J.slice(7):J,Q=this.widget.props.cwd;if(Z.startsWith(Q))return Z.slice(Q.length+1);return Z}statusIcon(J){let Z=i8.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=u0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new e({text:new C("No plugins found.",new h({dim:!0}))});let Y=[],X=this.plugins.length,K=this.plugins.filter((F)=>F.status==="active").length,V=this.plugins.reduce((F,q)=>F+q.registeredCommands.length,0),z=this.plugins.reduce((F,q)=>F+q.registeredTools.length,0);if(Y.push(new C(`${K}/${X} ${S4(X,"plugin")} active`,new h({bold:!0}))),V>0||z>0)Y.push(new C(` (${V} ${S4(V,"command")}, ${z} ${S4(z,"tool")})`,new h({dim:!0})));Y.push(new C(`
7342
7342
 
7343
7343
  `));for(let F of this.plugins){let{icon:q,color:G}=this.statusIcon(F.status),D=this.getRelativePath(F.uri.toString());if(Y.push(new C(`${q} `,new h({color:G}))),Y.push(new C(D,new h({bold:!0}))),Y.push(new C(` ${F.status}`,new h({dim:!0}))),Y.push(new C(`
7344
7344
  `)),F.status==="active"&&F.registeredEvents.length>0)Y.push(new C(" Events: ",new h({dim:!0}))),Y.push(new C(F.registeredEvents.join(", "),new h({color:Q.link}))),Y.push(new C(`
@@ -7555,7 +7555,7 @@ ${X0.content||""}`:X0.content||"",Y1=[],U1=X0.baseDir.startsWith("file://")?qZ0(
7555
7555
  `),process.exit(1)}process.stdout.write(await B13(F.result.displayText)+`
7556
7556
  `),process.exit(0)})}hP();import{stdout as w13}from"node:process";function N13({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${hW(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function cj4(J){w13.write(`${N13(J)}
7557
7557
  `)}function lj4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{cj4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{cj4(Z),process.exit(0)})}var h33=CB.join(x$,"logs","headless.log"),ui0=CB.join(nC,"device-id.json");async function g33(){for(let J of WN)try{if((await J.listConfigs()).length>0)return J}catch(Z){I.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => W4(x_(),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}
7558
- `)}function m33(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",z=!1;J.warn(K,{name:V,code:Y})}}function Z2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")u$("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")u$("experimental.agentMode",Z.mode)}function AC4(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 p33(J){try{return await LC4(J,"utf-8")}catch{return J}}async function fi0(J,Z,Q){let Y=AC4(J,Z);if(!Y)return;let X=j6(Q)?Q.features:[],K=j6(Q)?Q.user.email:void 0;if(!pi0(X,S2.HARNESS_SYSTEM_PROMPT)&&!jC4(K))throw new v1("You are not allowed to do this.",1);u$("systemPrompt",await p33(Y))}function jC4(J){return!!(J&&$r(J))}function pi0(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function bi0(J){return(J.userEmail?kZ(J.userEmail):!1)||pi0(J.features,S2.DTW_TUI)}function UC4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new v1("This TUI mode is not enabled for your user;",1)}function hi0(J,Z){if(typeof J==="boolean")return J;if(!j6(Z))return!1;return bi0({userEmail:Z.user.email,features:Z.features})}function gi0(J){if(!j6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function d33(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 $Q0(J){let Y=d33(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 v1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function WC4(J){if(!d6.write(J))await x33(d6,"drain")}var HC4=[{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??nY,description:`Custom settings file path (overrides the default location ${nY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(I).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${lO})`},{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:e9(),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:bV.SMART.key,description:`Set the agent mode (${fX().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:fX().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:"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}],BC4=(J)=>("deprecated"in J)&&J.deprecated===!0,c33=(J)=>("hidden"in J)&&J.hidden===!0,l33=(J)=>("default"in J),i33=(J)=>("default"in J)?J.default:void 0,IC4=[{name:"toggle-skills-count",entryPoint:Jb0}];function n33(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((z)=>Q.includes(z)||z.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 v1(z3.unknownCommand(Q),1,V)}}async function di0(J){return{...J,getThreadEnvironment:ZJ,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new JK(J.fileSystem),generateThreadTitle:R10,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>nJ(J.configService),pluginService:J.pluginService}}function RC4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:ZJ,filesystem:J.fileSystem,threadService:J.threadService}}var JQ0=V1.file(MC4.homedir()),mi0=process.env.XDG_CONFIG_HOME?V1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(JQ0,".config");function a33(J){return a$4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){n$4(Z);let Q=z20(),Y=Mb0();if((!Q||Y||$q4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(vG("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(vG("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(z20()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function o33(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>v0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function D9(J,Z,Q){let Y=Q?.deferAuth??!1;$I1("0.0.1773878033-g2f2f23");let X=Ur({storage:J.settings,secretStorage:J.secrets,workspaceRoot:v0.of(V1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:JQ0,userConfigDir:mi0});oF4(X);let K=await X.getLatest();I.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let B0=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(B0),I.info("API key lookup before login",{found:Boolean(B0),ampURL:J.ampURL,deferAuth:Y}),!B0)if(Y)I.info("No API key found, continuing startup with deferred auth");else{d6.write(`No API key found. Starting login flow...
7558
+ `)}function m33(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",z=!1;J.warn(K,{name:V,code:Y})}}function Z2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")u$("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")u$("experimental.agentMode",Z.mode)}function AC4(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 p33(J){try{return await LC4(J,"utf-8")}catch{return J}}async function fi0(J,Z,Q){let Y=AC4(J,Z);if(!Y)return;let X=j6(Q)?Q.features:[],K=j6(Q)?Q.user.email:void 0;if(!pi0(X,S2.HARNESS_SYSTEM_PROMPT)&&!jC4(K))throw new v1("You are not allowed to do this.",1);u$("systemPrompt",await p33(Y))}function jC4(J){return!!(J&&$r(J))}function pi0(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function bi0(J){return(J.userEmail?kZ(J.userEmail):!1)||pi0(J.features,S2.DTW_TUI)}function UC4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new v1("This TUI mode is not enabled for your user;",1)}function hi0(J,Z){if(typeof J==="boolean")return J;if(!j6(Z))return!1;return bi0({userEmail:Z.user.email,features:Z.features})}function gi0(J){if(!j6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function d33(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 $Q0(J){let Y=d33(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 v1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function WC4(J){if(!d6.write(J))await x33(d6,"drain")}var HC4=[{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??nY,description:`Custom settings file path (overrides the default location ${nY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(I).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${lO})`},{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:e9(),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:bV.SMART.key,description:`Set the agent mode (${fX().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:fX().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:"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}],BC4=(J)=>("deprecated"in J)&&J.deprecated===!0,c33=(J)=>("hidden"in J)&&J.hidden===!0,l33=(J)=>("default"in J),i33=(J)=>("default"in J)?J.default:void 0,IC4=[{name:"toggle-skills-count",entryPoint:Jb0}];function n33(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((z)=>Q.includes(z)||z.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 v1(z3.unknownCommand(Q),1,V)}}async function di0(J){return{...J,getThreadEnvironment:ZJ,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new JK(J.fileSystem),generateThreadTitle:R10,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>nJ(J.configService),pluginService:J.pluginService}}function RC4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:ZJ,filesystem:J.fileSystem,threadService:J.threadService}}var JQ0=V1.file(MC4.homedir()),mi0=process.env.XDG_CONFIG_HOME?V1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(JQ0,".config");function a33(J){return a$4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){n$4(Z);let Q=z20(),Y=Mb0();if((!Q||Y||$q4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(vG("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(vG("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(z20()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function o33(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>v0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function D9(J,Z,Q){let Y=Q?.deferAuth??!1;$I1("0.0.1773878698-g9a9736");let X=Ur({storage:J.settings,secretStorage:J.secrets,workspaceRoot:v0.of(V1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:JQ0,userConfigDir:mi0});oF4(X);let K=await X.getLatest();I.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let B0=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(B0),I.info("API key lookup before login",{found:Boolean(B0),ampURL:J.ampURL,deferAuth:Y}),!B0)if(Y)I.info("No API key found, continuing startup with deferred auth");else{d6.write(`No API key found. Starting login flow...
7559
7559
  `);let o=await r33(J),q0=await J.secrets.get("apiKey",J.ampURL);if(I.info("Login flow completed",{success:o,storedKeyPresent:Boolean(q0),ampURL:J.ampURL}),!o)await PG(),process.exit(1);V=!0}}{let B0=await X.getLatest(),o=B0.settings.url,q0=B0.secrets.isSet?.[o];I.info("Config secrets state after login",{configURL:o,apiKeySet:q0?.apiKey??!1})}let z=O1(nJ(X).pipe(Q5((B0)=>B0!=="pending"))),F=Y?"pending":await z;if(!Y)I.info("Server status resolved",{status:"ready",isAuthenticated:j6(F),isError:Rq(F),errorMessage:Rq(F)?F.error.message:void 0});let{toolService:q,dispose:G}=p$4({configService:X}),D=new Map,U=()=>D.clear(),W=new fM0(X,J.settings.getWorkspaceRootPath()),H=Km1({configService:X,filesystem:r6}),B=au1({configService:X,trustStore:W,skillMCPServers:H.skillMCPServers,createOAuthProvider:async(B0,o,q0)=>{let O0=`${B0}:${o}`,z0=D.get(O0);if(z0)return I.debug("Reusing existing OAuth provider for server",{serverName:B0,serverUrl:o}),z0;I.debug("Creating OAuth provider for server",{serverName:B0,serverUrl:o});let $0=(async()=>{let D0=new bN(J.secrets),i=await D0.getClientInfo(B0,o),n=q0?.scopes??i?.scopes,t=vV4();I.info("OAuth headless mode check",{useHeadless:t,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:d6.isTTY});let J0;if(t)J0=J.executeMode?SV4():_V4(B0);let X0=new cL0({storage:D0,serverName:B0,serverUrl:o,clientId:q0?.clientId??i?.clientId,clientSecret:q0?.clientSecret??i?.clientSecret,authUrl:q0?.authUrl??i?.authUrl,tokenUrl:q0?.tokenUrl??i?.tokenUrl,scopes:n,headlessAuthHandler:J0});return I.debug("OAuth provider created",{serverName:B0,serverUrl:o,hasManualClientId:!!(q0?.clientId??i?.clientId),willUseDCR:!(q0?.clientId??i?.clientId),scopes:n,headlessMode:t,executeMode:J.executeMode}),X0})();return D.set(O0,$0),$0}}),w=dk0({configService:X,filesystem:r6,spawn:_30}),N;if(J.executeMode){let B0=await i94({toolService:q,providers:[B,w],initialTimeout:15000});N=B0.registrations;for(let[o,q0]of B0.initErrors)I.warn(`${o} provider initialization slow or failed:`,q0)}else N=ck0({toolService:q,providers:[B,w]});if(Z.jetbrains)qN("JetBrains");else if(Z.ide&&Wz4())qN("VS Code");else if(Z.ide&&Hz4())qN("Neovim");else if(Z.ide){let B0=await g33();if(B0){let o=Mr(B0.ideName);if(o)qN(o)}}if(J.executeMode)JI1(!0);let E,O=g8.status.pipe(D1((B0)=>Boolean(B0.connected&&B0.authenticated&&B0.ideName&&hI1(B0.ideName))),M4()).subscribe((B0)=>{if(B0){if(!E)E=q.registerTool(l94)}else E?.dispose(),E=void 0}),L;if(!J.executeMode){let B0=await J.settings.get("fuzzy.alwaysIncludePaths")??[];L=new G90(process.cwd(),{alwaysIncludePaths:B0},!0)}else L=new class extends G90{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let M=await Dm1({isDevelopment:!1}),A=new mI0(M,X),j=new _j0(M,{lazy:!0,maxThreads:200});I.info("Starting Amp background services");let P=Z.takeMeBack?!1:void 0,_=hi0(P,F),S=Boolean(_||Z.headless);if(S)I.info("DTW mode enabled: thread sync service disabled");let y=S?o33():gp1({threadService:A,threadHistoryService:j,configService:X,isExtensionDevelopment:!1}),m;g8.status.subscribe((B0)=>{m=B0});let b=new Yw0({workspaceRoots:[V1.file(process.cwd())],fileSystem:Z.jetbrains||Z.ide?qe:r6,getCurrentFile:()=>{if(!m?.openFile)return;try{return V1.parse(m.openFile)}catch(B0){I.warn("Failed to parse current file URI",{uri:m.openFile,error:B0});return}},getOpenFiles:()=>{if(!m?.visibleFiles?.length)return[];let B0=m.openFile;return m.visibleFiles.filter((o)=>o!==B0).map((o)=>{try{return V1.parse(o)}catch(q0){return I.warn("Failed to parse visible file URI",{uri:o,error:q0}),null}}).filter((o)=>o!==null)}}),v=new Ib0,u=process.env.PLUGINS??"off",p=Z.headless?yF4():void 0,c=p??new d90({configService:X}),f=c instanceof d90?c:void 0;if(f)f.pluginExecutorKind=_?"local":"unknown";let a=JA0({configService:X,fileSystem:Z.jetbrains||Z.ide?qe:r6,platform:c,internalPlugins:IC4,pluginFilter:u}),l=of1({pluginService:a,toolService:q}),s={codebaseContextService:b,configService:X,toolService:q,mcpService:B,skillService:H,toolboxService:w,trustStore:W,threadService:A,threadHistoryService:j,threadSyncService:y,threadStorage:M,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:L,fileSystem:Z.jetbrains||Z.ide?qe:r6,terminal:v,pluginService:a,pluginPlatform:f,headlessPluginPlatform:p,serverStatus:F,serverStatusPromise:z,hasAPIKeyAtStartup:V};return{...s,async asyncDispose(){if(s.mcpService.hasAuthenticatingClients())I.info("Waiting for OAuth authentication to complete before exit..."),await s.mcpService.waitForAuthentication();for(let B0 of N.values())B0.dispose();await s.mcpService.dispose(),U(),await s.threadService.asyncDispose(),s.configService.unsubscribe(),G(),s.fuzzyServer.dispose(),s.threadSyncService.dispose(),s.settingsStorage[Symbol.dispose](),O.unsubscribe(),E?.dispose(),l.dispose(),await s.pluginService.dispose()}}}async function r33(J){if(!J.executeMode){if(!await g90("Would you like to log in to Amp? [(y)es, (n)o]: "))return d6.write(`Login cancelled. Run the command again to retry.
7560
7560
  `),!1}return await PC4(J)}async function PC4(J){let Z=y33(32).toString("hex"),Q=await oC(J.ampURL,Z),Y=new AbortController;try{await xX(Q,Y.signal)}catch(K){I.error("Error opening browser",{error:K})}let X=await oC(J.ampURL,Z,!1);d6.write(`If your browser does not open automatically, visit:
7561
7561
 
@@ -7563,7 +7563,7 @@ ${J1.blue.bold(X)}
7563
7563
 
7564
7564
  `);try{return await UF4(J.ampURL,Z,J.secrets,Y),d6.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(K){return I.error("Login failed",{error:K}),j2.write(`
7565
7565
  Login failed: ${K instanceof Error?K.message:String(K)}
7566
- `),!1}}function wC4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function s33(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 v1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!B8(Y.threadId))throw new v1("Create response did not include a valid thread ID",1);return Y.threadId}function t33(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function e33(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 v1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!t33(Q))throw new v1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function $83(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 J83(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 v1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function Z83(){let J=new VH().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)nO(),process.exit(0);let B=H.originalError??H;fK4(B)}),lj4(J,{version:"0.0.1773878033-g2f2f23",buildTimestamp:"2026-03-18T23:57:58.449Z",buildType:"'release'"}),J.addHelpText("after",Gz4()),J.configureHelp({formatHelp:Dz4}),J.command("logout").description("Log out by removing stored API key").action(async(H,B)=>{let w=B.optsWithGlobals(),N=await U3(w);await F83(N)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(H,B)=>{let w=B.optsWithGlobals(),N=await U3(w);await z83(N,await Rf0(w,N.settings))}),J.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(H,B,w)=>{let N=w.optsWithGlobals(),E=await U3(N);await FV4(H??"get",E.ampURL,E.secrets),process.exit(process.exitCode??0)}),J.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(H,B)=>{let w=B.optsWithGlobals(),N=await U3(w);await qV4(N.ampURL,N.secrets),process.exit(process.exitCode??0)}),J.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
7566
+ `),!1}}function wC4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function s33(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 v1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!B8(Y.threadId))throw new v1("Create response did not include a valid thread ID",1);return Y.threadId}function t33(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function e33(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 v1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!t33(Q))throw new v1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function $83(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 J83(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 v1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function Z83(){let J=new VH().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)nO(),process.exit(0);let B=H.originalError??H;fK4(B)}),lj4(J,{version:"0.0.1773878698-g9a9736",buildTimestamp:"2026-03-19T00:09:00.436Z",buildType:"'release'"}),J.addHelpText("after",Gz4()),J.configureHelp({formatHelp:Dz4}),J.command("logout").description("Log out by removing stored API key").action(async(H,B)=>{let w=B.optsWithGlobals(),N=await U3(w);await F83(N)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(H,B)=>{let w=B.optsWithGlobals(),N=await U3(w);await z83(N,await Rf0(w,N.settings))}),J.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(H,B,w)=>{let N=w.optsWithGlobals(),E=await U3(N);await FV4(H??"get",E.ampURL,E.secrets),process.exit(process.exitCode??0)}),J.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(H,B)=>{let w=B.optsWithGlobals(),N=await U3(w);await qV4(N.ampURL,N.secrets),process.exit(process.exitCode??0)}),J.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
7567
7567
  Actions:
7568
7568
  create Create a new DTW thread and print its ID
7569
7569
  add-message <message> Send a user message and wait for message_added
@@ -7627,8 +7627,8 @@ ${L}
7627
7627
 
7628
7628
  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 Q83(J){I.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new mm({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized]).then(()=>{return}),toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:ZJ,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new JK(J.fileSystem),ampURL:J.ampURL});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw I.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function Y83(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await $T()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await $T()).trimEnd(),stdinInput:null}}function X83(J,Z,Q){if(J.remote&&!Z)throw new v1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new v1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new v1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new v1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new v1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new v1("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 v1("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"}]}}' | amp --execute --stream-json --stream-json-input`);if(Z&&Q===""&&!J.streamJsonInput&&!J.headless)throw new v1("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"
7629
7629
  Or pipe via stdin: echo "your message" | amp --execute`)}async function ZQ0(J,Z,Q){let Y=process.hrtime.bigint(),X=(z0,$0)=>{let D0=Number(process.hrtime.bigint()-$0)/1e6,i=fJ4();I.info("Startup phase",{phase:z0,phaseMs:Math.round(D0),sinceMainMs:i===null?void 0:Math.round(i)})},{userInput:K,stdinInput:V}=await Y83(Z),z=!!Z.streamJson||!!Z.streamJsonThinking;X83({...Z,streamJson:z},J.executeMode,K),Z2(Q,Z);let F=process.hrtime.bigint(),q=Boolean(await J.secrets.get("apiKey",J.ampURL)),G=!J.executeMode&&!Z.headless&&q;I.info("Interactive auth startup mode",{deferInteractiveAuth:G,hasAPIKeyAtStartup:q,executeMode:J.executeMode,headless:Boolean(Z.headless)});let D=await D9(J,Z,{deferAuth:G});X("runMainThread:createThreadDependencies",F),F=process.hrtime.bigint();let U=await di0(D);X("runMainThread:createWorkerDeps",F);let{serverStatus:W}=D;if(!G&&Rq(W)){let z0=hC(Error(W.error.message));if(z0.message===z3.networkOffline||z0.message===z3.networkTimeout)throw $Q0(J.ampURL);throw new v1(z3.invalidAPIKey,1)}let H=j6(W)?W:null,B=H?.user.email,w=jC4(B),N=bi0({userEmail:B,features:H?.features}),E=Z.takeMeBack?!1:void 0,O=H!==null&&hi0(E,H);if(!G)await fi0(Q,Z,W);let L=gi0(W),M=L?.features??[],A=L?.team??null,j=m90(Z,L);if(j instanceof Error)W3(j.message);if((J.executeMode||z)&&d3(Z.mode)&&!w)throw new v1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(H&&!zU(Z.mode,B))throw new v1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await fF4(K,V,D.configService),await D.asyncDispose(),process.exit(0);if(Z.headless){if(!B||!kZ(B))throw new v1("Headless DTW mode is only available for Amp employees",1);let z0=await D.secretStorage.get("apiKey",J.ampURL);if(!z0)throw new v1("API key required for headless mode. Please run `amp login` first.",1);let $0=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if($0&&!B8($0))throw new v1(`Invalid thread ID: ${$0}`,1);let D0=$0??await w83({dependencies:D,visibility:j??void 0}),i=await uV4(D0);if(i.status==="already-running")await D.asyncDispose(),await PG(),process.exit(0);try{await TV4({ampURL:J.ampURL,apiKey:z0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:D0,initialToolDiscovery:Promise.all([D.mcpService.initialized,D.toolboxService.initialized]).then(()=>{return}),configService:D.configService,mcpService:D.mcpService,toolService:D.toolService,skillService:D.skillService,fileSystem:D.fileSystem,pluginService:D.pluginService,pluginPlatform:D.headlessPluginPlatform})}finally{await i.release(),await D.asyncDispose()}await PG(),process.exit(0)}let P=J.executeMode?void 0:async(z0)=>Yc(z0,"interactive"),_={threadService:D.threadService,workerDeps:U,createThread:async()=>{let z0=G?await D.serverStatusPromise:W,$0=await r80(J.settings,process.cwd(),gi0(z0),j);if($0 instanceof Error)W3($0.message);return hm0(U,{threadMeta:$0?xK($0):void 0,agentMode:Z.mode,onFirstAssistantMessage:P})},validateThreadOwnership:async(z0,$0)=>{if($0?.nonBlockingOwnershipCheck){NC4(z0,D.configService).catch((D0)=>{if(D0 instanceof v1){if($0.onOwnershipError){$0.onOwnershipError(D0,z0);return}gC(D0,z0);return}I.warn("Failed to validate thread ownership in CLI, allowing to open",{error:D0})});return}try{await NC4(z0,D.configService)}catch(D0){if(D0 instanceof v1)throw D0;I.warn("Failed to validate thread ownership in CLI, allowing to open",{error:D0})}},switchThreadVisibility:j,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:P},S=async(z0)=>{try{if(z0==="dtw")return Q83({ampURL:J.ampURL,configService:D.configService,threadService:D.threadService,mcpService:D.mcpService,toolboxService:D.toolboxService,toolService:D.toolService,skillService:D.skillService,fileSystem:D.fileSystem,threadId:Z.threadId});return qw4(_,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch($0){if($0 instanceof v1)throw $0;throw await gC($0,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.
7630
- `),await PG(),process.exit(1);let y=(async()=>{if(G){I.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await D.configService.getLatest(),$0=ok(z0),D0=await A6.getUserFreeTierStatus({},{config:D.configService,signal:AbortSignal.timeout($0)});if(D0.ok)return I.info("User free tier status:",D0),D0.result;return}catch(z0){I.error("Failed to fetch free tier status:",z0);return}})(),b=!J.executeMode?new xb0:null,v,u=null;if(b)v=b,u=(async()=>{let z0=G?await D.serverStatusPromise:D.serverStatus;await fi0(Q,Z,z0);let $0=process.hrtime.bigint(),D0=hi0(E,z0),i=j6(z0)?bi0({userEmail:z0.user.email,features:z0.features}):!1;UC4({dtwEnabled:D0,hasV2TUIAccess:i});let n=await S(D0?"dtw":"worker");if(X("runMainThread:createThreadPool",$0),b.attach(n),K){let t=await O1(n.threadHandles$);if(!t)throw new v1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:K}]})}})(),u.catch(async(z0)=>{let $0=z0 instanceof Error?z0:Error(String(z0));b.setInitError($0),await gC(z0,Z.threadId)});else F=process.hrtime.bigint(),UC4({dtwEnabled:O,hasV2TUIAccess:N}),v=await S(O?"dtw":"worker"),X("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let c=await D.configService.getLatest();if(X("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),a33({configService:D.configService,threadService:D.threadService,config:c,useNotificationsForService:p,threadViewStates$:()=>v.threadHandles$.pipe(Q4((z0)=>{if(!z0)return v0.of({});return K5(z0.thread$,z0.threadViewState$).pipe(D1(([$0,D0])=>({[$0.id]:D0})))}))}),X("runMainThread:createCliNotificationService",F),J.executeMode){IF4(D.mcpService,J.settings);let z0={userInput:K,stdinInput:V,dependencies:D,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},$0=await aK4({threadPool:v,...z0});if(await Yc($0,"execute"),Z.archive)await A6.archiveThread({thread:$0,archived:!0},{config:D.configService});await D.asyncDispose(),process.exit(0)}let f=!1,a=!1;if(Z.jetbrains||Z.ide){await lI1();let z0=await BN({jetbrainsOnly:Z.jetbrains});if(z0.length===0){if(Z.jetbrains)f=!await D.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let $0=z0[0];if($0)g8.selectConfig($0)}else a=!0}F=process.hrtime.bigint();let l=lf0("0.0.1773878033-g2f2f23",D.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",F),F=process.hrtime.bigint();let s=new Tj0(D.threadStorage);X("runMainThread:createThreadFuzzyIndexer",F),F=process.hrtime.bigint();let B0=new $b0(D.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",F),K&&J.executeMode){let z0=await O1(v.threadHandles$);if(!z0)throw new v1("No active thread is available yet.",1);await z0.sendMessage({content:[{type:"text",text:K}]})}F=process.hrtime.bigint();let o=await QL();X("runMainThread:loadSessionState",F),I.info("Loaded session state:",o);let q0={...o,launchCount:o.launchCount+1};YL(q0);let O0=Z.threadId&&B8(Z.threadId)?Z.threadId:void 0;try{if(F=process.hrtime.bigint(),await NN4({codebaseContextService:D.codebaseContextService,history:new zf0,fuzzyServer:D.fuzzyServer,settingsStorage:D.settingsStorage,threadService:D.threadService,threadHistoryService:D.threadHistoryService,threadFuzzyIndexer:s,skillService:D.skillService,configService:D.configService,secretStorage:D.secretStorage,internalAPIClient:A6,threadPool:v,createSystemPromptDeps:async()=>RC4(D),ideClient:g8,mcpService:D.mcpService,toolboxService:D.toolboxService,mcpTrustHandler:B0,updateService:l,pluginPlatform:D.pluginPlatform,pluginService:D.pluginService},{initialServerStatus:D.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:D.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:O0,showJetBrainsInstaller:f,showIdePickerHint:a,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:q0,freeTierStatusPromise:y,workspace:A??null,features:M,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-18T23:57:58.449Z"},(z0)=>new qp0({...z0,threadPool:z0.threadPool},($0)=>new zl0({...$0,threadState:$0.threadState}))),X("runMainThread:mountApp-returned",F),u)await u}finally{}await D.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function U3(J){if(I.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.
7631
- `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;I.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await eu1({get:async(z)=>{if(z!==px)return;try{let F=await LC4(ui0,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(z,F)=>{if(z!==px)return;await OC4(CB.dirname(ui0),{recursive:!0}),await u33(ui0,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:uV()});ZI1(Y);let X=await oV4({...J,workspaceTrust:{current:!0,changes:Sk},getHook:process.env.AMP_URL?(z,F)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(J.mcpConfig){let z=await AF4(J.mcpConfig);X=jF4(X,z)}let K=CB.dirname(X.getSettingsFilePath());i$4(nC,K);let V=await X.get("url","global");if(!V)V=X2;if(I.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!KU(V))I.info("Targeting custom Amp server",{ampURL:V});return X=lj1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:pF4(await Rf0(J,X))}}function K83(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,(z,F)=>F.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}async function V83(){uJ4();let J=K83(process.argv),Z=process.argv.includes("--headless")||process.argv.some((K)=>K.startsWith("--headless="));oX4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?h33:void 0)});let Q=process.argv.includes("--no-color"),Y=process.argv.includes("--color"),X=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!Y&&!X)J1.level=0;if(m33(I),I.info("Starting Amp CLI.",{version:"0.0.1773878033-g2f2f23",buildTimestamp:"2026-03-18T23:57:58.449Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new v1(z3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Z83().parseAsync(process.argv)}c$4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await V83().catch(gC)});async function z83(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"),d6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7630
+ `),await PG(),process.exit(1);let y=(async()=>{if(G){I.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await D.configService.getLatest(),$0=ok(z0),D0=await A6.getUserFreeTierStatus({},{config:D.configService,signal:AbortSignal.timeout($0)});if(D0.ok)return I.info("User free tier status:",D0),D0.result;return}catch(z0){I.error("Failed to fetch free tier status:",z0);return}})(),b=!J.executeMode?new xb0:null,v,u=null;if(b)v=b,u=(async()=>{let z0=G?await D.serverStatusPromise:D.serverStatus;await fi0(Q,Z,z0);let $0=process.hrtime.bigint(),D0=hi0(E,z0),i=j6(z0)?bi0({userEmail:z0.user.email,features:z0.features}):!1;UC4({dtwEnabled:D0,hasV2TUIAccess:i});let n=await S(D0?"dtw":"worker");if(X("runMainThread:createThreadPool",$0),b.attach(n),K){let t=await O1(n.threadHandles$);if(!t)throw new v1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:K}]})}})(),u.catch(async(z0)=>{let $0=z0 instanceof Error?z0:Error(String(z0));b.setInitError($0),await gC(z0,Z.threadId)});else F=process.hrtime.bigint(),UC4({dtwEnabled:O,hasV2TUIAccess:N}),v=await S(O?"dtw":"worker"),X("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let c=await D.configService.getLatest();if(X("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),a33({configService:D.configService,threadService:D.threadService,config:c,useNotificationsForService:p,threadViewStates$:()=>v.threadHandles$.pipe(Q4((z0)=>{if(!z0)return v0.of({});return K5(z0.thread$,z0.threadViewState$).pipe(D1(([$0,D0])=>({[$0.id]:D0})))}))}),X("runMainThread:createCliNotificationService",F),J.executeMode){IF4(D.mcpService,J.settings);let z0={userInput:K,stdinInput:V,dependencies:D,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},$0=await aK4({threadPool:v,...z0});if(await Yc($0,"execute"),Z.archive)await A6.archiveThread({thread:$0,archived:!0},{config:D.configService});await D.asyncDispose(),process.exit(0)}let f=!1,a=!1;if(Z.jetbrains||Z.ide){await lI1();let z0=await BN({jetbrainsOnly:Z.jetbrains});if(z0.length===0){if(Z.jetbrains)f=!await D.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let $0=z0[0];if($0)g8.selectConfig($0)}else a=!0}F=process.hrtime.bigint();let l=lf0("0.0.1773878698-g9a9736",D.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",F),F=process.hrtime.bigint();let s=new Tj0(D.threadStorage);X("runMainThread:createThreadFuzzyIndexer",F),F=process.hrtime.bigint();let B0=new $b0(D.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",F),K&&J.executeMode){let z0=await O1(v.threadHandles$);if(!z0)throw new v1("No active thread is available yet.",1);await z0.sendMessage({content:[{type:"text",text:K}]})}F=process.hrtime.bigint();let o=await QL();X("runMainThread:loadSessionState",F),I.info("Loaded session state:",o);let q0={...o,launchCount:o.launchCount+1};YL(q0);let O0=Z.threadId&&B8(Z.threadId)?Z.threadId:void 0;try{if(F=process.hrtime.bigint(),await NN4({codebaseContextService:D.codebaseContextService,history:new zf0,fuzzyServer:D.fuzzyServer,settingsStorage:D.settingsStorage,threadService:D.threadService,threadHistoryService:D.threadHistoryService,threadFuzzyIndexer:s,skillService:D.skillService,configService:D.configService,secretStorage:D.secretStorage,internalAPIClient:A6,threadPool:v,createSystemPromptDeps:async()=>RC4(D),ideClient:g8,mcpService:D.mcpService,toolboxService:D.toolboxService,mcpTrustHandler:B0,updateService:l,pluginPlatform:D.pluginPlatform,pluginService:D.pluginService},{initialServerStatus:D.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:D.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:O0,showJetBrainsInstaller:f,showIdePickerHint:a,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:q0,freeTierStatusPromise:y,workspace:A??null,features:M,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-19T00:09:00.436Z"},(z0)=>new qp0({...z0,threadPool:z0.threadPool},($0)=>new zl0({...$0,threadState:$0.threadState}))),X("runMainThread:mountApp-returned",F),u)await u}finally{}await D.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function U3(J){if(I.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.
7631
+ `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;I.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await eu1({get:async(z)=>{if(z!==px)return;try{let F=await LC4(ui0,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(z,F)=>{if(z!==px)return;await OC4(CB.dirname(ui0),{recursive:!0}),await u33(ui0,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:uV()});ZI1(Y);let X=await oV4({...J,workspaceTrust:{current:!0,changes:Sk},getHook:process.env.AMP_URL?(z,F)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(J.mcpConfig){let z=await AF4(J.mcpConfig);X=jF4(X,z)}let K=CB.dirname(X.getSettingsFilePath());i$4(nC,K);let V=await X.get("url","global");if(!V)V=X2;if(I.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!KU(V))I.info("Targeting custom Amp server",{ampURL:V});return X=lj1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:pF4(await Rf0(J,X))}}function K83(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,(z,F)=>F.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}async function V83(){uJ4();let J=K83(process.argv),Z=process.argv.includes("--headless")||process.argv.some((K)=>K.startsWith("--headless="));oX4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?h33:void 0)});let Q=process.argv.includes("--no-color"),Y=process.argv.includes("--color"),X=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!Y&&!X)J1.level=0;if(m33(I),I.info("Starting Amp CLI.",{version:"0.0.1773878698-g9a9736",buildTimestamp:"2026-03-19T00:09:00.436Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new v1(z3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Z83().parseAsync(process.argv)}c$4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await V83().catch(gC)});async function z83(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"),d6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7632
7632
  `);else if(!KU(J.ampURL))d6.write(`Logging in to ${new URL(J.ampURL).hostname}
7633
7633
  `);let Y=process.env.AMP_API_KEY;if(Y)d6.write(`API key found in environment variable, storing...
7634
7634
  `),await Z.set("apiKey",Y,J.ampURL),d6.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1773878033-g2f2f23",
3
+ "version": "0.0.1773878698-g9a9736",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {