@sourcegraph/amp 0.0.1774126892-geb7ca3 → 0.0.1774154108-geea41d
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
|
@@ -6159,11 +6159,11 @@ ${D}`))}},error:(U)=>{if(!W)W=!0,z(Error(`Failed to spawn brew: ${U.message}`))}
|
|
|
6159
6159
|
${D}`;if(X==="pnpm"&&D.includes("Unable to find the global bin directory"))H+=`
|
|
6160
6160
|
|
|
6161
6161
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
6162
|
-
npm install -g @sourcegraph/amp`;z(Error(H))}},error:(U)=>{if(!q)q=!0,z(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}g0();g0();nM();async function VQ0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let z=await fetch(X,{signal:K.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),F=G.version??G["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=jL4(J,F),W=q<0,U,D;if(G.time){let H=G.time[J],B=G.time[F],N=Date.now();if(H)U=Math.floor((N-new Date(H).getTime())/3600000);if(B)D=Math.floor((N-new Date(B).getTime())/3600000)}return I.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:U,latestVersionAge:D}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:U,latestVersionAge:D,source:"npm"}}catch(z){return I.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var Fa5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function zQ0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${Fa5}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let K=jL4(J,X),V=K<0;return I.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return I.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var qa5=604800000;function AL4(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>qa5)return{ageMs:Q};return null}function jL4(J,Z){let Q=(V)=>{let[z,G]=V.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let z=Y.parts[V]||0,G=X.parts[V]||0;if(z<G)return-1;if(z>G)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function Il0(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?EF(Q):void 0;return{sha:Y,age:X}}catch{return null}}N1();function Pl0(J,Z,Q={}){let Y=new s1,X=Y.pipe(c6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new PG().scoped("update"),V=Q.startDelayMs??0;if(V>0)await eG(V);let z=X.subscribe({next:(G)=>{K.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){K.debug("using fake update status for testing",{status:G}),await eG(500),Y.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){K.debug("checking disabled");return}let q=await KQ0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await zQ0(J):await VQ0(J,eA());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let D=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let H=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!F)F=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:F});if(q==="brew"){if(!D())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==Ll0()){if(K.debug("non-standard binary path, showing warning"),!D())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!D())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!D())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!D())Y.next("update-available");return}try{await pl(U.latestVersion,q);let H=await tN(U.latestVersion),B={from:U.currentVersion,to:U.latestVersion,...H};if(H.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(G){K.debug("check failed",{error:G})}finally{await eG(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}nM();import{stderr as oF}from"node:process";function RL4(J){let Z=new mN().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 Bl0(Y.force||!1,Y.verbose||!1,"0.0.
|
|
6162
|
+
npm install -g @sourcegraph/amp`;z(Error(H))}},error:(U)=>{if(!q)q=!0,z(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}g0();g0();nM();async function VQ0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let z=await fetch(X,{signal:K.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),F=G.version??G["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=jL4(J,F),W=q<0,U,D;if(G.time){let H=G.time[J],B=G.time[F],N=Date.now();if(H)U=Math.floor((N-new Date(H).getTime())/3600000);if(B)D=Math.floor((N-new Date(B).getTime())/3600000)}return I.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:U,latestVersionAge:D}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:U,latestVersionAge:D,source:"npm"}}catch(z){return I.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var Fa5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function zQ0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${Fa5}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let K=jL4(J,X),V=K<0;return I.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return I.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var qa5=604800000;function AL4(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>qa5)return{ageMs:Q};return null}function jL4(J,Z){let Q=(V)=>{let[z,G]=V.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let z=Y.parts[V]||0,G=X.parts[V]||0;if(z<G)return-1;if(z>G)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function Il0(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?EF(Q):void 0;return{sha:Y,age:X}}catch{return null}}N1();function Pl0(J,Z,Q={}){let Y=new s1,X=Y.pipe(c6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new PG().scoped("update"),V=Q.startDelayMs??0;if(V>0)await eG(V);let z=X.subscribe({next:(G)=>{K.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){K.debug("using fake update status for testing",{status:G}),await eG(500),Y.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){K.debug("checking disabled");return}let q=await KQ0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await zQ0(J):await VQ0(J,eA());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let D=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let H=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!F)F=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:F});if(q==="brew"){if(!D())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==Ll0()){if(K.debug("non-standard binary path, showing warning"),!D())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!D())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!D())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!D())Y.next("update-available");return}try{await pl(U.latestVersion,q);let H=await tN(U.latestVersion),B={from:U.currentVersion,to:U.latestVersion,...H};if(H.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(G){K.debug("check failed",{error:G})}finally{await eG(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}nM();import{stderr as oF}from"node:process";function RL4(J){let Z=new mN().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 Bl0(Y.force||!1,Y.verbose||!1,"0.0.1774154108-geea41d"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new mN("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await Wa5(Y.targetVersion)});J.addCommand(Q)}async function Wa5(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")oF.write(c0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
6163
6163
|
|
|
6164
6164
|
`));try{if(!J){oF.write(c0.blue(`Checking for updates...
|
|
6165
|
-
`));let{hasUpdate:Y,latestVersion:X}=Nl0()?await zQ0("0.0.
|
|
6166
|
-
`));let z=await tN("0.0.
|
|
6165
|
+
`));let{hasUpdate:Y,latestVersion:X}=Nl0()?await zQ0("0.0.1774154108-geea41d"):await VQ0("0.0.1774154108-geea41d",eA());if(!Y){let K=Il0("0.0.1774154108-geea41d"),V=K?.age?`released ${K.age} ago`:`built ${EF(new Date("2026-03-22T04:38:48.639Z"))} ago`;oF.write(c0.green(`✓ Amp is already up to date on version ${"0.0.1774154108-geea41d"} (${V})
|
|
6166
|
+
`));let z=await tN("0.0.1774154108-geea41d");if(z.warning)oF.write(`
|
|
6167
6167
|
`+c0.yellow(z.warning)+`
|
|
6168
6168
|
`);process.exit(0)}if(!X)oF.write(c0.yellow("[WARN] could not find latest version")),process.exit(0);J=X}oF.write(c0.blue(`Updating to version ${J}...
|
|
6169
6169
|
`)),await pl(J,void 0,(Y)=>{oF.write(c0.dim(`Running: ${Y}
|
|
@@ -7371,7 +7371,7 @@ Ctrl-X, Y, Z to unlock`;if(U){let f=F.text.replace(/`([^`]+)`/g,"$1")+`
|
|
|
7371
7371
|
`),K=[];for(let V=0;V<X.length;V++){let F=X[V].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let q of F)if(q.startsWith("\x00")&&q.endsWith("\x01"))K.push(new C(q.slice(1,-1),new g({color:Y.app.keybind,bold:!0})));else K.push(new C(q,new g({color:Q.colorScheme.foreground})));if(V<X.length-1)K.push(new C(`
|
|
7372
7372
|
`))}return new i0({decoration:{color:Q.colorScheme.background,border:c1.all(new h1(Y.app.keybind,1,"rounded"))},child:new a0({padding:C0.symmetric(0,1),child:new $0({text:new C(void 0,void 0,K)})})})}}class S01 extends k${chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=YG0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new T01({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 Vg4(J,Z,Q,Y,X,K,V){if(K<=0)return null;switch(J){case"horizontal-bar":{let z=Q;return z>=0&&z<K?z:null}case"bar":case"stacked-bar":{let z=V?k9:0,G=Y-z;if(G<=0)return null;let F=Z-z;if(F<0||F>=G)return null;let q=Math.max(1,Math.floor(G/K)),W=Math.floor(F/q);return W>=0&&W<K?W:null}case"line":case"sparkline":case"stacked-area":{let z=V?k9:0,G=Y-z;if(G<=0)return null;let F=Math.max(0,Math.min(G-1,Z-z));if(K===1)return 0;let q=G/(K-1),W=Math.round(F/q);return Math.max(0,Math.min(K-1,W))}default:return null}}function pR3(J,Z,Q,Y,X,K,V,z){if(X<=0||Z<0||Z>=X)return null;let G=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let F=K?k9:0,q=Q-F,W=Y-(K?G:0);if(q<=0||W<=0)return null;let U=Math.max(1,Math.floor(q/X)),D=F+Z*U+Math.floor(U/2),H=z>0?V/z:0,B=Math.round((1-H)*(W-1));return{x:D,y:B}}case"line":case"sparkline":case"stacked-area":{let F=K?k9:0,q=Q-F,W=Y-(K?G:0);if(q<=0||W<=0)return null;let U=X>1?F+Math.round(Z/(X-1)*(q-1)):F+Math.floor(q/2),D=z>0?V/z:0,H=Math.round((1-D)*(W-1));return{x:U,y:H}}default:return null}}function dR3(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 cR3(J,Z,Q,Y,X){if(Q.length<=1){let z=Y(J.value),G=J.meta?` (${J.meta})`:"";return J.label.length+2+z.length+G.length}let K=J.label.length,V=0;for(let z of Q){let G=z.points[Z];if(!G)continue;V+=G.value;let F=2+z.name.length+2+Y(G.value).length;K=Math.max(K,F)}if(X){let z=9+Y(V).length;K=Math.max(K,z)}return K}function lR3(J,Z,Q,Y,X,K,V){let z;try{let H=_1.of(J),B=f0.of(J);z={foreground:H.colorScheme.foreground,background:H.colorScheme.background,border:B.app.keybind}}catch{z={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let G=new g({color:z.foreground,bold:!0}),F=new g({color:z.foreground}),q=new g({color:z.foreground,dim:!0}),W=[],U=new g({color:z.foreground,underline:!0}),D=(H,B)=>new C(B,U,void 0,OQ0(H),()=>{t3(J,H)});if(Y.length<=1){if(W.push(new C(`${Z.label}: `,G)),Z.link)W.push(D(Z.link,K(Z.value)));else W.push(new C(K(Z.value),F));if(Z.meta)W.push(new C(` (${Z.meta})`,q))}else{let H=V==="stacked-bar"||V==="stacked-area";W.push(new C(`${Z.label}
|
|
7373
7373
|
`,G));let B=0;for(let N=0;N<Y.length;N++){let w=Y[N],O=w.points[Q];if(!O)continue;B+=O.value;let L=w.color??X[N%X.length]??z.foreground;if(W.push(new C("● ",new g({color:L}))),W.push(new C(`${w.name}: `,q)),O.link)W.push(D(O.link,K(O.value)));else W.push(new C(K(O.value),F));if(N<Y.length-1||H)W.push(new C(`
|
|
7374
|
-
`))}if(H)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),F))}return new i0({decoration:{color:z.background,border:c1.all(new h1(z.border,1,"rounded"))},child:new $0({text:new C(void 0,void 0,W)})})}YE();g0();P2();import{execSync as OI3}from"node:child_process";GE();B$();n3();I7();fd();nM();LV();O$();rJ();FY();RA();f4();ag();ou();N1();var Vm4=z4($U(),1);import{writeFile as Zm4}from"fs/promises";import Qm4 from"path";g0();O$();class k01{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.1774126892-geb7ca3"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await x40(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 VO extends l0{props;constructor(J){super();this.props=J}createState(){return new zg4}}class zg4 extends d0{_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 Gg4 extends d0{controller=new J$;focusNode=new W6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,z=c1.all(new h1(Q.foreground,1,"solid")),G=new CZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(D)=>{let H=D.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new q1({children:[new i0({decoration:{color:Q.background},child:new $0({text:new C(">",new g({color:Q.foreground}))})}),new k1({child:G})]}),q=new i0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new C("Enter",new g({color:Y.keybind}))),W.push(new C(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new C("Esc",new g({color:Y.keybind}))),W.push(new C(" to cancel",new g({color:Q.foreground,dim:!0})));let U=new i0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,W)})});return new i0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new I0({height:1}),F,new b3,U]})})}}class pa extends l0{props;constructor(J){super();this.props=J}createState(){return new Gg4}}import{isDeepStrictEqual as y01}from"node:util";var iR3=/[\\/_ +.#"@[({&]/,nR3=/[\\/_ +.#"@[({&]/g,aR3=/[\s-]/,Fg4=/[\s-]/g;function VG0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let z=`${X},${K}`;if(V[z]!==void 0)return V[z];let G=Y.charAt(K),F=Q.indexOf(G,X),q=0,W,U,D,H;while(F>=0){if(W=VG0(J,Z,Q,Y,F+1,K+1,V),W>q){if(F===X)W*=1;else if(aR3.test(J.charAt(F-1))){if(W*=0.9,H=J.slice(X,F-1).match(Fg4),H&&X>0)W*=0.999**H.length}else if(iR3.test(J.charAt(F-1))){if(W*=0.8,D=J.slice(X,F-1).match(nR3),D&&X>0)W*=0.999**D.length}else if(W*=0.3,X>0)W*=0.999**(F-X);if(J.charAt(F)!==Z.charAt(K))W*=0.9999}if(W<0.1&&(Q.charAt(F-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(F-1)!==Y.charAt(K))){if(U=VG0(J,Z,Q,Y,F+1,K+2,V),U*0.1>W)W=U*0.1}if(W>q)q=W;F=Q.indexOf(G,F+1)}return V[z]=q,q}function KG0(J){return J.toLowerCase().replace(Fg4," ")}function qg4(J,Z){let Q=VG0(J,Z,KG0(J),KG0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let z of Y){let G=VG0(J,z,KG0(J),KG0(z),0,0,{});if(G===0)return Q;X+=G,K+=z.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class Ov{}class Lv{}class zG0{}class GG0{}class Wg4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Ug4}}class Ug4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}function oR3(J,Z){if(J==="")return{matches:!0,score:1};let Q=qg4(Z,J);return{matches:Q>0.15,score:Q}}class a2 extends l0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new Dg4}}class Dg4 extends d0{textController;focusNode;scrollController=new A5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new J$(this.widget.props.controller?.query??""),this.focusNode=new W6({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>y01(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!y01(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>y01(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 Ov){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof Lv){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof zG0){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 GG0)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,...oR3(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,K)=>this.widget.props.sortItems(X,K,J):(X,K)=>K.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Z=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Z)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;Uv(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=c1.all(new h1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,z=new CZ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:V,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),G=new h$({shortcuts:new Map([[new D4("ArrowDown"),new Ov],[new D4("ArrowUp"),new Lv],[new D4("Tab"),new Ov],[new D4("Tab",{shift:!0}),new Lv],[new D4("n",{ctrl:!0}),new Ov],[new D4("p",{ctrl:!0}),new Lv],[new D4("Enter"),new zG0],[new D4("Escape"),new GG0]]),focusNode:this.focusNode,child:z}),F=new L2({actions:new Map([[Ov,new U6(this.invoke)],[Lv,new U6(this.invoke)],[zG0,new U6(this.invoke)],[GG0,new U6(this.invoke)]]),child:G}),q=new q1({children:[new i0({decoration:{color:Q.background},child:new $0({text:new C(">",new g({color:Q.foreground}))})}),new k1({child:F})]});this.itemContexts=[];let W;if(this.widget.props.isLoading){let N=this.widget.props.loadingText??"Loading...";W=new I0({height:10,child:new $4({child:new $0({text:new C(N,new g({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)W=new k1({child:new $4({child:new $0({text:new C(this.widget.props.emptyStateText,new g({color:Q.foreground,dim:!0}))})})});else{let N=Y.map((w,O)=>{let L=O===this.selectedIndex,E=this.widget.props.isItemDisabled?.(w)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(w,L,E,J);else{let A=L?Z.app.selectionBackground:void 0,j=L?Z.app.selectionForeground:Q.foreground;M=new i0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(this.widget.props.getLabel(w),new g({color:j,dim:E}))})})}return new Wg4(new e1({onClick:(A)=>this.handleItemClick(O,A.clickCount),child:M}),(A)=>{this.itemContexts[O]=A})});W=new x0({children:N,crossAxisAlignment:"start"})}let U=new e1({onScroll:this.handleScroll,opaque:!1,child:new T6({controller:this.scrollController,autofocus:!1,child:W})}),D=[];if(this.widget.props.title){let N=new i0({padding:C0.symmetric(1,0),child:new $0({text:new C(this.widget.props.title,new g({color:Z.app.command,bold:!0}))})});D.push(N)}if(!K)D.push(q,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);D.push(new k1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new k1({child:U}),new i0({padding:C0.only({top:1}),child:new $4({child:w??new I0({height:1})})})]})}))}else D.push(new k1({child:U}));if(this.widget.props.footer)D.push(this.widget.props.footer);return new i0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:D})})}}function Hg4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),K=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(K<7)return`${K}d ago`;return J.toLocaleDateString()}class v01 extends t1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,K)=>K.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>Hg4(X.pubDate).length));return new a2({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,K,V,z)=>{let G=f0.of(z),{colors:F}=G,q=G.app,W=K?q.selectionBackground:void 0,U=K?q.selectionForeground:F.foreground,D=F.mutedForeground,H=(B,N)=>new I0({width:N,child:q1.end([new $0({text:new C(B,new g({color:D}))})])});return new i0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[new k1({child:new $0({text:new C(X.title,new g({color:U})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),H(Hg4(X.pubDate),Q)]})})}})}}class x01 extends l0{createState(){return new Bg4}}class Bg4 extends d0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new $0({text:new C("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function rR3(J){return EY(J,{acceptedHostnames:["ampcode.com","localhost"],allowThreadsPathExtraction:!0})}function sR3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let z=V.relationships.find((G)=>G.role==="child"&&Z.has(G.threadID)&&(G.type==="fork"||G.type==="handoff"));if(z){Y.set(V.id,z.type);let G=z.threadID,F=Q.get(G)||[];F.push(V),Q.set(G,F)}else X.push(V)}return gV0.flatten(X,(V)=>Q.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function f01(J,Z,Q){return new $0({text:new C(`${J}${Z}`,new g({color:Q})),maxLines:1})}function tR3(J,Z,Q,Y){return[f01("+",J,Y.success),b3.horizontal(1),f01("~",Z,Y.warning),b3.horizontal(1),f01("-",Q,Y.destructive)]}function eR3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class FG0 extends l0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new Ng4}}class Ng4 extends d0{spinner=new M3;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,K=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((O)=>O.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((O)=>O.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],z=new Set(V),G=Z.currentThreadID,F=[...K].sort((O,L)=>{if(G){if(O.id===G)return-1;if(L.id===G)return 1}let E=V.indexOf(O.id),M=V.indexOf(L.id);if(E!==-1&&M!==-1)return E-M;if(E!==-1)return-1;if(M!==-1)return 1;return 0}),q=sR3(F),W=Math.max(0,...q.map((O)=>O.description.timeAgo.length)),U=f0.of(J),D=new a0({padding:C0.symmetric(0,1),child:new $4({child:new $0({text:new C("",new g({color:U.colors.foreground,dim:!0}),[new C("Ctrl+T",new g({color:U.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:U.colors.foreground,dim:!0}))])})})}),H="",B=null,N=(O)=>{if(O!==H)H=O,B=rR3(O);return B};return new a2({items:q,getLabel:(O)=>`${O.title} ${O.id}`,filterItem:(O,L)=>{let E=N(L);if(E)return O.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(O)=>N(O)?"":O,onAccept:async(O,L)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(O.id,L);if(!eR3(E))return;this.setSwitchingThread(!0);try{await E}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(O)=>{if(Z.previewController){if(O)Z.previewController.select(O.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:D,renderItem:(O,L,E,M)=>{let A=f0.of(M),{app:j,colors:R}=A,_=L?j.selectionBackground:void 0,k=L?j.selectionForeground:R.foreground,u=R.mutedForeground,m=(s,F0)=>new I0({width:F0,child:q1.end([new $0({text:new C(s,new g({color:u}))})])}),x=Z.threadViewStates[O.id],T=[],f=O.relationshipType==="handoff",p=new Ha({connectorColor:R.mutedForeground});if(O.depth>0){let s=[],F0=O.ancestorsAreLast.slice(1);for(let O0 of F0)s.push(new C(p.getAncestorPrefix(O0),new g({color:p.connectorColor,dim:p.connectorDim})));let a=O.isLast?p.elbow:p.tee,U0=p.getConnectorText(a);s.push(new C(U0,new g({color:p.connectorColor,dim:p.connectorDim}))),T.push(new $0({text:new C("",void 0,s)}))}let d=[],h=G===O.id?new C("(current) ",new g({color:R.success})):z.has(O.id)?new C("(visited) ",new g({color:R.foreground,dim:!0})):null;if(h)d.push(new $0({text:h}));if(ON(x))d.push(new x01),d.push(new I0({width:1}));let n=O.title;if(O.relationshipType==="fork"){let s=n.match(/^Forked\((\d+)\): /);if(s)n=n.slice(s[0].length);else while(n.startsWith("Forked: "))n=n.slice(8);d.push(new $0({text:new C("[fork] ",new g({color:R.primary}))}))}else if(f)d.push(new $0({text:new C("[handoff] ",new g({color:R.accent}))}));if(d.push(new k1({child:new $0({text:new C(n,new g({color:k})),overflow:"ellipsis",maxLines:1})})),d.push(new I0({width:2})),O.diffStats&&(O.diffStats.added>0||O.diffStats.changed>0||O.diffStats.deleted>0)){let s=L?{success:u,warning:u,destructive:u}:R;d.push(...tR3(O.diffStats.added,O.diffStats.changed,O.diffStats.deleted,s)),d.push(new I0({width:2}))}return d.push(m(O.description.timeAgo,W)),new i0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[...T,...d]})})}})}}function wg4(J){return 1-(1-J)**3}function Og4(J,Z,Q){return J+(Z-J)*Q}function da(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),K=wg4(Y),V=wg4(X);return{x:Og4(J.startOffset.x,J.targetOffset.x,K),y:Og4(J.startOffset.y,J.targetOffset.y,V)}}var $I3={nodeWidth:3,horizontalSpacing:3};class Ev{options;constructor(J={}){this.options={...$I3,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let K=0,V=(z,G)=>{let F=Z.get(z.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let q={...z,parentID:Q.get(z.id)};if(F.length===0){Y.push({node:q,position:{x:K,y:G}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let W=[];for(let B of F)W.push(V(B,G+1));let U=Math.min(...W),D=Math.max(...W),H=Math.floor((U+D)/2);return Y.push({node:q,position:{x:H,y:G}}),H};for(let z of X)V(z,0);return Y}buildTree(J){let Z=new Set(J.map((K)=>K.id)),Q=[...J].sort((K,V)=>K.id.localeCompare(V.id)),Y=new Map;for(let K of Q){if(!K.parentID||!Z.has(K.parentID)){Y.set(K.id,void 0);continue}let V=!1,z=K.parentID;while(z){if(z===K.id){V=!0;break}z=Y.get(z)}Y.set(K.id,V?void 0:K.parentID)}let X=new Map;for(let K of J){let V=Y.get(K.id);if(!X.has(V))X.set(V,[]);X.get(V).push(K)}return{childrenMap:X,resolvedParent:Y}}}var JI3={nodeWidth:3,nodeHeight:2};class Mv{options;constructor(J={}){this.options={...JI3,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let K=this.calculateConnectorLine(X.position,Y.position);Z.push({points:K,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,K=Z.x+Q,V=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:V});let z=V+1;if(Y.push({x:X,y:z}),X!==K)Y.push({x:K,y:z});let G=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:G}),Y}}var ZI3={nodeWidth:3,nodeHeight:2},QI3={x:0,y:0};class WG0{options;constructor(J={}){this.options={...ZI3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=QI3,X,K,V,z){let G=z?f0.of(z):null,F=G?.colors,q=G?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let _=[],k=0;for(let u of R){if(u.position.x>k)_.push(new I0({width:u.position.x-k}));let m=u.node.id===Q,x=V?.(u.node.data)??!1,T=K?.activeFlashOn??!1,f=u.node.id===K?.copyFlashNodeId;_.push(this.renderNode(m,x,T,f,q,F)),k=u.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:_})),j>0){let u=J.filter((T)=>T.position.y===j-1),m=R,x=this.renderConnectors(u,m,Z,H,F,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),O=Math.round(Y.x),L=Math.round(Y.y*B),E=(U+1)*B,M=[new I0({width:H,height:E}),new t6({left:O,top:L,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,k=L+R*B+1,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new t6({left:_,top:k,child:this.renderInfoBox(j,u,F,q)}))}return new i0({padding:C0.horizontal(2),child:new xz(new G5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",z="└─┘",G=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,F=!1;if(Y)G=X?.threadGraphNodeSelected??K?.primary??G,V="┏━┓",z="┗━┛",F=!0;else if(Z&&Q)G=X?.toolSuccess??K?.primary??G,V="┏━┓",z="┗━┛";return new x0({crossAxisAlignment:"start",children:[new $0({text:new C(V,new g({color:G,bold:F}))}),new $0({text:new C(z,new g({color:G,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),K=Math.min(Z,Math.max(1,...X.map((U)=>U.length))),V=K+2,z="┌"+"─".repeat(V)+"┐",G="└"+"─".repeat(V)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,W=[new $0({text:new C(z,new g({color:F}))})];for(let U of X){let D=" ".repeat(K-U.length);W.push(new $0({text:new C("│ ",new g({color:F}),[new C(U+D,new g({color:q??F})),new C(" │",new g({color:F}))])}))}return W.push(new $0({text:new C(G,new g({color:F}))})),new x0({crossAxisAlignment:"start",children:W})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),G=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of Z){let D=U.position.x+z;if(D>=0&&D<Y)F[D]="▲"}V.push(new $0({text:new C(F.join(""),new g({color:G}))}));let q=Array(Y).fill(" ");for(let U of J){let D=Z.filter((O)=>O.node.parentID===U.node.id);if(D.length===0)continue;let H=U.position.x+z,B=D.map((O)=>O.position.x+z),N=Math.min(...B),w=Math.max(...B);for(let O=N;O<=w;O++)if(O>=0&&O<Y){if(O===H)if(D.length===1&&B[0]===H)q[O]="│";else if(O===N)q[O]="└";else if(O===w)q[O]="┘";else q[O]="┬";else if(B.includes(O))if(O===N)q[O]="└";else if(O===w)q[O]="┘";else q[O]="┴";else if(q[O]===" ")q[O]="─"}}V.push(new $0({text:new C(q.join(""),new g({color:G}))}));let W=Array(Y).fill(" ");for(let U of J){if(Z.filter((B)=>B.node.parentID===U.node.id).length===0)continue;let H=U.position.x+z;if(H>=0&&H<Y)W[H]="│"}return V.push(new $0({text:new C(W.join(""),new g({color:G}))})),V}}var YI3={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},XI3={x:0,y:0};class u01{options;constructor(J={}){this.options={...YI3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=XI3,X,K,V,z){let G=z?f0.of(z):null,F=G?.colors,q=G?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let _=[],k=0;for(let u of R){if(u.position.x>k)_.push(new I0({width:u.position.x-k}));let m=u.node.id===Q,x=V?.(u.node.data)??!1,T=K?.activeFlashOn??!1;_.push(this.renderNode(m,x,T,q,F)),k=u.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:_})),j>0){let u=J.filter((T)=>T.position.y===j-1),m=R,x=this.renderConnectors(u,m,Z,H,F,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),O=Math.round(Y.x),L=Math.round(Y.y*B),E=(U+1)*B,M=[new I0({width:H,height:E}),new t6({left:O,top:L,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,k=L+R*B,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new t6({left:_,top:k,child:this.renderInfoBox(j,u,F)}))}return new i0({padding:C0.horizontal(2),child:new xz(new G5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let K=J?this.options.selectedIcon:this.options.nodeIcon,V=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)V=Y?.toolSuccess??X?.primary??V,K="■";return new $0({text:new C(K,new g({color:V}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,K=[];for(let V of Y)K.push(new $0({text:new C(V,new g({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:K})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),G=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let q of J){let W=Z.filter((N)=>N.node.parentID===q.node.id);if(W.length===0)continue;let U=q.position.x+z,D=W.map((N)=>N.position.x+z),H=Math.min(...D),B=Math.max(...D);for(let N=H;N<=B;N++)if(N>=0&&N<Y){let w=N===U,O=D.includes(N);if(w&&O)if(W.length===1)F[N]="│";else if(N===H)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┼";else if(w)if(N===H)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┬";else if(O)if(N===H)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┴";else if(F[N]===" ")F[N]="─"}}return V.push(new $0({text:new C(F.join(""),new g({color:G}))})),V}}class ca extends o3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new Lg4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class Lg4 extends v4{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 RR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Ag4}}var Eg4=400,Mg4=300,KI3=16;class Ag4 extends d0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new Ev({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new Mv;renderer=new u01;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((G)=>G.id)),Q=new Set(this.widget.props.threads.map((G)=>G.id));if(Z.size!==Q.size||[...Z].some((G)=>!Q.has(G)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,K=this.widget.props.initialSelectedThreadID;if(X!==K&&K){let F=this.widget.props.threads.find((q)=>q.id===K);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((G)=>G.isActive),z=this.widget.props.threads.some((G)=>G.isActive);if(V!==z){if(this.stopActiveFlashTimer(),z)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:Eg4,durationY:Mg4};let Z=Math.max(Eg4,Mg4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=da(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},KI3)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),K=Math.floor(this.viewportWidth/2)-J-Y,V=Q-Z,z=2,G=Math.floor(this.viewportHeight/2),q=Math.floor(G/2)-V;return{x:K,y:q}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((K)=>K.node.parentID===Q.node.id);if(X.length>0){X.sort((V,z)=>V.position.x-z.position.x);let K=Math.floor(X.length/2);Y=X[K]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x<Q.position.x);if(X.length>0)X.sort((K,V)=>V.position.x-K.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x>Q.position.x);if(X.length>0)X.sort((K,V)=>K.position.x-V.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let q=(this.selectedNodeId?this.positionedNodes.find((W)=>W.node.id===this.selectedNodeId):null)??this.positionedNodes.find((W)=>!W.node.parentID);if(q){let W=Math.max(...this.positionedNodes.map((U)=>U.position.y));this.currentOffset=this.calculateCenterOffset(q.position.x,q.position.y,W)}}let X=this.widget.props.showTitle??!0,K=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+K},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),G=new ca({onWidth:(F)=>{if(this.viewportWidth!==F)this.viewportWidth=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(F)=>{if(this.viewportHeight!==F)this.viewportHeight=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new s4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:G})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class Rg4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Ig4}}class Ig4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}var jg4=30,VI3=30;class Av{}class jv{}class UG0{}class DG0{}class b01 extends l0{props;constructor(J){super();this.props=J}createState(){return new Pg4}}class Pg4 extends d0{highlightedIndex=0;controller=new J$;focusNode;scrollController=new A5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new W6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;Uv(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 Av){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof jv){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof UG0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof DG0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,z=K4.of(J).size.width>=VI3+jg4,G=c1.all(new h1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,q=new i0({padding:C0.symmetric(1,0),child:new $0({text:new C("Select a cluster",new g({color:X.command,bold:!0}))})}),W=new CZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),U=new h$({shortcuts:new Map([[new D4("ArrowDown"),new Av],[new D4("ArrowUp"),new jv],[new D4("Tab"),new Av],[new D4("Tab",{shift:!0}),new jv],[new D4("n",{ctrl:!0}),new Av],[new D4("p",{ctrl:!0}),new jv],[new D4("Enter"),new UG0],[new D4("Escape"),new DG0]]),focusNode:this.focusNode,child:W}),D=new L2({actions:new Map([[Av,new U6(this.invoke)],[jv,new U6(this.invoke)],[UG0,new U6(this.invoke)],[DG0,new U6(this.invoke)]]),child:U}),H=new q1({children:[new i0({decoration:{color:Y.background},child:new $0({text:new C(">",new g({color:Y.foreground}))})}),new k1({child:D})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,R=Z?M.threads.some((m)=>m.id===Z):!1,_=j?X.selectionBackground:void 0,k=j?X.selectionForeground:Y.foreground,u=[new C(M.label,new g({color:k})),new C(` (${M.threads.length})`,new g({color:k,dim:!0}))];if(R)u.push(new C(" (current)",new g({color:j?X.selectionForeground:Y.success})));return new Rg4(new e1({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new i0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,u)})})}),(m)=>{this.itemContexts[A]=m})}),N=new x0({children:B,crossAxisAlignment:"start"}),w=new k1({child:new e1({onScroll:this.handleScroll,child:new T6({controller:this.scrollController,autofocus:!1,child:N})})}),O=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],L=F?new i0({padding:C0.all(1),child:new RR({threads:O,autofocus:!1,offsetY:2})}):null,E;if(z){let M=L?new k1({child:L}):new I0({width:jg4});E=new q1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,M]})}else{let M=[new k1({child:new e1({onScroll:this.handleScroll,child:new T6({controller:this.scrollController,autofocus:!1,child:N})})})];if(L)M.push(new k1({child:L}));E=new x0({crossAxisAlignment:"stretch",children:M})}return new i0({decoration:{border:G,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[q,H,new I0({height:1}),new k1({child:E})]})})}}class kJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!kJ._instance)kJ._instance=new kJ;return kJ._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()}}g0();class Cg4 extends d0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){I.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){I.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((K)=>K.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=f0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),K=X.length>0?this.getValidationError(X):null,V=this.getAvailableLabels(),G=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...V];return new a2({title:"Add Label",items:G,getLabel:(F)=>{if("__isCreateMarker"in F)return this.currentQuery.trim().toLowerCase();return F.name},onAccept:(F)=>{if("__isCreateMarker"in F)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(F.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:K||"Type to create a new label",renderItem:(F,q,W,U)=>{let D=q?Q.selectionBackground:void 0,H=q?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in F&&F.__isCreateMarker){let N=this.currentQuery.trim().toLowerCase();return new i0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,[new C("Create new label: ",new g({color:H})),new C(N,new g({color:H,bold:!0}))])})})}return new i0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(F.name,new g({color:H}))})})},filterItem:(F,q)=>{if(this.currentQuery!==q)this.currentQuery=q,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in F&&F.__isCreateMarker)return this.shouldShowCreateMarker(q);let U=q.trim().toLowerCase();return U.length===0||F.name.includes(U)},sortItems:(F,q,W)=>{let U="__isCreateMarker"in F.item&&F.item.__isCreateMarker,D="__isCreateMarker"in q.item&&q.item.__isCreateMarker;if(U&&!D)return-1;if(!U&&D)return 1;return q.score-F.score}})}}class h01 extends l0{props;constructor(J){super();this.props=J}createState(){return new Cg4}}class dz extends l0{props;constructor(J){super();this.props=J}createState(){return new Tg4}}class Tg4 extends d0{_spinner=new M3;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=c1.all(new h1(Q.foreground,1,"solid")),K=this._spinner.toBraille(),V=new $0({textAlign:"center",text:new C("",void 0,[new C(K,new g({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new g({color:Q.foreground}))])}),G=[new k1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[V]})})];if(this.widget.props.onAbort)G.push(new I0({height:2,child:new i0({padding:C0.symmetric(2,0),child:new $0({text:new C("",new g({dim:!0}),[new C("Press ",new g({color:Q.foreground})),new C("Esc",new g({color:Q.info})),new C(" to cancel",new g({color:Q.foreground}))])})})}));let F=new i0({decoration:new r4(Q.background,X),child:new I0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:G})})});if(this.widget.props.onAbort)return new s4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(q)=>{if(q.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:F});return F}}var la={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"}},HG0=["workspace","global","flag","default","external","skill","other"];function zI3(J){return Array.from(new Set(J))}function _g4(J){return zI3([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function Rv(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 _g4(J).length>0?"skill":"other"}function g01(J){return Rv(J)==="skill"}function Sg4(J){let Z=_g4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=Rv(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${la[Y].description}: ${Q}`}function kg4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}var yg4=process.platform==="win32"?" ":"█",vg4=process.platform==="win32"?"░":"█";class O9 extends l0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=yg4,thumbChar:K=vg4,showTrack:V=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=z,this.trackColor=G}createState(){return new xg4}}class xg4 extends d0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),X=this.context.findRenderObject()?.size.height??0;if(X===0||Z<=Q)return!1;let K=this.widget.getScrollInfo(),V=Math.min(1,Q/Z),z=Math.max(1,X*V),G=Math.max(0,Math.min(1,K.scrollOffset/(Z-Q))),F=X-z,q=Math.max(0,F*G),W=q+z;return J>=q&&J<=W}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let V=J.localPosition.y-this._dragStartY,z=Math.min(1,Q/Z),G=Math.max(1,K*z),F=K-G;if(F<=0)return;let q=Z-Q,W=F/q,U=V/W,D=Math.max(0,Math.min(q,this._dragStartOffset+U));this.widget.controller.jumpTo(D)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Q<=Y)return;let z=Math.min(1,Y/Q),G=Math.max(1,V*z),F=Q-Y,q=V-G,W=Math.max(0,Math.min(1,X/(Q-Y))),U=Math.max(0,q*W),D=U+G;if(Z>=U&&Z<=D)return;if(Z<U)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(F,X+Y))};build(J){return new e1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?b5.POINTER:b5.DEFAULT,child:new fg4({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 fg4 extends jk{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=yg4,thumbChar:K=vg4,showTrack:V=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=z,this.trackColor=G}createRenderObject(){return new ug4(this)}updateRenderObject(J){J.updateWidget(this)}}class ug4 extends v4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;J6(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:K}=this._calculateScrollbarMetrics();if(!K)return;let V=this._widget.trackColor,z=this._widget.thumbColor,G=process.platform==="win32",F=Y,q=Y+X;if(!G){let W=["▁","▂","▃","▄","▅","▆","▇","█"];for(let U=0;U<this.size.height;U++){let D="█",H=!0;if(U===Math.floor(F)){let B=1-(F-U),N=Math.floor(B*8);D=W[N]||"█",H=!1}else if(U===Math.floor(q)){let B=1-(q-U),N=Math.floor(B*8);D=W[N]||"█"}else if(U>F&&U<q)H=!1;J.setChar(Z,Q+U,D,{fg:z,bg:V,reverse:H},1)}return}for(let W=0;W<this.size.height;W++){let U=W+0.5,D=U>=F&&U<q,H=D?this._widget.thumbChar:this._widget.trackChar;J.setChar(Z,Q+W,H,{fg:D?z:V,bg:V,reverse:!1},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),K=Math.min(1,Z/J),V=Math.max(1,Y*K),z=Y-V;return{thumbStartFloat:Math.max(0,z*X),thumbSizeFloat:V,showScrollbar:!0}}}class IR extends l0{props;constructor(J){super();this.props=J}createState(){return new bg4}}class bg4 extends d0{scrollController=new A5;scrollAreaKey=new p7("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 n2}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=f0.of(J),Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let q=dz0(Q);return{title:q.title,type:q.type,description:q.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,K=c1.all(new h1(Z.colors.border,1,"solid")),V=new i0({padding:C0.symmetric(1,0),child:new $0({text:new C(Y.title,new g({color:X,bold:!0}))})}),z=this.isWidgetMessage(Q)?Q.widget:new $0({text:new C(Y.description,new g({color:Z.colors.foreground})),selectable:!0}),G=new k1({child:new g$({child:new i0({padding:C0.symmetric(1,0),child:new q1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new k1({child:new T6({controller:this.scrollController,autofocus:!0,child:z})}),new O9({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let q=this.scrollController.maxScrollExtent,W=this.scrollController.offset,U=this.getViewportHeight(),D=q+U;return{totalContentHeight:Math.max(D,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(W,0)}}})]})})})}),F=new i0({padding:C0.symmetric(1,0),child:new $0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new g({color:Z.colors.foreground,dim:!0})),new C("R",new g({color:Z.app.keybind})),new C(" to retry, ",new g({color:Z.colors.foreground,dim:!0})),new C("Esc",new g({color:Z.app.keybind})),new C(" to cancel",new g({color:Z.colors.foreground,dim:!0}))]);let q=this.resolveFooterStyle(this.widget.props.message);if(q==="none")return new C("",new g({color:Z.colors.foreground,dim:!0}));if(q==="help"){let W=new g({color:Z.app.keybind}),U=new g({color:Z.colors.foreground,dim:!0});return new C("",U,[new C("Press ",U),new C("Escape",W),new C(" to close • Use ",U),new C("↑↓",W),new C(" or ",U),new C("j/k",W),new C(" to scroll",U)])}return new C("Press any key to close",new g({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new s4({onKey:(q)=>{if(this.widget.props.onRetry&&q.key==="r")return this.widget.props.onRetry(),"handled";if(q.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 i0({decoration:{border:K,color:Z.colors.background},padding:C0.all(1),child:new x0({mainAxisAlignment:"center",children:[V,new I0({height:1}),G,F]})})})}}P2();class hg4 extends l0{props;constructor(J){super();this.props=J}createState(){return new gg4}}class gg4 extends d0{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=_9.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new $0({text:new C("No plugins found.",new g({dim:!0}))});let Y=[],X=this.plugins.length,K=this.plugins.filter((G)=>G.status==="active").length,V=this.plugins.reduce((G,F)=>G+F.registeredCommands.length,0),z=this.plugins.reduce((G,F)=>G+F.registeredTools.length,0);if(Y.push(new C(`${K}/${X} ${d4(X,"plugin")} active`,new g({bold:!0}))),V>0||z>0)Y.push(new C(` (${V} ${d4(V,"command")}, ${z} ${d4(z,"tool")})`,new g({dim:!0})));Y.push(new C(`
|
|
7374
|
+
`))}if(H)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),F))}return new i0({decoration:{color:z.background,border:c1.all(new h1(z.border,1,"rounded"))},child:new $0({text:new C(void 0,void 0,W)})})}YE();g0();P2();import{execSync as OI3}from"node:child_process";GE();B$();n3();I7();fd();nM();LV();O$();rJ();FY();RA();f4();ag();ou();N1();var Vm4=z4($U(),1);import{writeFile as Zm4}from"fs/promises";import Qm4 from"path";g0();O$();class k01{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.1774154108-geea41d"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await x40(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 VO extends l0{props;constructor(J){super();this.props=J}createState(){return new zg4}}class zg4 extends d0{_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 Gg4 extends d0{controller=new J$;focusNode=new W6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,z=c1.all(new h1(Q.foreground,1,"solid")),G=new CZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(D)=>{let H=D.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new q1({children:[new i0({decoration:{color:Q.background},child:new $0({text:new C(">",new g({color:Q.foreground}))})}),new k1({child:G})]}),q=new i0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new C("Enter",new g({color:Y.keybind}))),W.push(new C(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new C("Esc",new g({color:Y.keybind}))),W.push(new C(" to cancel",new g({color:Q.foreground,dim:!0})));let U=new i0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,W)})});return new i0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new I0({height:1}),F,new b3,U]})})}}class pa extends l0{props;constructor(J){super();this.props=J}createState(){return new Gg4}}import{isDeepStrictEqual as y01}from"node:util";var iR3=/[\\/_ +.#"@[({&]/,nR3=/[\\/_ +.#"@[({&]/g,aR3=/[\s-]/,Fg4=/[\s-]/g;function VG0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let z=`${X},${K}`;if(V[z]!==void 0)return V[z];let G=Y.charAt(K),F=Q.indexOf(G,X),q=0,W,U,D,H;while(F>=0){if(W=VG0(J,Z,Q,Y,F+1,K+1,V),W>q){if(F===X)W*=1;else if(aR3.test(J.charAt(F-1))){if(W*=0.9,H=J.slice(X,F-1).match(Fg4),H&&X>0)W*=0.999**H.length}else if(iR3.test(J.charAt(F-1))){if(W*=0.8,D=J.slice(X,F-1).match(nR3),D&&X>0)W*=0.999**D.length}else if(W*=0.3,X>0)W*=0.999**(F-X);if(J.charAt(F)!==Z.charAt(K))W*=0.9999}if(W<0.1&&(Q.charAt(F-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(F-1)!==Y.charAt(K))){if(U=VG0(J,Z,Q,Y,F+1,K+2,V),U*0.1>W)W=U*0.1}if(W>q)q=W;F=Q.indexOf(G,F+1)}return V[z]=q,q}function KG0(J){return J.toLowerCase().replace(Fg4," ")}function qg4(J,Z){let Q=VG0(J,Z,KG0(J),KG0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let z of Y){let G=VG0(J,z,KG0(J),KG0(z),0,0,{});if(G===0)return Q;X+=G,K+=z.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class Ov{}class Lv{}class zG0{}class GG0{}class Wg4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Ug4}}class Ug4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}function oR3(J,Z){if(J==="")return{matches:!0,score:1};let Q=qg4(Z,J);return{matches:Q>0.15,score:Q}}class a2 extends l0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new Dg4}}class Dg4 extends d0{textController;focusNode;scrollController=new A5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new J$(this.widget.props.controller?.query??""),this.focusNode=new W6({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>y01(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!y01(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>y01(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 Ov){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof Lv){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof zG0){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 GG0)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,...oR3(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,K)=>this.widget.props.sortItems(X,K,J):(X,K)=>K.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Z=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Z)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;Uv(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=c1.all(new h1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,z=new CZ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:V,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),G=new h$({shortcuts:new Map([[new D4("ArrowDown"),new Ov],[new D4("ArrowUp"),new Lv],[new D4("Tab"),new Ov],[new D4("Tab",{shift:!0}),new Lv],[new D4("n",{ctrl:!0}),new Ov],[new D4("p",{ctrl:!0}),new Lv],[new D4("Enter"),new zG0],[new D4("Escape"),new GG0]]),focusNode:this.focusNode,child:z}),F=new L2({actions:new Map([[Ov,new U6(this.invoke)],[Lv,new U6(this.invoke)],[zG0,new U6(this.invoke)],[GG0,new U6(this.invoke)]]),child:G}),q=new q1({children:[new i0({decoration:{color:Q.background},child:new $0({text:new C(">",new g({color:Q.foreground}))})}),new k1({child:F})]});this.itemContexts=[];let W;if(this.widget.props.isLoading){let N=this.widget.props.loadingText??"Loading...";W=new I0({height:10,child:new $4({child:new $0({text:new C(N,new g({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)W=new k1({child:new $4({child:new $0({text:new C(this.widget.props.emptyStateText,new g({color:Q.foreground,dim:!0}))})})});else{let N=Y.map((w,O)=>{let L=O===this.selectedIndex,E=this.widget.props.isItemDisabled?.(w)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(w,L,E,J);else{let A=L?Z.app.selectionBackground:void 0,j=L?Z.app.selectionForeground:Q.foreground;M=new i0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(this.widget.props.getLabel(w),new g({color:j,dim:E}))})})}return new Wg4(new e1({onClick:(A)=>this.handleItemClick(O,A.clickCount),child:M}),(A)=>{this.itemContexts[O]=A})});W=new x0({children:N,crossAxisAlignment:"start"})}let U=new e1({onScroll:this.handleScroll,opaque:!1,child:new T6({controller:this.scrollController,autofocus:!1,child:W})}),D=[];if(this.widget.props.title){let N=new i0({padding:C0.symmetric(1,0),child:new $0({text:new C(this.widget.props.title,new g({color:Z.app.command,bold:!0}))})});D.push(N)}if(!K)D.push(q,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);D.push(new k1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new k1({child:U}),new i0({padding:C0.only({top:1}),child:new $4({child:w??new I0({height:1})})})]})}))}else D.push(new k1({child:U}));if(this.widget.props.footer)D.push(this.widget.props.footer);return new i0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:D})})}}function Hg4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),K=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(K<7)return`${K}d ago`;return J.toLocaleDateString()}class v01 extends t1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,K)=>K.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>Hg4(X.pubDate).length));return new a2({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,K,V,z)=>{let G=f0.of(z),{colors:F}=G,q=G.app,W=K?q.selectionBackground:void 0,U=K?q.selectionForeground:F.foreground,D=F.mutedForeground,H=(B,N)=>new I0({width:N,child:q1.end([new $0({text:new C(B,new g({color:D}))})])});return new i0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[new k1({child:new $0({text:new C(X.title,new g({color:U})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),H(Hg4(X.pubDate),Q)]})})}})}}class x01 extends l0{createState(){return new Bg4}}class Bg4 extends d0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new $0({text:new C("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function rR3(J){return EY(J,{acceptedHostnames:["ampcode.com","localhost"],allowThreadsPathExtraction:!0})}function sR3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let z=V.relationships.find((G)=>G.role==="child"&&Z.has(G.threadID)&&(G.type==="fork"||G.type==="handoff"));if(z){Y.set(V.id,z.type);let G=z.threadID,F=Q.get(G)||[];F.push(V),Q.set(G,F)}else X.push(V)}return gV0.flatten(X,(V)=>Q.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function f01(J,Z,Q){return new $0({text:new C(`${J}${Z}`,new g({color:Q})),maxLines:1})}function tR3(J,Z,Q,Y){return[f01("+",J,Y.success),b3.horizontal(1),f01("~",Z,Y.warning),b3.horizontal(1),f01("-",Q,Y.destructive)]}function eR3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class FG0 extends l0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new Ng4}}class Ng4 extends d0{spinner=new M3;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,K=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((O)=>O.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((O)=>O.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],z=new Set(V),G=Z.currentThreadID,F=[...K].sort((O,L)=>{if(G){if(O.id===G)return-1;if(L.id===G)return 1}let E=V.indexOf(O.id),M=V.indexOf(L.id);if(E!==-1&&M!==-1)return E-M;if(E!==-1)return-1;if(M!==-1)return 1;return 0}),q=sR3(F),W=Math.max(0,...q.map((O)=>O.description.timeAgo.length)),U=f0.of(J),D=new a0({padding:C0.symmetric(0,1),child:new $4({child:new $0({text:new C("",new g({color:U.colors.foreground,dim:!0}),[new C("Ctrl+T",new g({color:U.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:U.colors.foreground,dim:!0}))])})})}),H="",B=null,N=(O)=>{if(O!==H)H=O,B=rR3(O);return B};return new a2({items:q,getLabel:(O)=>`${O.title} ${O.id}`,filterItem:(O,L)=>{let E=N(L);if(E)return O.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(O)=>N(O)?"":O,onAccept:async(O,L)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(O.id,L);if(!eR3(E))return;this.setSwitchingThread(!0);try{await E}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(O)=>{if(Z.previewController){if(O)Z.previewController.select(O.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:D,renderItem:(O,L,E,M)=>{let A=f0.of(M),{app:j,colors:R}=A,_=L?j.selectionBackground:void 0,k=L?j.selectionForeground:R.foreground,u=R.mutedForeground,m=(s,F0)=>new I0({width:F0,child:q1.end([new $0({text:new C(s,new g({color:u}))})])}),x=Z.threadViewStates[O.id],T=[],f=O.relationshipType==="handoff",p=new Ha({connectorColor:R.mutedForeground});if(O.depth>0){let s=[],F0=O.ancestorsAreLast.slice(1);for(let O0 of F0)s.push(new C(p.getAncestorPrefix(O0),new g({color:p.connectorColor,dim:p.connectorDim})));let a=O.isLast?p.elbow:p.tee,U0=p.getConnectorText(a);s.push(new C(U0,new g({color:p.connectorColor,dim:p.connectorDim}))),T.push(new $0({text:new C("",void 0,s)}))}let d=[],h=G===O.id?new C("(current) ",new g({color:R.success})):z.has(O.id)?new C("(visited) ",new g({color:R.foreground,dim:!0})):null;if(h)d.push(new $0({text:h}));if(ON(x))d.push(new x01),d.push(new I0({width:1}));let n=O.title;if(O.relationshipType==="fork"){let s=n.match(/^Forked\((\d+)\): /);if(s)n=n.slice(s[0].length);else while(n.startsWith("Forked: "))n=n.slice(8);d.push(new $0({text:new C("[fork] ",new g({color:R.primary}))}))}else if(f)d.push(new $0({text:new C("[handoff] ",new g({color:R.accent}))}));if(d.push(new k1({child:new $0({text:new C(n,new g({color:k})),overflow:"ellipsis",maxLines:1})})),d.push(new I0({width:2})),O.diffStats&&(O.diffStats.added>0||O.diffStats.changed>0||O.diffStats.deleted>0)){let s=L?{success:u,warning:u,destructive:u}:R;d.push(...tR3(O.diffStats.added,O.diffStats.changed,O.diffStats.deleted,s)),d.push(new I0({width:2}))}return d.push(m(O.description.timeAgo,W)),new i0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[...T,...d]})})}})}}function wg4(J){return 1-(1-J)**3}function Og4(J,Z,Q){return J+(Z-J)*Q}function da(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),K=wg4(Y),V=wg4(X);return{x:Og4(J.startOffset.x,J.targetOffset.x,K),y:Og4(J.startOffset.y,J.targetOffset.y,V)}}var $I3={nodeWidth:3,horizontalSpacing:3};class Ev{options;constructor(J={}){this.options={...$I3,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let K=0,V=(z,G)=>{let F=Z.get(z.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let q={...z,parentID:Q.get(z.id)};if(F.length===0){Y.push({node:q,position:{x:K,y:G}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let W=[];for(let B of F)W.push(V(B,G+1));let U=Math.min(...W),D=Math.max(...W),H=Math.floor((U+D)/2);return Y.push({node:q,position:{x:H,y:G}}),H};for(let z of X)V(z,0);return Y}buildTree(J){let Z=new Set(J.map((K)=>K.id)),Q=[...J].sort((K,V)=>K.id.localeCompare(V.id)),Y=new Map;for(let K of Q){if(!K.parentID||!Z.has(K.parentID)){Y.set(K.id,void 0);continue}let V=!1,z=K.parentID;while(z){if(z===K.id){V=!0;break}z=Y.get(z)}Y.set(K.id,V?void 0:K.parentID)}let X=new Map;for(let K of J){let V=Y.get(K.id);if(!X.has(V))X.set(V,[]);X.get(V).push(K)}return{childrenMap:X,resolvedParent:Y}}}var JI3={nodeWidth:3,nodeHeight:2};class Mv{options;constructor(J={}){this.options={...JI3,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let K=this.calculateConnectorLine(X.position,Y.position);Z.push({points:K,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,K=Z.x+Q,V=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:V});let z=V+1;if(Y.push({x:X,y:z}),X!==K)Y.push({x:K,y:z});let G=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:G}),Y}}var ZI3={nodeWidth:3,nodeHeight:2},QI3={x:0,y:0};class WG0{options;constructor(J={}){this.options={...ZI3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=QI3,X,K,V,z){let G=z?f0.of(z):null,F=G?.colors,q=G?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let _=[],k=0;for(let u of R){if(u.position.x>k)_.push(new I0({width:u.position.x-k}));let m=u.node.id===Q,x=V?.(u.node.data)??!1,T=K?.activeFlashOn??!1,f=u.node.id===K?.copyFlashNodeId;_.push(this.renderNode(m,x,T,f,q,F)),k=u.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:_})),j>0){let u=J.filter((T)=>T.position.y===j-1),m=R,x=this.renderConnectors(u,m,Z,H,F,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),O=Math.round(Y.x),L=Math.round(Y.y*B),E=(U+1)*B,M=[new I0({width:H,height:E}),new t6({left:O,top:L,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,k=L+R*B+1,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new t6({left:_,top:k,child:this.renderInfoBox(j,u,F,q)}))}return new i0({padding:C0.horizontal(2),child:new xz(new G5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",z="└─┘",G=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,F=!1;if(Y)G=X?.threadGraphNodeSelected??K?.primary??G,V="┏━┓",z="┗━┛",F=!0;else if(Z&&Q)G=X?.toolSuccess??K?.primary??G,V="┏━┓",z="┗━┛";return new x0({crossAxisAlignment:"start",children:[new $0({text:new C(V,new g({color:G,bold:F}))}),new $0({text:new C(z,new g({color:G,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),K=Math.min(Z,Math.max(1,...X.map((U)=>U.length))),V=K+2,z="┌"+"─".repeat(V)+"┐",G="└"+"─".repeat(V)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,W=[new $0({text:new C(z,new g({color:F}))})];for(let U of X){let D=" ".repeat(K-U.length);W.push(new $0({text:new C("│ ",new g({color:F}),[new C(U+D,new g({color:q??F})),new C(" │",new g({color:F}))])}))}return W.push(new $0({text:new C(G,new g({color:F}))})),new x0({crossAxisAlignment:"start",children:W})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),G=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of Z){let D=U.position.x+z;if(D>=0&&D<Y)F[D]="▲"}V.push(new $0({text:new C(F.join(""),new g({color:G}))}));let q=Array(Y).fill(" ");for(let U of J){let D=Z.filter((O)=>O.node.parentID===U.node.id);if(D.length===0)continue;let H=U.position.x+z,B=D.map((O)=>O.position.x+z),N=Math.min(...B),w=Math.max(...B);for(let O=N;O<=w;O++)if(O>=0&&O<Y){if(O===H)if(D.length===1&&B[0]===H)q[O]="│";else if(O===N)q[O]="└";else if(O===w)q[O]="┘";else q[O]="┬";else if(B.includes(O))if(O===N)q[O]="└";else if(O===w)q[O]="┘";else q[O]="┴";else if(q[O]===" ")q[O]="─"}}V.push(new $0({text:new C(q.join(""),new g({color:G}))}));let W=Array(Y).fill(" ");for(let U of J){if(Z.filter((B)=>B.node.parentID===U.node.id).length===0)continue;let H=U.position.x+z;if(H>=0&&H<Y)W[H]="│"}return V.push(new $0({text:new C(W.join(""),new g({color:G}))})),V}}var YI3={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},XI3={x:0,y:0};class u01{options;constructor(J={}){this.options={...YI3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=XI3,X,K,V,z){let G=z?f0.of(z):null,F=G?.colors,q=G?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let _=[],k=0;for(let u of R){if(u.position.x>k)_.push(new I0({width:u.position.x-k}));let m=u.node.id===Q,x=V?.(u.node.data)??!1,T=K?.activeFlashOn??!1;_.push(this.renderNode(m,x,T,q,F)),k=u.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:_})),j>0){let u=J.filter((T)=>T.position.y===j-1),m=R,x=this.renderConnectors(u,m,Z,H,F,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),O=Math.round(Y.x),L=Math.round(Y.y*B),E=(U+1)*B,M=[new I0({width:H,height:E}),new t6({left:O,top:L,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,k=L+R*B,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new t6({left:_,top:k,child:this.renderInfoBox(j,u,F)}))}return new i0({padding:C0.horizontal(2),child:new xz(new G5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let K=J?this.options.selectedIcon:this.options.nodeIcon,V=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)V=Y?.toolSuccess??X?.primary??V,K="■";return new $0({text:new C(K,new g({color:V}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,K=[];for(let V of Y)K.push(new $0({text:new C(V,new g({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:K})}renderConnectors(J,Z,Q,Y,X,K){let V=[],z=Math.floor(this.options.nodeWidth/2),G=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let q of J){let W=Z.filter((N)=>N.node.parentID===q.node.id);if(W.length===0)continue;let U=q.position.x+z,D=W.map((N)=>N.position.x+z),H=Math.min(...D),B=Math.max(...D);for(let N=H;N<=B;N++)if(N>=0&&N<Y){let w=N===U,O=D.includes(N);if(w&&O)if(W.length===1)F[N]="│";else if(N===H)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┼";else if(w)if(N===H)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┬";else if(O)if(N===H)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┴";else if(F[N]===" ")F[N]="─"}}return V.push(new $0({text:new C(F.join(""),new g({color:G}))})),V}}class ca extends o3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new Lg4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class Lg4 extends v4{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 RR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Ag4}}var Eg4=400,Mg4=300,KI3=16;class Ag4 extends d0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new Ev({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new Mv;renderer=new u01;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((G)=>G.id)),Q=new Set(this.widget.props.threads.map((G)=>G.id));if(Z.size!==Q.size||[...Z].some((G)=>!Q.has(G)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,K=this.widget.props.initialSelectedThreadID;if(X!==K&&K){let F=this.widget.props.threads.find((q)=>q.id===K);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((G)=>G.isActive),z=this.widget.props.threads.some((G)=>G.isActive);if(V!==z){if(this.stopActiveFlashTimer(),z)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:Eg4,durationY:Mg4};let Z=Math.max(Eg4,Mg4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=da(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},KI3)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),K=Math.floor(this.viewportWidth/2)-J-Y,V=Q-Z,z=2,G=Math.floor(this.viewportHeight/2),q=Math.floor(G/2)-V;return{x:K,y:q}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((K)=>K.node.parentID===Q.node.id);if(X.length>0){X.sort((V,z)=>V.position.x-z.position.x);let K=Math.floor(X.length/2);Y=X[K]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x<Q.position.x);if(X.length>0)X.sort((K,V)=>V.position.x-K.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x>Q.position.x);if(X.length>0)X.sort((K,V)=>K.position.x-V.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let q=(this.selectedNodeId?this.positionedNodes.find((W)=>W.node.id===this.selectedNodeId):null)??this.positionedNodes.find((W)=>!W.node.parentID);if(q){let W=Math.max(...this.positionedNodes.map((U)=>U.position.y));this.currentOffset=this.calculateCenterOffset(q.position.x,q.position.y,W)}}let X=this.widget.props.showTitle??!0,K=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+K},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),G=new ca({onWidth:(F)=>{if(this.viewportWidth!==F)this.viewportWidth=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(F)=>{if(this.viewportHeight!==F)this.viewportHeight=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new s4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:G})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class Rg4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Ig4}}class Ig4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}var jg4=30,VI3=30;class Av{}class jv{}class UG0{}class DG0{}class b01 extends l0{props;constructor(J){super();this.props=J}createState(){return new Pg4}}class Pg4 extends d0{highlightedIndex=0;controller=new J$;focusNode;scrollController=new A5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new W6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;Uv(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 Av){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof jv){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof UG0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof DG0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,z=K4.of(J).size.width>=VI3+jg4,G=c1.all(new h1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,q=new i0({padding:C0.symmetric(1,0),child:new $0({text:new C("Select a cluster",new g({color:X.command,bold:!0}))})}),W=new CZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),U=new h$({shortcuts:new Map([[new D4("ArrowDown"),new Av],[new D4("ArrowUp"),new jv],[new D4("Tab"),new Av],[new D4("Tab",{shift:!0}),new jv],[new D4("n",{ctrl:!0}),new Av],[new D4("p",{ctrl:!0}),new jv],[new D4("Enter"),new UG0],[new D4("Escape"),new DG0]]),focusNode:this.focusNode,child:W}),D=new L2({actions:new Map([[Av,new U6(this.invoke)],[jv,new U6(this.invoke)],[UG0,new U6(this.invoke)],[DG0,new U6(this.invoke)]]),child:U}),H=new q1({children:[new i0({decoration:{color:Y.background},child:new $0({text:new C(">",new g({color:Y.foreground}))})}),new k1({child:D})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,R=Z?M.threads.some((m)=>m.id===Z):!1,_=j?X.selectionBackground:void 0,k=j?X.selectionForeground:Y.foreground,u=[new C(M.label,new g({color:k})),new C(` (${M.threads.length})`,new g({color:k,dim:!0}))];if(R)u.push(new C(" (current)",new g({color:j?X.selectionForeground:Y.success})));return new Rg4(new e1({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new i0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,u)})})}),(m)=>{this.itemContexts[A]=m})}),N=new x0({children:B,crossAxisAlignment:"start"}),w=new k1({child:new e1({onScroll:this.handleScroll,child:new T6({controller:this.scrollController,autofocus:!1,child:N})})}),O=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],L=F?new i0({padding:C0.all(1),child:new RR({threads:O,autofocus:!1,offsetY:2})}):null,E;if(z){let M=L?new k1({child:L}):new I0({width:jg4});E=new q1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,M]})}else{let M=[new k1({child:new e1({onScroll:this.handleScroll,child:new T6({controller:this.scrollController,autofocus:!1,child:N})})})];if(L)M.push(new k1({child:L}));E=new x0({crossAxisAlignment:"stretch",children:M})}return new i0({decoration:{border:G,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[q,H,new I0({height:1}),new k1({child:E})]})})}}class kJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!kJ._instance)kJ._instance=new kJ;return kJ._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()}}g0();class Cg4 extends d0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){I.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){I.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((K)=>K.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=f0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),K=X.length>0?this.getValidationError(X):null,V=this.getAvailableLabels(),G=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...V];return new a2({title:"Add Label",items:G,getLabel:(F)=>{if("__isCreateMarker"in F)return this.currentQuery.trim().toLowerCase();return F.name},onAccept:(F)=>{if("__isCreateMarker"in F)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(F.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:K||"Type to create a new label",renderItem:(F,q,W,U)=>{let D=q?Q.selectionBackground:void 0,H=q?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in F&&F.__isCreateMarker){let N=this.currentQuery.trim().toLowerCase();return new i0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,[new C("Create new label: ",new g({color:H})),new C(N,new g({color:H,bold:!0}))])})})}return new i0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(F.name,new g({color:H}))})})},filterItem:(F,q)=>{if(this.currentQuery!==q)this.currentQuery=q,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in F&&F.__isCreateMarker)return this.shouldShowCreateMarker(q);let U=q.trim().toLowerCase();return U.length===0||F.name.includes(U)},sortItems:(F,q,W)=>{let U="__isCreateMarker"in F.item&&F.item.__isCreateMarker,D="__isCreateMarker"in q.item&&q.item.__isCreateMarker;if(U&&!D)return-1;if(!U&&D)return 1;return q.score-F.score}})}}class h01 extends l0{props;constructor(J){super();this.props=J}createState(){return new Cg4}}class dz extends l0{props;constructor(J){super();this.props=J}createState(){return new Tg4}}class Tg4 extends d0{_spinner=new M3;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=c1.all(new h1(Q.foreground,1,"solid")),K=this._spinner.toBraille(),V=new $0({textAlign:"center",text:new C("",void 0,[new C(K,new g({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new g({color:Q.foreground}))])}),G=[new k1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[V]})})];if(this.widget.props.onAbort)G.push(new I0({height:2,child:new i0({padding:C0.symmetric(2,0),child:new $0({text:new C("",new g({dim:!0}),[new C("Press ",new g({color:Q.foreground})),new C("Esc",new g({color:Q.info})),new C(" to cancel",new g({color:Q.foreground}))])})})}));let F=new i0({decoration:new r4(Q.background,X),child:new I0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:G})})});if(this.widget.props.onAbort)return new s4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(q)=>{if(q.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:F});return F}}var la={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"}},HG0=["workspace","global","flag","default","external","skill","other"];function zI3(J){return Array.from(new Set(J))}function _g4(J){return zI3([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function Rv(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 _g4(J).length>0?"skill":"other"}function g01(J){return Rv(J)==="skill"}function Sg4(J){let Z=_g4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=Rv(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${la[Y].description}: ${Q}`}function kg4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}var yg4=process.platform==="win32"?" ":"█",vg4=process.platform==="win32"?"░":"█";class O9 extends l0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=yg4,thumbChar:K=vg4,showTrack:V=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=z,this.trackColor=G}createState(){return new xg4}}class xg4 extends d0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),X=this.context.findRenderObject()?.size.height??0;if(X===0||Z<=Q)return!1;let K=this.widget.getScrollInfo(),V=Math.min(1,Q/Z),z=Math.max(1,X*V),G=Math.max(0,Math.min(1,K.scrollOffset/(Z-Q))),F=X-z,q=Math.max(0,F*G),W=q+z;return J>=q&&J<=W}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let V=J.localPosition.y-this._dragStartY,z=Math.min(1,Q/Z),G=Math.max(1,K*z),F=K-G;if(F<=0)return;let q=Z-Q,W=F/q,U=V/W,D=Math.max(0,Math.min(q,this._dragStartOffset+U));this.widget.controller.jumpTo(D)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Q<=Y)return;let z=Math.min(1,Y/Q),G=Math.max(1,V*z),F=Q-Y,q=V-G,W=Math.max(0,Math.min(1,X/(Q-Y))),U=Math.max(0,q*W),D=U+G;if(Z>=U&&Z<=D)return;if(Z<U)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(F,X+Y))};build(J){return new e1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?b5.POINTER:b5.DEFAULT,child:new fg4({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 fg4 extends jk{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=yg4,thumbChar:K=vg4,showTrack:V=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=z,this.trackColor=G}createRenderObject(){return new ug4(this)}updateRenderObject(J){J.updateWidget(this)}}class ug4 extends v4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;J6(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:K}=this._calculateScrollbarMetrics();if(!K)return;let V=this._widget.trackColor,z=this._widget.thumbColor,G=process.platform==="win32",F=Y,q=Y+X;if(!G){let W=["▁","▂","▃","▄","▅","▆","▇","█"];for(let U=0;U<this.size.height;U++){let D="█",H=!0;if(U===Math.floor(F)){let B=1-(F-U),N=Math.floor(B*8);D=W[N]||"█",H=!1}else if(U===Math.floor(q)){let B=1-(q-U),N=Math.floor(B*8);D=W[N]||"█"}else if(U>F&&U<q)H=!1;J.setChar(Z,Q+U,D,{fg:z,bg:V,reverse:H},1)}return}for(let W=0;W<this.size.height;W++){let U=W+0.5,D=U>=F&&U<q,H=D?this._widget.thumbChar:this._widget.trackChar;J.setChar(Z,Q+W,H,{fg:D?z:V,bg:V,reverse:!1},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),K=Math.min(1,Z/J),V=Math.max(1,Y*K),z=Y-V;return{thumbStartFloat:Math.max(0,z*X),thumbSizeFloat:V,showScrollbar:!0}}}class IR extends l0{props;constructor(J){super();this.props=J}createState(){return new bg4}}class bg4 extends d0{scrollController=new A5;scrollAreaKey=new p7("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 n2}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=f0.of(J),Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let q=dz0(Q);return{title:q.title,type:q.type,description:q.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,K=c1.all(new h1(Z.colors.border,1,"solid")),V=new i0({padding:C0.symmetric(1,0),child:new $0({text:new C(Y.title,new g({color:X,bold:!0}))})}),z=this.isWidgetMessage(Q)?Q.widget:new $0({text:new C(Y.description,new g({color:Z.colors.foreground})),selectable:!0}),G=new k1({child:new g$({child:new i0({padding:C0.symmetric(1,0),child:new q1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new k1({child:new T6({controller:this.scrollController,autofocus:!0,child:z})}),new O9({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let q=this.scrollController.maxScrollExtent,W=this.scrollController.offset,U=this.getViewportHeight(),D=q+U;return{totalContentHeight:Math.max(D,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(W,0)}}})]})})})}),F=new i0({padding:C0.symmetric(1,0),child:new $0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new g({color:Z.colors.foreground,dim:!0})),new C("R",new g({color:Z.app.keybind})),new C(" to retry, ",new g({color:Z.colors.foreground,dim:!0})),new C("Esc",new g({color:Z.app.keybind})),new C(" to cancel",new g({color:Z.colors.foreground,dim:!0}))]);let q=this.resolveFooterStyle(this.widget.props.message);if(q==="none")return new C("",new g({color:Z.colors.foreground,dim:!0}));if(q==="help"){let W=new g({color:Z.app.keybind}),U=new g({color:Z.colors.foreground,dim:!0});return new C("",U,[new C("Press ",U),new C("Escape",W),new C(" to close • Use ",U),new C("↑↓",W),new C(" or ",U),new C("j/k",W),new C(" to scroll",U)])}return new C("Press any key to close",new g({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new s4({onKey:(q)=>{if(this.widget.props.onRetry&&q.key==="r")return this.widget.props.onRetry(),"handled";if(q.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 i0({decoration:{border:K,color:Z.colors.background},padding:C0.all(1),child:new x0({mainAxisAlignment:"center",children:[V,new I0({height:1}),G,F]})})})}}P2();class hg4 extends l0{props;constructor(J){super();this.props=J}createState(){return new gg4}}class gg4 extends d0{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=_9.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new $0({text:new C("No plugins found.",new g({dim:!0}))});let Y=[],X=this.plugins.length,K=this.plugins.filter((G)=>G.status==="active").length,V=this.plugins.reduce((G,F)=>G+F.registeredCommands.length,0),z=this.plugins.reduce((G,F)=>G+F.registeredTools.length,0);if(Y.push(new C(`${K}/${X} ${d4(X,"plugin")} active`,new g({bold:!0}))),V>0||z>0)Y.push(new C(` (${V} ${d4(V,"command")}, ${z} ${d4(z,"tool")})`,new g({dim:!0})));Y.push(new C(`
|
|
7375
7375
|
|
|
7376
7376
|
`));for(let G of this.plugins){let{icon:F,color:q}=this.statusIcon(G.status),W=this.getRelativePath(G.uri.toString());if(Y.push(new C(`${F} `,new g({color:q}))),Y.push(new C(W,new g({bold:!0}))),Y.push(new C(` ${G.status}`,new g({dim:!0}))),Y.push(new C(`
|
|
7377
7377
|
`)),G.status==="active"&&G.registeredEvents.length>0)Y.push(new C(" Events: ",new g({dim:!0}))),Y.push(new C(G.registeredEvents.join(", "),new g({color:Q.link}))),Y.push(new C(`
|
|
@@ -7600,7 +7600,7 @@ ${X0.content||""}`:X0.content||"",J1=[],H1=X0.baseDir.startsWith("file://")?eG0(
|
|
|
7600
7600
|
`),process.exit(1)}process.stdout.write(await s_3(G.result.displayText)+`
|
|
7601
7601
|
`),process.exit(0)})}nM();import{stdout as t_3}from"node:process";function e_3({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${EF(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function Tc4(J){t_3.write(`${e_3(J)}
|
|
7602
7602
|
`)}function _c4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{Tc4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{Tc4(Z),process.exit(0)})}var Lx3=PO.join(oZ,"logs","headless.log"),U51=PO.join(Ak,"device-id.json");async function Ex3(){for(let J of qE)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(() => z4($x(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){E7.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
7603
|
-
`)}function Mx3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",z=!1;J.warn(K,{name:V,code:Y})}}function r2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")aJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")aJ("experimental.agentMode",Z.mode)}function za4(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 Ax3(J){try{return await Ka4(J,"utf-8")}catch{return J}}async function D51(J,Z,Q){let Y=za4(J,Z);if(!Y)return;let X=m6(Q)?Q.features:[],K=m6(Q)?Q.user.email:void 0;if(!O51(X,P7.HARNESS_SYSTEM_PROMPT)&&!Ga4(K))throw new I1("You are not allowed to do this.",1);aJ("systemPrompt",await Ax3(Y))}function Ga4(J){return!!(J&&_10(J))}function O51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function H51(J){return(J.userEmail?$J(J.userEmail):!1)||O51(J.features,P7.DTW_TUI)}function tn4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new I1("This TUI mode is not enabled for your user;",1)}function B51(J,Z){if(typeof J==="boolean")return J;if(!m6(Z))return!1;return H51({userEmail:Z.user.email,features:Z.features})}function N51(J){if(!m6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function jx3(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 dF0(J){let Y=jx3(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 I1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function en4(J){if(!X5.write(J))await Bx3(X5,"drain")}var $a4=[{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??EK,description:`Custom settings file path (overrides the default location ${EK})`},{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 ${cA})`},{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:b2(),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:vG.SMART.key,description:`Set the agent mode (${EV().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:EV().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"threadActors",long:"thread-actors",type:"optional-option",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],Ja4=(J)=>("deprecated"in J)&&J.deprecated===!0,Rx3=(J)=>("hidden"in J)&&J.hidden===!0,Ix3=(J)=>("default"in J),Px3=(J)=>("default"in J)?J.default:void 0,Fa4=[{name:"toggle-skills-count",entryPoint:Vi0}];function Cx3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((z)=>Q.includes(z)||z.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new I1(L3.unknownCommand(Q),1,V)}}async function L51(J){return{...J,getThreadEnvironment:HZ,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new bV(J.fileSystem),generateThreadTitle:s80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>eZ(J.configService),pluginService:J.pluginService}}function qa4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:HZ,filesystem:J.fileSystem,threadService:J.threadService}}var cF0=X1.file(Va4.homedir()),w51=process.env.XDG_CONFIG_HOME?X1.file(process.env.XDG_CONFIG_HOME):K1.joinPath(cF0,".config");function Tx3(J){return AW4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){MW4(Z);let Q=oQ0(),Y=Mi0();if((!Q||Y||TM4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(QD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(QD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(oQ0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function _x3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function t9(J,Z,Q){let Y=Q?.deferAuth??!1;Pf1("0.0.
|
|
7603
|
+
`)}function Mx3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",z=!1;J.warn(K,{name:V,code:Y})}}function r2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")aJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")aJ("experimental.agentMode",Z.mode)}function za4(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 Ax3(J){try{return await Ka4(J,"utf-8")}catch{return J}}async function D51(J,Z,Q){let Y=za4(J,Z);if(!Y)return;let X=m6(Q)?Q.features:[],K=m6(Q)?Q.user.email:void 0;if(!O51(X,P7.HARNESS_SYSTEM_PROMPT)&&!Ga4(K))throw new I1("You are not allowed to do this.",1);aJ("systemPrompt",await Ax3(Y))}function Ga4(J){return!!(J&&_10(J))}function O51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function H51(J){return(J.userEmail?$J(J.userEmail):!1)||O51(J.features,P7.DTW_TUI)}function tn4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new I1("This TUI mode is not enabled for your user;",1)}function B51(J,Z){if(typeof J==="boolean")return J;if(!m6(Z))return!1;return H51({userEmail:Z.user.email,features:Z.features})}function N51(J){if(!m6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function jx3(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 dF0(J){let Y=jx3(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 I1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function en4(J){if(!X5.write(J))await Bx3(X5,"drain")}var $a4=[{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??EK,description:`Custom settings file path (overrides the default location ${EK})`},{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 ${cA})`},{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:b2(),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:vG.SMART.key,description:`Set the agent mode (${EV().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:EV().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"threadActors",long:"thread-actors",type:"optional-option",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],Ja4=(J)=>("deprecated"in J)&&J.deprecated===!0,Rx3=(J)=>("hidden"in J)&&J.hidden===!0,Ix3=(J)=>("default"in J),Px3=(J)=>("default"in J)?J.default:void 0,Fa4=[{name:"toggle-skills-count",entryPoint:Vi0}];function Cx3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((z)=>Q.includes(z)||z.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new I1(L3.unknownCommand(Q),1,V)}}async function L51(J){return{...J,getThreadEnvironment:HZ,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new bV(J.fileSystem),generateThreadTitle:s80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>eZ(J.configService),pluginService:J.pluginService}}function qa4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:HZ,filesystem:J.fileSystem,threadService:J.threadService}}var cF0=X1.file(Va4.homedir()),w51=process.env.XDG_CONFIG_HOME?X1.file(process.env.XDG_CONFIG_HOME):K1.joinPath(cF0,".config");function Tx3(J){return AW4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){MW4(Z);let Q=oQ0(),Y=Mi0();if((!Q||Y||TM4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(QD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(QD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(oQ0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function _x3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function t9(J,Z,Q){let Y=Q?.deferAuth??!1;Pf1("0.0.1774154108-geea41d");let X=d10({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(X1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:cF0,userConfigDir:w51});CM4(X);let K=await X.getLatest();I.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let F0=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(F0),I.info("API key lookup before login",{found:Boolean(F0),ampURL:J.ampURL,deferAuth:Y}),!F0)if(Y)I.info("No API key found, continuing startup with deferred auth");else{X5.write(`No API key found. Starting login flow...
|
|
7604
7604
|
`);let a=await Sx3(J),U0=await J.secrets.get("apiKey",J.ampURL);if(I.info("Login flow completed",{success:a,storedKeyPresent:Boolean(U0),ampURL:J.ampURL}),!a)await dF(),process.exit(1);V=!0}}{let F0=await X.getLatest(),a=F0.settings.url,U0=F0.secrets.isSet?.[a];I.info("Config secrets state after login",{configURL:a,apiKeySet:U0?.apiKey??!1})}let z=M1(eZ(X).pipe(L5((F0)=>F0!=="pending"))),G=Y?"pending":await z;if(!Y)I.info("Server status resolved",{status:"ready",isAuthenticated:m6(G),isError:hW(G),errorMessage:hW(G)?G.error.message:void 0});let{toolService:F,dispose:q}=NW4({configService:X}),W=new Map,U=()=>W.clear(),D=new A_0(X,J.settings.getWorkspaceRootPath()),H=It1({configService:X,filesystem:E8}),B=Ea1({configService:X,trustStore:D,skillMCPServers:H.skillMCPServers,createOAuthProvider:async(F0,a,U0)=>{let O0=`${F0}:${a}`,G0=W.get(O0);if(G0)return I.debug("Reusing existing OAuth provider for server",{serverName:F0,serverUrl:a}),G0;I.debug("Creating OAuth provider for server",{serverName:F0,serverUrl:a});let e=(async()=>{let W0=new LE(J.secrets),i=await W0.getClientInfo(F0,a),o=U0?.scopes??i?.scopes,t=zO4();I.info("OAuth headless mode check",{useHeadless:t,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:X5.isTTY});let Z0;if(t)Z0=J.executeMode?VO4():KO4(F0);let X0=new QI0({storage:W0,serverName:F0,serverUrl:a,clientId:U0?.clientId??i?.clientId,clientSecret:U0?.clientSecret??i?.clientSecret,authUrl:U0?.authUrl??i?.authUrl,tokenUrl:U0?.tokenUrl??i?.tokenUrl,scopes:o,headlessAuthHandler:Z0});return I.debug("OAuth provider created",{serverName:F0,serverUrl:a,hasManualClientId:!!(U0?.clientId??i?.clientId),willUseDCR:!(U0?.clientId??i?.clientId),scopes:o,headlessMode:t,executeMode:J.executeMode}),X0})();return W.set(O0,e),e}}),N=Rm0({configService:X,filesystem:E8,spawn:ZJ0}),w;if(J.executeMode){let F0=await EG4({toolService:F,providers:[B,N],initialTimeout:15000});w=F0.registrations;for(let[a,U0]of F0.initErrors)I.warn(`${a} provider initialization slow or failed:`,U0)}else w=Im0({toolService:F,providers:[B,N]});if(Z.jetbrains)VE("JetBrains");else if(Z.ide&&iO4())VE("VS Code");else if(Z.ide&&nO4())VE("Neovim");else if(Z.ide){let F0=await Ex3();if(F0){let a=t10(F0.ideName);if(a)VE(a)}}if(J.executeMode)Cf1(!0);let O,L=N$.status.pipe(W1((F0)=>Boolean(F0.connected&&F0.authenticated&&F0.ideName&&Wu1(F0.ideName))),y4()).subscribe((F0)=>{if(F0){if(!O)O=F.registerTool(LG4)}else O?.dispose(),O=void 0}),E;if(!J.executeMode){let F0=await J.settings.get("fuzzy.alwaysIncludePaths")??[];E=new uZ0(process.cwd(),{alwaysIncludePaths:F0},!0)}else E=new class extends uZ0{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let M=await kt1({isDevelopment:!1}),A=new Ay0(M,X),j=new Dk0(M,{lazy:!0,maxThreads:200});I.info("Starting Amp background services");let R=Z.takeMeBack?!1:void 0,_=B51(R,G),k=Boolean(_||Z.headless);if(k)I.info("DTW mode enabled: thread sync service disabled");let u=k?_x3():z04({threadService:A,threadHistoryService:j,configService:X,isExtensionDevelopment:!1}),m;N$.status.subscribe((F0)=>{m=F0});let x=new dj0({workspaceRoots:[X1.file(process.cwd())],fileSystem:E8,getCurrentFile:()=>{if(!m?.openFile)return;try{return X1.parse(m.openFile)}catch(F0){I.warn("Failed to parse current file URI",{uri:m.openFile,error:F0});return}},getOpenFiles:()=>{if(!m?.visibleFiles?.length)return[];let F0=m.openFile;return m.visibleFiles.filter((a)=>a!==F0).map((a)=>{try{return X1.parse(a)}catch(U0){return I.warn("Failed to parse visible file URI",{uri:a,error:U0}),null}}).filter((a)=>a!==null)}}),T=new Ri0,f=process.env.PLUGINS??"off",p=Z.headless?WM4():void 0,d=p??new dQ0({configService:X}),h=d instanceof dQ0?d:void 0;if(h)h.pluginExecutorKind=_?"local":"unknown";let n=h_0({configService:X,fileSystem:E8,platform:d,internalPlugins:Fa4,pluginFilter:f}),c=Ho1({pluginService:n,toolService:F}),s={codebaseContextService:x,configService:X,toolService:F,mcpService:B,skillService:H,toolboxService:N,trustStore:D,threadService:A,threadHistoryService:j,threadSyncService:u,threadStorage:M,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:E,fileSystem:E8,terminal:T,pluginService:n,pluginPlatform:h,headlessPluginPlatform:p,serverStatus:G,serverStatusPromise:z,hasAPIKeyAtStartup:V};return{...s,async asyncDispose(){if(s.mcpService.hasAuthenticatingClients())I.info("Waiting for OAuth authentication to complete before exit..."),await s.mcpService.waitForAuthentication();for(let F0 of w.values())F0.dispose();await s.mcpService.dispose(),U(),await s.threadService.asyncDispose(),s.configService.unsubscribe(),q(),s.fuzzyServer.dispose(),s.threadSyncService.dispose(),s.settingsStorage[Symbol.dispose](),L.unsubscribe(),O?.dispose(),c.dispose(),await s.pluginService.dispose()}}}async function Sx3(J){if(!J.executeMode){if(!await gQ0("Would you like to log in to Amp? [(y)es, (n)o]: "))return X5.write(`Login cancelled. Run the command again to retry.
|
|
7605
7605
|
`),!1}return await Wa4(J)}async function Wa4(J){let Z=Hx3(32).toString("hex"),Q=await kk(J.ampURL,Z),Y=new AbortController;try{await wV(Q,Y.signal)}catch(K){I.error("Error opening browser",{error:K})}let X=await kk(J.ampURL,Z,!1);X5.write(`If your browser does not open automatically, visit:
|
|
7606
7606
|
|
|
@@ -7608,7 +7608,7 @@ ${c0.blue.bold(X)}
|
|
|
7608
7608
|
|
|
7609
7609
|
`);try{return await lE4(J.ampURL,Z,J.secrets,Y),X5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(K){return I.error("Login failed",{error:K}),E7.write(`
|
|
7610
7610
|
Login failed: ${K instanceof Error?K.message:String(K)}
|
|
7611
|
-
`),!1}}function Za4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function kx3(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 I1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!f9(Y.threadId))throw new I1("Create response did not include a valid thread ID",1);return Y.threadId}function yx3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function vx3(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 I1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!yx3(Q))throw new I1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function xx3(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 fx3(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 I1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function ux3(){let J=new mN().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)iA(),process.exit(0);let B=H.originalError??H;Ww4(B)}),_c4(J,{version:"0.0.
|
|
7611
|
+
`),!1}}function Za4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function kx3(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 I1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!f9(Y.threadId))throw new I1("Create response did not include a valid thread ID",1);return Y.threadId}function yx3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function vx3(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 I1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!yx3(Q))throw new I1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function xx3(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 fx3(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 I1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function ux3(){let J=new mN().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)iA(),process.exit(0);let B=H.originalError??H;Ww4(B)}),_c4(J,{version:"0.0.1774154108-geea41d",buildTimestamp:"2026-03-22T04:38:48.639Z",buildType:"'release'"}),J.addHelpText("after",dO4()),J.configureHelp({formatHelp:cO4}),J.command("logout").description("Log out by removing stored API key").action(async(H,B)=>{let N=B.optsWithGlobals(),w=await m3(N);await cx3(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 m3(N);await dx3(w,await Vl0(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(),O=await m3(w);await bw4(H??"get",O.ampURL,O.secrets),process.exit(process.exitCode??0)}),J.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(H,B)=>{let N=B.optsWithGlobals(),w=await m3(N);await hw4(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",`
|
|
7612
7612
|
Actions:
|
|
7613
7613
|
create Create a new DTW thread and print its ID
|
|
7614
7614
|
add-message <message> Send a user message and wait for message_added
|
|
@@ -7672,8 +7672,8 @@ ${E}
|
|
|
7672
7672
|
|
|
7673
7673
|
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 bx3(J){I.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new Ln({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:HZ,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new bV(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 hx3(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await uk()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await uk()).trimEnd(),stdinInput:null}}function gx3(J,Z,Q){if(J.remote&&!Z)throw new I1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new I1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new I1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new I1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new I1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new I1("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 I1("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Z&&Q===""&&!J.streamJsonInput&&!J.headless)throw new I1("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"
|
|
7674
7674
|
Or pipe via stdin: echo "your message" | amp --execute`)}async function lF0(J,Z,Q){let Y=process.hrtime.bigint(),X=(G0,e)=>{let W0=Number(process.hrtime.bigint()-e)/1e6,i=WU4();I.info("Startup phase",{phase:G0,phaseMs:Math.round(W0),sinceMainMs:i===null?void 0:Math.round(i)})},{userInput:K,stdinInput:V}=await hx3(Z),z=!!Z.streamJson||!!Z.streamJsonThinking;gx3({...Z,streamJson:z},J.executeMode,K),r2(Q,Z);let G=process.hrtime.bigint(),F=Boolean(await J.secrets.get("apiKey",J.ampURL)),q=!J.executeMode&&!Z.headless&&!Z.threadActors&&F;I.info("Interactive auth startup mode",{deferInteractiveAuth:q,hasAPIKeyAtStartup:F,executeMode:J.executeMode,headless:Boolean(Z.headless)});let W=await t9(J,Z,{deferAuth:q});X("runMainThread:createThreadDependencies",G),G=process.hrtime.bigint();let U=await L51(W);X("runMainThread:createWorkerDeps",G);let{serverStatus:D}=W;if(!q&&hW(D)){let G0=Hk(Error(D.error.message));if(G0.message===L3.networkOffline||G0.message===L3.networkTimeout)throw dF0(J.ampURL);throw new I1(L3.invalidAPIKey,1)}let H=m6(D)?D:null,B=H?.user.email,N=Ga4(B),w=H51({userEmail:B,features:H?.features}),O=Z.takeMeBack?!1:void 0,L=H!==null&&B51(O,H);if(!q)await D51(Q,Z,D);let E=N51(D),M=E?.features??[],A=E?.team??null,j=mQ0(Z,E);if(j instanceof Error)p3(j.message);if((J.executeMode||z)&&w8(Z.mode)&&!N)throw new I1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(H&&!dH(Z.mode,B))throw new I1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await HM4(K,V,W.configService),await W.asyncDispose(),process.exit(0);if(Z.threadActors){if(!B||!$J(B))throw new I1("Thread-actors mode is only available for Amp employees",1);let G0=await W.secretStorage.get("apiKey",J.ampURL);if(!G0)throw new I1("API key required. Please run `amp login` first.",1);let e=typeof Z.threadActors==="string"&&Z.threadActors!=="true"?Z.threadActors:void 0;await u_4({configService:W.configService,apiKey:G0,threadId:e}),await W.asyncDispose(),await dF(),process.exit(0)}if(Z.headless){if(!B||!$J(B))throw new I1("Headless DTW mode is only available for Amp employees",1);let G0=await W.secretStorage.get("apiKey",J.ampURL);if(!G0)throw new I1("API key required for headless mode. Please run `amp login` first.",1);let e=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if(e&&!f9(e))throw new I1(`Invalid thread ID: ${e}`,1);let W0=e??await tx3({dependencies:W,visibility:j??void 0}),i=await WO4(W0);if(i.status==="already-running")await W.asyncDispose(),await dF(),process.exit(0);try{await XO4({ampURL:J.ampURL,apiKey:G0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:W0,initialToolDiscovery:Promise.all([W.mcpService.initialized,W.toolboxService.initialized]).then(()=>{return}),configService:W.configService,mcpService:W.mcpService,toolService:W.toolService,skillService:W.skillService,fileSystem:W.fileSystem,pluginService:W.pluginService,pluginPlatform:W.headlessPluginPlatform})}finally{await i.release(),await W.asyncDispose()}await dF(),process.exit(0)}let R=J.executeMode?void 0:async(G0)=>fo(G0,"interactive"),_={threadService:W.threadService,workerDeps:U,createThread:async()=>{let G0=q?await W.serverStatusPromise:D,e=await MZ0(J.settings,process.cwd(),N51(G0),j);if(e instanceof Error)p3(e.message);return Pe0(U,{threadMeta:e?Oz(e):void 0,agentMode:Z.mode,onFirstAssistantMessage:R})},validateThreadOwnership:async(G0,e)=>{if(e?.nonBlockingOwnershipCheck){Qa4(G0,W.configService).catch((W0)=>{if(W0 instanceof I1){if(e.onOwnershipError){e.onOwnershipError(W0,G0);return}Bk(W0,G0);return}I.warn("Failed to validate thread ownership in CLI, allowing to open",{error:W0})});return}try{await Qa4(G0,W.configService)}catch(W0){if(W0 instanceof I1)throw W0;I.warn("Failed to validate thread ownership in CLI, allowing to open",{error:W0})}},switchThreadVisibility:j,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:R},k=async(G0)=>{try{if(G0==="dtw")return bx3({ampURL:J.ampURL,configService:W.configService,threadService:W.threadService,mcpService:W.mcpService,toolboxService:W.toolboxService,toolService:W.toolService,skillService:W.skillService,fileSystem:W.fileSystem,threadId:Z.threadId});return zu4(_,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(e){if(e instanceof I1)throw e;throw await Bk(e,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")E7.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
7675
|
-
`),await dF(),process.exit(1);let u=(async()=>{if(q){I.info("Skipping initial free tier status fetch until auth is complete");return}try{let G0=await W.configService.getLatest(),e=Hb(G0),W0=await g6.getUserFreeTierStatus({},{config:W.configService,signal:AbortSignal.timeout(e)});if(W0.ok)return I.info("User free tier status:",W0),W0.result;return}catch(G0){I.error("Failed to fetch free tier status:",G0);return}})(),x=!J.executeMode?new Ar0:null,T,f=null;if(x)T=x,f=(async()=>{let G0=q?await W.serverStatusPromise:W.serverStatus;await D51(Q,Z,G0);let e=process.hrtime.bigint(),W0=B51(O,G0),i=m6(G0)?H51({userEmail:G0.user.email,features:G0.features}):!1;tn4({dtwEnabled:W0,hasV2TUIAccess:i});let o=await k(W0?"dtw":"worker");if(X("runMainThread:createThreadPool",e),x.attach(o),K){let t=await M1(o.threadHandles$);if(!t)throw new I1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:K}]})}})(),f.catch(async(G0)=>{let e=G0 instanceof Error?G0:Error(String(G0));x.setInitError(e),await Bk(G0,Z.threadId)});else G=process.hrtime.bigint(),tn4({dtwEnabled:L,hasV2TUIAccess:w}),T=await k(L?"dtw":"worker"),X("runMainThread:createThreadPool",G);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;G=process.hrtime.bigint();let d=await W.configService.getLatest();if(X("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),Tx3({configService:W.configService,threadService:W.threadService,config:d,useNotificationsForService:p,threadViewStates$:()=>T.threadHandles$.pipe(q4((G0)=>{if(!G0)return k0.of({});return V5(G0.thread$,G0.threadViewState$).pipe(W1(([e,W0])=>({[e.id]:W0})))}))}),X("runMainThread:createCliNotificationService",G),J.executeMode){QM4(W.mcpService,J.settings);let G0={userInput:K,stdinInput:V,dependencies:W,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},e=await Aw4({threadPool:T,...G0});if(await fo(e,"execute"),Z.archive)await g6.archiveThread({thread:e,archived:!0},{config:W.configService});await W.asyncDispose(),process.exit(0)}let h=!1,n=!1;if(Z.jetbrains||Z.ide){await wu1();let G0=await UE({jetbrainsOnly:Z.jetbrains});if(G0.length===0){if(Z.jetbrains)h=!await W.configService.get("jetbrains.skipInstall")}else if(G0.length===1){let e=G0[0];if(e)N$.selectConfig(e)}else n=!0}G=process.hrtime.bigint();let c=Pl0("0.0.
|
|
7676
|
-
`);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 Ia1({get:async(z)=>{if(z!==zg)return;try{let G=await Ka4(U51,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==zg)return;await Xa4(PO.dirname(U51),{recursive:!0}),await Nx3(U51,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:kG()});Tf1(Y);let X=await RO4({...J,workspaceTrust:{current:!0,changes:su},getHook:process.env.AMP_URL?(z,G)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let z=await JM4(J.mcpConfig);X=ZM4(X,z)}let K=PO.dirname(X.getSettingsFilePath());EW4(Ak,K);let V=await X.get("url","global");if(!V)V=V2;if(I.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!OV(V))I.info("Targeting custom Amp server",{ampURL:V});return X=wf1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:LM4(await Vl0(J,X))}}function mx3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}async function px3(){qU4();let J=mx3(process.argv),Z=process.argv.includes("--headless")||process.argv.some((K)=>K.startsWith("--headless="));jN4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?Lx3: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)c0.level=0;if(Mx3(I),I.info("Starting Amp CLI.",{version:"0.0.
|
|
7675
|
+
`),await dF(),process.exit(1);let u=(async()=>{if(q){I.info("Skipping initial free tier status fetch until auth is complete");return}try{let G0=await W.configService.getLatest(),e=Hb(G0),W0=await g6.getUserFreeTierStatus({},{config:W.configService,signal:AbortSignal.timeout(e)});if(W0.ok)return I.info("User free tier status:",W0),W0.result;return}catch(G0){I.error("Failed to fetch free tier status:",G0);return}})(),x=!J.executeMode?new Ar0:null,T,f=null;if(x)T=x,f=(async()=>{let G0=q?await W.serverStatusPromise:W.serverStatus;await D51(Q,Z,G0);let e=process.hrtime.bigint(),W0=B51(O,G0),i=m6(G0)?H51({userEmail:G0.user.email,features:G0.features}):!1;tn4({dtwEnabled:W0,hasV2TUIAccess:i});let o=await k(W0?"dtw":"worker");if(X("runMainThread:createThreadPool",e),x.attach(o),K){let t=await M1(o.threadHandles$);if(!t)throw new I1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:K}]})}})(),f.catch(async(G0)=>{let e=G0 instanceof Error?G0:Error(String(G0));x.setInitError(e),await Bk(G0,Z.threadId)});else G=process.hrtime.bigint(),tn4({dtwEnabled:L,hasV2TUIAccess:w}),T=await k(L?"dtw":"worker"),X("runMainThread:createThreadPool",G);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;G=process.hrtime.bigint();let d=await W.configService.getLatest();if(X("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),Tx3({configService:W.configService,threadService:W.threadService,config:d,useNotificationsForService:p,threadViewStates$:()=>T.threadHandles$.pipe(q4((G0)=>{if(!G0)return k0.of({});return V5(G0.thread$,G0.threadViewState$).pipe(W1(([e,W0])=>({[e.id]:W0})))}))}),X("runMainThread:createCliNotificationService",G),J.executeMode){QM4(W.mcpService,J.settings);let G0={userInput:K,stdinInput:V,dependencies:W,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},e=await Aw4({threadPool:T,...G0});if(await fo(e,"execute"),Z.archive)await g6.archiveThread({thread:e,archived:!0},{config:W.configService});await W.asyncDispose(),process.exit(0)}let h=!1,n=!1;if(Z.jetbrains||Z.ide){await wu1();let G0=await UE({jetbrainsOnly:Z.jetbrains});if(G0.length===0){if(Z.jetbrains)h=!await W.configService.get("jetbrains.skipInstall")}else if(G0.length===1){let e=G0[0];if(e)N$.selectConfig(e)}else n=!0}G=process.hrtime.bigint();let c=Pl0("0.0.1774154108-geea41d",W.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let s=new Uk0(W.threadStorage);X("runMainThread:createThreadFuzzyIndexer",G),G=process.hrtime.bigint();let F0=new Ki0(W.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",G),K&&J.executeMode){let G0=await M1(T.threadHandles$);if(!G0)throw new I1("No active thread is available yet.",1);await G0.sendMessage({content:[{type:"text",text:K}]})}G=process.hrtime.bigint();let a=await lQ0();X("runMainThread:loadSessionState",G),I.info("Loaded session state:",a);let U0={...a,launchCount:a.launchCount+1};Kj((G0)=>({...G0,launchCount:G0.launchCount+1}));let O0=Z.threadId&&f9(Z.threadId)?Z.threadId:void 0;try{if(G=process.hrtime.bigint(),await su4({codebaseContextService:W.codebaseContextService,history:new dc0,fuzzyServer:W.fuzzyServer,settingsStorage:W.settingsStorage,threadService:W.threadService,threadHistoryService:W.threadHistoryService,threadFuzzyIndexer:s,skillService:W.skillService,configService:W.configService,secretStorage:W.secretStorage,internalAPIClient:g6,threadPool:T,createSystemPromptDeps:async()=>qa4(W),ideClient:N$,mcpService:W.mcpService,toolboxService:W.toolboxService,mcpTrustHandler:F0,updateService:c,pluginPlatform:W.pluginPlatform,pluginService:W.pluginService},{initialServerStatus:W.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:W.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:O0,showJetBrainsInstaller:h,showIdePickerHint:n,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:U0,freeTierStatusPromise:u,workspace:A??null,features:M,isDogfooding:N,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-22T04:38:48.639Z"},(G0)=>new ge0({...G0,threadPool:G0.threadPool},(e)=>new h41({...e,threadState:e.threadState}))),X("runMainThread:mountApp-returned",G),f)await f}finally{}await W.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function m3(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)E7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
7676
|
+
`);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 Ia1({get:async(z)=>{if(z!==zg)return;try{let G=await Ka4(U51,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==zg)return;await Xa4(PO.dirname(U51),{recursive:!0}),await Nx3(U51,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:kG()});Tf1(Y);let X=await RO4({...J,workspaceTrust:{current:!0,changes:su},getHook:process.env.AMP_URL?(z,G)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let z=await JM4(J.mcpConfig);X=ZM4(X,z)}let K=PO.dirname(X.getSettingsFilePath());EW4(Ak,K);let V=await X.get("url","global");if(!V)V=V2;if(I.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!OV(V))I.info("Targeting custom Amp server",{ampURL:V});return X=wf1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:LM4(await Vl0(J,X))}}function mx3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}async function px3(){qU4();let J=mx3(process.argv),Z=process.argv.includes("--headless")||process.argv.some((K)=>K.startsWith("--headless="));jN4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?Lx3: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)c0.level=0;if(Mx3(I),I.info("Starting Amp CLI.",{version:"0.0.1774154108-geea41d",buildTimestamp:"2026-03-22T04:38:48.639Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new I1(L3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await ux3().parseAsync(process.argv)}OW4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await px3().catch(Bk)});async function dx3(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"),X5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
7677
7677
|
`);else if(!OV(J.ampURL))X5.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
7678
7678
|
`);let Y=process.env.AMP_API_KEY;if(Y)X5.write(`API key found in environment variable, storing...
|
|
7679
7679
|
`),await Z.set("apiKey",Y,J.ampURL),X5.write(`API key successfully stored.
|