@sourcegraph/amp 0.0.1773590611-g8ab646 → 0.0.1773604945-g8ab646

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
@@ -6119,11 +6119,11 @@ ${W}`))}},error:(D)=>{if(!q)q=!0,z(Error(`Failed to spawn brew: ${D.message}`))}
6119
6119
  ${W}`;if(X==="pnpm"&&W.includes("Unable to find the global bin directory"))H+=`
6120
6120
 
6121
6121
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
6122
- npm install -g @sourcegraph/amp`;z(Error(H))}},error:(D)=>{if(!U)U=!0,z(Error(`Failed to spawn ${X}: ${D.message}`))},complete:()=>{if(!U)U=!0,K()}})})}h0();h0();Rj();async function J90(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,V=new AbortController,K=setTimeout(()=>V.abort(),5000);try{let z=await fetch(X,{signal:V.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),F=G.version??G["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let U=yK4(J,F),q=U<0,D,W;if(G.time){let H=G.time[J],B=G.time[F],w=Date.now();if(H)D=Math.floor((w-new Date(H).getTime())/3600000);if(B)W=Math.floor((w-new Date(B).getTime())/3600000)}return j.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:U,hasUpdate:q,currentVersionAge:D,latestVersionAge:W}),{hasUpdate:q,latestVersion:F,currentVersion:J,currentVersionAge:D,latestVersionAge:W,source:"npm"}}catch(z){return j.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(K)}}var KR5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function Z90(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${KR5}?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 V=yK4(J,X),K=V<0;return j.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:V,hasUpdate:K}),{hasUpdate:K,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return j.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var zR5=604800000;function kK4(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>zR5)return{ageMs:Q};return null}function yK4(J,Z){let Q=(K)=>{let[z,G]=K.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),V=Math.max(Y.parts.length,X.parts.length);for(let K=0;K<V;K++){let z=Y.parts[K]||0,G=X.parts[K]||0;if(z<G)return-1;if(z>G)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 ax0(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?PD(Q):void 0;return{sha:Y,age:X}}catch{return null}}H1();function ox0(J,Z,Q={}){let Y=new s1,X=Y.pipe(R6({shouldCountRefs:!1}));return setImmediate(async()=>{let V=new TK().scoped("update"),K=Q.startDelayMs??0;if(K>0)await Yz(K);let z=X.subscribe({next:(G)=>{V.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){V.debug("using fake update status for testing",{status:G}),await Yz(500),Y.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){V.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){V.debug("checking disabled");return}let U=await $90(),q=U==="binary"||U==="brew";V.debug("checking",{currentVersion:J,mode:F,packageManager:U,isBinaryDistribution:q});let D=q?await Z90(J):await J90(J,aE());if(!(D.latestVersion&&D.hasUpdate)){V.debug("no update available");return}let W=()=>{if(D.currentVersionAge!==void 0&&D.latestVersionAge!==void 0){let H=D.currentVersionAge-D.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return V.debug("versions too close together, suppressing update warning",{currentVersionAge:D.currentVersionAge,latestVersionAge:D.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!F)F=U==="pnpm"?"warn":"auto",V.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:F});if(U==="brew"){if(!W())Y.next("update-available-brew");return}if(U==="binary"&&process.execPath!==px0()){if(V.debug("non-standard binary path, showing warning"),!W())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!W())Y.next("update-available");return}if(!U){if(V.debug("auto-update not supported, falling back to warn mode"),!W())Y.next("update-available");return}if(U==="binary"&&process.platform==="win32"){if(V.debug("binary auto-update not supported on Windows, falling back to warn mode"),!W())Y.next("update-available");return}try{await Zg(D.latestVersion,U);let H=await FH(D.latestVersion),B={from:D.currentVersion,to:D.latestVersion,...H};if(H.status==="same")V.info("success",B),Y.next("updated");else V.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(G){V.debug("check failed",{error:G})}finally{await Yz(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}Rj();import{stderr as az}from"node:process";function uK4(J){let Z=new sW().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 bx0(Y.force||!1,Y.verbose||!1,"0.0.1773590611-g8ab646"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new sW("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await GR5(Y.targetVersion)});J.addCommand(Q)}async function GR5(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")az.write(Z1.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6122
+ npm install -g @sourcegraph/amp`;z(Error(H))}},error:(D)=>{if(!U)U=!0,z(Error(`Failed to spawn ${X}: ${D.message}`))},complete:()=>{if(!U)U=!0,K()}})})}h0();h0();Rj();async function J90(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,V=new AbortController,K=setTimeout(()=>V.abort(),5000);try{let z=await fetch(X,{signal:V.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),F=G.version??G["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let U=yK4(J,F),q=U<0,D,W;if(G.time){let H=G.time[J],B=G.time[F],w=Date.now();if(H)D=Math.floor((w-new Date(H).getTime())/3600000);if(B)W=Math.floor((w-new Date(B).getTime())/3600000)}return j.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:U,hasUpdate:q,currentVersionAge:D,latestVersionAge:W}),{hasUpdate:q,latestVersion:F,currentVersion:J,currentVersionAge:D,latestVersionAge:W,source:"npm"}}catch(z){return j.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(K)}}var KR5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function Z90(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${KR5}?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 V=yK4(J,X),K=V<0;return j.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:V,hasUpdate:K}),{hasUpdate:K,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return j.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var zR5=604800000;function kK4(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>zR5)return{ageMs:Q};return null}function yK4(J,Z){let Q=(K)=>{let[z,G]=K.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),V=Math.max(Y.parts.length,X.parts.length);for(let K=0;K<V;K++){let z=Y.parts[K]||0,G=X.parts[K]||0;if(z<G)return-1;if(z>G)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 ax0(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?PD(Q):void 0;return{sha:Y,age:X}}catch{return null}}H1();function ox0(J,Z,Q={}){let Y=new s1,X=Y.pipe(R6({shouldCountRefs:!1}));return setImmediate(async()=>{let V=new TK().scoped("update"),K=Q.startDelayMs??0;if(K>0)await Yz(K);let z=X.subscribe({next:(G)=>{V.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){V.debug("using fake update status for testing",{status:G}),await Yz(500),Y.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){V.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){V.debug("checking disabled");return}let U=await $90(),q=U==="binary"||U==="brew";V.debug("checking",{currentVersion:J,mode:F,packageManager:U,isBinaryDistribution:q});let D=q?await Z90(J):await J90(J,aE());if(!(D.latestVersion&&D.hasUpdate)){V.debug("no update available");return}let W=()=>{if(D.currentVersionAge!==void 0&&D.latestVersionAge!==void 0){let H=D.currentVersionAge-D.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return V.debug("versions too close together, suppressing update warning",{currentVersionAge:D.currentVersionAge,latestVersionAge:D.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!F)F=U==="pnpm"?"warn":"auto",V.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:F});if(U==="brew"){if(!W())Y.next("update-available-brew");return}if(U==="binary"&&process.execPath!==px0()){if(V.debug("non-standard binary path, showing warning"),!W())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!W())Y.next("update-available");return}if(!U){if(V.debug("auto-update not supported, falling back to warn mode"),!W())Y.next("update-available");return}if(U==="binary"&&process.platform==="win32"){if(V.debug("binary auto-update not supported on Windows, falling back to warn mode"),!W())Y.next("update-available");return}try{await Zg(D.latestVersion,U);let H=await FH(D.latestVersion),B={from:D.currentVersion,to:D.latestVersion,...H};if(H.status==="same")V.info("success",B),Y.next("updated");else V.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(G){V.debug("check failed",{error:G})}finally{await Yz(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}Rj();import{stderr as az}from"node:process";function uK4(J){let Z=new sW().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 bx0(Y.force||!1,Y.verbose||!1,"0.0.1773604945-g8ab646"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new sW("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await GR5(Y.targetVersion)});J.addCommand(Q)}async function GR5(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")az.write(Z1.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6123
6123
 
6124
6124
  `));try{if(!J){az.write(Z1.blue(`Checking for updates...
6125
- `));let{hasUpdate:Y,latestVersion:X}=hx0()?await Z90("0.0.1773590611-g8ab646"):await J90("0.0.1773590611-g8ab646",aE());if(!Y){let V=ax0("0.0.1773590611-g8ab646"),K=V?.age?`released ${V.age} ago`:`built ${PD(new Date("2026-03-15T16:09:16.701Z"))} ago`;az.write(Z1.green(`✓ Amp is already up to date on version ${"0.0.1773590611-g8ab646"} (${K})
6126
- `));let z=await FH("0.0.1773590611-g8ab646");if(z.warning)az.write(`
6125
+ `));let{hasUpdate:Y,latestVersion:X}=hx0()?await Z90("0.0.1773604945-g8ab646"):await J90("0.0.1773604945-g8ab646",aE());if(!Y){let V=ax0("0.0.1773604945-g8ab646"),K=V?.age?`released ${V.age} ago`:`built ${PD(new Date("2026-03-15T20:08:02.843Z"))} ago`;az.write(Z1.green(`✓ Amp is already up to date on version ${"0.0.1773604945-g8ab646"} (${K})
6126
+ `));let z=await FH("0.0.1773604945-g8ab646");if(z.warning)az.write(`
6127
6127
  `+Z1.yellow(z.warning)+`
6128
6128
  `);process.exit(0)}if(!X)az.write(Z1.yellow("[WARN] could not find latest version")),process.exit(0);J=X}az.write(Z1.blue(`Updating to version ${J}...
6129
6129
  `)),await Zg(J,void 0,(Y)=>{az.write(Z1.dim(`Running: ${Y}
@@ -7286,7 +7286,7 @@ Ctrl-X, Y, Z to unlock`;if(D){let b=F.text.replace(/`([^`]+)`/g,"$1")+`
7286
7286
  `),V=[];for(let K=0;K<X.length;K++){let F=X[K].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 U of F)if(U.startsWith("\x00")&&U.endsWith("\x01"))V.push(new C(U.slice(1,-1),new h({color:Y.app.keybind,bold:!0})));else V.push(new C(U,new h({color:Q.colorScheme.foreground})));if(K<X.length-1)V.push(new C(`
7287
7287
  `))}return new c0({decoration:{color:Q.colorScheme.background,border:u1.all(new v1(Y.app.keybind,1,"rounded"))},child:new i0({padding:C0.symmetric(0,1),child:new $0({text:new C(void 0,void 0,V)})})})}}class Zp0 extends A2{chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=v$0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new $p0({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 gN4(J,Z,Q,Y,X,V,K){if(V<=0)return null;switch(J){case"horizontal-bar":{let z=Q;return z>=0&&z<V?z:null}case"bar":case"stacked-bar":{let z=K?i8:0,G=Y-z;if(G<=0)return null;let F=Z-z;if(F<0||F>=G)return null;let U=Math.max(1,Math.floor(G/V)),q=Math.floor(F/U);return q>=0&&q<V?q:null}case"line":case"sparkline":case"stacked-area":{let z=K?i8:0,G=Y-z;if(G<=0)return null;let F=Math.max(0,Math.min(G-1,Z-z));if(V===1)return 0;let U=G/(V-1),q=Math.round(F/U);return Math.max(0,Math.min(V-1,q))}default:return null}}function xi5(J,Z,Q,Y,X,V,K,z){if(X<=0||Z<0||Z>=X)return null;let G=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let F=V?i8:0,U=Q-F,q=Y-(V?G:0);if(U<=0||q<=0)return null;let D=Math.max(1,Math.floor(U/X)),W=F+Z*D+Math.floor(D/2),H=z>0?K/z:0,B=Math.round((1-H)*(q-1));return{x:W,y:B}}case"line":case"sparkline":case"stacked-area":{let F=V?i8:0,U=Q-F,q=Y-(V?G:0);if(U<=0||q<=0)return null;let D=X>1?F+Math.round(Z/(X-1)*(U-1)):F+Math.floor(U/2),W=z>0?K/z:0,H=Math.round((1-W)*(q-1));return{x:D,y:H}}default:return null}}function fi5(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 bi5(J,Z,Q,Y,X){if(Q.length<=1){let z=Y(J.value),G=J.meta?` (${J.meta})`:"";return J.label.length+2+z.length+G.length}let V=J.label.length,K=0;for(let z of Q){let G=z.points[Z];if(!G)continue;K+=G.value;let F=2+z.name.length+2+Y(G.value).length;V=Math.max(V,F)}if(X){let z=9+Y(K).length;V=Math.max(V,z)}return V}function hi5(J,Z,Q,Y,X,V,K){let z;try{let H=I1.of(J),B=f0.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 G=new h({color:z.foreground,bold:!0}),F=new h({color:z.foreground}),U=new h({color:z.foreground,dim:!0}),q=[],D=new h({color:z.foreground,underline:!0}),W=(H,B)=>new C(B,D,void 0,H90(H),()=>{w8(J,H)});if(Y.length<=1){if(q.push(new C(`${Z.label}: `,G)),Z.link)q.push(W(Z.link,V(Z.value)));else q.push(new C(V(Z.value),F));if(Z.meta)q.push(new C(` (${Z.meta})`,U))}else{let H=K==="stacked-bar"||K==="stacked-area";q.push(new C(`${Z.label}
7288
7288
  `,G));let B=0;for(let w=0;w<Y.length;w++){let N=Y[w],O=N.points[Q];if(!O)continue;B+=O.value;let E=N.color??X[w%X.length]??z.foreground;if(q.push(new C("● ",new h({color:E}))),q.push(new C(`${N.name}: `,U)),O.link)q.push(W(O.link,V(O.value)));else q.push(new C(V(O.value),F));if(w<Y.length-1||H)q.push(new C(`
7289
- `))}if(H)q.push(new C(" ",U)),q.push(new C("Total: ",U)),q.push(new C(V(B),F))}return new c0({decoration:{color:z.background,border:u1.all(new v1(z.border,1,"rounded"))},child:new $0({text:new C(void 0,void 0,q)})})}ow();h0();e9();import{execSync as Wn5}from"node:child_process";KN();C7();H3();P7();rb();bX();a2();h$();xX();OE();_4();zx();Uk();H1();var hO4=D4(CF(),1);import{writeFile as yO4}from"fs/promises";import uO4 from"path";h0();a2();class Qp0{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.1773590611-g8ab646"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await Ct(Z,this.configService)}catch(Z){j.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 sH extends d0{props;constructor(J){super();this.props=J}createState(){return new pN4}}class pN4 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 dN4 extends p0{controller=new i7;focusNode=new r4({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,V=this.controller.text.trim().length>0,K=!X||V,z=u1.all(new v1(Q.foreground,1,"solid")),G=new FJ({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}),F=new U1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:G})]}),U=new c0({padding:C0.symmetric(1,0),child:new $0({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}))])})}),q=[];if(K)q.push(new C("Enter",new h({color:Y.keybind}))),q.push(new C(" to submit, ",new h({color:Q.foreground,dim:!0})));q.push(new C("Esc",new h({color:Y.keybind}))),q.push(new C(" to cancel",new h({color:Q.foreground,dim:!0})));let D=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,q)})});return new c0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new u0({children:[U,new R0({height:1}),F,new V3,D]})})}}class dp extends d0{props;constructor(J){super();this.props=J}createState(){return new dN4}}import{isDeepStrictEqual as Yp0}from"node:util";var mi5=/[\\/_ +.#"@[({&]/,gi5=/[\\/_ +.#"@[({&]/g,pi5=/[\s-]/,cN4=/[\s-]/g;function u$0(J,Z,Q,Y,X,V,K){if(V===Z.length){if(X===J.length)return 1;return 0.99}let z=`${X},${V}`;if(K[z]!==void 0)return K[z];let G=Y.charAt(V),F=Q.indexOf(G,X),U=0,q,D,W,H;while(F>=0){if(q=u$0(J,Z,Q,Y,F+1,V+1,K),q>U){if(F===X)q*=1;else if(pi5.test(J.charAt(F-1))){if(q*=0.9,H=J.slice(X,F-1).match(cN4),H&&X>0)q*=0.999**H.length}else if(mi5.test(J.charAt(F-1))){if(q*=0.8,W=J.slice(X,F-1).match(gi5),W&&X>0)q*=0.999**W.length}else if(q*=0.3,X>0)q*=0.999**(F-X);if(J.charAt(F)!==Z.charAt(V))q*=0.9999}if(q<0.1&&(Q.charAt(F-1)===Y.charAt(V+1)||Y.charAt(V+1)===Y.charAt(V)&&Q.charAt(F-1)!==Y.charAt(V))){if(D=u$0(J,Z,Q,Y,F+1,V+2,K),D*0.1>q)q=D*0.1}if(q>U)U=q;F=Q.indexOf(G,F+1)}return K[z]=U,U}function y$0(J){return J.toLowerCase().replace(cN4," ")}function lN4(J,Z){let Q=u$0(J,Z,y$0(J),y$0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,V=0;for(let z of Y){let G=u$0(J,z,y$0(J),y$0(z),0,0,{});if(G===0)return Q;X+=G,V+=z.length}let K=X/Y.length*0.95;return Math.max(Q,K)}return Q}class bT{}class hT{}class x$0{}class f$0{}class iN4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new nN4}}class nN4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function di5(J,Z){if(J==="")return{matches:!0,score:1};let Q=lN4(Z,J);return{matches:Q>0.15,score:Q}}class o9 extends d0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new aN4}}class aN4 extends p0{textController;focusNode;scrollController=new Y5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new i7(this.widget.props.controller?.query??""),this.focusNode=new r4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),H6.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)=>Yp0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!Yp0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>Yp0(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 bT){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof hT){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof x$0){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 f$0)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,...di5(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,V)=>this.widget.props.sortItems(X,V,J):(X,V)=>V.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;vT(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(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=u1.all(new v1(Q.foreground,1,"solid")),V=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,K=this.widget.props.enabled??!0,z=new FJ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:K,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),G=new C2({shortcuts:new Map([[new Y4("ArrowDown"),new bT],[new Y4("ArrowUp"),new hT],[new Y4("Tab"),new bT],[new Y4("Tab",{shift:!0}),new hT],[new Y4("n",{ctrl:!0}),new bT],[new Y4("p",{ctrl:!0}),new hT],[new Y4("Enter"),new x$0],[new Y4("Escape"),new f$0]]),focusNode:this.focusNode,child:z}),F=new S9({actions:new Map([[bT,new s4(this.invoke)],[hT,new s4(this.invoke)],[x$0,new s4(this.invoke)],[f$0,new s4(this.invoke)]]),child:G}),U=new U1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:F})]});this.itemContexts=[];let q;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";q=new R0({height:10,child:new l1({child:new $0({text:new C(w,new h({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)q=new T1({child:new l1({child:new $0({text:new C(this.widget.props.emptyStateText,new h({color:Q.foreground,dim:!0}))})})});else{let w=Y.map((N,O)=>{let E=O===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(N,E,L,J);else{let A=E?Z.app.selectionBackground:void 0,I=E?Z.app.selectionForeground:Q.foreground;M=new c0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(this.widget.props.getLabel(N),new h({color:I,dim:L}))})})}return new iN4(new n1({onClick:(A)=>this.handleItemClick(O,A.clickCount),child:M}),(A)=>{this.itemContexts[O]=A})});q=new u0({children:w,crossAxisAlignment:"start"})}let D=new n1({onScroll:this.handleScroll,opaque:!1,child:new j6({controller:this.scrollController,autofocus:!1,child:q})}),W=[];if(this.widget.props.title){let w=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(this.widget.props.title,new h({color:Z.app.command,bold:!0}))})});W.push(w)}if(!V)W.push(U,new R0({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 u0({mainAxisAlignment:"spaceBetween",children:[new T1({child:D}),new c0({padding:C0.only({top:1}),child:new l1({child:N??new R0({height:1})})})]})}))}else W.push(new T1({child:D}));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 u0({children:W})})}}function oN4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),V=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(V<7)return`${V}d ago`;return J.toLocaleDateString()}class Xp0 extends d1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,V)=>V.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>oN4(X.pubDate).length));return new o9({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,V,K,z)=>{let G=f0.of(z),{colors:F}=G,U=G.app,q=V?U.selectionBackground:void 0,D=V?U.selectionForeground:F.foreground,W=F.mutedForeground,H=(B,w)=>new R0({width:w,child:U1.end([new $0({text:new C(B,new h({color:W}))})])});return new c0({decoration:q?{color:q}:void 0,padding:C0.symmetric(2,0),child:new U1({children:[new T1({child:new $0({text:new C(X.title,new h({color:D})),overflow:"ellipsis",maxLines:1})}),new R0({width:2}),H(oN4(X.pubDate),Q)]})})}})}}_4();class Vp0 extends d0{createState(){return new rN4}}class rN4 extends p0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new $0({text:new C("●",new h({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}var ci5=/\/threads\/(T-[^/?#\s<>]+)/i;function li5(J){let Z=J.trim(),Y=Z.match(ci5)?.[1];if(Y&&D8(Y))return Y;let X=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(D8(X))return X;return null}function ii5(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let K of J)Z.set(K.id,K);for(let K of J){let z=K.relationships.find((G)=>G.role==="child"&&Z.has(G.threadID)&&(G.type==="fork"||G.type==="handoff"));if(z){Y.set(K.id,z.type);let G=z.threadID,F=Q.get(G)||[];F.push(K),Q.set(G,F)}else X.push(K)}return K20.flatten(X,(K)=>Q.get(K.id)).map((K)=>({...K.item,depth:K.depth,isLast:K.isLast,ancestorsAreLast:K.ancestorsAreLast,relationshipType:Y.get(K.item.id)}))}function Kp0(J,Z,Q){return new $0({text:new C(`${J}${Z}`,new h({color:Q})),maxLines:1})}function ni5(J,Z,Q,Y){return[Kp0("+",J,Y.success),V3.horizontal(1),Kp0("~",Z,Y.warning),V3.horizontal(1),Kp0("-",Q,Y.destructive)]}function ai5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class b$0 extends d0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new sN4}}class sN4 extends p0{spinner=new S3;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}`,V=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((O)=>O.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)V=V.filter((O)=>O.id!==Z.currentThreadID);let K=Z.recentThreadIDs||[],z=new Set(K),G=Z.currentThreadID,F=[...V].sort((O,E)=>{if(G){if(O.id===G)return-1;if(E.id===G)return 1}let L=K.indexOf(O.id),M=K.indexOf(E.id);if(L!==-1&&M!==-1)return L-M;if(L!==-1)return-1;if(M!==-1)return 1;return 0}),U=ii5(F),q=Math.max(0,...U.map((O)=>O.description.timeAgo.length)),D=f0.of(J),W=new i0({padding:C0.symmetric(0,1),child:new l1({child:new $0({text:new C("",new h({color:D.colors.foreground,dim:!0}),[new C("Ctrl+T",new h({color:D.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new h({color:D.colors.foreground,dim:!0}))])})})}),H="",B=null,w=(O)=>{if(O!==H)H=O,B=li5(O);return B};return new o9({items:U,getLabel:(O)=>`${O.title} ${O.id}`,filterItem:(O,E)=>{let L=w(E);if(L)return O.id.toLowerCase()===L.toLowerCase();return!0},normalizeQuery:(O)=>w(O)?"":O,onAccept:async(O,E)=>{if(!Z.onSelect||this.isSwitchingThread)return;let L=Z.onSelect(O.id,E);if(!ai5(L))return;this.setSwitchingThread(!0);try{await L}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(O)=>{if(Z.previewController){if(O)Z.previewController.select(O.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:(O,E,L,M)=>{let A=f0.of(M),{app:I,colors:P}=A,_=E?I.selectionBackground:void 0,S=E?I.selectionForeground:P.foreground,y=P.mutedForeground,m=(s,w0)=>new R0({width:w0,child:U1.end([new $0({text:new C(s,new h({color:y}))})])}),b=Z.threadViewStates[O.id],k=[],f=O.relationshipType==="handoff",p=new qp({connectorColor:P.mutedForeground});if(O.depth>0){let s=[],w0=O.ancestorsAreLast.slice(1);for(let H0 of w0)s.push(new C(p.getAncestorPrefix(H0),new h({color:p.connectorColor,dim:p.connectorDim})));let a=O.isLast?p.elbow:p.tee,G0=p.getConnectorText(a);s.push(new C(G0,new h({color:p.connectorColor,dim:p.connectorDim}))),k.push(new $0({text:new C("",void 0,s)}))}let l=[],x=G===O.id?new C("(current) ",new h({color:P.success})):z.has(O.id)?new C("(visited) ",new h({color:P.foreground,dim:!0})):null;if(x)l.push(new $0({text:x}));if(gO(b))l.push(new Vp0),l.push(new R0({width:1}));let r=O.title;if(O.relationshipType==="fork"){let s=r.match(/^Forked\((\d+)\): /);if(s)r=r.slice(s[0].length);else while(r.startsWith("Forked: "))r=r.slice(8);l.push(new $0({text:new C("[fork] ",new h({color:P.primary}))}))}else if(f)l.push(new $0({text:new C("[handoff] ",new h({color:P.accent}))}));if(l.push(new T1({child:new $0({text:new C(r,new h({color:S})),overflow:"ellipsis",maxLines:1})})),l.push(new R0({width:2})),O.diffStats&&(O.diffStats.added>0||O.diffStats.changed>0||O.diffStats.deleted>0)){let s=E?{success:y,warning:y,destructive:y}:P;l.push(...ni5(O.diffStats.added,O.diffStats.changed,O.diffStats.deleted,s)),l.push(new R0({width:2}))}return l.push(m(O.description.timeAgo,q)),new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new U1({children:[...k,...l]})})}})}}function tN4(J){return 1-(1-J)**3}function eN4(J,Z,Q){return J+(Z-J)*Q}function cp(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),V=tN4(Y),K=tN4(X);return{x:eN4(J.startOffset.x,J.targetOffset.x,V),y:eN4(J.startOffset.y,J.targetOffset.y,K)}}var oi5={nodeWidth:3,horizontalSpacing:3};class mT{options;constructor(J={}){this.options={...oi5,...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 V=0,K=(z,G)=>{let F=Z.get(z.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let U={...z,parentID:Q.get(z.id)};if(F.length===0){Y.push({node:U,position:{x:V,y:G}});let B=V;return V+=this.options.nodeWidth+this.options.horizontalSpacing,B}let q=[];for(let B of F)q.push(K(B,G+1));let D=Math.min(...q),W=Math.max(...q),H=Math.floor((D+W)/2);return Y.push({node:U,position:{x:H,y:G}}),H};for(let z of X)K(z,0);return Y}buildTree(J){let Z=new Set(J.map((V)=>V.id)),Q=[...J].sort((V,K)=>V.id.localeCompare(K.id)),Y=new Map;for(let V of Q){if(!V.parentID||!Z.has(V.parentID)){Y.set(V.id,void 0);continue}let K=!1,z=V.parentID;while(z){if(z===V.id){K=!0;break}z=Y.get(z)}Y.set(V.id,K?void 0:V.parentID)}let X=new Map;for(let V of J){let K=Y.get(V.id);if(!X.has(K))X.set(K,[]);X.get(K).push(V)}return{childrenMap:X,resolvedParent:Y}}}var ri5={nodeWidth:3,nodeHeight:2};class gT{options;constructor(J={}){this.options={...ri5,...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 V=this.calculateConnectorLine(X.position,Y.position);Z.push({points:V,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,V=Z.x+Q,K=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:K});let z=K+1;if(Y.push({x:X,y:z}),X!==V)Y.push({x:V,y:z});let G=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:V,y:G}),Y}}var si5={nodeWidth:3,nodeHeight:2},ti5={x:0,y:0};class m$0{options;constructor(J={}){this.options={...si5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=ti5,X,V,K,z){let G=z?f0.of(z):null,F=G?.colors,U=G?.app,q=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:q}))});let D=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,w=[];for(let I=D;I>=0;I--){let P=J.filter((y)=>y.position.y===I);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 R0({width:y.position.x-S}));let m=y.node.id===Q,b=K?.(y.node.data)??!1,k=V?.activeFlashOn??!1,f=y.node.id===V?.copyFlashNodeId;_.push(this.renderNode(m,b,k,f,U,F)),S=y.position.x+this.options.nodeWidth}if(w.push(new U1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((k)=>k.position.y===I-1),m=P,b=this.renderConnectors(y,m,Z,H,F,U);w.push(...b)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(D+1)*B,M=[new R0({width:H,height:L}),new x6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&X){let I=X(A.node.data),P=D-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+P*B+1,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(I,y,F,U)}))}return new c0({padding:C0.horizontal(2),child:new LH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,V){let K="┌─┐",z="└─┘",G=J?X?.threadGraphNodeSelected??V?.primary??V?.foreground:X?.threadGraphNode??V?.primary??V?.foreground,F=!1;if(Y)G=X?.threadGraphNodeSelected??V?.primary??G,K="┏━┓",z="┗━┛",F=!0;else if(Z&&Q)G=X?.toolSuccess??V?.primary??G,K="┏━┓",z="┗━┛";return new u0({crossAxisAlignment:"start",children:[new $0({text:new C(K,new h({color:G,bold:F}))}),new $0({text:new C(z,new h({color:G,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(X.length===0)X=V;else if(X.length+1+V.length<=Z)X+=" "+V;else Y.push(X),X=V}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),V=Math.min(Z,Math.max(1,...X.map((D)=>D.length))),K=V+2,z="┌"+"─".repeat(K)+"┐",G="└"+"─".repeat(K)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,U=Q?.foreground,q=[new $0({text:new C(z,new h({color:F}))})];for(let D of X){let W=" ".repeat(V-D.length);q.push(new $0({text:new C("│ ",new h({color:F}),[new C(D+W,new h({color:U??F})),new C(" │",new h({color:F}))])}))}return q.push(new $0({text:new C(G,new h({color:F}))})),new u0({crossAxisAlignment:"start",children:q})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let D of Z){let W=D.position.x+z;if(W>=0&&W<Y)F[W]="▲"}K.push(new $0({text:new C(F.join(""),new h({color:G}))}));let U=Array(Y).fill(" ");for(let D of J){let W=Z.filter((O)=>O.node.parentID===D.node.id);if(W.length===0)continue;let H=D.position.x+z,B=W.map((O)=>O.position.x+z),w=Math.min(...B),N=Math.max(...B);for(let O=w;O<=N;O++)if(O>=0&&O<Y){if(O===H)if(W.length===1&&B[0]===H)U[O]="│";else if(O===w)U[O]="└";else if(O===N)U[O]="┘";else U[O]="┬";else if(B.includes(O))if(O===w)U[O]="└";else if(O===N)U[O]="┘";else U[O]="┴";else if(U[O]===" ")U[O]="─"}}K.push(new $0({text:new C(U.join(""),new h({color:G}))}));let q=Array(Y).fill(" ");for(let D of J){if(Z.filter((B)=>B.node.parentID===D.node.id).length===0)continue;let H=D.position.x+z;if(H>=0&&H<Y)q[H]="│"}return K.push(new $0({text:new C(q.join(""),new h({color:G}))})),K}}var ei5={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},$n5={x:0,y:0};class zp0{options;constructor(J={}){this.options={...ei5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=$n5,X,V,K,z){let G=z?f0.of(z):null,F=G?.colors,U=G?.app,q=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:q}))});let D=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,w=[];for(let I=D;I>=0;I--){let P=J.filter((y)=>y.position.y===I);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 R0({width:y.position.x-S}));let m=y.node.id===Q,b=K?.(y.node.data)??!1,k=V?.activeFlashOn??!1;_.push(this.renderNode(m,b,k,U,F)),S=y.position.x+this.options.nodeWidth}if(w.push(new U1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((k)=>k.position.y===I-1),m=P,b=this.renderConnectors(y,m,Z,H,F,U);w.push(...b)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(D+1)*B,M=[new R0({width:H,height:L}),new x6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&X){let I=X(A.node.data),P=D-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+P*B,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(I,y,F)}))}return new c0({padding:C0.horizontal(2),child:new LH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let V=J?this.options.selectedIcon:this.options.nodeIcon,K=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)K=Y?.toolSuccess??X?.primary??K,V="■";return new $0({text:new C(V,new h({color:K}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(X.length===0)X=V;else if(X.length+1+V.length<=Z)X+=" "+V;else Y.push(X),X=V}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,V=[];for(let K of Y)V.push(new $0({text:new C(K,new h({color:X??Q?.primary??Q?.foreground}))}));return new u0({crossAxisAlignment:"start",children:V})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of J){let q=Z.filter((w)=>w.node.parentID===U.node.id);if(q.length===0)continue;let D=U.position.x+z,W=q.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===D,O=W.includes(w);if(N&&O)if(q.length===1)F[w]="│";else if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┼";else if(N)if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┬";else if(O)if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┴";else if(F[w]===" ")F[w]="─"}}return K.push(new $0({text:new C(F.join(""),new h({color:G}))})),K}}class lp extends N3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new $O4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class $O4 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 bL extends d0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new QO4}}var JO4=400,ZO4=300,Jn5=16;class QO4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new mT({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new gT;renderer=new zp0;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((G)=>G.id)),Q=new Set(this.widget.props.threads.map((G)=>G.id));if(Z.size!==Q.size||[...Z].some((G)=>!Q.has(G)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,V=this.widget.props.initialSelectedThreadID;if(X!==V&&V){let F=this.widget.props.threads.find((U)=>U.id===V);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let K=J.props.threads.some((G)=>G.isActive),z=this.widget.props.threads.some((G)=>G.isActive);if(K!==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:JO4,durationY:ZO4};let Z=Math.max(JO4,ZO4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=cp(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},Jn5)}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),V=Math.floor(this.viewportWidth/2)-J-Y,K=Q-Z,z=2,G=Math.floor(this.viewportHeight/2),U=Math.floor(G/2)-K;return{x:V,y:U}}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((V)=>V.node.parentID===Q.node.id);if(X.length>0){X.sort((K,z)=>K.position.x-z.position.x);let V=Math.floor(X.length/2);Y=X[V]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x<Q.position.x);if(X.length>0)X.sort((V,K)=>K.position.x-V.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x>Q.position.x);if(X.length>0)X.sort((V,K)=>V.position.x-K.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 U=(this.selectedNodeId?this.positionedNodes.find((q)=>q.node.id===this.selectedNodeId):null)??this.positionedNodes.find((q)=>!q.node.parentID);if(U){let q=Math.max(...this.positionedNodes.map((D)=>D.position.y));this.currentOffset=this.calculateCenterOffset(U.position.x,U.position.y,q)}}let X=this.widget.props.showTitle??!0,V=this.widget.props.offsetY??0,K={x:this.currentOffset.x,y:this.currentOffset.y+V},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,K,X?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),G=new lp({onWidth:(F)=>{if(this.viewportWidth!==F)this.viewportWidth=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(F)=>{if(this.viewportHeight!==F)this.viewportHeight=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new k4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:G})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class XO4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new VO4}}class VO4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var YO4=30,Zn5=30;class pT{}class dT{}class g$0{}class p$0{}class Gp0 extends d0{props;constructor(J){super();this.props=J}createState(){return new KO4}}class KO4 extends p0{highlightedIndex=0;controller=new i7;focusNode;scrollController=new Y5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new r4({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),H6.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;vT(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 pT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof dT){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof g$0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof p$0)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(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,z=t1.of(J).size.width>=Zn5+YO4,G=u1.all(new v1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,U=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("Select a cluster",new h({color:X.command,bold:!0}))})}),q=new FJ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),D=new C2({shortcuts:new Map([[new Y4("ArrowDown"),new pT],[new Y4("ArrowUp"),new dT],[new Y4("Tab"),new pT],[new Y4("Tab",{shift:!0}),new dT],[new Y4("n",{ctrl:!0}),new pT],[new Y4("p",{ctrl:!0}),new dT],[new Y4("Enter"),new g$0],[new Y4("Escape"),new p$0]]),focusNode:this.focusNode,child:q}),W=new S9({actions:new Map([[pT,new s4(this.invoke)],[dT,new s4(this.invoke)],[g$0,new s4(this.invoke)],[p$0,new s4(this.invoke)]]),child:D}),H=new U1({children:[new c0({decoration:{color:Y.background},child:new $0({text:new C(">",new h({color:Y.foreground}))})}),new T1({child:W})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let I=A===this.highlightedIndex,P=Z?M.threads.some((m)=>m.id===Z):!1,_=I?X.selectionBackground:void 0,S=I?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:I?X.selectionForeground:Y.success})));return new XO4(new n1({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,y)})})}),(m)=>{this.itemContexts[A]=m})}),w=new u0({children:B,crossAxisAlignment:"start"}),N=new T1({child:new n1({onScroll:this.handleScroll,child:new j6({controller:this.scrollController,autofocus:!1,child:w})})}),O=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],E=F?new c0({padding:C0.all(1),child:new bL({threads:O,autofocus:!1,offsetY:2})}):null,L;if(z){let M=E?new T1({child:E}):new R0({width:YO4});L=new U1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,M]})}else{let M=[new T1({child:new n1({onScroll:this.handleScroll,child:new j6({controller:this.scrollController,autofocus:!1,child:w})})})];if(E)M.push(new T1({child:E}));L=new u0({crossAxisAlignment:"stretch",children:M})}return new c0({decoration:{border:G,color:Y.background},padding:C0.symmetric(1,0),child:new u0({children:[U,H,new R0({height:1}),new T1({child:L})]})})}}class UJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!UJ._instance)UJ._instance=new UJ;return UJ._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 zO4 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){j.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){j.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((V)=>V.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=f0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),V=X.length>0?this.getValidationError(X):null,K=this.getAvailableLabels(),G=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...K];return new o9({title:"Add Label",items:G,getLabel:(F)=>{if("__isCreateMarker"in F)return this.currentQuery.trim().toLowerCase();return F.name},onAccept:(F)=>{if("__isCreateMarker"in F)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(F.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:V||"Type to create a new label",renderItem:(F,U,q,D)=>{let W=U?Q.selectionBackground:void 0,H=U?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in F&&F.__isCreateMarker){let w=this.currentQuery.trim().toLowerCase();return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new $0({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 $0({text:new C(F.name,new h({color:H}))})})},filterItem:(F,U)=>{if(this.currentQuery!==U)this.currentQuery=U,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in F&&F.__isCreateMarker)return this.shouldShowCreateMarker(U);let D=U.trim().toLowerCase();return D.length===0||F.name.includes(D)},sortItems:(F,U,q)=>{let D="__isCreateMarker"in F.item&&F.item.__isCreateMarker,W="__isCreateMarker"in U.item&&U.item.__isCreateMarker;if(D&&!W)return-1;if(!D&&W)return 1;return U.score-F.score}})}}class Fp0 extends d0{props;constructor(J){super();this.props=J}createState(){return new zO4}}class iV extends d0{props;constructor(J){super();this.props=J}createState(){return new GO4}}class GO4 extends p0{_spinner=new S3;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=f0.of(J),{colors:Q,app:Y}=Z,X=u1.all(new v1(Q.foreground,1,"solid")),V=this._spinner.toBraille(),K=new $0({textAlign:"center",text:new C("",void 0,[new C(V,new h({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new h({color:Q.foreground}))])}),G=[new T1({child:new u0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[K]})})];if(this.widget.props.onAbort)G.push(new R0({height:2,child:new c0({padding:C0.symmetric(2,0),child:new $0({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 F=new c0({decoration:new v4(Q.background,X),child:new R0({width:60,height:7,child:new u0({mainAxisAlignment:"start",children:G})})});if(this.widget.props.onAbort)return new k4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(U)=>{if(U.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:F});return F}}var ip={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"}},d$0=["workspace","global","flag","default","external","skill","other"];function Qn5(J){return Array.from(new Set(J))}function FO4(J){return Qn5([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function cT(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 FO4(J).length>0?"skill":"other"}function Up0(J){return cT(J)==="skill"}function UO4(J){let Z=FO4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=cT(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${ip[Y].description}: ${Q}`}function qO4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}class u8 extends d0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:V="█",showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createState(){return new DO4}}class DO4 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 V=this.widget.getScrollInfo(),K=Math.min(1,Q/Z),z=Math.max(1,X*K),G=Math.max(0,Math.min(1,V.scrollOffset/(Z-Q))),F=X-z,U=Math.max(0,F*G),q=U+z;return J>=U&&J<=q}_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(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let K=J.localPosition.y-this._dragStartY,z=Math.min(1,Q/Z),G=Math.max(1,V*z),F=V-G;if(F<=0)return;let U=Z-Q,q=F/U,D=K/q,W=Math.max(0,Math.min(U,this._dragStartOffset+D));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(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Q<=Y)return;let z=Math.min(1,Y/Q),G=Math.max(1,K*z),F=Q-Y,U=K-G,q=Math.max(0,Math.min(1,X/(Q-Y))),D=Math.max(0,U*q),W=D+G;if(Z>=D&&Z<=W)return;if(Z<D)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(F,X+Y))};build(J){return new n1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?E5.POINTER:E5.DEFAULT,child:new WO4({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 WO4 extends pC{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:V="█",showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createRenderObject(){return new HO4(this)}updateRenderObject(J){J.updateWidget(this)}}class HO4 extends A4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;f4(!!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:V}=this._calculateScrollbarMetrics();if(!V)return;let K=this._widget.trackColor,z=this._widget.thumbColor,G=["▁","▂","▃","▄","▅","▆","▇","█"],F=Y,U=Y+X;for(let q=0;q<this.size.height;q++){let D="█",W=!0;if(q===Math.floor(F)){let H=1-(F-q),B=Math.floor(H*8);D=G[B]||"█",W=!1}else if(q===Math.floor(U)){let H=1-(U-q),B=Math.floor(H*8);D=G[B]||"█"}else if(q>F&&q<U)W=!1;J.setChar(Z,Q+q,D,{fg:z,bg:K,reverse:W},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))),V=Math.min(1,Z/J),K=Math.max(1,Y*V),z=Y-K;return{thumbStartFloat:Math.max(0,z*X),thumbSizeFloat:K,showScrollbar:!0}}}class hL extends d0{props;constructor(J){super();this.props=J}createState(){return new BO4}}class BO4 extends p0{scrollController=new Y5;scrollAreaKey=new g7("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 S2}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=f0.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 U=N$0(Q);return{title:U.title,type:U.type,description:U.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,V=u1.all(new v1(Z.colors.border,1,"solid")),K=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(Y.title,new h({color:X,bold:!0}))})}),z=this.isWidgetMessage(Q)?Q.widget:new $0({text:new C(Y.description,new h({color:Z.colors.foreground})),selectable:!0}),G=new T1({child:new T2({child:new c0({padding:C0.symmetric(1,0),child:new U1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new j6({controller:this.scrollController,autofocus:!0,child:z})}),new u8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let U=this.scrollController.maxScrollExtent,q=this.scrollController.offset,D=this.getViewportHeight(),W=U+D;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(D,1),scrollOffset:Math.max(q,0)}}})]})})})}),F=new c0({padding:C0.symmetric(1,0),child:new $0({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 U=this.resolveFooterStyle(this.widget.props.message);if(U==="none")return new C("",new h({color:Z.colors.foreground,dim:!0}));if(U==="help"){let q=new h({color:Z.app.keybind}),D=new h({color:Z.colors.foreground,dim:!0});return new C("",D,[new C("Press ",D),new C("Escape",q),new C(" to close • Use ",D),new C("↑↓",q),new C(" or ",D),new C("j/k",q),new C(" to scroll",D)])}return new C("Press any key to close",new h({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new k4({onKey:(U)=>{if(this.widget.props.onRetry&&U.key==="r")return this.widget.props.onRetry(),"handled";if(U.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:V,color:Z.colors.background},padding:C0.all(1),child:new u0({mainAxisAlignment:"center",children:[K,new R0({height:1}),G,F]})})})}}e9();class wO4 extends d0{props;constructor(J){super();this.props=J}createState(){return new NO4}}class NO4 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=c8.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=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new $0({text:new C("No plugins found.",new h({dim:!0}))});let Y=[],X=this.plugins.length,V=this.plugins.filter((G)=>G.status==="active").length,K=this.plugins.reduce((G,F)=>G+F.registeredCommands.length,0),z=this.plugins.reduce((G,F)=>G+F.registeredTools.length,0);if(Y.push(new C(`${V}/${X} ${m4(X,"plugin")} active`,new h({bold:!0}))),K>0||z>0)Y.push(new C(` (${K} ${m4(K,"command")}, ${z} ${m4(z,"tool")})`,new h({dim:!0})));Y.push(new C(`
7289
+ `))}if(H)q.push(new C(" ",U)),q.push(new C("Total: ",U)),q.push(new C(V(B),F))}return new c0({decoration:{color:z.background,border:u1.all(new v1(z.border,1,"rounded"))},child:new $0({text:new C(void 0,void 0,q)})})}ow();h0();e9();import{execSync as Wn5}from"node:child_process";KN();C7();H3();P7();rb();bX();a2();h$();xX();OE();_4();zx();Uk();H1();var hO4=D4(CF(),1);import{writeFile as yO4}from"fs/promises";import uO4 from"path";h0();a2();class Qp0{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.1773604945-g8ab646"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await Ct(Z,this.configService)}catch(Z){j.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 sH extends d0{props;constructor(J){super();this.props=J}createState(){return new pN4}}class pN4 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 dN4 extends p0{controller=new i7;focusNode=new r4({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,V=this.controller.text.trim().length>0,K=!X||V,z=u1.all(new v1(Q.foreground,1,"solid")),G=new FJ({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}),F=new U1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:G})]}),U=new c0({padding:C0.symmetric(1,0),child:new $0({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}))])})}),q=[];if(K)q.push(new C("Enter",new h({color:Y.keybind}))),q.push(new C(" to submit, ",new h({color:Q.foreground,dim:!0})));q.push(new C("Esc",new h({color:Y.keybind}))),q.push(new C(" to cancel",new h({color:Q.foreground,dim:!0})));let D=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,q)})});return new c0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new u0({children:[U,new R0({height:1}),F,new V3,D]})})}}class dp extends d0{props;constructor(J){super();this.props=J}createState(){return new dN4}}import{isDeepStrictEqual as Yp0}from"node:util";var mi5=/[\\/_ +.#"@[({&]/,gi5=/[\\/_ +.#"@[({&]/g,pi5=/[\s-]/,cN4=/[\s-]/g;function u$0(J,Z,Q,Y,X,V,K){if(V===Z.length){if(X===J.length)return 1;return 0.99}let z=`${X},${V}`;if(K[z]!==void 0)return K[z];let G=Y.charAt(V),F=Q.indexOf(G,X),U=0,q,D,W,H;while(F>=0){if(q=u$0(J,Z,Q,Y,F+1,V+1,K),q>U){if(F===X)q*=1;else if(pi5.test(J.charAt(F-1))){if(q*=0.9,H=J.slice(X,F-1).match(cN4),H&&X>0)q*=0.999**H.length}else if(mi5.test(J.charAt(F-1))){if(q*=0.8,W=J.slice(X,F-1).match(gi5),W&&X>0)q*=0.999**W.length}else if(q*=0.3,X>0)q*=0.999**(F-X);if(J.charAt(F)!==Z.charAt(V))q*=0.9999}if(q<0.1&&(Q.charAt(F-1)===Y.charAt(V+1)||Y.charAt(V+1)===Y.charAt(V)&&Q.charAt(F-1)!==Y.charAt(V))){if(D=u$0(J,Z,Q,Y,F+1,V+2,K),D*0.1>q)q=D*0.1}if(q>U)U=q;F=Q.indexOf(G,F+1)}return K[z]=U,U}function y$0(J){return J.toLowerCase().replace(cN4," ")}function lN4(J,Z){let Q=u$0(J,Z,y$0(J),y$0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,V=0;for(let z of Y){let G=u$0(J,z,y$0(J),y$0(z),0,0,{});if(G===0)return Q;X+=G,V+=z.length}let K=X/Y.length*0.95;return Math.max(Q,K)}return Q}class bT{}class hT{}class x$0{}class f$0{}class iN4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new nN4}}class nN4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function di5(J,Z){if(J==="")return{matches:!0,score:1};let Q=lN4(Z,J);return{matches:Q>0.15,score:Q}}class o9 extends d0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new aN4}}class aN4 extends p0{textController;focusNode;scrollController=new Y5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new i7(this.widget.props.controller?.query??""),this.focusNode=new r4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),H6.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)=>Yp0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!Yp0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>Yp0(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 bT){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof hT){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof x$0){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 f$0)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,...di5(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,V)=>this.widget.props.sortItems(X,V,J):(X,V)=>V.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;vT(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(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=u1.all(new v1(Q.foreground,1,"solid")),V=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,K=this.widget.props.enabled??!0,z=new FJ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:K,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),G=new C2({shortcuts:new Map([[new Y4("ArrowDown"),new bT],[new Y4("ArrowUp"),new hT],[new Y4("Tab"),new bT],[new Y4("Tab",{shift:!0}),new hT],[new Y4("n",{ctrl:!0}),new bT],[new Y4("p",{ctrl:!0}),new hT],[new Y4("Enter"),new x$0],[new Y4("Escape"),new f$0]]),focusNode:this.focusNode,child:z}),F=new S9({actions:new Map([[bT,new s4(this.invoke)],[hT,new s4(this.invoke)],[x$0,new s4(this.invoke)],[f$0,new s4(this.invoke)]]),child:G}),U=new U1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:F})]});this.itemContexts=[];let q;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";q=new R0({height:10,child:new l1({child:new $0({text:new C(w,new h({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)q=new T1({child:new l1({child:new $0({text:new C(this.widget.props.emptyStateText,new h({color:Q.foreground,dim:!0}))})})});else{let w=Y.map((N,O)=>{let E=O===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(N,E,L,J);else{let A=E?Z.app.selectionBackground:void 0,I=E?Z.app.selectionForeground:Q.foreground;M=new c0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(this.widget.props.getLabel(N),new h({color:I,dim:L}))})})}return new iN4(new n1({onClick:(A)=>this.handleItemClick(O,A.clickCount),child:M}),(A)=>{this.itemContexts[O]=A})});q=new u0({children:w,crossAxisAlignment:"start"})}let D=new n1({onScroll:this.handleScroll,opaque:!1,child:new j6({controller:this.scrollController,autofocus:!1,child:q})}),W=[];if(this.widget.props.title){let w=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(this.widget.props.title,new h({color:Z.app.command,bold:!0}))})});W.push(w)}if(!V)W.push(U,new R0({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 u0({mainAxisAlignment:"spaceBetween",children:[new T1({child:D}),new c0({padding:C0.only({top:1}),child:new l1({child:N??new R0({height:1})})})]})}))}else W.push(new T1({child:D}));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 u0({children:W})})}}function oN4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),V=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(V<7)return`${V}d ago`;return J.toLocaleDateString()}class Xp0 extends d1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,V)=>V.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>oN4(X.pubDate).length));return new o9({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,V,K,z)=>{let G=f0.of(z),{colors:F}=G,U=G.app,q=V?U.selectionBackground:void 0,D=V?U.selectionForeground:F.foreground,W=F.mutedForeground,H=(B,w)=>new R0({width:w,child:U1.end([new $0({text:new C(B,new h({color:W}))})])});return new c0({decoration:q?{color:q}:void 0,padding:C0.symmetric(2,0),child:new U1({children:[new T1({child:new $0({text:new C(X.title,new h({color:D})),overflow:"ellipsis",maxLines:1})}),new R0({width:2}),H(oN4(X.pubDate),Q)]})})}})}}_4();class Vp0 extends d0{createState(){return new rN4}}class rN4 extends p0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new $0({text:new C("●",new h({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}var ci5=/\/threads\/(T-[^/?#\s<>]+)/i;function li5(J){let Z=J.trim(),Y=Z.match(ci5)?.[1];if(Y&&D8(Y))return Y;let X=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(D8(X))return X;return null}function ii5(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let K of J)Z.set(K.id,K);for(let K of J){let z=K.relationships.find((G)=>G.role==="child"&&Z.has(G.threadID)&&(G.type==="fork"||G.type==="handoff"));if(z){Y.set(K.id,z.type);let G=z.threadID,F=Q.get(G)||[];F.push(K),Q.set(G,F)}else X.push(K)}return K20.flatten(X,(K)=>Q.get(K.id)).map((K)=>({...K.item,depth:K.depth,isLast:K.isLast,ancestorsAreLast:K.ancestorsAreLast,relationshipType:Y.get(K.item.id)}))}function Kp0(J,Z,Q){return new $0({text:new C(`${J}${Z}`,new h({color:Q})),maxLines:1})}function ni5(J,Z,Q,Y){return[Kp0("+",J,Y.success),V3.horizontal(1),Kp0("~",Z,Y.warning),V3.horizontal(1),Kp0("-",Q,Y.destructive)]}function ai5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class b$0 extends d0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new sN4}}class sN4 extends p0{spinner=new S3;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}`,V=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((O)=>O.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)V=V.filter((O)=>O.id!==Z.currentThreadID);let K=Z.recentThreadIDs||[],z=new Set(K),G=Z.currentThreadID,F=[...V].sort((O,E)=>{if(G){if(O.id===G)return-1;if(E.id===G)return 1}let L=K.indexOf(O.id),M=K.indexOf(E.id);if(L!==-1&&M!==-1)return L-M;if(L!==-1)return-1;if(M!==-1)return 1;return 0}),U=ii5(F),q=Math.max(0,...U.map((O)=>O.description.timeAgo.length)),D=f0.of(J),W=new i0({padding:C0.symmetric(0,1),child:new l1({child:new $0({text:new C("",new h({color:D.colors.foreground,dim:!0}),[new C("Ctrl+T",new h({color:D.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new h({color:D.colors.foreground,dim:!0}))])})})}),H="",B=null,w=(O)=>{if(O!==H)H=O,B=li5(O);return B};return new o9({items:U,getLabel:(O)=>`${O.title} ${O.id}`,filterItem:(O,E)=>{let L=w(E);if(L)return O.id.toLowerCase()===L.toLowerCase();return!0},normalizeQuery:(O)=>w(O)?"":O,onAccept:async(O,E)=>{if(!Z.onSelect||this.isSwitchingThread)return;let L=Z.onSelect(O.id,E);if(!ai5(L))return;this.setSwitchingThread(!0);try{await L}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(O)=>{if(Z.previewController){if(O)Z.previewController.select(O.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:(O,E,L,M)=>{let A=f0.of(M),{app:I,colors:P}=A,_=E?I.selectionBackground:void 0,S=E?I.selectionForeground:P.foreground,y=P.mutedForeground,m=(s,w0)=>new R0({width:w0,child:U1.end([new $0({text:new C(s,new h({color:y}))})])}),b=Z.threadViewStates[O.id],k=[],f=O.relationshipType==="handoff",p=new qp({connectorColor:P.mutedForeground});if(O.depth>0){let s=[],w0=O.ancestorsAreLast.slice(1);for(let H0 of w0)s.push(new C(p.getAncestorPrefix(H0),new h({color:p.connectorColor,dim:p.connectorDim})));let a=O.isLast?p.elbow:p.tee,G0=p.getConnectorText(a);s.push(new C(G0,new h({color:p.connectorColor,dim:p.connectorDim}))),k.push(new $0({text:new C("",void 0,s)}))}let l=[],x=G===O.id?new C("(current) ",new h({color:P.success})):z.has(O.id)?new C("(visited) ",new h({color:P.foreground,dim:!0})):null;if(x)l.push(new $0({text:x}));if(gO(b))l.push(new Vp0),l.push(new R0({width:1}));let r=O.title;if(O.relationshipType==="fork"){let s=r.match(/^Forked\((\d+)\): /);if(s)r=r.slice(s[0].length);else while(r.startsWith("Forked: "))r=r.slice(8);l.push(new $0({text:new C("[fork] ",new h({color:P.primary}))}))}else if(f)l.push(new $0({text:new C("[handoff] ",new h({color:P.accent}))}));if(l.push(new T1({child:new $0({text:new C(r,new h({color:S})),overflow:"ellipsis",maxLines:1})})),l.push(new R0({width:2})),O.diffStats&&(O.diffStats.added>0||O.diffStats.changed>0||O.diffStats.deleted>0)){let s=E?{success:y,warning:y,destructive:y}:P;l.push(...ni5(O.diffStats.added,O.diffStats.changed,O.diffStats.deleted,s)),l.push(new R0({width:2}))}return l.push(m(O.description.timeAgo,q)),new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new U1({children:[...k,...l]})})}})}}function tN4(J){return 1-(1-J)**3}function eN4(J,Z,Q){return J+(Z-J)*Q}function cp(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),V=tN4(Y),K=tN4(X);return{x:eN4(J.startOffset.x,J.targetOffset.x,V),y:eN4(J.startOffset.y,J.targetOffset.y,K)}}var oi5={nodeWidth:3,horizontalSpacing:3};class mT{options;constructor(J={}){this.options={...oi5,...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 V=0,K=(z,G)=>{let F=Z.get(z.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let U={...z,parentID:Q.get(z.id)};if(F.length===0){Y.push({node:U,position:{x:V,y:G}});let B=V;return V+=this.options.nodeWidth+this.options.horizontalSpacing,B}let q=[];for(let B of F)q.push(K(B,G+1));let D=Math.min(...q),W=Math.max(...q),H=Math.floor((D+W)/2);return Y.push({node:U,position:{x:H,y:G}}),H};for(let z of X)K(z,0);return Y}buildTree(J){let Z=new Set(J.map((V)=>V.id)),Q=[...J].sort((V,K)=>V.id.localeCompare(K.id)),Y=new Map;for(let V of Q){if(!V.parentID||!Z.has(V.parentID)){Y.set(V.id,void 0);continue}let K=!1,z=V.parentID;while(z){if(z===V.id){K=!0;break}z=Y.get(z)}Y.set(V.id,K?void 0:V.parentID)}let X=new Map;for(let V of J){let K=Y.get(V.id);if(!X.has(K))X.set(K,[]);X.get(K).push(V)}return{childrenMap:X,resolvedParent:Y}}}var ri5={nodeWidth:3,nodeHeight:2};class gT{options;constructor(J={}){this.options={...ri5,...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 V=this.calculateConnectorLine(X.position,Y.position);Z.push({points:V,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,V=Z.x+Q,K=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:K});let z=K+1;if(Y.push({x:X,y:z}),X!==V)Y.push({x:V,y:z});let G=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:V,y:G}),Y}}var si5={nodeWidth:3,nodeHeight:2},ti5={x:0,y:0};class m$0{options;constructor(J={}){this.options={...si5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=ti5,X,V,K,z){let G=z?f0.of(z):null,F=G?.colors,U=G?.app,q=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:q}))});let D=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,w=[];for(let I=D;I>=0;I--){let P=J.filter((y)=>y.position.y===I);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 R0({width:y.position.x-S}));let m=y.node.id===Q,b=K?.(y.node.data)??!1,k=V?.activeFlashOn??!1,f=y.node.id===V?.copyFlashNodeId;_.push(this.renderNode(m,b,k,f,U,F)),S=y.position.x+this.options.nodeWidth}if(w.push(new U1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((k)=>k.position.y===I-1),m=P,b=this.renderConnectors(y,m,Z,H,F,U);w.push(...b)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(D+1)*B,M=[new R0({width:H,height:L}),new x6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&X){let I=X(A.node.data),P=D-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+P*B+1,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(I,y,F,U)}))}return new c0({padding:C0.horizontal(2),child:new LH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,V){let K="┌─┐",z="└─┘",G=J?X?.threadGraphNodeSelected??V?.primary??V?.foreground:X?.threadGraphNode??V?.primary??V?.foreground,F=!1;if(Y)G=X?.threadGraphNodeSelected??V?.primary??G,K="┏━┓",z="┗━┛",F=!0;else if(Z&&Q)G=X?.toolSuccess??V?.primary??G,K="┏━┓",z="┗━┛";return new u0({crossAxisAlignment:"start",children:[new $0({text:new C(K,new h({color:G,bold:F}))}),new $0({text:new C(z,new h({color:G,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(X.length===0)X=V;else if(X.length+1+V.length<=Z)X+=" "+V;else Y.push(X),X=V}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),V=Math.min(Z,Math.max(1,...X.map((D)=>D.length))),K=V+2,z="┌"+"─".repeat(K)+"┐",G="└"+"─".repeat(K)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,U=Q?.foreground,q=[new $0({text:new C(z,new h({color:F}))})];for(let D of X){let W=" ".repeat(V-D.length);q.push(new $0({text:new C("│ ",new h({color:F}),[new C(D+W,new h({color:U??F})),new C(" │",new h({color:F}))])}))}return q.push(new $0({text:new C(G,new h({color:F}))})),new u0({crossAxisAlignment:"start",children:q})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let D of Z){let W=D.position.x+z;if(W>=0&&W<Y)F[W]="▲"}K.push(new $0({text:new C(F.join(""),new h({color:G}))}));let U=Array(Y).fill(" ");for(let D of J){let W=Z.filter((O)=>O.node.parentID===D.node.id);if(W.length===0)continue;let H=D.position.x+z,B=W.map((O)=>O.position.x+z),w=Math.min(...B),N=Math.max(...B);for(let O=w;O<=N;O++)if(O>=0&&O<Y){if(O===H)if(W.length===1&&B[0]===H)U[O]="│";else if(O===w)U[O]="└";else if(O===N)U[O]="┘";else U[O]="┬";else if(B.includes(O))if(O===w)U[O]="└";else if(O===N)U[O]="┘";else U[O]="┴";else if(U[O]===" ")U[O]="─"}}K.push(new $0({text:new C(U.join(""),new h({color:G}))}));let q=Array(Y).fill(" ");for(let D of J){if(Z.filter((B)=>B.node.parentID===D.node.id).length===0)continue;let H=D.position.x+z;if(H>=0&&H<Y)q[H]="│"}return K.push(new $0({text:new C(q.join(""),new h({color:G}))})),K}}var ei5={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},$n5={x:0,y:0};class zp0{options;constructor(J={}){this.options={...ei5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=$n5,X,V,K,z){let G=z?f0.of(z):null,F=G?.colors,U=G?.app,q=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:q}))});let D=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,w=[];for(let I=D;I>=0;I--){let P=J.filter((y)=>y.position.y===I);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 R0({width:y.position.x-S}));let m=y.node.id===Q,b=K?.(y.node.data)??!1,k=V?.activeFlashOn??!1;_.push(this.renderNode(m,b,k,U,F)),S=y.position.x+this.options.nodeWidth}if(w.push(new U1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((k)=>k.position.y===I-1),m=P,b=this.renderConnectors(y,m,Z,H,F,U);w.push(...b)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(D+1)*B,M=[new R0({width:H,height:L}),new x6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&X){let I=X(A.node.data),P=D-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+P*B,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(I,y,F)}))}return new c0({padding:C0.horizontal(2),child:new LH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let V=J?this.options.selectedIcon:this.options.nodeIcon,K=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)K=Y?.toolSuccess??X?.primary??K,V="■";return new $0({text:new C(V,new h({color:K}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(X.length===0)X=V;else if(X.length+1+V.length<=Z)X+=" "+V;else Y.push(X),X=V}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,V=[];for(let K of Y)V.push(new $0({text:new C(K,new h({color:X??Q?.primary??Q?.foreground}))}));return new u0({crossAxisAlignment:"start",children:V})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of J){let q=Z.filter((w)=>w.node.parentID===U.node.id);if(q.length===0)continue;let D=U.position.x+z,W=q.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===D,O=W.includes(w);if(N&&O)if(q.length===1)F[w]="│";else if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┼";else if(N)if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┬";else if(O)if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┴";else if(F[w]===" ")F[w]="─"}}return K.push(new $0({text:new C(F.join(""),new h({color:G}))})),K}}class lp extends N3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new $O4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class $O4 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 bL extends d0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new QO4}}var JO4=400,ZO4=300,Jn5=16;class QO4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new mT({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new gT;renderer=new zp0;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((G)=>G.id)),Q=new Set(this.widget.props.threads.map((G)=>G.id));if(Z.size!==Q.size||[...Z].some((G)=>!Q.has(G)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,V=this.widget.props.initialSelectedThreadID;if(X!==V&&V){let F=this.widget.props.threads.find((U)=>U.id===V);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let K=J.props.threads.some((G)=>G.isActive),z=this.widget.props.threads.some((G)=>G.isActive);if(K!==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:JO4,durationY:ZO4};let Z=Math.max(JO4,ZO4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=cp(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},Jn5)}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),V=Math.floor(this.viewportWidth/2)-J-Y,K=Q-Z,z=2,G=Math.floor(this.viewportHeight/2),U=Math.floor(G/2)-K;return{x:V,y:U}}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((V)=>V.node.parentID===Q.node.id);if(X.length>0){X.sort((K,z)=>K.position.x-z.position.x);let V=Math.floor(X.length/2);Y=X[V]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x<Q.position.x);if(X.length>0)X.sort((V,K)=>K.position.x-V.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x>Q.position.x);if(X.length>0)X.sort((V,K)=>V.position.x-K.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 U=(this.selectedNodeId?this.positionedNodes.find((q)=>q.node.id===this.selectedNodeId):null)??this.positionedNodes.find((q)=>!q.node.parentID);if(U){let q=Math.max(...this.positionedNodes.map((D)=>D.position.y));this.currentOffset=this.calculateCenterOffset(U.position.x,U.position.y,q)}}let X=this.widget.props.showTitle??!0,V=this.widget.props.offsetY??0,K={x:this.currentOffset.x,y:this.currentOffset.y+V},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,K,X?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),G=new lp({onWidth:(F)=>{if(this.viewportWidth!==F)this.viewportWidth=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(F)=>{if(this.viewportHeight!==F)this.viewportHeight=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new k4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:G})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class XO4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new VO4}}class VO4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var YO4=30,Zn5=30;class pT{}class dT{}class g$0{}class p$0{}class Gp0 extends d0{props;constructor(J){super();this.props=J}createState(){return new KO4}}class KO4 extends p0{highlightedIndex=0;controller=new i7;focusNode;scrollController=new Y5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new r4({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),H6.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;vT(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 pT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof dT){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof g$0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof p$0)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(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,z=t1.of(J).size.width>=Zn5+YO4,G=u1.all(new v1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,U=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("Select a cluster",new h({color:X.command,bold:!0}))})}),q=new FJ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),D=new C2({shortcuts:new Map([[new Y4("ArrowDown"),new pT],[new Y4("ArrowUp"),new dT],[new Y4("Tab"),new pT],[new Y4("Tab",{shift:!0}),new dT],[new Y4("n",{ctrl:!0}),new pT],[new Y4("p",{ctrl:!0}),new dT],[new Y4("Enter"),new g$0],[new Y4("Escape"),new p$0]]),focusNode:this.focusNode,child:q}),W=new S9({actions:new Map([[pT,new s4(this.invoke)],[dT,new s4(this.invoke)],[g$0,new s4(this.invoke)],[p$0,new s4(this.invoke)]]),child:D}),H=new U1({children:[new c0({decoration:{color:Y.background},child:new $0({text:new C(">",new h({color:Y.foreground}))})}),new T1({child:W})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let I=A===this.highlightedIndex,P=Z?M.threads.some((m)=>m.id===Z):!1,_=I?X.selectionBackground:void 0,S=I?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:I?X.selectionForeground:Y.success})));return new XO4(new n1({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,y)})})}),(m)=>{this.itemContexts[A]=m})}),w=new u0({children:B,crossAxisAlignment:"start"}),N=new T1({child:new n1({onScroll:this.handleScroll,child:new j6({controller:this.scrollController,autofocus:!1,child:w})})}),O=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],E=F?new c0({padding:C0.all(1),child:new bL({threads:O,autofocus:!1,offsetY:2})}):null,L;if(z){let M=E?new T1({child:E}):new R0({width:YO4});L=new U1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,M]})}else{let M=[new T1({child:new n1({onScroll:this.handleScroll,child:new j6({controller:this.scrollController,autofocus:!1,child:w})})})];if(E)M.push(new T1({child:E}));L=new u0({crossAxisAlignment:"stretch",children:M})}return new c0({decoration:{border:G,color:Y.background},padding:C0.symmetric(1,0),child:new u0({children:[U,H,new R0({height:1}),new T1({child:L})]})})}}class UJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!UJ._instance)UJ._instance=new UJ;return UJ._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 zO4 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){j.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){j.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((V)=>V.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=f0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),V=X.length>0?this.getValidationError(X):null,K=this.getAvailableLabels(),G=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...K];return new o9({title:"Add Label",items:G,getLabel:(F)=>{if("__isCreateMarker"in F)return this.currentQuery.trim().toLowerCase();return F.name},onAccept:(F)=>{if("__isCreateMarker"in F)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(F.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:V||"Type to create a new label",renderItem:(F,U,q,D)=>{let W=U?Q.selectionBackground:void 0,H=U?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in F&&F.__isCreateMarker){let w=this.currentQuery.trim().toLowerCase();return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new $0({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 $0({text:new C(F.name,new h({color:H}))})})},filterItem:(F,U)=>{if(this.currentQuery!==U)this.currentQuery=U,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in F&&F.__isCreateMarker)return this.shouldShowCreateMarker(U);let D=U.trim().toLowerCase();return D.length===0||F.name.includes(D)},sortItems:(F,U,q)=>{let D="__isCreateMarker"in F.item&&F.item.__isCreateMarker,W="__isCreateMarker"in U.item&&U.item.__isCreateMarker;if(D&&!W)return-1;if(!D&&W)return 1;return U.score-F.score}})}}class Fp0 extends d0{props;constructor(J){super();this.props=J}createState(){return new zO4}}class iV extends d0{props;constructor(J){super();this.props=J}createState(){return new GO4}}class GO4 extends p0{_spinner=new S3;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=f0.of(J),{colors:Q,app:Y}=Z,X=u1.all(new v1(Q.foreground,1,"solid")),V=this._spinner.toBraille(),K=new $0({textAlign:"center",text:new C("",void 0,[new C(V,new h({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new h({color:Q.foreground}))])}),G=[new T1({child:new u0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[K]})})];if(this.widget.props.onAbort)G.push(new R0({height:2,child:new c0({padding:C0.symmetric(2,0),child:new $0({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 F=new c0({decoration:new v4(Q.background,X),child:new R0({width:60,height:7,child:new u0({mainAxisAlignment:"start",children:G})})});if(this.widget.props.onAbort)return new k4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(U)=>{if(U.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:F});return F}}var ip={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"}},d$0=["workspace","global","flag","default","external","skill","other"];function Qn5(J){return Array.from(new Set(J))}function FO4(J){return Qn5([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function cT(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 FO4(J).length>0?"skill":"other"}function Up0(J){return cT(J)==="skill"}function UO4(J){let Z=FO4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=cT(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${ip[Y].description}: ${Q}`}function qO4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}class u8 extends d0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:V="█",showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createState(){return new DO4}}class DO4 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 V=this.widget.getScrollInfo(),K=Math.min(1,Q/Z),z=Math.max(1,X*K),G=Math.max(0,Math.min(1,V.scrollOffset/(Z-Q))),F=X-z,U=Math.max(0,F*G),q=U+z;return J>=U&&J<=q}_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(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let K=J.localPosition.y-this._dragStartY,z=Math.min(1,Q/Z),G=Math.max(1,V*z),F=V-G;if(F<=0)return;let U=Z-Q,q=F/U,D=K/q,W=Math.max(0,Math.min(U,this._dragStartOffset+D));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(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Q<=Y)return;let z=Math.min(1,Y/Q),G=Math.max(1,K*z),F=Q-Y,U=K-G,q=Math.max(0,Math.min(1,X/(Q-Y))),D=Math.max(0,U*q),W=D+G;if(Z>=D&&Z<=W)return;if(Z<D)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(F,X+Y))};build(J){return new n1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?E5.POINTER:E5.DEFAULT,child:new WO4({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 WO4 extends pC{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:V="█",showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createRenderObject(){return new HO4(this)}updateRenderObject(J){J.updateWidget(this)}}class HO4 extends A4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;f4(!!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:V}=this._calculateScrollbarMetrics();if(!V)return;let K=this._widget.trackColor,z=this._widget.thumbColor,G=["▁","▂","▃","▄","▅","▆","▇","█"],F=Y,U=Y+X;for(let q=0;q<this.size.height;q++){let D="█",W=!0;if(q===Math.floor(F)){let H=1-(F-q),B=Math.floor(H*8);D=G[B]||"█",W=!1}else if(q===Math.floor(U)){let H=1-(U-q),B=Math.floor(H*8);D=G[B]||"█"}else if(q>F&&q<U)W=!1;J.setChar(Z,Q+q,D,{fg:z,bg:K,reverse:W},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))),V=Math.min(1,Z/J),K=Math.max(1,Y*V),z=Y-K;return{thumbStartFloat:Math.max(0,z*X),thumbSizeFloat:K,showScrollbar:!0}}}class hL extends d0{props;constructor(J){super();this.props=J}createState(){return new BO4}}class BO4 extends p0{scrollController=new Y5;scrollAreaKey=new g7("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 S2}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=f0.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 U=N$0(Q);return{title:U.title,type:U.type,description:U.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,V=u1.all(new v1(Z.colors.border,1,"solid")),K=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(Y.title,new h({color:X,bold:!0}))})}),z=this.isWidgetMessage(Q)?Q.widget:new $0({text:new C(Y.description,new h({color:Z.colors.foreground})),selectable:!0}),G=new T1({child:new T2({child:new c0({padding:C0.symmetric(1,0),child:new U1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new j6({controller:this.scrollController,autofocus:!0,child:z})}),new u8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let U=this.scrollController.maxScrollExtent,q=this.scrollController.offset,D=this.getViewportHeight(),W=U+D;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(D,1),scrollOffset:Math.max(q,0)}}})]})})})}),F=new c0({padding:C0.symmetric(1,0),child:new $0({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 U=this.resolveFooterStyle(this.widget.props.message);if(U==="none")return new C("",new h({color:Z.colors.foreground,dim:!0}));if(U==="help"){let q=new h({color:Z.app.keybind}),D=new h({color:Z.colors.foreground,dim:!0});return new C("",D,[new C("Press ",D),new C("Escape",q),new C(" to close • Use ",D),new C("↑↓",q),new C(" or ",D),new C("j/k",q),new C(" to scroll",D)])}return new C("Press any key to close",new h({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new k4({onKey:(U)=>{if(this.widget.props.onRetry&&U.key==="r")return this.widget.props.onRetry(),"handled";if(U.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:V,color:Z.colors.background},padding:C0.all(1),child:new u0({mainAxisAlignment:"center",children:[K,new R0({height:1}),G,F]})})})}}e9();class wO4 extends d0{props;constructor(J){super();this.props=J}createState(){return new NO4}}class NO4 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=c8.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=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new $0({text:new C("No plugins found.",new h({dim:!0}))});let Y=[],X=this.plugins.length,V=this.plugins.filter((G)=>G.status==="active").length,K=this.plugins.reduce((G,F)=>G+F.registeredCommands.length,0),z=this.plugins.reduce((G,F)=>G+F.registeredTools.length,0);if(Y.push(new C(`${V}/${X} ${m4(X,"plugin")} active`,new h({bold:!0}))),K>0||z>0)Y.push(new C(` (${K} ${m4(K,"command")}, ${z} ${m4(z,"tool")})`,new h({dim:!0})));Y.push(new C(`
7290
7290
 
7291
7291
  `));for(let G of this.plugins){let{icon:F,color:U}=this.statusIcon(G.status),q=this.getRelativePath(G.uri.toString());if(Y.push(new C(`${F} `,new h({color:U}))),Y.push(new C(q,new h({bold:!0}))),Y.push(new C(` ${G.status}`,new h({dim:!0}))),Y.push(new C(`
7292
7292
  `)),G.status==="active"&&G.registeredEvents.length>0)Y.push(new C(" Events: ",new h({dim:!0}))),Y.push(new C(G.registeredEvents.join(", "),new h({color:Q.link}))),Y.push(new C(`
@@ -7502,7 +7502,7 @@ ${Q0.content||""}`:Q0.content||"",a0=[],F1=Q0.baseDir.startsWith("file://")?RJ0(
7502
7502
  `)}function tM4(J,Z){J.command("usage").description("Show your current Amp usage and credit balance").action(async(Q,Y)=>{let X=Y.optsWithGlobals(),V=await Z(X),K=await V.settings.get("proxy"),z=Hj1({settings:{url:V.ampURL,proxy:K},secrets:{getToken:(F,U)=>V.secrets.get(F,U)}}),G=await A6.userDisplayBalanceInfo({},{config:z});if(!G.ok){if(G.error.code==="auth-required")process.stderr.write(Z1.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(Z1.red("Error: ")+G.error.message+`
7503
7503
  `),process.exit(1)}process.stdout.write(await ys5(G.result.displayText)+`
7504
7504
  `),process.exit(0)})}var J43=wB.join(y$,"logs","headless.log"),yl0=wB.join(vC,"device-id.json");async function Z43(){for(let J of GN)try{if((await J.listConfigs()).length>0)return J}catch(Z){j.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => D4(w_(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){E7.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
7505
- `)}function Q43(J){process.emitWarning=(Z,Q,Y,X)=>{let V=typeof Z==="string"?Z:Z.message||String(Z),K=Q||"Warning",z=!1;J.warn(V,{name:K,code:Y})}}function O7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")u$("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")u$("experimental.agentMode",Z.mode)}function SR4(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 Y43(J){try{return await TR4(J,"utf-8")}catch{return J}}async function ul0(J,Z,Q){let Y=SR4(J,Z);if(!Y)return;let X=y6(Q)?Q.features:[],V=y6(Q)?Q.user.email:void 0;if(!kR4(X,z2.HARNESS_SYSTEM_PROMPT)&&!vR4(V))throw new c1("You are not allowed to do this.",1);u$("systemPrompt",await Y43(Y))}function vR4(J){return!!(J&&Ao(J))}function kR4(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function xl0(J){return(J.userEmail?vZ(J.userEmail):!1)||kR4(J.features,z2.DTW_TUI)}function ER4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new c1("This TUI mode is not enabled for your user;",1)}function fl0(J,Z){if(typeof J==="boolean")return J;if(!y6(Z))return!1;return xl0({userEmail:Z.user.email,features:Z.features})}function bl0(J){if(!y6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function X43(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 hl0(J){let Y=X43(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 c1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function LR4(J){if(!p6.write(J))await s13(p6,"drain")}var MR4=[{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??cY,description:`Custom settings file path (overrides the default location ${cY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${hE})`},{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:a9(),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:xK.SMART.key,description:`Set the agent mode (${vX().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:vX().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}],AR4=(J)=>("deprecated"in J)&&J.deprecated===!0,V43=(J)=>("hidden"in J)&&J.hidden===!0,K43=(J)=>("default"in J),z43=(J)=>("default"in J)?J.default:void 0,yR4=[{name:"toggle-skills-count",entryPoint:ex0}];function G43(J,Z){let Q=Z.args[0],Y=Z.commands.map((V)=>V.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let V=Y.filter((z)=>Q.includes(z)||z.includes(Q)),K="Run amp --help for a list of available commands.";if(V.length>0)K=`Did you mean: ${V.join(", ")}? Or run amp --help for all commands.`;throw new c1(B8.unknownCommand(Q),1,K)}}async function gl0(J){return{...J,getThreadEnvironment:$J,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new JV(J.fileSystem),generateThreadTitle:r00,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>nJ(J.configService),pluginService:J.pluginService}}function uR4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:$J,filesystem:J.fileSystem,threadService:J.threadService}}var BZ0=K1.file(_R4.homedir()),ml0=process.env.XDG_CONFIG_HOME?K1.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(BZ0,".config");function F43(J){return f24({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){x24(Z);let Q=A90(),Y=Ef0();if((!Q||Y||Az4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(jU("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(jU("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(A90()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function U43(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>v0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function k9(J,Z,Q){let Y=Q?.deferAuth??!1;zj1("0.0.1773590611-g8ab646");let X=Dr({storage:J.settings,secretStorage:J.secrets,workspaceRoots:v0.of([K1.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:BZ0,userConfigDir:ml0});Nz4(X);let V=await X.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(V.settings)});let{toolService:K,dispose:z}=S24({configService:X}),G=new Map,F=()=>G.clear(),U=new tL0(X,J.settings.getWorkspaceRootPath()),q=zm1({configService:X,filesystem:r6}),D=ou1({configService:X,trustStore:U,skillMCPServers:q.skillMCPServers,createOAuthProvider:async(w0,a,G0)=>{let H0=`${w0}:${a}`,F0=G.get(H0);if(F0)return j.debug("Reusing existing OAuth provider for server",{serverName:w0,serverUrl:a}),F0;j.debug("Creating OAuth provider for server",{serverName:w0,serverUrl:a});let J0=(async()=>{let q0=new _N(J.secrets),i=await q0.getClientInfo(w0,a),n=G0?.scopes??i?.scopes,e=EV4();j.info("OAuth headless mode check",{useHeadless:e,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:p6.isTTY});let Z0;if(e)Z0=J.executeMode?OV4():NV4(w0);let Q0=new BL0({storage:q0,serverName:w0,serverUrl:a,clientId:G0?.clientId??i?.clientId,clientSecret:G0?.clientSecret??i?.clientSecret,authUrl:G0?.authUrl??i?.authUrl,tokenUrl:G0?.tokenUrl??i?.tokenUrl,scopes:n,headlessAuthHandler:Z0});return j.debug("OAuth provider created",{serverName:w0,serverUrl:a,hasManualClientId:!!(G0?.clientId??i?.clientId),willUseDCR:!(G0?.clientId??i?.clientId),scopes:n,headlessMode:e,executeMode:J.executeMode}),Q0})();return G.set(H0,J0),J0}}),W=$k0({configService:X,filesystem:r6,spawn:e50}),H;if(J.executeMode){let w0=await m84({toolService:K,providers:[D,W],initialTimeout:15000});H=w0.registrations;for(let[a,G0]of w0.initErrors)j.warn(`${a} provider initialization slow or failed:`,G0)}else H=Jk0({toolService:K,providers:[D,W]});if(Z.jetbrains)XN("JetBrains");else if(Z.ide&&ZK4())XN("VS Code");else if(Z.ide&&QK4())XN("Neovim");else if(Z.ide){let w0=await Z43();if(w0){let a=Mr(w0.ideName);if(a)XN(a)}}if(J.executeMode)Gj1(!0);let B,w=m8.status.pipe(D1((w0)=>Boolean(w0.connected&&w0.authenticated&&w0.ideName&&gj1(w0.ideName))),M4()).subscribe((w0)=>{if(w0){if(!B)B=K.registerTool(h84)}else B?.dispose(),B=void 0}),N;if(!J.executeMode){let w0=await J.settings.get("fuzzy.alwaysIncludePaths")??[];N=new y80(process.cwd(),{alwaysIncludePaths:w0},!0)}else N=new class extends y80{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let O=!1;{let w0=await J.secrets.get("apiKey",J.ampURL);if(O=Boolean(w0),j.info("API key lookup before login",{found:Boolean(w0),ampURL:J.ampURL,deferAuth:Y}),!w0)if(Y)j.info("No API key found, continuing startup with deferred auth");else{p6.write(`No API key found. Starting login flow...
7505
+ `)}function Q43(J){process.emitWarning=(Z,Q,Y,X)=>{let V=typeof Z==="string"?Z:Z.message||String(Z),K=Q||"Warning",z=!1;J.warn(V,{name:K,code:Y})}}function O7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")u$("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")u$("experimental.agentMode",Z.mode)}function SR4(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 Y43(J){try{return await TR4(J,"utf-8")}catch{return J}}async function ul0(J,Z,Q){let Y=SR4(J,Z);if(!Y)return;let X=y6(Q)?Q.features:[],V=y6(Q)?Q.user.email:void 0;if(!kR4(X,z2.HARNESS_SYSTEM_PROMPT)&&!vR4(V))throw new c1("You are not allowed to do this.",1);u$("systemPrompt",await Y43(Y))}function vR4(J){return!!(J&&Ao(J))}function kR4(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function xl0(J){return(J.userEmail?vZ(J.userEmail):!1)||kR4(J.features,z2.DTW_TUI)}function ER4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new c1("This TUI mode is not enabled for your user;",1)}function fl0(J,Z){if(typeof J==="boolean")return J;if(!y6(Z))return!1;return xl0({userEmail:Z.user.email,features:Z.features})}function bl0(J){if(!y6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function X43(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 hl0(J){let Y=X43(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 c1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function LR4(J){if(!p6.write(J))await s13(p6,"drain")}var MR4=[{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??cY,description:`Custom settings file path (overrides the default location ${cY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${hE})`},{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:a9(),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:xK.SMART.key,description:`Set the agent mode (${vX().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:vX().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}],AR4=(J)=>("deprecated"in J)&&J.deprecated===!0,V43=(J)=>("hidden"in J)&&J.hidden===!0,K43=(J)=>("default"in J),z43=(J)=>("default"in J)?J.default:void 0,yR4=[{name:"toggle-skills-count",entryPoint:ex0}];function G43(J,Z){let Q=Z.args[0],Y=Z.commands.map((V)=>V.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let V=Y.filter((z)=>Q.includes(z)||z.includes(Q)),K="Run amp --help for a list of available commands.";if(V.length>0)K=`Did you mean: ${V.join(", ")}? Or run amp --help for all commands.`;throw new c1(B8.unknownCommand(Q),1,K)}}async function gl0(J){return{...J,getThreadEnvironment:$J,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new JV(J.fileSystem),generateThreadTitle:r00,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>nJ(J.configService),pluginService:J.pluginService}}function uR4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:$J,filesystem:J.fileSystem,threadService:J.threadService}}var BZ0=K1.file(_R4.homedir()),ml0=process.env.XDG_CONFIG_HOME?K1.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(BZ0,".config");function F43(J){return f24({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){x24(Z);let Q=A90(),Y=Ef0();if((!Q||Y||Az4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(jU("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(jU("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(A90()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function U43(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>v0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function k9(J,Z,Q){let Y=Q?.deferAuth??!1;zj1("0.0.1773604945-g8ab646");let X=Dr({storage:J.settings,secretStorage:J.secrets,workspaceRoots:v0.of([K1.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:BZ0,userConfigDir:ml0});Nz4(X);let V=await X.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(V.settings)});let{toolService:K,dispose:z}=S24({configService:X}),G=new Map,F=()=>G.clear(),U=new tL0(X,J.settings.getWorkspaceRootPath()),q=zm1({configService:X,filesystem:r6}),D=ou1({configService:X,trustStore:U,skillMCPServers:q.skillMCPServers,createOAuthProvider:async(w0,a,G0)=>{let H0=`${w0}:${a}`,F0=G.get(H0);if(F0)return j.debug("Reusing existing OAuth provider for server",{serverName:w0,serverUrl:a}),F0;j.debug("Creating OAuth provider for server",{serverName:w0,serverUrl:a});let J0=(async()=>{let q0=new _N(J.secrets),i=await q0.getClientInfo(w0,a),n=G0?.scopes??i?.scopes,e=EV4();j.info("OAuth headless mode check",{useHeadless:e,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:p6.isTTY});let Z0;if(e)Z0=J.executeMode?OV4():NV4(w0);let Q0=new BL0({storage:q0,serverName:w0,serverUrl:a,clientId:G0?.clientId??i?.clientId,clientSecret:G0?.clientSecret??i?.clientSecret,authUrl:G0?.authUrl??i?.authUrl,tokenUrl:G0?.tokenUrl??i?.tokenUrl,scopes:n,headlessAuthHandler:Z0});return j.debug("OAuth provider created",{serverName:w0,serverUrl:a,hasManualClientId:!!(G0?.clientId??i?.clientId),willUseDCR:!(G0?.clientId??i?.clientId),scopes:n,headlessMode:e,executeMode:J.executeMode}),Q0})();return G.set(H0,J0),J0}}),W=$k0({configService:X,filesystem:r6,spawn:e50}),H;if(J.executeMode){let w0=await m84({toolService:K,providers:[D,W],initialTimeout:15000});H=w0.registrations;for(let[a,G0]of w0.initErrors)j.warn(`${a} provider initialization slow or failed:`,G0)}else H=Jk0({toolService:K,providers:[D,W]});if(Z.jetbrains)XN("JetBrains");else if(Z.ide&&ZK4())XN("VS Code");else if(Z.ide&&QK4())XN("Neovim");else if(Z.ide){let w0=await Z43();if(w0){let a=Mr(w0.ideName);if(a)XN(a)}}if(J.executeMode)Gj1(!0);let B,w=m8.status.pipe(D1((w0)=>Boolean(w0.connected&&w0.authenticated&&w0.ideName&&gj1(w0.ideName))),M4()).subscribe((w0)=>{if(w0){if(!B)B=K.registerTool(h84)}else B?.dispose(),B=void 0}),N;if(!J.executeMode){let w0=await J.settings.get("fuzzy.alwaysIncludePaths")??[];N=new y80(process.cwd(),{alwaysIncludePaths:w0},!0)}else N=new class extends y80{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let O=!1;{let w0=await J.secrets.get("apiKey",J.ampURL);if(O=Boolean(w0),j.info("API key lookup before login",{found:Boolean(w0),ampURL:J.ampURL,deferAuth:Y}),!w0)if(Y)j.info("No API key found, continuing startup with deferred auth");else{p6.write(`No API key found. Starting login flow...
7506
7506
  `);let a=await q43(J),G0=await J.secrets.get("apiKey",J.ampURL);if(j.info("Login flow completed",{success:a,storedKeyPresent:Boolean(G0),ampURL:J.ampURL}),!a)await EU(),process.exit(1);O=!0}}{let w0=await X.getLatest(),a=w0.settings.url,G0=w0.secrets.isSet?.[a];j.info("Config secrets state after login",{configURL:a,apiKeySet:G0?.apiKey??!1})}let E=E1(nJ(X).pipe(F5((w0)=>w0!=="pending"))),L=await Wm1({isDevelopment:!1}),M=Y?"pending":await E;if(!Y)j.info("Server status resolved",{status:"ready",isAuthenticated:y6(M),isError:RD(M),errorMessage:RD(M)?M.error.message:void 0});let A=new eI0(L,X),I=new iA0(L,{lazy:!0,maxThreads:200});j.info("Starting Amp background services");let P=Z.takeMeBack?!1:void 0,_=fl0(P,M),S=Boolean(_||Z.headless);if(S)j.info("DTW mode enabled: thread sync service disabled");let y=S?U43():bg1({threadService:A,threadHistoryService:I,configService:X,isExtensionDevelopment:!1}),m;m8.status.subscribe((w0)=>{m=w0});let b=new Dw0({workspaceRoots:[K1.file(process.cwd())],fileSystem:Z.jetbrains||Z.ide?xt:r6,getCurrentFile:()=>{if(!m?.openFile)return;try{return K1.parse(m.openFile)}catch(w0){j.warn("Failed to parse current file URI",{uri:m.openFile,error:w0});return}},getOpenFiles:()=>{if(!m?.visibleFiles?.length)return[];let w0=m.openFile;return m.visibleFiles.filter((a)=>a!==w0).map((a)=>{try{return K1.parse(a)}catch(G0){return j.warn("Failed to parse visible file URI",{uri:a,error:G0}),null}}).filter((a)=>a!==null)}}),k=new Af0,f=process.env.PLUGINS??"off",p=Z.headless?Yz4():void 0,l=p??new X90({configService:X}),x=l instanceof X90?l:void 0;if(x)x.pluginExecutorKind=_?"local":"unknown";let r=wM0({configService:X,fileSystem:Z.jetbrains||Z.ide?xt:r6,platform:l,internalPlugins:yR4,pluginFilter:f}),c=sx1({pluginService:r,toolService:K}),s={codebaseContextService:b,configService:X,toolService:K,mcpService:D,skillService:q,toolboxService:W,trustStore:U,threadService:A,threadHistoryService:I,threadSyncService:y,threadStorage:L,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:N,fileSystem:Z.jetbrains||Z.ide?xt:r6,terminal:k,pluginService:r,pluginPlatform:x,headlessPluginPlatform:p,serverStatus:M,serverStatusPromise:E,hasAPIKeyAtStartup:O};return{...s,async asyncDispose(){if(s.mcpService.hasAuthenticatingClients())j.info("Waiting for OAuth authentication to complete before exit..."),await s.mcpService.waitForAuthentication();for(let w0 of H.values())w0.dispose();await s.mcpService.dispose(),F(),await s.threadService.asyncDispose(),s.configService.unsubscribe(),z(),s.fuzzyServer.dispose(),s.threadSyncService.dispose(),s.settingsStorage[Symbol.dispose](),w.unsubscribe(),B?.dispose(),c.dispose(),await s.pluginService.dispose()}}}async function q43(J){if(!J.executeMode){if(!await sx0("Would you like to log in to Amp? [(y)es, (n)o]: "))return p6.write(`Login cancelled. Run the command again to retry.
7507
7507
  `),!1}return await xR4(J)}async function xR4(J){let Z=r13(32).toString("hex"),Q=await yC(J.ampURL,Z),Y=new AbortController;try{await fX(Q,Y.signal)}catch(V){j.error("Error opening browser",{error:V})}let X=await yC(J.ampURL,Z,!1);p6.write(`If your browser does not open automatically, visit:
7508
7508
 
@@ -7510,7 +7510,7 @@ ${Z1.blue.bold(X)}
7510
7510
 
7511
7511
  `);try{return await fK4(J.ampURL,Z,J.secrets,Y),p6.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(V){return j.error("Login failed",{error:V}),E7.write(`
7512
7512
  Login failed: ${V instanceof Error?V.message:String(V)}
7513
- `),!1}}function IR4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function D43(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 c1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!D8(Y.threadId))throw new c1("Create response did not include a valid thread ID",1);return Y.threadId}function W43(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 H43(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 c1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function B43(){let J=new sW().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)gE(),process.exit(0);let B=H.originalError??H;jX4(B)}),J.option("-V, --version","Print the version number and exit",()=>{let B;try{B=`, ${PD(new Date("2026-03-15T16:09:16.701Z"))} ago`}catch{}p6.write(`0.0.1773590611-g8ab646 (released 2026-03-15T16:09:16.701Z${B??""})
7513
+ `),!1}}function IR4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function D43(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 c1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!D8(Y.threadId))throw new c1("Create response did not include a valid thread ID",1);return Y.threadId}function W43(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 H43(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 c1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function B43(){let J=new sW().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)gE(),process.exit(0);let B=H.originalError??H;jX4(B)}),J.option("-V, --version","Print the version number and exit",()=>{let B;try{B=`, ${PD(new Date("2026-03-15T20:08:02.843Z"))} ago`}catch{}p6.write(`0.0.1773604945-g8ab646 (released 2026-03-15T20:08:02.843Z${B??""})
7514
7514
  `),process.exit(0)}),J.addHelpText("after",eV4()),J.configureHelp({formatHelp:$K4}),J.command("logout").description("Log out by removing stored API key").action(async(H,B)=>{let w=B.optsWithGlobals(),N=await E3(w);await A43(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 E3(w);await M43(N,await _x0(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(),O=await E3(N);await sX4(H??"get",O.ampURL,O.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 E3(w);await tX4(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",`
7515
7515
  Actions:
7516
7516
  create Create a new DTW thread and print its ID
@@ -7573,8 +7573,8 @@ ${L}
7573
7573
 
7574
7574
  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 w43(J){j.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new Lg({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:$J,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new JV(J.fileSystem),ampURL:J.ampURL});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw j.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function N43(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await hC()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await hC()).trimEnd(),stdinInput:null}}function O43(J,Z,Q){if(J.remote&&!Z)throw new c1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new c1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new c1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new c1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new c1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new c1("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 c1("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 c1("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"
7575
7575
  Or pipe via stdin: echo "your message" | amp --execute`)}async function wZ0(J,Z,Q){let Y=process.hrtime.bigint(),X=(H0,F0)=>{let J0=Number(process.hrtime.bigint()-F0)/1e6,q0=R$4();j.info("Startup phase",{phase:H0,phaseMs:Math.round(J0),sinceMainMs:q0===null?void 0:Math.round(q0)})},{userInput:V,stdinInput:K}=await N43(Z),z=!!Z.streamJson||!!Z.streamJsonThinking;O43({...Z,streamJson:z},J.executeMode,V),O7(Q,Z);let G=process.hrtime.bigint(),F=Boolean(await J.secrets.get("apiKey",J.ampURL)),U=!J.executeMode&&!Z.headless&&F;j.info("Interactive auth startup mode",{deferInteractiveAuth:U,hasAPIKeyAtStartup:F,executeMode:J.executeMode,headless:Boolean(Z.headless)});let q=await k9(J,Z,{deferAuth:U});X("runMainThread:createThreadDependencies",G),G=process.hrtime.bigint();let D=await gl0(q);X("runMainThread:createWorkerDeps",G);let{serverStatus:W}=q;if(!U&&RD(W)){let H0=km(Error(W.error.message));if(H0.message===B8.networkOffline||H0.message===B8.networkTimeout)throw hl0(J.ampURL);throw new c1(B8.invalidAPIKey,1)}let H=y6(W)?W:null,B=H?.user.email,w=vR4(B),N=xl0({userEmail:B,features:H?.features}),O=Z.takeMeBack?!1:void 0,E=H!==null&&fl0(O,H);if(!U)await ul0(Q,Z,W);let L=bl0(W),M=L?.features??[],A=L?.team??null,I=Q90(Z,L);if(I instanceof Error)G3(I.message);if((J.executeMode||z)&&h3(Z.mode)&&!w)throw new c1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(H&&!iq(Z.mode,B))throw new c1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await Kz4(V,K,q.configService),await q.asyncDispose(),process.exit(0);if(Z.headless){if(!B||!vZ(B))throw new c1("Headless DTW mode is only available for Amp employees",1);let H0=await q.secretStorage.get("apiKey",J.ampURL);if(!H0)throw new c1("API key required for headless mode. Please run `amp login` first.",1);let F0=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if(F0&&!D8(F0))throw new c1(`Invalid thread ID: ${F0}`,1);let J0=F0??await S43({dependencies:q,visibility:I??void 0}),q0=await IV4(J0);if(q0.status==="already-running")await q.asyncDispose(),await EU(),process.exit(0);try{await wV4({ampURL:J.ampURL,apiKey:H0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:J0,initialToolDiscovery:Promise.all([q.mcpService.initialized,q.toolboxService.initialized]).then(()=>{return}),configService:q.configService,mcpService:q.mcpService,toolService:q.toolService,skillService:q.skillService,fileSystem:q.fileSystem,pluginService:q.pluginService,pluginPlatform:q.headlessPluginPlatform})}finally{await q0.release(),await q.asyncDispose()}await EU(),process.exit(0)}let P={threadService:q.threadService,workerDeps:D,createThread:async()=>{let H0=U?await q.serverStatusPromise:W,F0=await N80(J.settings,process.cwd(),bl0(H0),I);if(F0 instanceof Error)G3(F0.message);return bm0(D,{threadMeta:F0?yV(F0):void 0,agentMode:Z.mode,onFirstAssistantMessage:jR4})},validateThreadOwnership:async(H0,F0)=>{if(F0?.nonBlockingOwnershipCheck){RR4(H0,q.configService).catch((J0)=>{if(J0 instanceof c1){if(F0.onOwnershipError){F0.onOwnershipError(J0,H0);return}RC(J0,H0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:J0})});return}try{await RR4(H0,q.configService)}catch(J0){if(J0 instanceof c1)throw J0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:J0})}},switchThreadVisibility:I,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:jR4},_=async(H0)=>{try{if(H0==="dtw")return w43({ampURL:J.ampURL,configService:q.configService,threadService:q.threadService,mcpService:q.mcpService,toolboxService:q.toolboxService,toolService:q.toolService,skillService:q.skillService,fileSystem:q.fileSystem,threadId:Z.threadId});return PH4(P,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(F0){if(F0 instanceof c1)throw F0;throw await RC(F0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")E7.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
7576
- `),await EU(),process.exit(1);let S=(async()=>{if(U){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let H0=await q.configService.getLatest(),F0=Tk(H0),J0=await A6.getUserFreeTierStatus({},{config:q.configService,signal:AbortSignal.timeout(F0)});if(J0.ok)return j.info("User free tier status:",J0),J0.result;return}catch(H0){j.error("Failed to fetch free tier status:",H0);return}})(),m=!J.executeMode?new kf0:null,b,k=null;if(m)b=m,k=(async()=>{let H0=U?await q.serverStatusPromise:q.serverStatus;await ul0(Q,Z,H0);let F0=process.hrtime.bigint(),J0=fl0(O,H0),q0=y6(H0)?xl0({userEmail:H0.user.email,features:H0.features}):!1;ER4({dtwEnabled:J0,hasV2TUIAccess:q0});let i=await _(J0?"dtw":"worker");if(X("runMainThread:createThreadPool",F0),m.attach(i),V){let n=await E1(i.threadHandles$);if(!n)throw new c1("No active thread is available yet.",1);await n.sendMessage({content:[{type:"text",text:V}]})}})(),k.catch(async(H0)=>{let F0=H0 instanceof Error?H0:Error(String(H0));m.setInitError(F0),await RC(H0,Z.threadId)});else G=process.hrtime.bigint(),ER4({dtwEnabled:E,hasV2TUIAccess:N}),b=await _(E?"dtw":"worker"),X("runMainThread:createThreadPool",G);let f=Z.notifications!==void 0?Z.notifications:!J.executeMode;G=process.hrtime.bigint();let p=await q.configService.getLatest();if(X("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),F43({configService:q.configService,threadService:q.threadService,config:p,useNotificationsForService:f,threadViewStates$:()=>b.threadHandles$.pipe(Q4((H0)=>{if(!H0)return v0.of({});return X5(H0.thread$,H0.threadViewState$).pipe(D1(([F0,J0])=>({[F0.id]:J0})))}))}),X("runMainThread:createCliNotificationService",G),J.executeMode){oK4(q.mcpService,J.settings);let H0={userInput:V,stdinInput:K,dependencies:q,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},F0=await xX4({threadPool:b,...H0});if(Z.archive)await A6.archiveThread({thread:F0,archived:!0},{config:q.configService});await q.asyncDispose(),process.exit(0)}let l=!1,x=!1;if(Z.jetbrains||Z.ide){await nj1();let H0=await UN({jetbrainsOnly:Z.jetbrains});if(H0.length===0){if(Z.jetbrains)l=!await q.configService.get("jetbrains.skipInstall")}else if(H0.length===1){let F0=H0[0];if(F0)m8.selectConfig(F0)}else x=!0}G=process.hrtime.bigint();let r=ox0("0.0.1773590611-g8ab646",q.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let c=new lA0(q.threadStorage);X("runMainThread:createThreadFuzzyIndexer",G),G=process.hrtime.bigint();let s=new tx0(q.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",G),V&&J.executeMode){let H0=await E1(b.threadHandles$);if(!H0)throw new c1("No active thread is available yet.",1);await H0.sendMessage({content:[{type:"text",text:V}]})}G=process.hrtime.bigint();let w0=await oz();X("runMainThread:loadSessionState",G),j.info("Loaded session state:",w0);let a={...w0,launchCount:w0.launchCount+1};rz(a);let G0=Z.threadId&&D8(Z.threadId)?Z.threadId:void 0;try{if(G=process.hrtime.bigint(),await uB4({codebaseContextService:q.codebaseContextService,history:new Dx0,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadHistoryService:q.threadHistoryService,threadFuzzyIndexer:c,skillService:q.skillService,configService:q.configService,secretStorage:q.secretStorage,internalAPIClient:A6,threadPool:b,createSystemPromptDeps:async()=>uR4(q),ideClient:m8,mcpService:q.mcpService,toolboxService:q.toolboxService,mcpTrustHandler:s,updateService:r,pluginPlatform:q.pluginPlatform,pluginService:q.pluginService},{initialServerStatus:q.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:q.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:G0,showJetBrainsInstaller:l,showIdePickerHint:x,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:a,freeTierStatusPromise:S,workspace:A??null,features:M,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-15T16:09:16.701Z"},(H0)=>new Fg0({...H0,threadPool:H0.threadPool},(F0)=>new Vc0({...F0,threadState:F0.threadState}))),X("runMainThread:mountApp-returned",G),k)await k}finally{}await q.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function E3(J){if(j.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)E7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7577
- `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Jx1({get:async(z)=>{if(z!==Mu)return;try{let G=await TR4(yl0,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==Mu)return;await CR4(wB.dirname(yl0),{recursive:!0}),await t13(yl0,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:gK()});Fj1(Y);let X=await fV4({...J,workspaceTrust:{current:!0,changes:Dk},getHook:process.env.AMP_URL?(z,G)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let z=await nK4(J.mcpConfig);X=aK4(X,z)}let V=wB.dirname(X.getSettingsFilePath());u24(vC,V);let K=await X.get("url","global");if(!K)K=J7;if(j.info("Resolved Amp URL",{ampURL:K,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!QD(K))j.info("Targeting custom Amp server",{ampURL:K});return X=$j1(X),{executeMode:Z,isTTY:Q,ampURL:K,settings:X,secrets:qz4(await _x0(J,X))}}function E43(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let V=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),K=J[Q+1];if(K&&!K.startsWith("--"))Z[V]=K,Q++}}return Z}async function L43(){j$4();let J=E43(process.argv),Z=process.argv.includes("--headless")||process.argv.some((V)=>V.startsWith("--headless="));bY4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?J43: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)Z1.level=0;if(Q43(j),j.info("Starting Amp CLI.",{version:"0.0.1773590611-g8ab646",buildTimestamp:"2026-03-15T16:09:16.701Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new c1(B8.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await B43().parseAsync(process.argv)}k24().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await L43().catch(RC)});async function M43(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"),p6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7576
+ `),await EU(),process.exit(1);let S=(async()=>{if(U){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let H0=await q.configService.getLatest(),F0=Tk(H0),J0=await A6.getUserFreeTierStatus({},{config:q.configService,signal:AbortSignal.timeout(F0)});if(J0.ok)return j.info("User free tier status:",J0),J0.result;return}catch(H0){j.error("Failed to fetch free tier status:",H0);return}})(),m=!J.executeMode?new kf0:null,b,k=null;if(m)b=m,k=(async()=>{let H0=U?await q.serverStatusPromise:q.serverStatus;await ul0(Q,Z,H0);let F0=process.hrtime.bigint(),J0=fl0(O,H0),q0=y6(H0)?xl0({userEmail:H0.user.email,features:H0.features}):!1;ER4({dtwEnabled:J0,hasV2TUIAccess:q0});let i=await _(J0?"dtw":"worker");if(X("runMainThread:createThreadPool",F0),m.attach(i),V){let n=await E1(i.threadHandles$);if(!n)throw new c1("No active thread is available yet.",1);await n.sendMessage({content:[{type:"text",text:V}]})}})(),k.catch(async(H0)=>{let F0=H0 instanceof Error?H0:Error(String(H0));m.setInitError(F0),await RC(H0,Z.threadId)});else G=process.hrtime.bigint(),ER4({dtwEnabled:E,hasV2TUIAccess:N}),b=await _(E?"dtw":"worker"),X("runMainThread:createThreadPool",G);let f=Z.notifications!==void 0?Z.notifications:!J.executeMode;G=process.hrtime.bigint();let p=await q.configService.getLatest();if(X("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),F43({configService:q.configService,threadService:q.threadService,config:p,useNotificationsForService:f,threadViewStates$:()=>b.threadHandles$.pipe(Q4((H0)=>{if(!H0)return v0.of({});return X5(H0.thread$,H0.threadViewState$).pipe(D1(([F0,J0])=>({[F0.id]:J0})))}))}),X("runMainThread:createCliNotificationService",G),J.executeMode){oK4(q.mcpService,J.settings);let H0={userInput:V,stdinInput:K,dependencies:q,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},F0=await xX4({threadPool:b,...H0});if(Z.archive)await A6.archiveThread({thread:F0,archived:!0},{config:q.configService});await q.asyncDispose(),process.exit(0)}let l=!1,x=!1;if(Z.jetbrains||Z.ide){await nj1();let H0=await UN({jetbrainsOnly:Z.jetbrains});if(H0.length===0){if(Z.jetbrains)l=!await q.configService.get("jetbrains.skipInstall")}else if(H0.length===1){let F0=H0[0];if(F0)m8.selectConfig(F0)}else x=!0}G=process.hrtime.bigint();let r=ox0("0.0.1773604945-g8ab646",q.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let c=new lA0(q.threadStorage);X("runMainThread:createThreadFuzzyIndexer",G),G=process.hrtime.bigint();let s=new tx0(q.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",G),V&&J.executeMode){let H0=await E1(b.threadHandles$);if(!H0)throw new c1("No active thread is available yet.",1);await H0.sendMessage({content:[{type:"text",text:V}]})}G=process.hrtime.bigint();let w0=await oz();X("runMainThread:loadSessionState",G),j.info("Loaded session state:",w0);let a={...w0,launchCount:w0.launchCount+1};rz(a);let G0=Z.threadId&&D8(Z.threadId)?Z.threadId:void 0;try{if(G=process.hrtime.bigint(),await uB4({codebaseContextService:q.codebaseContextService,history:new Dx0,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadHistoryService:q.threadHistoryService,threadFuzzyIndexer:c,skillService:q.skillService,configService:q.configService,secretStorage:q.secretStorage,internalAPIClient:A6,threadPool:b,createSystemPromptDeps:async()=>uR4(q),ideClient:m8,mcpService:q.mcpService,toolboxService:q.toolboxService,mcpTrustHandler:s,updateService:r,pluginPlatform:q.pluginPlatform,pluginService:q.pluginService},{initialServerStatus:q.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:q.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:G0,showJetBrainsInstaller:l,showIdePickerHint:x,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:a,freeTierStatusPromise:S,workspace:A??null,features:M,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-15T20:08:02.843Z"},(H0)=>new Fg0({...H0,threadPool:H0.threadPool},(F0)=>new Vc0({...F0,threadState:F0.threadState}))),X("runMainThread:mountApp-returned",G),k)await k}finally{}await q.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function E3(J){if(j.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)E7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7577
+ `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Jx1({get:async(z)=>{if(z!==Mu)return;try{let G=await TR4(yl0,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==Mu)return;await CR4(wB.dirname(yl0),{recursive:!0}),await t13(yl0,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:gK()});Fj1(Y);let X=await fV4({...J,workspaceTrust:{current:!0,changes:Dk},getHook:process.env.AMP_URL?(z,G)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let z=await nK4(J.mcpConfig);X=aK4(X,z)}let V=wB.dirname(X.getSettingsFilePath());u24(vC,V);let K=await X.get("url","global");if(!K)K=J7;if(j.info("Resolved Amp URL",{ampURL:K,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!QD(K))j.info("Targeting custom Amp server",{ampURL:K});return X=$j1(X),{executeMode:Z,isTTY:Q,ampURL:K,settings:X,secrets:qz4(await _x0(J,X))}}function E43(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let V=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),K=J[Q+1];if(K&&!K.startsWith("--"))Z[V]=K,Q++}}return Z}async function L43(){j$4();let J=E43(process.argv),Z=process.argv.includes("--headless")||process.argv.some((V)=>V.startsWith("--headless="));bY4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?J43: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)Z1.level=0;if(Q43(j),j.info("Starting Amp CLI.",{version:"0.0.1773604945-g8ab646",buildTimestamp:"2026-03-15T20:08:02.843Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new c1(B8.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await B43().parseAsync(process.argv)}k24().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await L43().catch(RC)});async function M43(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"),p6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7578
7578
  `);else if(!QD(J.ampURL))p6.write(`Logging in to ${new URL(J.ampURL).hostname}
7579
7579
  `);let Y=process.env.AMP_API_KEY;if(Y)p6.write(`API key found in environment variable, storing...
7580
7580
  `),await Z.set("apiKey",Y,J.ampURL),p6.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1773590611-g8ab646",
3
+ "version": "0.0.1773604945-g8ab646",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {