@sourcegraph/amp 0.0.1773835286-g08fd18 → 0.0.1773836198-g08fd18
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.
- package/dist/main.js +8 -8
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -6168,11 +6168,11 @@ ${U}`))}},error:(W)=>{if(!D)D=!0,z(Error(`Failed to spawn brew: ${W.message}`))}
|
|
|
6168
6168
|
${U}`;if(X==="pnpm"&&U.includes("Unable to find the global bin directory"))H+=`
|
|
6169
6169
|
|
|
6170
6170
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
6171
|
-
npm install -g @sourcegraph/amp`;z(Error(H))}},error:(W)=>{if(!G)G=!0,z(Error(`Failed to spawn ${X}: ${W.message}`))},complete:()=>{if(!G)G=!0,K()}})})}h0();h0();xP();async function N90(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 F=await z.json(),q=F.version??F["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=Nz4(J,q),D=G<0,W,U;if(F.time){let H=F.time[J],B=F.time[q],N=Date.now();if(H)W=Math.floor((N-new Date(H).getTime())/3600000);if(B)U=Math.floor((N-new Date(B).getTime())/3600000)}return I.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:G,hasUpdate:D,currentVersionAge:W,latestVersionAge:U}),{hasUpdate:D,latestVersion:q,currentVersion:J,currentVersionAge:W,latestVersionAge:U,source:"npm"}}catch(z){return I.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(K)}}var PP5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function w90(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${PP5}?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=Nz4(J,X),K=V<0;return I.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:V,hasUpdate:K}),{hasUpdate:K,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return I.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var CP5=604800000;function Bz4(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>CP5)return{ageMs:Q};return null}function Nz4(J,Z){let Q=(K)=>{let[z,F]=K.split("-");return{parts:z?.split(".").map(Number)||[],label:F}},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,F=X.parts[K]||0;if(z<F)return-1;if(z>F)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function Bf0(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?fU(Q):void 0;return{sha:Y,age:X}}catch{return null}}H1();function Nf0(J,Z,Q={}){let Y=new r1,X=Y.pipe(P6({shouldCountRefs:!1}));return setImmediate(async()=>{let V=new CK().scoped("update"),K=Q.startDelayMs??0;if(K>0)await Qz(K);let z=X.subscribe({next:(F)=>{V.debug("emit new state",F)}});try{let F=process.env.AMP_TEST_UPDATE_STATUS;if(F){V.debug("using fake update status for testing",{status:F}),await Qz(500),Y.next(F);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){V.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let q=await Z.get("updates.mode");if(q==="disabled"){V.debug("checking disabled");return}let G=await B90(),D=G==="binary"||G==="brew";V.debug("checking",{currentVersion:J,mode:q,packageManager:G,isBinaryDistribution:D});let W=D?await w90(J):await N90(J,$L());if(!(W.latestVersion&&W.hasUpdate)){V.debug("no update available");return}let U=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let H=W.currentVersionAge-W.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return V.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!q)q=G==="pnpm"?"warn":"auto",V.debug("no configured update mode; selected default based on package manager",{packageManager:G,mode:q});if(G==="brew"){if(!U())Y.next("update-available-brew");return}if(G==="binary"&&process.execPath!==qf0()){if(V.debug("non-standard binary path, showing warning"),!U())Y.next("update-available-unrecognized-path");return}if(q==="warn"){if(!U())Y.next("update-available");return}if(!G){if(V.debug("auto-update not supported, falling back to warn mode"),!U())Y.next("update-available");return}if(G==="binary"&&process.platform==="win32"){if(V.debug("binary auto-update not supported on Windows, falling back to warn mode"),!U())Y.next("update-available");return}try{await Dm(W.latestVersion,G);let H=await NH(W.latestVersion),B={from:W.currentVersion,to:W.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(F){V.debug("check failed",{error:F})}finally{await Qz(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}xP();import{stderr as sz}from"node:process";function wz4(J){let Z=new XH().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 Vf0(Y.force||!1,Y.verbose||!1,"0.0.
|
|
6171
|
+
npm install -g @sourcegraph/amp`;z(Error(H))}},error:(W)=>{if(!G)G=!0,z(Error(`Failed to spawn ${X}: ${W.message}`))},complete:()=>{if(!G)G=!0,K()}})})}h0();h0();xP();async function N90(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 F=await z.json(),q=F.version??F["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=Nz4(J,q),D=G<0,W,U;if(F.time){let H=F.time[J],B=F.time[q],N=Date.now();if(H)W=Math.floor((N-new Date(H).getTime())/3600000);if(B)U=Math.floor((N-new Date(B).getTime())/3600000)}return I.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:G,hasUpdate:D,currentVersionAge:W,latestVersionAge:U}),{hasUpdate:D,latestVersion:q,currentVersion:J,currentVersionAge:W,latestVersionAge:U,source:"npm"}}catch(z){return I.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(K)}}var PP5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function w90(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${PP5}?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=Nz4(J,X),K=V<0;return I.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:V,hasUpdate:K}),{hasUpdate:K,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return I.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var CP5=604800000;function Bz4(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>CP5)return{ageMs:Q};return null}function Nz4(J,Z){let Q=(K)=>{let[z,F]=K.split("-");return{parts:z?.split(".").map(Number)||[],label:F}},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,F=X.parts[K]||0;if(z<F)return-1;if(z>F)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function Bf0(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?fU(Q):void 0;return{sha:Y,age:X}}catch{return null}}H1();function Nf0(J,Z,Q={}){let Y=new r1,X=Y.pipe(P6({shouldCountRefs:!1}));return setImmediate(async()=>{let V=new CK().scoped("update"),K=Q.startDelayMs??0;if(K>0)await Qz(K);let z=X.subscribe({next:(F)=>{V.debug("emit new state",F)}});try{let F=process.env.AMP_TEST_UPDATE_STATUS;if(F){V.debug("using fake update status for testing",{status:F}),await Qz(500),Y.next(F);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){V.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let q=await Z.get("updates.mode");if(q==="disabled"){V.debug("checking disabled");return}let G=await B90(),D=G==="binary"||G==="brew";V.debug("checking",{currentVersion:J,mode:q,packageManager:G,isBinaryDistribution:D});let W=D?await w90(J):await N90(J,$L());if(!(W.latestVersion&&W.hasUpdate)){V.debug("no update available");return}let U=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let H=W.currentVersionAge-W.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return V.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!q)q=G==="pnpm"?"warn":"auto",V.debug("no configured update mode; selected default based on package manager",{packageManager:G,mode:q});if(G==="brew"){if(!U())Y.next("update-available-brew");return}if(G==="binary"&&process.execPath!==qf0()){if(V.debug("non-standard binary path, showing warning"),!U())Y.next("update-available-unrecognized-path");return}if(q==="warn"){if(!U())Y.next("update-available");return}if(!G){if(V.debug("auto-update not supported, falling back to warn mode"),!U())Y.next("update-available");return}if(G==="binary"&&process.platform==="win32"){if(V.debug("binary auto-update not supported on Windows, falling back to warn mode"),!U())Y.next("update-available");return}try{await Dm(W.latestVersion,G);let H=await NH(W.latestVersion),B={from:W.currentVersion,to:W.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(F){V.debug("check failed",{error:F})}finally{await Qz(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}xP();import{stderr as sz}from"node:process";function wz4(J){let Z=new XH().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 Vf0(Y.force||!1,Y.verbose||!1,"0.0.1773836198-g08fd18"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new XH("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 TP5(Y.targetVersion)});J.addCommand(Q)}async function TP5(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")sz.write(J1.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
6172
6172
|
|
|
6173
6173
|
`));try{if(!J){sz.write(J1.blue(`Checking for updates...
|
|
6174
|
-
`));let{hasUpdate:Y,latestVersion:X}=Kf0()?await w90("0.0.
|
|
6175
|
-
`));let z=await NH("0.0.
|
|
6174
|
+
`));let{hasUpdate:Y,latestVersion:X}=Kf0()?await w90("0.0.1773836198-g08fd18"):await N90("0.0.1773836198-g08fd18",$L());if(!Y){let V=Bf0("0.0.1773836198-g08fd18"),K=V?.age?`released ${V.age} ago`:`built ${fU(new Date("2026-03-18T12:20:59.741Z"))} ago`;sz.write(J1.green(`✓ Amp is already up to date on version ${"0.0.1773836198-g08fd18"} (${K})
|
|
6175
|
+
`));let z=await NH("0.0.1773836198-g08fd18");if(z.warning)sz.write(`
|
|
6176
6176
|
`+J1.yellow(z.warning)+`
|
|
6177
6177
|
`);process.exit(0)}if(!X)sz.write(J1.yellow("[WARN] could not find latest version")),process.exit(0);J=X}sz.write(J1.blue(`Updating to version ${J}...
|
|
6178
6178
|
`)),await Dm(J,void 0,(Y)=>{sz.write(J1.dim(`Running: ${Y}
|
|
@@ -7338,7 +7338,7 @@ Ctrl-X, Y, Z to unlock`;if(W){let f=q.text.replace(/`([^`]+)`/g,"$1")+`
|
|
|
7338
7338
|
`),V=[];for(let K=0;K<X.length;K++){let q=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 G of q)if(G.startsWith("\x00")&&G.endsWith("\x01"))V.push(new C(G.slice(1,-1),new h({color:Y.app.keybind,bold:!0})));else V.push(new C(G,new h({color:Q.colorScheme.foreground})));if(K<X.length-1)V.push(new C(`
|
|
7339
7339
|
`))}return new c0({decoration:{color:Q.colorScheme.background,border:f1.all(new k1(Y.app.keybind,1,"rounded"))},child:new i0({padding:C0.symmetric(0,1),child:new e({text:new C(void 0,void 0,V)})})})}}class Cp0 extends R7{chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=r$0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new Rp0({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 bE4(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?a8:0,F=Y-z;if(F<=0)return null;let q=Z-z;if(q<0||q>=F)return null;let G=Math.max(1,Math.floor(F/V)),D=Math.floor(q/G);return D>=0&&D<V?D:null}case"line":case"sparkline":case"stacked-area":{let z=K?a8:0,F=Y-z;if(F<=0)return null;let q=Math.max(0,Math.min(F-1,Z-z));if(V===1)return 0;let G=F/(V-1),D=Math.round(q/G);return Math.max(0,Math.min(V-1,D))}default:return null}}function pa5(J,Z,Q,Y,X,V,K,z){if(X<=0||Z<0||Z>=X)return null;let F=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let q=V?a8:0,G=Q-q,D=Y-(V?F:0);if(G<=0||D<=0)return null;let W=Math.max(1,Math.floor(G/X)),U=q+Z*W+Math.floor(W/2),H=z>0?K/z:0,B=Math.round((1-H)*(D-1));return{x:U,y:B}}case"line":case"sparkline":case"stacked-area":{let q=V?a8:0,G=Q-q,D=Y-(V?F:0);if(G<=0||D<=0)return null;let W=X>1?q+Math.round(Z/(X-1)*(G-1)):q+Math.floor(G/2),U=z>0?K/z:0,H=Math.round((1-U)*(D-1));return{x:W,y:H}}default:return null}}function da5(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 ca5(J,Z,Q,Y,X){if(Q.length<=1){let z=Y(J.value),F=J.meta?` (${J.meta})`:"";return J.label.length+2+z.length+F.length}let V=J.label.length,K=0;for(let z of Q){let F=z.points[Z];if(!F)continue;K+=F.value;let q=2+z.name.length+2+Y(F.value).length;V=Math.max(V,q)}if(X){let z=9+Y(K).length;V=Math.max(V,z)}return V}function la5(J,Z,Q,Y,X,V,K){let z;try{let H=j1.of(J),B=u0.of(J);z={foreground:H.colorScheme.foreground,background:H.colorScheme.background,border:B.app.keybind}}catch{z={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let F=new h({color:z.foreground,bold:!0}),q=new h({color:z.foreground}),G=new h({color:z.foreground,dim:!0}),D=[],W=new h({color:z.foreground,underline:!0}),U=(H,B)=>new C(B,W,void 0,x90(H),()=>{w8(J,H)});if(Y.length<=1){if(D.push(new C(`${Z.label}: `,F)),Z.link)D.push(U(Z.link,V(Z.value)));else D.push(new C(V(Z.value),q));if(Z.meta)D.push(new C(` (${Z.meta})`,G))}else{let H=K==="stacked-bar"||K==="stacked-area";D.push(new C(`${Z.label}
|
|
7340
7340
|
`,F));let B=0;for(let N=0;N<Y.length;N++){let w=Y[N],E=w.points[Q];if(!E)continue;B+=E.value;let O=w.color??X[N%X.length]??z.foreground;if(D.push(new C("● ",new h({color:O}))),D.push(new C(`${w.name}: `,G)),E.link)D.push(U(E.link,V(E.value)));else D.push(new C(V(E.value),q));if(N<Y.length-1||H)D.push(new C(`
|
|
7341
|
-
`))}if(H)D.push(new C(" ",G)),D.push(new C("Total: ",G)),D.push(new C(V(B),q))}return new c0({decoration:{color:z.background,border:f1.all(new k1(z.border,1,"rounded"))},child:new e({text:new C(void 0,void 0,D)})})}Xw();h0();d9();import{execSync as Oo5}from"node:child_process";qw();_2();E3();T2();Kh();yX();s7();g$();nX();RO();P4();Eu();Ok();H1();var bO4=U4(yq(),1);import{writeFile as kO4}from"fs/promises";import yO4 from"path";h0();s7();class Tp0{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.1773835286-g08fd18"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await vt(Z,this.configService)}catch(Z){I.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class VB extends d0{props;constructor(J){super();this.props=J}createState(){return new hE4}}class hE4 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 gE4 extends p0{controller=new r2;focusNode=new s4({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=u0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,V=this.controller.text.trim().length>0,K=!X||V,z=f1.all(new k1(Q.foreground,1,"solid")),F=new qJ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(U)=>{let H=U.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),q=new q1({children:[new c0({decoration:{color:Q.background},child:new e({text:new C(">",new h({color:Q.foreground}))})}),new _1({child:F})]}),G=new c0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,[new C("Command: ",new h({color:Q.foreground})),new C(this.widget.props.commandName,new h({color:Y.command,bold:!0}))])})}),D=[];if(K)D.push(new C("Enter",new h({color:Y.keybind}))),D.push(new C(" to submit, ",new h({color:Q.foreground,dim:!0})));D.push(new C("Esc",new h({color:Y.keybind}))),D.push(new C(" to cancel",new h({color:Q.foreground,dim:!0})));let W=new c0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,D)})});return new c0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new x0({children:[G,new I0({height:1}),q,new F3,W]})})}}class tp extends d0{props;constructor(J){super();this.props=J}createState(){return new gE4}}import{isDeepStrictEqual as _p0}from"node:util";var ia5=/[\\/_ +.#"@[({&]/,na5=/[\\/_ +.#"@[({&]/g,aa5=/[\s-]/,mE4=/[\s-]/g;function e$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 F=Y.charAt(V),q=Q.indexOf(F,X),G=0,D,W,U,H;while(q>=0){if(D=e$0(J,Z,Q,Y,q+1,V+1,K),D>G){if(q===X)D*=1;else if(aa5.test(J.charAt(q-1))){if(D*=0.9,H=J.slice(X,q-1).match(mE4),H&&X>0)D*=0.999**H.length}else if(ia5.test(J.charAt(q-1))){if(D*=0.8,U=J.slice(X,q-1).match(na5),U&&X>0)D*=0.999**U.length}else if(D*=0.3,X>0)D*=0.999**(q-X);if(J.charAt(q)!==Z.charAt(V))D*=0.9999}if(D<0.1&&(Q.charAt(q-1)===Y.charAt(V+1)||Y.charAt(V+1)===Y.charAt(V)&&Q.charAt(q-1)!==Y.charAt(V))){if(W=e$0(J,Z,Q,Y,q+1,V+2,K),W*0.1>D)D=W*0.1}if(D>G)G=D;q=Q.indexOf(F,q+1)}return K[z]=G,G}function t$0(J){return J.toLowerCase().replace(mE4," ")}function pE4(J,Z){let Q=e$0(J,Z,t$0(J),t$0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,V=0;for(let z of Y){let F=e$0(J,z,t$0(J),t$0(z),0,0,{});if(F===0)return Q;X+=F,V+=z.length}let K=X/Y.length*0.95;return Math.max(Q,K)}return Q}class nT{}class aT{}class $J0{}class JJ0{}class dE4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new cE4}}class cE4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function oa5(J,Z){if(J==="")return{matches:!0,score:1};let Q=pE4(Z,J);return{matches:Q>0.15,score:Q}}class e9 extends d0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new lE4}}class lE4 extends p0{textController;focusNode;scrollController=new Y5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new r2(this.widget.props.controller?.query??""),this.focusNode=new s4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),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)=>_p0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!_p0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>_p0(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 nT){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 aT){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 $J0){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 JJ0)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,...oa5(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;mT(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=u0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=f1.all(new k1(Q.foreground,1,"solid")),V=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,K=this.widget.props.enabled??!0,z=new qJ({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}),F=new S7({shortcuts:new Map([[new X4("ArrowDown"),new nT],[new X4("ArrowUp"),new aT],[new X4("Tab"),new nT],[new X4("Tab",{shift:!0}),new aT],[new X4("n",{ctrl:!0}),new nT],[new X4("p",{ctrl:!0}),new aT],[new X4("Enter"),new $J0],[new X4("Escape"),new JJ0]]),focusNode:this.focusNode,child:z}),q=new y9({actions:new Map([[nT,new t4(this.invoke)],[aT,new t4(this.invoke)],[$J0,new t4(this.invoke)],[JJ0,new t4(this.invoke)]]),child:F}),G=new q1({children:[new c0({decoration:{color:Q.background},child:new e({text:new C(">",new h({color:Q.foreground}))})}),new _1({child:q})]});this.itemContexts=[];let D;if(this.widget.props.isLoading){let N=this.widget.props.loadingText??"Loading...";D=new I0({height:10,child:new n1({child:new e({text:new C(N,new h({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)D=new _1({child:new n1({child:new e({text:new C(this.widget.props.emptyStateText,new h({color:Q.foreground,dim:!0}))})})});else{let N=Y.map((w,E)=>{let O=E===this.selectedIndex,L=this.widget.props.isItemDisabled?.(w)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(w,O,L,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new c0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C(this.widget.props.getLabel(w),new h({color:j,dim:L}))})})}return new dE4(new o1({onClick:(A)=>this.handleItemClick(E,A.clickCount),child:M}),(A)=>{this.itemContexts[E]=A})});D=new x0({children:N,crossAxisAlignment:"start"})}let W=new o1({onScroll:this.handleScroll,opaque:!1,child:new R6({controller:this.scrollController,autofocus:!1,child:D})}),U=[];if(this.widget.props.title){let N=new c0({padding:C0.symmetric(1,0),child:new e({text:new C(this.widget.props.title,new h({color:Z.app.command,bold:!0}))})});U.push(N)}if(!V)U.push(G,new I0({height:1}));if(this.textController.text!==""){let N=Y.length>0?Y[this.selectedIndex]:void 0,w=N&&this.widget.props.buildDisabledReasonWidget?.(N,J);U.push(new _1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new _1({child:W}),new c0({padding:C0.only({top:1}),child:new n1({child:w??new I0({height:1})})})]})}))}else U.push(new _1({child:W}));if(this.widget.props.footer)U.push(this.widget.props.footer);return new c0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:U})})}}function iE4(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 Sp0 extends l1{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)=>iE4(X.pubDate).length));return new e9({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 F=u0.of(z),{colors:q}=F,G=F.app,D=V?G.selectionBackground:void 0,W=V?G.selectionForeground:q.foreground,U=q.mutedForeground,H=(B,N)=>new I0({width:N,child:q1.end([new e({text:new C(B,new h({color:U}))})])});return new c0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[new _1({child:new e({text:new C(X.title,new h({color:W})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),H(iE4(X.pubDate),Q)]})})}})}}P4();class vp0 extends d0{createState(){return new nE4}}class nE4 extends p0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=u0.of(J).colors;return new e({text:new C("●",new h({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}var ra5=/\/threads\/(T-[^/?#\s<>]+)/i;function sa5(J){let Z=J.trim(),Y=Z.match(ra5)?.[1];if(Y&&H8(Y))return Y;let X=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(H8(X))return X;return null}function ta5(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((F)=>F.role==="child"&&Z.has(F.threadID)&&(F.type==="fork"||F.type==="handoff"));if(z){Y.set(K.id,z.type);let F=z.threadID,q=Q.get(F)||[];q.push(K),Q.set(F,q)}else X.push(K)}return j70.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 e({text:new C(`${J}${Z}`,new h({color:Q})),maxLines:1})}function ea5(J,Z,Q,Y){return[kp0("+",J,Y.success),F3.horizontal(1),kp0("~",Z,Y.warning),F3.horizontal(1),kp0("-",Q,Y.destructive)]}function $o5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class ZJ0 extends d0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new aE4}}class aE4 extends p0{spinner=new z3;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((E)=>E.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)V=V.filter((E)=>E.id!==Z.currentThreadID);let K=Z.recentThreadIDs||[],z=new Set(K),F=Z.currentThreadID,q=[...V].sort((E,O)=>{if(F){if(E.id===F)return-1;if(O.id===F)return 1}let L=K.indexOf(E.id),M=K.indexOf(O.id);if(L!==-1&&M!==-1)return L-M;if(L!==-1)return-1;if(M!==-1)return 1;return 0}),G=ta5(q),D=Math.max(0,...G.map((E)=>E.description.timeAgo.length)),W=u0.of(J),U=new i0({padding:C0.symmetric(0,1),child:new n1({child:new e({text:new C("",new h({color:W.colors.foreground,dim:!0}),[new C("Ctrl+T",new h({color:W.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new h({color:W.colors.foreground,dim:!0}))])})})}),H="",B=null,N=(E)=>{if(E!==H)H=E,B=sa5(E);return B};return new e9({items:G,getLabel:(E)=>`${E.title} ${E.id}`,filterItem:(E,O)=>{let L=N(O);if(L)return E.id.toLowerCase()===L.toLowerCase();return!0},normalizeQuery:(E)=>N(E)?"":E,onAccept:async(E,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let L=Z.onSelect(E.id,O);if(!$o5(L))return;this.setSwitchingThread(!0);try{await L}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(E)=>{if(Z.previewController){if(E)Z.previewController.select(E.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:U,renderItem:(E,O,L,M)=>{let A=u0.of(M),{app:j,colors:P}=A,_=O?j.selectionBackground:void 0,S=O?j.selectionForeground:P.foreground,y=P.mutedForeground,g=(s,N0)=>new I0({width:N0,child:q1.end([new e({text:new C(s,new h({color:y}))})])}),b=Z.threadViewStates[E.id],v=[],f=E.relationshipType==="handoff",m=new Mp({connectorColor:P.mutedForeground});if(E.depth>0){let s=[],N0=E.ancestorsAreLast.slice(1);for(let U0 of N0)s.push(new C(m.getAncestorPrefix(U0),new h({color:m.connectorColor,dim:m.connectorDim})));let o=E.isLast?m.elbow:m.tee,G0=m.getConnectorText(o);s.push(new C(G0,new h({color:m.connectorColor,dim:m.connectorDim}))),v.push(new e({text:new C("",void 0,s)}))}let d=[],u=F===E.id?new C("(current) ",new h({color:P.success})):z.has(E.id)?new C("(visited) ",new h({color:P.foreground,dim:!0})):null;if(u)d.push(new e({text:u}));if(oE(b))d.push(new vp0),d.push(new I0({width:1}));let a=E.title;if(E.relationshipType==="fork"){let s=a.match(/^Forked\((\d+)\): /);if(s)a=a.slice(s[0].length);else while(a.startsWith("Forked: "))a=a.slice(8);d.push(new e({text:new C("[fork] ",new h({color:P.primary}))}))}else if(f)d.push(new e({text:new C("[handoff] ",new h({color:P.accent}))}));if(d.push(new _1({child:new e({text:new C(a,new h({color:S})),overflow:"ellipsis",maxLines:1})})),d.push(new I0({width:2})),E.diffStats&&(E.diffStats.added>0||E.diffStats.changed>0||E.diffStats.deleted>0)){let s=O?{success:y,warning:y,destructive:y}:P;d.push(...ea5(E.diffStats.added,E.diffStats.changed,E.diffStats.deleted,s)),d.push(new I0({width:2}))}return d.push(g(E.description.timeAgo,D)),new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[...v,...d]})})}})}}function oE4(J){return 1-(1-J)**3}function rE4(J,Z,Q){return J+(Z-J)*Q}function ep(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=oE4(Y),K=oE4(X);return{x:rE4(J.startOffset.x,J.targetOffset.x,V),y:rE4(J.startOffset.y,J.targetOffset.y,K)}}var Jo5={nodeWidth:3,horizontalSpacing:3};class oT{options;constructor(J={}){this.options={...Jo5,...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,F)=>{let q=Z.get(z.id)??[];if(this.options.comparator)q.sort(this.options.comparator);let G={...z,parentID:Q.get(z.id)};if(q.length===0){Y.push({node:G,position:{x:V,y:F}});let B=V;return V+=this.options.nodeWidth+this.options.horizontalSpacing,B}let D=[];for(let B of q)D.push(K(B,F+1));let W=Math.min(...D),U=Math.max(...D),H=Math.floor((W+U)/2);return Y.push({node:G,position:{x:H,y:F}}),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 Zo5={nodeWidth:3,nodeHeight:2};class rT{options;constructor(J={}){this.options={...Zo5,...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 F=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:V,y:F}),Y}}var Qo5={nodeWidth:3,nodeHeight:2},Yo5={x:0,y:0};class YJ0{options;constructor(J={}){this.options={...Qo5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=Yo5,X,V,K,z){let F=z?u0.of(z):null,q=F?.colors,G=F?.app,D=q?.mutedForeground??q?.foreground;if(J.length===0)return new e({text:new C("No nodes",new h({color:D}))});let W=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,N=[];for(let j=W;j>=0;j--){let P=J.filter((y)=>y.position.y===j);P.sort((y,g)=>y.position.x-g.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new I0({width:y.position.x-S}));let g=y.node.id===Q,b=K?.(y.node.data)??!1,v=V?.activeFlashOn??!1,f=y.node.id===V?.copyFlashNodeId;_.push(this.renderNode(g,b,v,f,G,q)),S=y.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:_})),j>0){let y=J.filter((v)=>v.position.y===j-1),g=P,b=this.renderConnectors(y,g,Z,H,q,G);N.push(...b)}}let w=new x0({crossAxisAlignment:"start",children:N}),E=Math.round(Y.x),O=Math.round(Y.y*B),L=(W+1)*B,M=[new I0({width:H,height:L}),new x6({left:E,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),P=W-A.position.y,_=E+A.position.x+this.options.nodeWidth+1,S=O+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(j,y,q,G)}))}return new c0({padding:C0.horizontal(2),child:new _H(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,V){let K="┌─┐",z="└─┘",F=J?X?.threadGraphNodeSelected??V?.primary??V?.foreground:X?.threadGraphNode??V?.primary??V?.foreground,q=!1;if(Y)F=X?.threadGraphNodeSelected??V?.primary??F,K="┏━┓",z="┗━┛",q=!0;else if(Z&&Q)F=X?.toolSuccess??V?.primary??F,K="┏━┓",z="┗━┛";return new x0({crossAxisAlignment:"start",children:[new e({text:new C(K,new h({color:F,bold:q}))}),new e({text:new C(z,new h({color:F,bold:q}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let 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((W)=>W.length))),K=V+2,z="┌"+"─".repeat(K)+"┐",F="└"+"─".repeat(K)+"┘",q=Q?.border??Y?.threadGraphConnector??Q?.foreground,G=Q?.foreground,D=[new e({text:new C(z,new h({color:q}))})];for(let W of X){let U=" ".repeat(V-W.length);D.push(new e({text:new C("│ ",new h({color:q}),[new C(W+U,new h({color:G??q})),new C(" │",new h({color:q}))])}))}return D.push(new e({text:new C(F,new h({color:q}))})),new x0({crossAxisAlignment:"start",children:D})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),F=V?.threadGraphConnector??X?.primary??X?.foreground,q=Array(Y).fill(" ");for(let W of Z){let U=W.position.x+z;if(U>=0&&U<Y)q[U]="▲"}K.push(new e({text:new C(q.join(""),new h({color:F}))}));let G=Array(Y).fill(" ");for(let W of J){let U=Z.filter((E)=>E.node.parentID===W.node.id);if(U.length===0)continue;let H=W.position.x+z,B=U.map((E)=>E.position.x+z),N=Math.min(...B),w=Math.max(...B);for(let E=N;E<=w;E++)if(E>=0&&E<Y){if(E===H)if(U.length===1&&B[0]===H)G[E]="│";else if(E===N)G[E]="└";else if(E===w)G[E]="┘";else G[E]="┬";else if(B.includes(E))if(E===N)G[E]="└";else if(E===w)G[E]="┘";else G[E]="┴";else if(G[E]===" ")G[E]="─"}}K.push(new e({text:new C(G.join(""),new h({color:F}))}));let D=Array(Y).fill(" ");for(let W of J){if(Z.filter((B)=>B.node.parentID===W.node.id).length===0)continue;let H=W.position.x+z;if(H>=0&&H<Y)D[H]="│"}return K.push(new e({text:new C(D.join(""),new h({color:F}))})),K}}var Xo5={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},Vo5={x:0,y:0};class yp0{options;constructor(J={}){this.options={...Xo5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=Vo5,X,V,K,z){let F=z?u0.of(z):null,q=F?.colors,G=F?.app,D=q?.mutedForeground??q?.foreground;if(J.length===0)return new e({text:new C("No nodes",new h({color:D}))});let W=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,N=[];for(let j=W;j>=0;j--){let P=J.filter((y)=>y.position.y===j);P.sort((y,g)=>y.position.x-g.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new I0({width:y.position.x-S}));let g=y.node.id===Q,b=K?.(y.node.data)??!1,v=V?.activeFlashOn??!1;_.push(this.renderNode(g,b,v,G,q)),S=y.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:_})),j>0){let y=J.filter((v)=>v.position.y===j-1),g=P,b=this.renderConnectors(y,g,Z,H,q,G);N.push(...b)}}let w=new x0({crossAxisAlignment:"start",children:N}),E=Math.round(Y.x),O=Math.round(Y.y*B),L=(W+1)*B,M=[new I0({width:H,height:L}),new x6({left:E,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),P=W-A.position.y,_=E+A.position.x+this.options.nodeWidth+1,S=O+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(j,y,q)}))}return new c0({padding:C0.horizontal(2),child:new _H(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 e({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 e({text:new C(K,new h({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:V})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),F=V?.threadGraphConnector??X?.primary??X?.foreground,q=Array(Y).fill(" ");for(let G of J){let D=Z.filter((N)=>N.node.parentID===G.node.id);if(D.length===0)continue;let W=G.position.x+z,U=D.map((N)=>N.position.x+z),H=Math.min(...U),B=Math.max(...U);for(let N=H;N<=B;N++)if(N>=0&&N<Y){let w=N===W,E=U.includes(N);if(w&&E)if(D.length===1)q[N]="│";else if(N===H)q[N]="└";else if(N===B)q[N]="┘";else q[N]="┼";else if(w)if(N===H)q[N]="└";else if(N===B)q[N]="┘";else q[N]="┬";else if(E)if(N===H)q[N]="└";else if(N===B)q[N]="┘";else q[N]="┴";else if(q[N]===" ")q[N]="─"}}return K.push(new e({text:new C(q.join(""),new h({color:F}))})),K}}class $d extends M3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new sE4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class sE4 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 nL extends d0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new $O4}}var tE4=400,eE4=300,Ko5=16;class $O4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new oT({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new rT;renderer=new yp0;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((F)=>F.id)),Q=new Set(this.widget.props.threads.map((F)=>F.id));if(Z.size!==Q.size||[...Z].some((F)=>!Q.has(F)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,V=this.widget.props.initialSelectedThreadID;if(X!==V&&V){let q=this.widget.props.threads.find((G)=>G.id===V);if(q)this.selectedNodeId=q.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let K=J.props.threads.some((F)=>F.isActive),z=this.widget.props.threads.some((F)=>F.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:tE4,durationY:eE4};let Z=Math.max(tE4,eE4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=ep(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},Ko5)}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,F=Math.floor(this.viewportHeight/2),G=Math.floor(F/2)-K;return{x:V,y:G}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((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 G=(this.selectedNodeId?this.positionedNodes.find((D)=>D.node.id===this.selectedNodeId):null)??this.positionedNodes.find((D)=>!D.node.parentID);if(G){let D=Math.max(...this.positionedNodes.map((W)=>W.position.y));this.currentOffset=this.calculateCenterOffset(G.position.x,G.position.y,D)}}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?(q)=>q.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(q)=>q.isActive??!1,J),F=new $d({onWidth:(q)=>{if(this.viewportWidth!==q)this.viewportWidth=q,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(q)=>{if(this.viewportHeight!==q)this.viewportHeight=q,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new x4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:F})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class ZO4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new QO4}}class QO4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var JO4=30,zo5=30;class sT{}class tT{}class XJ0{}class VJ0{}class xp0 extends d0{props;constructor(J){super();this.props=J}createState(){return new YO4}}class YO4 extends p0{highlightedIndex=0;controller=new r2;focusNode;scrollController=new Y5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new s4({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;mT(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 sT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof tT){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof XJ0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof VJ0)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=u0.of(J),{colors:Y,app:X}=Q,z=t1.of(J).size.width>=zo5+JO4,F=f1.all(new k1(Y.foreground,1,"solid")),q=this.filteredClusters[this.highlightedIndex]??null,G=new c0({padding:C0.symmetric(1,0),child:new e({text:new C("Select a cluster",new h({color:X.command,bold:!0}))})}),D=new qJ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new S7({shortcuts:new Map([[new X4("ArrowDown"),new sT],[new X4("ArrowUp"),new tT],[new X4("Tab"),new sT],[new X4("Tab",{shift:!0}),new tT],[new X4("n",{ctrl:!0}),new sT],[new X4("p",{ctrl:!0}),new tT],[new X4("Enter"),new XJ0],[new X4("Escape"),new VJ0]]),focusNode:this.focusNode,child:D}),U=new y9({actions:new Map([[sT,new t4(this.invoke)],[tT,new t4(this.invoke)],[XJ0,new t4(this.invoke)],[VJ0,new t4(this.invoke)]]),child:W}),H=new q1({children:[new c0({decoration:{color:Y.background},child:new e({text:new C(">",new h({color:Y.foreground}))})}),new _1({child:U})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,P=Z?M.threads.some((g)=>g.id===Z):!1,_=j?X.selectionBackground:void 0,S=j?X.selectionForeground:Y.foreground,y=[new C(M.label,new h({color:S})),new C(` (${M.threads.length})`,new h({color:S,dim:!0}))];if(P)y.push(new C(" (current)",new h({color:j?X.selectionForeground:Y.success})));return new ZO4(new o1({onClick:(g)=>this.handleItemClick(A,g.clickCount),child:new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C("",void 0,y)})})}),(g)=>{this.itemContexts[A]=g})}),N=new x0({children:B,crossAxisAlignment:"start"}),w=new _1({child:new o1({onScroll:this.handleScroll,child:new R6({controller:this.scrollController,autofocus:!1,child:N})})}),E=q?q.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],O=q?new c0({padding:C0.all(1),child:new nL({threads:E,autofocus:!1,offsetY:2})}):null,L;if(z){let M=O?new _1({child:O}):new I0({width:JO4});L=new q1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,M]})}else{let M=[new _1({child:new o1({onScroll:this.handleScroll,child:new R6({controller:this.scrollController,autofocus:!1,child:N})})})];if(O)M.push(new _1({child:O}));L=new x0({crossAxisAlignment:"stretch",children:M})}return new c0({decoration:{border:F,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[G,H,new I0({height:1}),new _1({child:L})]})})}}class N${static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!N$._instance)N$._instance=new N$;return N$._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 XO4 extends p0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){I.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){I.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((V)=>V.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=u0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),V=X.length>0?this.getValidationError(X):null,K=this.getAvailableLabels(),F=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...K];return new e9({title:"Add Label",items:F,getLabel:(q)=>{if("__isCreateMarker"in q)return this.currentQuery.trim().toLowerCase();return q.name},onAccept:(q)=>{if("__isCreateMarker"in q)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(q.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:V||"Type to create a new label",renderItem:(q,G,D,W)=>{let U=G?Q.selectionBackground:void 0,H=G?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in q&&q.__isCreateMarker){let N=this.currentQuery.trim().toLowerCase();return new c0({decoration:U?{color:U}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C("",void 0,[new C("Create new label: ",new h({color:H})),new C(N,new h({color:H,bold:!0}))])})})}return new c0({decoration:U?{color:U}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C(q.name,new h({color:H}))})})},filterItem:(q,G)=>{if(this.currentQuery!==G)this.currentQuery=G,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in q&&q.__isCreateMarker)return this.shouldShowCreateMarker(G);let W=G.trim().toLowerCase();return W.length===0||q.name.includes(W)},sortItems:(q,G,D)=>{let W="__isCreateMarker"in q.item&&q.item.__isCreateMarker,U="__isCreateMarker"in G.item&&G.item.__isCreateMarker;if(W&&!U)return-1;if(!W&&U)return 1;return G.score-q.score}})}}class up0 extends d0{props;constructor(J){super();this.props=J}createState(){return new XO4}}class lV extends d0{props;constructor(J){super();this.props=J}createState(){return new VO4}}class VO4 extends p0{_spinner=new z3;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Z=u0.of(J),{colors:Q,app:Y}=Z,X=f1.all(new k1(Q.foreground,1,"solid")),V=this._spinner.toBraille(),K=new e({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}))])}),F=[new _1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[K]})})];if(this.widget.props.onAbort)F.push(new I0({height:2,child:new c0({padding:C0.symmetric(2,0),child:new e({text:new C("",new h({dim:!0}),[new C("Press ",new h({color:Q.foreground})),new C("Esc",new h({color:Q.info})),new C(" to cancel",new h({color:Q.foreground}))])})})}));let q=new c0({decoration:new y4(Q.background,X),child:new I0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:F})})});if(this.widget.props.onAbort)return new x4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:q});return q}}var Jd={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"}},KJ0=["workspace","global","flag","default","external","skill","other"];function Fo5(J){return Array.from(new Set(J))}function KO4(J){return Fo5([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function eT(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 KO4(J).length>0?"skill":"other"}function fp0(J){return eT(J)==="skill"}function zO4(J){let Z=KO4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=eT(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${Jd[Y].description}: ${Q}`}function FO4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}var qO4=process.platform==="win32"?" ":"█",GO4=process.platform==="win32"?"░":"█";class y8 extends d0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=qO4,thumbChar:V=GO4,showTrack:K=!0,thumbColor:z,trackColor:F}){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=F}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),F=Math.max(0,Math.min(1,V.scrollOffset/(Z-Q))),q=X-z,G=Math.max(0,q*F),D=G+z;return J>=G&&J<=D}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),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),F=Math.max(1,V*z),q=V-F;if(q<=0)return;let G=Z-Q,D=q/G,W=K/D,U=Math.max(0,Math.min(G,this._dragStartOffset+W));this.widget.controller.jumpTo(U)};_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),F=Math.max(1,K*z),q=Q-Y,G=K-F,D=Math.max(0,Math.min(1,X/(Q-Y))),W=Math.max(0,G*D),U=W+F;if(Z>=W&&Z<=U)return;if(Z<W)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(q,X+Y))};build(J){return new o1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?O5.POINTER:O5.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 sC{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=qO4,thumbChar:V=GO4,showTrack:K=!0,thumbColor:z,trackColor:F}){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=F}createRenderObject(){return new UO4(this)}updateRenderObject(J){J.updateWidget(this)}}class UO4 extends A4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;b4(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:V}=this._calculateScrollbarMetrics();if(!V)return;let K=this._widget.trackColor,z=this._widget.thumbColor,F=process.platform==="win32",q=Y,G=Y+X;if(!F){let D=["▁","▂","▃","▄","▅","▆","▇","█"];for(let W=0;W<this.size.height;W++){let U="█",H=!0;if(W===Math.floor(q)){let B=1-(q-W),N=Math.floor(B*8);U=D[N]||"█",H=!1}else if(W===Math.floor(G)){let B=1-(G-W),N=Math.floor(B*8);U=D[N]||"█"}else if(W>q&&W<G)H=!1;J.setChar(Z,Q+W,U,{fg:z,bg:K,reverse:H},1)}return}for(let D=0;D<this.size.height;D++){let W=D+0.5,U=W>=q&&W<G,H=U?this._widget.thumbChar:this._widget.trackChar;J.setChar(Z,Q+D,H,{fg:U?z:K,bg:K,reverse:!1},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),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 aL extends d0{props;constructor(J){super();this.props=J}createState(){return new HO4}}class HO4 extends p0{scrollController=new Y5;scrollAreaKey=new l2("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(J){return J instanceof y7}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=u0.of(J),Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let G=u$0(Q);return{title:G.title,type:G.type,description:G.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,V=f1.all(new k1(Z.colors.border,1,"solid")),K=new c0({padding:C0.symmetric(1,0),child:new e({text:new C(Y.title,new h({color:X,bold:!0}))})}),z=this.isWidgetMessage(Q)?Q.widget:new e({text:new C(Y.description,new h({color:Z.colors.foreground})),selectable:!0}),F=new _1({child:new v7({child:new c0({padding:C0.symmetric(1,0),child:new q1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new _1({child:new R6({controller:this.scrollController,autofocus:!0,child:z})}),new y8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let G=this.scrollController.maxScrollExtent,D=this.scrollController.offset,W=this.getViewportHeight(),U=G+W;return{totalContentHeight:Math.max(U,0),viewportHeight:Math.max(W,1),scrollOffset:Math.max(D,0)}}})]})})})}),q=new c0({padding:C0.symmetric(1,0),child:new e({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new h({color:Z.colors.foreground,dim:!0})),new C("R",new h({color:Z.app.keybind})),new C(" to retry, ",new h({color:Z.colors.foreground,dim:!0})),new C("Esc",new h({color:Z.app.keybind})),new C(" to cancel",new h({color:Z.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new C("",new h({color:Z.colors.foreground,dim:!0}));if(G==="help"){let D=new h({color:Z.app.keybind}),W=new h({color:Z.colors.foreground,dim:!0});return new C("",W,[new C("Press ",W),new C("Escape",D),new C(" to close • Use ",W),new C("↑↓",D),new C(" or ",W),new C("j/k",D),new C(" to scroll",W)])}return new C("Press any key to close",new h({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new x4({onKey:(G)=>{if(this.widget.props.onRetry&&G.key==="r")return this.widget.props.onRetry(),"handled";if(G.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new c0({decoration:{border:V,color:Z.colors.background},padding:C0.all(1),child:new x0({mainAxisAlignment:"center",children:[K,new I0({height:1}),F,q]})})})}}d9();class BO4 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=i8.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=u0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new e({text:new C("No plugins found.",new h({dim:!0}))});let Y=[],X=this.plugins.length,V=this.plugins.filter((F)=>F.status==="active").length,K=this.plugins.reduce((F,q)=>F+q.registeredCommands.length,0),z=this.plugins.reduce((F,q)=>F+q.registeredTools.length,0);if(Y.push(new C(`${V}/${X} ${S4(X,"plugin")} active`,new h({bold:!0}))),K>0||z>0)Y.push(new C(` (${K} ${S4(K,"command")}, ${z} ${S4(z,"tool")})`,new h({dim:!0})));Y.push(new C(`
|
|
7341
|
+
`))}if(H)D.push(new C(" ",G)),D.push(new C("Total: ",G)),D.push(new C(V(B),q))}return new c0({decoration:{color:z.background,border:f1.all(new k1(z.border,1,"rounded"))},child:new e({text:new C(void 0,void 0,D)})})}Xw();h0();d9();import{execSync as Oo5}from"node:child_process";qw();_2();E3();T2();Kh();yX();s7();g$();nX();RO();P4();Eu();Ok();H1();var bO4=U4(yq(),1);import{writeFile as kO4}from"fs/promises";import yO4 from"path";h0();s7();class Tp0{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.1773836198-g08fd18"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await vt(Z,this.configService)}catch(Z){I.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class VB extends d0{props;constructor(J){super();this.props=J}createState(){return new hE4}}class hE4 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 gE4 extends p0{controller=new r2;focusNode=new s4({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=u0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,V=this.controller.text.trim().length>0,K=!X||V,z=f1.all(new k1(Q.foreground,1,"solid")),F=new qJ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(U)=>{let H=U.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),q=new q1({children:[new c0({decoration:{color:Q.background},child:new e({text:new C(">",new h({color:Q.foreground}))})}),new _1({child:F})]}),G=new c0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,[new C("Command: ",new h({color:Q.foreground})),new C(this.widget.props.commandName,new h({color:Y.command,bold:!0}))])})}),D=[];if(K)D.push(new C("Enter",new h({color:Y.keybind}))),D.push(new C(" to submit, ",new h({color:Q.foreground,dim:!0})));D.push(new C("Esc",new h({color:Y.keybind}))),D.push(new C(" to cancel",new h({color:Q.foreground,dim:!0})));let W=new c0({padding:C0.symmetric(1,0),child:new e({text:new C("",void 0,D)})});return new c0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new x0({children:[G,new I0({height:1}),q,new F3,W]})})}}class tp extends d0{props;constructor(J){super();this.props=J}createState(){return new gE4}}import{isDeepStrictEqual as _p0}from"node:util";var ia5=/[\\/_ +.#"@[({&]/,na5=/[\\/_ +.#"@[({&]/g,aa5=/[\s-]/,mE4=/[\s-]/g;function e$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 F=Y.charAt(V),q=Q.indexOf(F,X),G=0,D,W,U,H;while(q>=0){if(D=e$0(J,Z,Q,Y,q+1,V+1,K),D>G){if(q===X)D*=1;else if(aa5.test(J.charAt(q-1))){if(D*=0.9,H=J.slice(X,q-1).match(mE4),H&&X>0)D*=0.999**H.length}else if(ia5.test(J.charAt(q-1))){if(D*=0.8,U=J.slice(X,q-1).match(na5),U&&X>0)D*=0.999**U.length}else if(D*=0.3,X>0)D*=0.999**(q-X);if(J.charAt(q)!==Z.charAt(V))D*=0.9999}if(D<0.1&&(Q.charAt(q-1)===Y.charAt(V+1)||Y.charAt(V+1)===Y.charAt(V)&&Q.charAt(q-1)!==Y.charAt(V))){if(W=e$0(J,Z,Q,Y,q+1,V+2,K),W*0.1>D)D=W*0.1}if(D>G)G=D;q=Q.indexOf(F,q+1)}return K[z]=G,G}function t$0(J){return J.toLowerCase().replace(mE4," ")}function pE4(J,Z){let Q=e$0(J,Z,t$0(J),t$0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,V=0;for(let z of Y){let F=e$0(J,z,t$0(J),t$0(z),0,0,{});if(F===0)return Q;X+=F,V+=z.length}let K=X/Y.length*0.95;return Math.max(Q,K)}return Q}class nT{}class aT{}class $J0{}class JJ0{}class dE4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new cE4}}class cE4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function oa5(J,Z){if(J==="")return{matches:!0,score:1};let Q=pE4(Z,J);return{matches:Q>0.15,score:Q}}class e9 extends d0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new lE4}}class lE4 extends p0{textController;focusNode;scrollController=new Y5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new r2(this.widget.props.controller?.query??""),this.focusNode=new s4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),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)=>_p0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!_p0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>_p0(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 nT){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 aT){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 $J0){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 JJ0)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,...oa5(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;mT(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=u0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=f1.all(new k1(Q.foreground,1,"solid")),V=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,K=this.widget.props.enabled??!0,z=new qJ({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}),F=new S7({shortcuts:new Map([[new X4("ArrowDown"),new nT],[new X4("ArrowUp"),new aT],[new X4("Tab"),new nT],[new X4("Tab",{shift:!0}),new aT],[new X4("n",{ctrl:!0}),new nT],[new X4("p",{ctrl:!0}),new aT],[new X4("Enter"),new $J0],[new X4("Escape"),new JJ0]]),focusNode:this.focusNode,child:z}),q=new y9({actions:new Map([[nT,new t4(this.invoke)],[aT,new t4(this.invoke)],[$J0,new t4(this.invoke)],[JJ0,new t4(this.invoke)]]),child:F}),G=new q1({children:[new c0({decoration:{color:Q.background},child:new e({text:new C(">",new h({color:Q.foreground}))})}),new _1({child:q})]});this.itemContexts=[];let D;if(this.widget.props.isLoading){let N=this.widget.props.loadingText??"Loading...";D=new I0({height:10,child:new n1({child:new e({text:new C(N,new h({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)D=new _1({child:new n1({child:new e({text:new C(this.widget.props.emptyStateText,new h({color:Q.foreground,dim:!0}))})})});else{let N=Y.map((w,E)=>{let O=E===this.selectedIndex,L=this.widget.props.isItemDisabled?.(w)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(w,O,L,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new c0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C(this.widget.props.getLabel(w),new h({color:j,dim:L}))})})}return new dE4(new o1({onClick:(A)=>this.handleItemClick(E,A.clickCount),child:M}),(A)=>{this.itemContexts[E]=A})});D=new x0({children:N,crossAxisAlignment:"start"})}let W=new o1({onScroll:this.handleScroll,opaque:!1,child:new R6({controller:this.scrollController,autofocus:!1,child:D})}),U=[];if(this.widget.props.title){let N=new c0({padding:C0.symmetric(1,0),child:new e({text:new C(this.widget.props.title,new h({color:Z.app.command,bold:!0}))})});U.push(N)}if(!V)U.push(G,new I0({height:1}));if(this.textController.text!==""){let N=Y.length>0?Y[this.selectedIndex]:void 0,w=N&&this.widget.props.buildDisabledReasonWidget?.(N,J);U.push(new _1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new _1({child:W}),new c0({padding:C0.only({top:1}),child:new n1({child:w??new I0({height:1})})})]})}))}else U.push(new _1({child:W}));if(this.widget.props.footer)U.push(this.widget.props.footer);return new c0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:U})})}}function iE4(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 Sp0 extends l1{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)=>iE4(X.pubDate).length));return new e9({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 F=u0.of(z),{colors:q}=F,G=F.app,D=V?G.selectionBackground:void 0,W=V?G.selectionForeground:q.foreground,U=q.mutedForeground,H=(B,N)=>new I0({width:N,child:q1.end([new e({text:new C(B,new h({color:U}))})])});return new c0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[new _1({child:new e({text:new C(X.title,new h({color:W})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),H(iE4(X.pubDate),Q)]})})}})}}P4();class vp0 extends d0{createState(){return new nE4}}class nE4 extends p0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=u0.of(J).colors;return new e({text:new C("●",new h({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}var ra5=/\/threads\/(T-[^/?#\s<>]+)/i;function sa5(J){let Z=J.trim(),Y=Z.match(ra5)?.[1];if(Y&&H8(Y))return Y;let X=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(H8(X))return X;return null}function ta5(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((F)=>F.role==="child"&&Z.has(F.threadID)&&(F.type==="fork"||F.type==="handoff"));if(z){Y.set(K.id,z.type);let F=z.threadID,q=Q.get(F)||[];q.push(K),Q.set(F,q)}else X.push(K)}return j70.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 e({text:new C(`${J}${Z}`,new h({color:Q})),maxLines:1})}function ea5(J,Z,Q,Y){return[kp0("+",J,Y.success),F3.horizontal(1),kp0("~",Z,Y.warning),F3.horizontal(1),kp0("-",Q,Y.destructive)]}function $o5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class ZJ0 extends d0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new aE4}}class aE4 extends p0{spinner=new z3;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((E)=>E.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)V=V.filter((E)=>E.id!==Z.currentThreadID);let K=Z.recentThreadIDs||[],z=new Set(K),F=Z.currentThreadID,q=[...V].sort((E,O)=>{if(F){if(E.id===F)return-1;if(O.id===F)return 1}let L=K.indexOf(E.id),M=K.indexOf(O.id);if(L!==-1&&M!==-1)return L-M;if(L!==-1)return-1;if(M!==-1)return 1;return 0}),G=ta5(q),D=Math.max(0,...G.map((E)=>E.description.timeAgo.length)),W=u0.of(J),U=new i0({padding:C0.symmetric(0,1),child:new n1({child:new e({text:new C("",new h({color:W.colors.foreground,dim:!0}),[new C("Ctrl+T",new h({color:W.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new h({color:W.colors.foreground,dim:!0}))])})})}),H="",B=null,N=(E)=>{if(E!==H)H=E,B=sa5(E);return B};return new e9({items:G,getLabel:(E)=>`${E.title} ${E.id}`,filterItem:(E,O)=>{let L=N(O);if(L)return E.id.toLowerCase()===L.toLowerCase();return!0},normalizeQuery:(E)=>N(E)?"":E,onAccept:async(E,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let L=Z.onSelect(E.id,O);if(!$o5(L))return;this.setSwitchingThread(!0);try{await L}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(E)=>{if(Z.previewController){if(E)Z.previewController.select(E.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:U,renderItem:(E,O,L,M)=>{let A=u0.of(M),{app:j,colors:P}=A,_=O?j.selectionBackground:void 0,S=O?j.selectionForeground:P.foreground,y=P.mutedForeground,g=(s,N0)=>new I0({width:N0,child:q1.end([new e({text:new C(s,new h({color:y}))})])}),b=Z.threadViewStates[E.id],v=[],f=E.relationshipType==="handoff",m=new Mp({connectorColor:P.mutedForeground});if(E.depth>0){let s=[],N0=E.ancestorsAreLast.slice(1);for(let U0 of N0)s.push(new C(m.getAncestorPrefix(U0),new h({color:m.connectorColor,dim:m.connectorDim})));let o=E.isLast?m.elbow:m.tee,G0=m.getConnectorText(o);s.push(new C(G0,new h({color:m.connectorColor,dim:m.connectorDim}))),v.push(new e({text:new C("",void 0,s)}))}let d=[],u=F===E.id?new C("(current) ",new h({color:P.success})):z.has(E.id)?new C("(visited) ",new h({color:P.foreground,dim:!0})):null;if(u)d.push(new e({text:u}));if(oE(b))d.push(new vp0),d.push(new I0({width:1}));let a=E.title;if(E.relationshipType==="fork"){let s=a.match(/^Forked\((\d+)\): /);if(s)a=a.slice(s[0].length);else while(a.startsWith("Forked: "))a=a.slice(8);d.push(new e({text:new C("[fork] ",new h({color:P.primary}))}))}else if(f)d.push(new e({text:new C("[handoff] ",new h({color:P.accent}))}));if(d.push(new _1({child:new e({text:new C(a,new h({color:S})),overflow:"ellipsis",maxLines:1})})),d.push(new I0({width:2})),E.diffStats&&(E.diffStats.added>0||E.diffStats.changed>0||E.diffStats.deleted>0)){let s=O?{success:y,warning:y,destructive:y}:P;d.push(...ea5(E.diffStats.added,E.diffStats.changed,E.diffStats.deleted,s)),d.push(new I0({width:2}))}return d.push(g(E.description.timeAgo,D)),new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[...v,...d]})})}})}}function oE4(J){return 1-(1-J)**3}function rE4(J,Z,Q){return J+(Z-J)*Q}function ep(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=oE4(Y),K=oE4(X);return{x:rE4(J.startOffset.x,J.targetOffset.x,V),y:rE4(J.startOffset.y,J.targetOffset.y,K)}}var Jo5={nodeWidth:3,horizontalSpacing:3};class oT{options;constructor(J={}){this.options={...Jo5,...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,F)=>{let q=Z.get(z.id)??[];if(this.options.comparator)q.sort(this.options.comparator);let G={...z,parentID:Q.get(z.id)};if(q.length===0){Y.push({node:G,position:{x:V,y:F}});let B=V;return V+=this.options.nodeWidth+this.options.horizontalSpacing,B}let D=[];for(let B of q)D.push(K(B,F+1));let W=Math.min(...D),U=Math.max(...D),H=Math.floor((W+U)/2);return Y.push({node:G,position:{x:H,y:F}}),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 Zo5={nodeWidth:3,nodeHeight:2};class rT{options;constructor(J={}){this.options={...Zo5,...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 F=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:V,y:F}),Y}}var Qo5={nodeWidth:3,nodeHeight:2},Yo5={x:0,y:0};class YJ0{options;constructor(J={}){this.options={...Qo5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=Yo5,X,V,K,z){let F=z?u0.of(z):null,q=F?.colors,G=F?.app,D=q?.mutedForeground??q?.foreground;if(J.length===0)return new e({text:new C("No nodes",new h({color:D}))});let W=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,N=[];for(let j=W;j>=0;j--){let P=J.filter((y)=>y.position.y===j);P.sort((y,g)=>y.position.x-g.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new I0({width:y.position.x-S}));let g=y.node.id===Q,b=K?.(y.node.data)??!1,v=V?.activeFlashOn??!1,f=y.node.id===V?.copyFlashNodeId;_.push(this.renderNode(g,b,v,f,G,q)),S=y.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:_})),j>0){let y=J.filter((v)=>v.position.y===j-1),g=P,b=this.renderConnectors(y,g,Z,H,q,G);N.push(...b)}}let w=new x0({crossAxisAlignment:"start",children:N}),E=Math.round(Y.x),O=Math.round(Y.y*B),L=(W+1)*B,M=[new I0({width:H,height:L}),new x6({left:E,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),P=W-A.position.y,_=E+A.position.x+this.options.nodeWidth+1,S=O+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(j,y,q,G)}))}return new c0({padding:C0.horizontal(2),child:new _H(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,V){let K="┌─┐",z="└─┘",F=J?X?.threadGraphNodeSelected??V?.primary??V?.foreground:X?.threadGraphNode??V?.primary??V?.foreground,q=!1;if(Y)F=X?.threadGraphNodeSelected??V?.primary??F,K="┏━┓",z="┗━┛",q=!0;else if(Z&&Q)F=X?.toolSuccess??V?.primary??F,K="┏━┓",z="┗━┛";return new x0({crossAxisAlignment:"start",children:[new e({text:new C(K,new h({color:F,bold:q}))}),new e({text:new C(z,new h({color:F,bold:q}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let 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((W)=>W.length))),K=V+2,z="┌"+"─".repeat(K)+"┐",F="└"+"─".repeat(K)+"┘",q=Q?.border??Y?.threadGraphConnector??Q?.foreground,G=Q?.foreground,D=[new e({text:new C(z,new h({color:q}))})];for(let W of X){let U=" ".repeat(V-W.length);D.push(new e({text:new C("│ ",new h({color:q}),[new C(W+U,new h({color:G??q})),new C(" │",new h({color:q}))])}))}return D.push(new e({text:new C(F,new h({color:q}))})),new x0({crossAxisAlignment:"start",children:D})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),F=V?.threadGraphConnector??X?.primary??X?.foreground,q=Array(Y).fill(" ");for(let W of Z){let U=W.position.x+z;if(U>=0&&U<Y)q[U]="▲"}K.push(new e({text:new C(q.join(""),new h({color:F}))}));let G=Array(Y).fill(" ");for(let W of J){let U=Z.filter((E)=>E.node.parentID===W.node.id);if(U.length===0)continue;let H=W.position.x+z,B=U.map((E)=>E.position.x+z),N=Math.min(...B),w=Math.max(...B);for(let E=N;E<=w;E++)if(E>=0&&E<Y){if(E===H)if(U.length===1&&B[0]===H)G[E]="│";else if(E===N)G[E]="└";else if(E===w)G[E]="┘";else G[E]="┬";else if(B.includes(E))if(E===N)G[E]="└";else if(E===w)G[E]="┘";else G[E]="┴";else if(G[E]===" ")G[E]="─"}}K.push(new e({text:new C(G.join(""),new h({color:F}))}));let D=Array(Y).fill(" ");for(let W of J){if(Z.filter((B)=>B.node.parentID===W.node.id).length===0)continue;let H=W.position.x+z;if(H>=0&&H<Y)D[H]="│"}return K.push(new e({text:new C(D.join(""),new h({color:F}))})),K}}var Xo5={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},Vo5={x:0,y:0};class yp0{options;constructor(J={}){this.options={...Xo5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=Vo5,X,V,K,z){let F=z?u0.of(z):null,q=F?.colors,G=F?.app,D=q?.mutedForeground??q?.foreground;if(J.length===0)return new e({text:new C("No nodes",new h({color:D}))});let W=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,N=[];for(let j=W;j>=0;j--){let P=J.filter((y)=>y.position.y===j);P.sort((y,g)=>y.position.x-g.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new I0({width:y.position.x-S}));let g=y.node.id===Q,b=K?.(y.node.data)??!1,v=V?.activeFlashOn??!1;_.push(this.renderNode(g,b,v,G,q)),S=y.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:_})),j>0){let y=J.filter((v)=>v.position.y===j-1),g=P,b=this.renderConnectors(y,g,Z,H,q,G);N.push(...b)}}let w=new x0({crossAxisAlignment:"start",children:N}),E=Math.round(Y.x),O=Math.round(Y.y*B),L=(W+1)*B,M=[new I0({width:H,height:L}),new x6({left:E,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),P=W-A.position.y,_=E+A.position.x+this.options.nodeWidth+1,S=O+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(j,y,q)}))}return new c0({padding:C0.horizontal(2),child:new _H(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 e({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 e({text:new C(K,new h({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:V})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),F=V?.threadGraphConnector??X?.primary??X?.foreground,q=Array(Y).fill(" ");for(let G of J){let D=Z.filter((N)=>N.node.parentID===G.node.id);if(D.length===0)continue;let W=G.position.x+z,U=D.map((N)=>N.position.x+z),H=Math.min(...U),B=Math.max(...U);for(let N=H;N<=B;N++)if(N>=0&&N<Y){let w=N===W,E=U.includes(N);if(w&&E)if(D.length===1)q[N]="│";else if(N===H)q[N]="└";else if(N===B)q[N]="┘";else q[N]="┼";else if(w)if(N===H)q[N]="└";else if(N===B)q[N]="┘";else q[N]="┬";else if(E)if(N===H)q[N]="└";else if(N===B)q[N]="┘";else q[N]="┴";else if(q[N]===" ")q[N]="─"}}return K.push(new e({text:new C(q.join(""),new h({color:F}))})),K}}class $d extends M3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new sE4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class sE4 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 nL extends d0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new $O4}}var tE4=400,eE4=300,Ko5=16;class $O4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new oT({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new rT;renderer=new yp0;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((F)=>F.id)),Q=new Set(this.widget.props.threads.map((F)=>F.id));if(Z.size!==Q.size||[...Z].some((F)=>!Q.has(F)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,V=this.widget.props.initialSelectedThreadID;if(X!==V&&V){let q=this.widget.props.threads.find((G)=>G.id===V);if(q)this.selectedNodeId=q.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let K=J.props.threads.some((F)=>F.isActive),z=this.widget.props.threads.some((F)=>F.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:tE4,durationY:eE4};let Z=Math.max(tE4,eE4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=ep(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},Ko5)}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,F=Math.floor(this.viewportHeight/2),G=Math.floor(F/2)-K;return{x:V,y:G}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((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 G=(this.selectedNodeId?this.positionedNodes.find((D)=>D.node.id===this.selectedNodeId):null)??this.positionedNodes.find((D)=>!D.node.parentID);if(G){let D=Math.max(...this.positionedNodes.map((W)=>W.position.y));this.currentOffset=this.calculateCenterOffset(G.position.x,G.position.y,D)}}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?(q)=>q.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(q)=>q.isActive??!1,J),F=new $d({onWidth:(q)=>{if(this.viewportWidth!==q)this.viewportWidth=q,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(q)=>{if(this.viewportHeight!==q)this.viewportHeight=q,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new x4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:F})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class ZO4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new QO4}}class QO4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var JO4=30,zo5=30;class sT{}class tT{}class XJ0{}class VJ0{}class xp0 extends d0{props;constructor(J){super();this.props=J}createState(){return new YO4}}class YO4 extends p0{highlightedIndex=0;controller=new r2;focusNode;scrollController=new Y5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new s4({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;mT(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 sT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof tT){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof XJ0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof VJ0)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=u0.of(J),{colors:Y,app:X}=Q,z=t1.of(J).size.width>=zo5+JO4,F=f1.all(new k1(Y.foreground,1,"solid")),q=this.filteredClusters[this.highlightedIndex]??null,G=new c0({padding:C0.symmetric(1,0),child:new e({text:new C("Select a cluster",new h({color:X.command,bold:!0}))})}),D=new qJ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new S7({shortcuts:new Map([[new X4("ArrowDown"),new sT],[new X4("ArrowUp"),new tT],[new X4("Tab"),new sT],[new X4("Tab",{shift:!0}),new tT],[new X4("n",{ctrl:!0}),new sT],[new X4("p",{ctrl:!0}),new tT],[new X4("Enter"),new XJ0],[new X4("Escape"),new VJ0]]),focusNode:this.focusNode,child:D}),U=new y9({actions:new Map([[sT,new t4(this.invoke)],[tT,new t4(this.invoke)],[XJ0,new t4(this.invoke)],[VJ0,new t4(this.invoke)]]),child:W}),H=new q1({children:[new c0({decoration:{color:Y.background},child:new e({text:new C(">",new h({color:Y.foreground}))})}),new _1({child:U})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,P=Z?M.threads.some((g)=>g.id===Z):!1,_=j?X.selectionBackground:void 0,S=j?X.selectionForeground:Y.foreground,y=[new C(M.label,new h({color:S})),new C(` (${M.threads.length})`,new h({color:S,dim:!0}))];if(P)y.push(new C(" (current)",new h({color:j?X.selectionForeground:Y.success})));return new ZO4(new o1({onClick:(g)=>this.handleItemClick(A,g.clickCount),child:new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C("",void 0,y)})})}),(g)=>{this.itemContexts[A]=g})}),N=new x0({children:B,crossAxisAlignment:"start"}),w=new _1({child:new o1({onScroll:this.handleScroll,child:new R6({controller:this.scrollController,autofocus:!1,child:N})})}),E=q?q.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],O=q?new c0({padding:C0.all(1),child:new nL({threads:E,autofocus:!1,offsetY:2})}):null,L;if(z){let M=O?new _1({child:O}):new I0({width:JO4});L=new q1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,M]})}else{let M=[new _1({child:new o1({onScroll:this.handleScroll,child:new R6({controller:this.scrollController,autofocus:!1,child:N})})})];if(O)M.push(new _1({child:O}));L=new x0({crossAxisAlignment:"stretch",children:M})}return new c0({decoration:{border:F,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[G,H,new I0({height:1}),new _1({child:L})]})})}}class N${static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!N$._instance)N$._instance=new N$;return N$._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 XO4 extends p0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){I.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){I.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((V)=>V.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=u0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),V=X.length>0?this.getValidationError(X):null,K=this.getAvailableLabels(),F=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...K];return new e9({title:"Add Label",items:F,getLabel:(q)=>{if("__isCreateMarker"in q)return this.currentQuery.trim().toLowerCase();return q.name},onAccept:(q)=>{if("__isCreateMarker"in q)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(q.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:V||"Type to create a new label",renderItem:(q,G,D,W)=>{let U=G?Q.selectionBackground:void 0,H=G?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in q&&q.__isCreateMarker){let N=this.currentQuery.trim().toLowerCase();return new c0({decoration:U?{color:U}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C("",void 0,[new C("Create new label: ",new h({color:H})),new C(N,new h({color:H,bold:!0}))])})})}return new c0({decoration:U?{color:U}:void 0,padding:C0.symmetric(2,0),child:new e({text:new C(q.name,new h({color:H}))})})},filterItem:(q,G)=>{if(this.currentQuery!==G)this.currentQuery=G,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in q&&q.__isCreateMarker)return this.shouldShowCreateMarker(G);let W=G.trim().toLowerCase();return W.length===0||q.name.includes(W)},sortItems:(q,G,D)=>{let W="__isCreateMarker"in q.item&&q.item.__isCreateMarker,U="__isCreateMarker"in G.item&&G.item.__isCreateMarker;if(W&&!U)return-1;if(!W&&U)return 1;return G.score-q.score}})}}class up0 extends d0{props;constructor(J){super();this.props=J}createState(){return new XO4}}class lV extends d0{props;constructor(J){super();this.props=J}createState(){return new VO4}}class VO4 extends p0{_spinner=new z3;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Z=u0.of(J),{colors:Q,app:Y}=Z,X=f1.all(new k1(Q.foreground,1,"solid")),V=this._spinner.toBraille(),K=new e({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}))])}),F=[new _1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[K]})})];if(this.widget.props.onAbort)F.push(new I0({height:2,child:new c0({padding:C0.symmetric(2,0),child:new e({text:new C("",new h({dim:!0}),[new C("Press ",new h({color:Q.foreground})),new C("Esc",new h({color:Q.info})),new C(" to cancel",new h({color:Q.foreground}))])})})}));let q=new c0({decoration:new y4(Q.background,X),child:new I0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:F})})});if(this.widget.props.onAbort)return new x4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:q});return q}}var Jd={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"}},KJ0=["workspace","global","flag","default","external","skill","other"];function Fo5(J){return Array.from(new Set(J))}function KO4(J){return Fo5([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function eT(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 KO4(J).length>0?"skill":"other"}function fp0(J){return eT(J)==="skill"}function zO4(J){let Z=KO4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=eT(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${Jd[Y].description}: ${Q}`}function FO4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}var qO4=process.platform==="win32"?" ":"█",GO4=process.platform==="win32"?"░":"█";class y8 extends d0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=qO4,thumbChar:V=GO4,showTrack:K=!0,thumbColor:z,trackColor:F}){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=F}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),F=Math.max(0,Math.min(1,V.scrollOffset/(Z-Q))),q=X-z,G=Math.max(0,q*F),D=G+z;return J>=G&&J<=D}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),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),F=Math.max(1,V*z),q=V-F;if(q<=0)return;let G=Z-Q,D=q/G,W=K/D,U=Math.max(0,Math.min(G,this._dragStartOffset+W));this.widget.controller.jumpTo(U)};_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),F=Math.max(1,K*z),q=Q-Y,G=K-F,D=Math.max(0,Math.min(1,X/(Q-Y))),W=Math.max(0,G*D),U=W+F;if(Z>=W&&Z<=U)return;if(Z<W)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(q,X+Y))};build(J){return new o1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?O5.POINTER:O5.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 sC{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=qO4,thumbChar:V=GO4,showTrack:K=!0,thumbColor:z,trackColor:F}){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=F}createRenderObject(){return new UO4(this)}updateRenderObject(J){J.updateWidget(this)}}class UO4 extends A4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;b4(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:V}=this._calculateScrollbarMetrics();if(!V)return;let K=this._widget.trackColor,z=this._widget.thumbColor,F=process.platform==="win32",q=Y,G=Y+X;if(!F){let D=["▁","▂","▃","▄","▅","▆","▇","█"];for(let W=0;W<this.size.height;W++){let U="█",H=!0;if(W===Math.floor(q)){let B=1-(q-W),N=Math.floor(B*8);U=D[N]||"█",H=!1}else if(W===Math.floor(G)){let B=1-(G-W),N=Math.floor(B*8);U=D[N]||"█"}else if(W>q&&W<G)H=!1;J.setChar(Z,Q+W,U,{fg:z,bg:K,reverse:H},1)}return}for(let D=0;D<this.size.height;D++){let W=D+0.5,U=W>=q&&W<G,H=U?this._widget.thumbChar:this._widget.trackChar;J.setChar(Z,Q+D,H,{fg:U?z:K,bg:K,reverse:!1},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),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 aL extends d0{props;constructor(J){super();this.props=J}createState(){return new HO4}}class HO4 extends p0{scrollController=new Y5;scrollAreaKey=new l2("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(J){return J instanceof y7}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=u0.of(J),Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let G=u$0(Q);return{title:G.title,type:G.type,description:G.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,V=f1.all(new k1(Z.colors.border,1,"solid")),K=new c0({padding:C0.symmetric(1,0),child:new e({text:new C(Y.title,new h({color:X,bold:!0}))})}),z=this.isWidgetMessage(Q)?Q.widget:new e({text:new C(Y.description,new h({color:Z.colors.foreground})),selectable:!0}),F=new _1({child:new v7({child:new c0({padding:C0.symmetric(1,0),child:new q1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new _1({child:new R6({controller:this.scrollController,autofocus:!0,child:z})}),new y8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let G=this.scrollController.maxScrollExtent,D=this.scrollController.offset,W=this.getViewportHeight(),U=G+W;return{totalContentHeight:Math.max(U,0),viewportHeight:Math.max(W,1),scrollOffset:Math.max(D,0)}}})]})})})}),q=new c0({padding:C0.symmetric(1,0),child:new e({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new h({color:Z.colors.foreground,dim:!0})),new C("R",new h({color:Z.app.keybind})),new C(" to retry, ",new h({color:Z.colors.foreground,dim:!0})),new C("Esc",new h({color:Z.app.keybind})),new C(" to cancel",new h({color:Z.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new C("",new h({color:Z.colors.foreground,dim:!0}));if(G==="help"){let D=new h({color:Z.app.keybind}),W=new h({color:Z.colors.foreground,dim:!0});return new C("",W,[new C("Press ",W),new C("Escape",D),new C(" to close • Use ",W),new C("↑↓",D),new C(" or ",W),new C("j/k",D),new C(" to scroll",W)])}return new C("Press any key to close",new h({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new x4({onKey:(G)=>{if(this.widget.props.onRetry&&G.key==="r")return this.widget.props.onRetry(),"handled";if(G.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new c0({decoration:{border:V,color:Z.colors.background},padding:C0.all(1),child:new x0({mainAxisAlignment:"center",children:[K,new I0({height:1}),F,q]})})})}}d9();class BO4 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=i8.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=u0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new e({text:new C("No plugins found.",new h({dim:!0}))});let Y=[],X=this.plugins.length,V=this.plugins.filter((F)=>F.status==="active").length,K=this.plugins.reduce((F,q)=>F+q.registeredCommands.length,0),z=this.plugins.reduce((F,q)=>F+q.registeredTools.length,0);if(Y.push(new C(`${V}/${X} ${S4(X,"plugin")} active`,new h({bold:!0}))),K>0||z>0)Y.push(new C(` (${K} ${S4(K,"command")}, ${z} ${S4(z,"tool")})`,new h({dim:!0})));Y.push(new C(`
|
|
7342
7342
|
|
|
7343
7343
|
`));for(let F of this.plugins){let{icon:q,color:G}=this.statusIcon(F.status),D=this.getRelativePath(F.uri.toString());if(Y.push(new C(`${q} `,new h({color:G}))),Y.push(new C(D,new h({bold:!0}))),Y.push(new C(` ${F.status}`,new h({dim:!0}))),Y.push(new C(`
|
|
7344
7344
|
`)),F.status==="active"&&F.registeredEvents.length>0)Y.push(new C(" Events: ",new h({dim:!0}))),Y.push(new C(F.registeredEvents.join(", "),new h({color:Q.link}))),Y.push(new C(`
|
|
@@ -7555,7 +7555,7 @@ ${J0.content||""}`:J0.content||"",Y1=[],D1=J0.baseDir.startsWith("file://")?dJ0(
|
|
|
7555
7555
|
`),process.exit(1)}process.stdout.write(await pe5(F.result.displayText)+`
|
|
7556
7556
|
`),process.exit(0)})}xP();import{stdout as de5}from"node:process";function ce5({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,V=X&&!Number.isNaN(X.getTime())?`, ${fU(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${V})`}function eA4(J){de5.write(`${ce5(J)}
|
|
7557
7557
|
`)}function $j4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{eA4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{eA4(Z),process.exit(0)})}var G53=RB.join(k$,"logs","headless.log"),zi0=RB.join(mC,"device-id.json");async function D53(){for(let J of Dw)try{if((await J.listConfigs()).length>0)return J}catch(Z){I.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => U4(R_(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){j2.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
7558
|
-
`)}function W53(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 J2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")y$("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")y$("experimental.agentMode",Z.mode)}function vP4(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 U53(J){try{return await _P4(J,"utf-8")}catch{return J}}async function qi0(J,Z,Q){let Y=vP4(J,Z);if(!Y)return;let X=j6(Q)?Q.features:[],V=j6(Q)?Q.user.email:void 0;if(!Hi0(X,S2.HARNESS_SYSTEM_PROMPT)&&!kP4(V))throw new T1("You are not allowed to do this.",1);y$("systemPrompt",await U53(Y))}function kP4(J){return!!(J&&go(J))}function Hi0(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function Gi0(J){return(J.userEmail?kZ(J.userEmail):!1)||Hi0(J.features,S2.DTW_TUI)}function MP4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new T1("This TUI mode is not enabled for your user;",1)}function Di0(J,Z){if(typeof J==="boolean")return J;if(!j6(Z))return!1;return Gi0({userEmail:Z.user.email,features:Z.features})}function Wi0(J){if(!j6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function H53(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 kZ0(J){let Y=H53(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new T1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function Fi0(J){if(!p6.write(J))await K53(p6,"drain")}var AP4=[{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??lY,description:`Custom settings file path (overrides the default location ${lY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(I).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${lO})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:t9(),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:fK.SMART.key,description:`Set the agent mode (${xX().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:xX().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}],jP4=(J)=>("deprecated"in J)&&J.deprecated===!0,B53=(J)=>("hidden"in J)&&J.hidden===!0,N53=(J)=>("default"in J),w53=(J)=>("default"in J)?J.default:void 0,yP4=[{name:"toggle-skills-count",entryPoint:Pf0}];function E53(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 T1(V3.unknownCommand(Q),1,K)}}async function Bi0(J){return{...J,getThreadEnvironment:JJ,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new $V(J.fileSystem),generateThreadTitle:G10,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>iJ(J.configService),pluginService:J.pluginService}}function xP4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:JJ,filesystem:J.fileSystem,threadService:J.threadService}}var yZ0=K1.file(SP4.homedir()),Ui0=process.env.XDG_CONFIG_HOME?K1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(yZ0,".config");function O53(J){return L$4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){O$4(Z);let Q=d90(),Y=af0();if((!Q||Y||AF4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(kG("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(kG("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(d90()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function L53(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>v0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function D9(J,Z,Q){let Y=Q?.deferAuth??!1;Cj1("0.0.
|
|
7558
|
+
`)}function W53(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 J2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")y$("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")y$("experimental.agentMode",Z.mode)}function vP4(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 U53(J){try{return await _P4(J,"utf-8")}catch{return J}}async function qi0(J,Z,Q){let Y=vP4(J,Z);if(!Y)return;let X=j6(Q)?Q.features:[],V=j6(Q)?Q.user.email:void 0;if(!Hi0(X,S2.HARNESS_SYSTEM_PROMPT)&&!kP4(V))throw new T1("You are not allowed to do this.",1);y$("systemPrompt",await U53(Y))}function kP4(J){return!!(J&&go(J))}function Hi0(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function Gi0(J){return(J.userEmail?kZ(J.userEmail):!1)||Hi0(J.features,S2.DTW_TUI)}function MP4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new T1("This TUI mode is not enabled for your user;",1)}function Di0(J,Z){if(typeof J==="boolean")return J;if(!j6(Z))return!1;return Gi0({userEmail:Z.user.email,features:Z.features})}function Wi0(J){if(!j6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function H53(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 kZ0(J){let Y=H53(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new T1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function Fi0(J){if(!p6.write(J))await K53(p6,"drain")}var AP4=[{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??lY,description:`Custom settings file path (overrides the default location ${lY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(I).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${lO})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:t9(),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:fK.SMART.key,description:`Set the agent mode (${xX().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:xX().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}],jP4=(J)=>("deprecated"in J)&&J.deprecated===!0,B53=(J)=>("hidden"in J)&&J.hidden===!0,N53=(J)=>("default"in J),w53=(J)=>("default"in J)?J.default:void 0,yP4=[{name:"toggle-skills-count",entryPoint:Pf0}];function E53(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 T1(V3.unknownCommand(Q),1,K)}}async function Bi0(J){return{...J,getThreadEnvironment:JJ,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new $V(J.fileSystem),generateThreadTitle:G10,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>iJ(J.configService),pluginService:J.pluginService}}function xP4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:JJ,filesystem:J.fileSystem,threadService:J.threadService}}var yZ0=K1.file(SP4.homedir()),Ui0=process.env.XDG_CONFIG_HOME?K1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(yZ0,".config");function O53(J){return L$4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){O$4(Z);let Q=d90(),Y=af0();if((!Q||Y||AF4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(kG("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(kG("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(d90()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function L53(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>v0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function D9(J,Z,Q){let Y=Q?.deferAuth??!1;Cj1("0.0.1773836198-g08fd18");let X=$r({storage:J.settings,secretStorage:J.secrets,workspaceRoot:v0.of(K1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:yZ0,userConfigDir:Ui0});wF4(X);let V=await X.getLatest();I.debug("Global configuration initialized",{settingsKeys:Object.keys(V.settings)});let K=!1;{let N0=await J.secrets.get("apiKey",J.ampURL);if(K=Boolean(N0),I.info("API key lookup before login",{found:Boolean(N0),ampURL:J.ampURL,deferAuth:Y}),!N0)if(Y)I.info("No API key found, continuing startup with deferred auth");else{p6.write(`No API key found. Starting login flow...
|
|
7559
7559
|
`);let o=await M53(J),G0=await J.secrets.get("apiKey",J.ampURL);if(I.info("Login flow completed",{success:o,storedKeyPresent:Boolean(G0),ampURL:J.ampURL}),!o)await CG(),process.exit(1);K=!0}}{let N0=await X.getLatest(),o=N0.settings.url,G0=N0.secrets.isSet?.[o];I.info("Config secrets state after login",{configURL:o,apiKeySet:G0?.apiKey??!1})}let z=O1(iJ(X).pipe(q5((N0)=>N0!=="pending"))),F=Y?"pending":await z;if(!Y)I.info("Server status resolved",{status:"ready",isAuthenticated:j6(F),isError:Cq(F),errorMessage:Cq(F)?F.error.message:void 0});let{toolService:q,dispose:G}=H$4({configService:X}),D=new Map,W=()=>D.clear(),U=new BM0(X,J.settings.getWorkspaceRootPath()),H=ug1({configService:X,filesystem:r6}),B=ju1({configService:X,trustStore:U,skillMCPServers:H.skillMCPServers,createOAuthProvider:async(N0,o,G0)=>{let U0=`${N0}:${o}`,F0=D.get(U0);if(F0)return I.debug("Reusing existing OAuth provider for server",{serverName:N0,serverUrl:o}),F0;I.debug("Creating OAuth provider for server",{serverName:N0,serverUrl:o});let Z0=(async()=>{let D0=new uw(J.secrets),i=await D0.getClientInfo(N0,o),n=G0?.scopes??i?.scopes,t=QK4();I.info("OAuth headless mode check",{useHeadless:t,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:p6.isTTY});let $0;if(t)$0=J.executeMode?ZK4():JK4(N0);let J0=new AL0({storage:D0,serverName:N0,serverUrl:o,clientId:G0?.clientId??i?.clientId,clientSecret:G0?.clientSecret??i?.clientSecret,authUrl:G0?.authUrl??i?.authUrl,tokenUrl:G0?.tokenUrl??i?.tokenUrl,scopes:n,headlessAuthHandler:$0});return I.debug("OAuth provider created",{serverName:N0,serverUrl:o,hasManualClientId:!!(G0?.clientId??i?.clientId),willUseDCR:!(G0?.clientId??i?.clientId),scopes:n,headlessMode:t,executeMode:J.executeMode}),J0})();return D.set(U0,Z0),Z0}}),N=Ek0({configService:X,filesystem:r6,spawn:H30}),w;if(J.executeMode){let N0=await E94({toolService:q,providers:[B,N],initialTimeout:15000});w=N0.registrations;for(let[o,G0]of N0.initErrors)I.warn(`${o} provider initialization slow or failed:`,G0)}else w=Ok0({toolService:q,providers:[B,N]});if(Z.jetbrains)zw("JetBrains");else if(Z.ide&&hK4())zw("VS Code");else if(Z.ide&&gK4())zw("Neovim");else if(Z.ide){let N0=await D53();if(N0){let o=Fr(N0.ideName);if(o)zw(o)}}if(J.executeMode)Tj1(!0);let E,O=g8.status.pipe(W1((N0)=>Boolean(N0.connected&&N0.authenticated&&N0.ideName&&WI1(N0.ideName))),M4()).subscribe((N0)=>{if(N0){if(!E)E=q.registerTool(w94)}else E?.dispose(),E=void 0}),L;if(!J.executeMode){let N0=await J.settings.get("fuzzy.alwaysIncludePaths")??[];L=new r80(process.cwd(),{alwaysIncludePaths:N0},!0)}else L=new class extends r80{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let M=await pg1({isDevelopment:!1}),A=new NI0(M,X),j=new Fj0(M,{lazy:!0,maxThreads:200});I.info("Starting Amp background services");let P=Z.takeMeBack?!1:void 0,_=Di0(P,F),S=Boolean(_||Z.headless);if(S)I.info("DTW mode enabled: thread sync service disabled");let y=S?L53():Wp1({threadService:A,threadHistoryService:j,configService:X,isExtensionDevelopment:!1}),g;g8.status.subscribe((N0)=>{g=N0});let b=new fB0({workspaceRoots:[K1.file(process.cwd())],fileSystem:Z.jetbrains||Z.ide?rt:r6,getCurrentFile:()=>{if(!g?.openFile)return;try{return K1.parse(g.openFile)}catch(N0){I.warn("Failed to parse current file URI",{uri:g.openFile,error:N0});return}},getOpenFiles:()=>{if(!g?.visibleFiles?.length)return[];let N0=g.openFile;return g.visibleFiles.filter((o)=>o!==N0).map((o)=>{try{return K1.parse(o)}catch(G0){return I.warn("Failed to parse visible file URI",{uri:o,error:G0}),null}}).filter((o)=>o!==null)}}),v=new sf0,f=process.env.PLUGINS??"off",m=Z.headless?YF4():void 0,d=m??new I90({configService:X}),u=d instanceof I90?d:void 0;if(u)u.pluginExecutorKind=_?"local":"unknown";let a=yM0({configService:X,fileSystem:Z.jetbrains||Z.ide?rt:r6,platform:d,internalPlugins:yP4,pluginFilter:f}),l=If1({pluginService:a,toolService:q}),s={codebaseContextService:b,configService:X,toolService:q,mcpService:B,skillService:H,toolboxService:N,trustStore:U,threadService:A,threadHistoryService:j,threadSyncService:y,threadStorage:M,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:L,fileSystem:Z.jetbrains||Z.ide?rt:r6,terminal:v,pluginService:a,pluginPlatform:u,headlessPluginPlatform:m,serverStatus:F,serverStatusPromise:z,hasAPIKeyAtStartup:K};return{...s,async asyncDispose(){if(s.mcpService.hasAuthenticatingClients())I.info("Waiting for OAuth authentication to complete before exit..."),await s.mcpService.waitForAuthentication();for(let N0 of w.values())N0.dispose();await s.mcpService.dispose(),W(),await s.threadService.asyncDispose(),s.configService.unsubscribe(),G(),s.fuzzyServer.dispose(),s.threadSyncService.dispose(),s.settingsStorage[Symbol.dispose](),O.unsubscribe(),E?.dispose(),l.dispose(),await s.pluginService.dispose()}}}async function M53(J){if(!J.executeMode){if(!await M90("Would you like to log in to Amp? [(y)es, (n)o]: "))return p6.write(`Login cancelled. Run the command again to retry.
|
|
7560
7560
|
`),!1}return await uP4(J)}async function uP4(J){let Z=V53(32).toString("hex"),Q=await dC(J.ampURL,Z),Y=new AbortController;try{await kX(Q,Y.signal)}catch(V){I.error("Error opening browser",{error:V})}let X=await dC(J.ampURL,Z,!1);p6.write(`If your browser does not open automatically, visit:
|
|
7561
7561
|
|
|
@@ -7563,7 +7563,7 @@ ${J1.blue.bold(X)}
|
|
|
7563
7563
|
|
|
7564
7564
|
`);try{return await fz4(J.ampURL,Z,J.secrets,Y),p6.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(V){return I.error("Login failed",{error:V}),j2.write(`
|
|
7565
7565
|
Login failed: ${V instanceof Error?V.message:String(V)}
|
|
7566
|
-
`),!1}}function IP4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function A53(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new T1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!H8(Y.threadId))throw new T1("Create response did not include a valid thread ID",1);return Y.threadId}function j53(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function I53(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new T1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!j53(Q))throw new T1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function R53(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 P53(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new T1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function C53(){let J=new XH().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)nO(),process.exit(0);let B=H.originalError??H;zV4(B)}),$j4(J,{version:"0.0.
|
|
7566
|
+
`),!1}}function IP4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function A53(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new T1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!H8(Y.threadId))throw new T1("Create response did not include a valid thread ID",1);return Y.threadId}function j53(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function I53(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new T1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!j53(Q))throw new T1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function R53(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 P53(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new T1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function C53(){let J=new XH().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)nO(),process.exit(0);let B=H.originalError??H;zV4(B)}),$j4(J,{version:"0.0.1773836198-g08fd18",buildTimestamp:"2026-03-18T12:20:59.741Z",buildType:"'release'"}),J.addHelpText("after",uK4()),J.configureHelp({formatHelp:fK4}),J.command("logout").description("Log out by removing stored API key").action(async(H,B)=>{let N=B.optsWithGlobals(),w=await D3(N);await x53(w)}),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 N=B.optsWithGlobals(),w=await D3(N);await y53(w,await tu0(N,w.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,N)=>{let w=N.optsWithGlobals(),E=await D3(w);await yV4(H??"get",E.ampURL,E.secrets),process.exit(process.exitCode??0)}),J.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(H,B)=>{let N=B.optsWithGlobals(),w=await D3(N);await xV4(w.ampURL,w.secrets),process.exit(process.exitCode??0)}),J.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
|
|
7567
7567
|
Actions:
|
|
7568
7568
|
create Create a new DTW thread and print its ID
|
|
7569
7569
|
add-message <message> Send a user message and wait for message_added
|
|
@@ -7631,8 +7631,8 @@ ${L}
|
|
|
7631
7631
|
|
|
7632
7632
|
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 T53(J){I.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new Sm({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:JJ,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new $V(J.fileSystem),ampURL:J.ampURL});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw I.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function _53(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await aC()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await aC()).trimEnd(),stdinInput:null}}function S53(J,Z,Q){if(J.remote&&!Z)throw new T1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new T1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new T1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new T1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new T1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new T1("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(J.streamJsonInput&&typeof J.execute==="string"&&J.execute.trim()!=="")throw new T1("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"}]}}' | amp --execute --stream-json --stream-json-input`);if(Z&&Q===""&&!J.streamJsonInput&&!J.headless)throw new T1("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
|
|
7633
7633
|
Or pipe via stdin: echo "your message" | amp --execute`)}async function xZ0(J,Z,Q){let Y=process.hrtime.bigint(),X=(U0,F0)=>{let Z0=Number(process.hrtime.bigint()-F0)/1e6,D0=qJ4();I.info("Startup phase",{phase:U0,phaseMs:Math.round(Z0),sinceMainMs:D0===null?void 0:Math.round(D0)})},{userInput:V,stdinInput:K}=await _53(Z),z=!!Z.streamJson||!!Z.streamJsonThinking;S53({...Z,streamJson:z},J.executeMode,V),J2(Q,Z);let F=process.hrtime.bigint(),q=Boolean(await J.secrets.get("apiKey",J.ampURL)),G=!J.executeMode&&!Z.headless&&q;I.info("Interactive auth startup mode",{deferInteractiveAuth:G,hasAPIKeyAtStartup:q,executeMode:J.executeMode,headless:Boolean(Z.headless)});let D=await D9(J,Z,{deferAuth:G});X("runMainThread:createThreadDependencies",F),F=process.hrtime.bigint();let W=await Bi0(D);X("runMainThread:createWorkerDeps",F);let{serverStatus:U}=D;if(!G&&Cq(U)){let U0=yC(Error(U.error.message));if(U0.message===V3.networkOffline||U0.message===V3.networkTimeout)throw kZ0(J.ampURL);throw new T1(V3.invalidAPIKey,1)}let H=j6(U)?U:null,B=H?.user.email,N=kP4(B),w=Gi0({userEmail:B,features:H?.features}),E=Z.takeMeBack?!1:void 0,O=H!==null&&Di0(E,H);if(!G)await qi0(Q,Z,U);let L=Wi0(U),M=L?.features??[],A=L?.team??null,j=A90(Z,L);if(j instanceof Error)W3(j.message);if((J.executeMode||z)&&m3(Z.mode)&&!N)throw new T1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(H&&!FW(Z.mode,B))throw new T1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await KF4(V,K,D.configService),await D.asyncDispose(),process.exit(0);if(Z.headless){if(!B||!kZ(B))throw new T1("Headless DTW mode is only available for Amp employees",1);let U0=await D.secretStorage.get("apiKey",J.ampURL);if(!U0)throw new T1("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&&!H8(F0))throw new T1(`Invalid thread ID: ${F0}`,1);let Z0=F0??await d53({dependencies:D,visibility:j??void 0}),D0=await KK4(Z0);if(D0.status==="already-running")await D.asyncDispose(),await CG(),process.exit(0);try{await $K4({ampURL:J.ampURL,apiKey:U0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:Z0,initialToolDiscovery:Promise.all([D.mcpService.initialized,D.toolboxService.initialized]).then(()=>{return}),configService:D.configService,mcpService:D.mcpService,toolService:D.toolService,skillService:D.skillService,fileSystem:D.fileSystem,pluginService:D.pluginService,pluginPlatform:D.headlessPluginPlatform})}finally{await D0.release(),await D.asyncDispose()}await CG(),process.exit(0)}let P={threadService:D.threadService,workerDeps:W,createThread:async()=>{let U0=G?await D.serverStatusPromise:U,F0=await x80(J.settings,process.cwd(),Wi0(U0),j);if(F0 instanceof Error)W3(F0.message);return Gm0(W,{threadMeta:F0?yV(F0):void 0,agentMode:Z.mode,onFirstAssistantMessage:RP4})},validateThreadOwnership:async(U0,F0)=>{if(F0?.nonBlockingOwnershipCheck){PP4(U0,D.configService).catch((Z0)=>{if(Z0 instanceof T1){if(F0.onOwnershipError){F0.onOwnershipError(Z0,U0);return}xC(Z0,U0);return}I.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Z0})});return}try{await PP4(U0,D.configService)}catch(Z0){if(Z0 instanceof T1)throw Z0;I.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Z0})}},switchThreadVisibility:j,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:RP4},_=async(U0)=>{try{if(U0==="dtw")return T53({ampURL:J.ampURL,configService:D.configService,threadService:D.threadService,mcpService:D.mcpService,toolboxService:D.toolboxService,toolService:D.toolService,skillService:D.skillService,fileSystem:D.fileSystem,threadId:Z.threadId});return jB4(P,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(F0){if(F0 instanceof T1)throw F0;throw await xC(F0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")j2.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
7634
|
-
`),await CG(),process.exit(1);let S=(async()=>{if(G){I.info("Skipping initial free tier status fetch until auth is complete");return}try{let U0=await D.configService.getLatest(),F0=gk(U0),Z0=await A6.getUserFreeTierStatus({},{config:D.configService,signal:AbortSignal.timeout(F0)});if(Z0.ok)return I.info("User free tier status:",Z0),Z0.result;return}catch(U0){I.error("Failed to fetch free tier status:",U0);return}})(),g=!J.executeMode?new Kb0:null,b,v=null;if(g)b=g,v=(async()=>{let U0=G?await D.serverStatusPromise:D.serverStatus;await qi0(Q,Z,U0);let F0=process.hrtime.bigint(),Z0=Di0(E,U0),D0=j6(U0)?Gi0({userEmail:U0.user.email,features:U0.features}):!1;MP4({dtwEnabled:Z0,hasV2TUIAccess:D0});let i=await _(Z0?"dtw":"worker");if(X("runMainThread:createThreadPool",F0),g.attach(i),V){let n=await O1(i.threadHandles$);if(!n)throw new T1("No active thread is available yet.",1);await n.sendMessage({content:[{type:"text",text:V}]})}})(),v.catch(async(U0)=>{let F0=U0 instanceof Error?U0:Error(String(U0));g.setInitError(F0),await xC(U0,Z.threadId)});else F=process.hrtime.bigint(),MP4({dtwEnabled:O,hasV2TUIAccess:w}),b=await _(O?"dtw":"worker"),X("runMainThread:createThreadPool",F);let f=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let m=await D.configService.getLatest();if(X("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),O53({configService:D.configService,threadService:D.threadService,config:m,useNotificationsForService:f,threadViewStates$:()=>b.threadHandles$.pipe(Q4((U0)=>{if(!U0)return v0.of({});return X5(U0.thread$,U0.threadViewState$).pipe(W1(([F0,Z0])=>({[F0.id]:Z0})))}))}),X("runMainThread:createCliNotificationService",F),J.executeMode){oz4(D.mcpService,J.settings);let U0={userInput:V,stdinInput:K,dependencies:D,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},F0=await EV4({threadPool:b,...U0});if(Z.archive)await A6.archiveThread({thread:F0,archived:!0},{config:D.configService});await D.asyncDispose(),process.exit(0)}let d=!1,u=!1;if(Z.jetbrains||Z.ide){await EI1();let U0=await Uw({jetbrainsOnly:Z.jetbrains});if(U0.length===0){if(Z.jetbrains)d=!await D.configService.get("jetbrains.skipInstall")}else if(U0.length===1){let F0=U0[0];if(F0)g8.selectConfig(F0)}else u=!0}F=process.hrtime.bigint();let a=Nf0("0.0.
|
|
7635
|
-
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;I.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Tu1({get:async(z)=>{if(z!==vx)return;try{let F=await _P4(zi0,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(z,F)=>{if(z!==vx)return;await TP4(RB.dirname(zi0),{recursive:!0}),await z53(zi0,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:xK()});_j1(Y);let X=await OK4({...J,workspaceTrust:{current:!0,changes:Mk},getHook:process.env.AMP_URL?(z,F)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(J.mcpConfig){let z=await nz4(J.mcpConfig);X=az4(X,z)}let V=RB.dirname(X.getSettingsFilePath());E$4(mC,V);let K=await X.get("url","global");if(!K)K=Y2;if(I.info("Resolved Amp URL",{ampURL:K,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!KW(K))I.info("Targeting custom Amp server",{ampURL:K});return X=Ej1(X),{executeMode:Z,isTTY:Q,ampURL:K,settings:X,secrets:DF4(await tu0(J,X))}}function v53(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,F)=>F.toUpperCase()),K=J[Q+1];if(K&&!K.startsWith("--"))Z[V]=K,Q++}}return Z}async function k53(){FJ4();let J=v53(process.argv),Z=process.argv.includes("--headless")||process.argv.some((V)=>V.startsWith("--headless="));MX4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?G53:void 0)});let Q=process.argv.includes("--no-color"),Y=process.argv.includes("--color"),X=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!Y&&!X)J1.level=0;if(W53(I),I.info("Starting Amp CLI.",{version:"0.0.
|
|
7634
|
+
`),await CG(),process.exit(1);let S=(async()=>{if(G){I.info("Skipping initial free tier status fetch until auth is complete");return}try{let U0=await D.configService.getLatest(),F0=gk(U0),Z0=await A6.getUserFreeTierStatus({},{config:D.configService,signal:AbortSignal.timeout(F0)});if(Z0.ok)return I.info("User free tier status:",Z0),Z0.result;return}catch(U0){I.error("Failed to fetch free tier status:",U0);return}})(),g=!J.executeMode?new Kb0:null,b,v=null;if(g)b=g,v=(async()=>{let U0=G?await D.serverStatusPromise:D.serverStatus;await qi0(Q,Z,U0);let F0=process.hrtime.bigint(),Z0=Di0(E,U0),D0=j6(U0)?Gi0({userEmail:U0.user.email,features:U0.features}):!1;MP4({dtwEnabled:Z0,hasV2TUIAccess:D0});let i=await _(Z0?"dtw":"worker");if(X("runMainThread:createThreadPool",F0),g.attach(i),V){let n=await O1(i.threadHandles$);if(!n)throw new T1("No active thread is available yet.",1);await n.sendMessage({content:[{type:"text",text:V}]})}})(),v.catch(async(U0)=>{let F0=U0 instanceof Error?U0:Error(String(U0));g.setInitError(F0),await xC(U0,Z.threadId)});else F=process.hrtime.bigint(),MP4({dtwEnabled:O,hasV2TUIAccess:w}),b=await _(O?"dtw":"worker"),X("runMainThread:createThreadPool",F);let f=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let m=await D.configService.getLatest();if(X("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),O53({configService:D.configService,threadService:D.threadService,config:m,useNotificationsForService:f,threadViewStates$:()=>b.threadHandles$.pipe(Q4((U0)=>{if(!U0)return v0.of({});return X5(U0.thread$,U0.threadViewState$).pipe(W1(([F0,Z0])=>({[F0.id]:Z0})))}))}),X("runMainThread:createCliNotificationService",F),J.executeMode){oz4(D.mcpService,J.settings);let U0={userInput:V,stdinInput:K,dependencies:D,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},F0=await EV4({threadPool:b,...U0});if(Z.archive)await A6.archiveThread({thread:F0,archived:!0},{config:D.configService});await D.asyncDispose(),process.exit(0)}let d=!1,u=!1;if(Z.jetbrains||Z.ide){await EI1();let U0=await Uw({jetbrainsOnly:Z.jetbrains});if(U0.length===0){if(Z.jetbrains)d=!await D.configService.get("jetbrains.skipInstall")}else if(U0.length===1){let F0=U0[0];if(F0)g8.selectConfig(F0)}else u=!0}F=process.hrtime.bigint();let a=Nf0("0.0.1773836198-g08fd18",D.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",F),F=process.hrtime.bigint();let l=new zj0(D.threadStorage);X("runMainThread:createThreadFuzzyIndexer",F),F=process.hrtime.bigint();let s=new Rf0(D.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",F),V&&J.executeMode){let U0=await O1(b.threadHandles$);if(!U0)throw new T1("No active thread is available yet.",1);await U0.sendMessage({content:[{type:"text",text:V}]})}F=process.hrtime.bigint();let N0=await ez();X("runMainThread:loadSessionState",F),I.info("Loaded session state:",N0);let o={...N0,launchCount:N0.launchCount+1};$F(o);let G0=Z.threadId&&H8(Z.threadId)?Z.threadId:void 0;try{if(F=process.hrtime.bigint(),await vN4({codebaseContextService:D.codebaseContextService,history:new yu0,fuzzyServer:D.fuzzyServer,settingsStorage:D.settingsStorage,threadService:D.threadService,threadHistoryService:D.threadHistoryService,threadFuzzyIndexer:l,skillService:D.skillService,configService:D.configService,secretStorage:D.secretStorage,internalAPIClient:A6,threadPool:b,createSystemPromptDeps:async()=>xP4(D),ideClient:g8,mcpService:D.mcpService,toolboxService:D.toolboxService,mcpTrustHandler:s,updateService:a,pluginPlatform:D.pluginPlatform,pluginService:D.pluginService},{initialServerStatus:D.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:D.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:G0,showJetBrainsInstaller:d,showIdePickerHint:u,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:o,freeTierStatusPromise:S,workspace:A??null,features:M,isDogfooding:N,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-18T12:20:59.741Z"},(U0)=>new um0({...U0,threadPool:U0.threadPool},(F0)=>new yc0({...F0,threadState:F0.threadState}))),X("runMainThread:mountApp-returned",F),v)await v}finally{}await D.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function D3(J){if(I.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)j2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
7635
|
+
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;I.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Tu1({get:async(z)=>{if(z!==vx)return;try{let F=await _P4(zi0,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(z,F)=>{if(z!==vx)return;await TP4(RB.dirname(zi0),{recursive:!0}),await z53(zi0,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:xK()});_j1(Y);let X=await OK4({...J,workspaceTrust:{current:!0,changes:Mk},getHook:process.env.AMP_URL?(z,F)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(J.mcpConfig){let z=await nz4(J.mcpConfig);X=az4(X,z)}let V=RB.dirname(X.getSettingsFilePath());E$4(mC,V);let K=await X.get("url","global");if(!K)K=Y2;if(I.info("Resolved Amp URL",{ampURL:K,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!KW(K))I.info("Targeting custom Amp server",{ampURL:K});return X=Ej1(X),{executeMode:Z,isTTY:Q,ampURL:K,settings:X,secrets:DF4(await tu0(J,X))}}function v53(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,F)=>F.toUpperCase()),K=J[Q+1];if(K&&!K.startsWith("--"))Z[V]=K,Q++}}return Z}async function k53(){FJ4();let J=v53(process.argv),Z=process.argv.includes("--headless")||process.argv.some((V)=>V.startsWith("--headless="));MX4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?G53:void 0)});let Q=process.argv.includes("--no-color"),Y=process.argv.includes("--color"),X=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!Y&&!X)J1.level=0;if(W53(I),I.info("Starting Amp CLI.",{version:"0.0.1773836198-g08fd18",buildTimestamp:"2026-03-18T12:20:59.741Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new T1(V3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await C53().parseAsync(process.argv)}N$4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await k53().catch(xC)});async function y53(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}
|
|
7636
7636
|
`);else if(!KW(J.ampURL))p6.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
7637
7637
|
`);let Y=process.env.AMP_API_KEY;if(Y)p6.write(`API key found in environment variable, storing...
|
|
7638
7638
|
`),await Z.set("apiKey",Y,J.ampURL),p6.write(`API key successfully stored.
|