@sourcegraph/amp 0.0.1774539491-g39ae67 → 0.0.1774542102-g618b9f
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
|
@@ -6204,11 +6204,11 @@ ${H}`))}},error:(U)=>{if(!W)W=!0,G(Error(`Failed to spawn brew: ${U.message}`))}
|
|
|
6204
6204
|
${H}`;if(X==="pnpm"&&H.includes("Unable to find the global bin directory"))D+=`
|
|
6205
6205
|
|
|
6206
6206
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
6207
|
-
npm install -g @sourcegraph/amp`;G(Error(D))}},error:(U)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}g0();g0();JA();async function PX0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let G=await fetch(X,{signal:K.signal});if(!G.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let z=await G.json(),F=z.version??z["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=cC4(J,F),W=q<0,U,H;if(z.time){let D=z.time[J],B=z.time[F],N=Date.now();if(D)U=Math.floor((N-new Date(D).getTime())/3600000);if(B)H=Math.floor((N-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:U,latestVersionAge:H}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:U,latestVersionAge:H,source:"npm"}}catch(G){return P.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var tQ3="https://static.ampcode.com/cli/cli-version.txt";async function CX0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${tQ3}?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=cC4(J,X),V=K<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return P.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var eQ3=604800000;function dC4(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>eQ3)return{ageMs:Q};return null}function cC4(J,Z){let Q=(V)=>{let[G,z]=V.split("-");return{parts:G?.split(".").map(Number)||[],label:z}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let G=Y.parts[V]||0,z=X.parts[V]||0;if(G<z)return-1;if(G>z)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function go0(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?PF(Q):void 0;return{sha:Y,age:X}}catch{return null}}w1();function mo0(J,Z,Q={}){let Y=new e1,X=Y.pipe(c6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new kz().scoped("update"),V=Q.startDelayMs??0;if(V>0)await XF(V);let G=X.subscribe({next:(z)=>{K.debug("emit new state",z)}});try{let z=process.env.AMP_TEST_UPDATE_STATUS;if(z){K.debug("using fake update status for testing",{status:z}),await XF(500),Y.next(z);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){K.debug("checking disabled");return}let q=await IX0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await CX0(J):await PX0(J,bj());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let H=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let D=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(D)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:D}),!0}return!1};if(!F)F=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:F});if(q==="brew"){if(!H())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==vo0()){if(K.debug("non-standard binary path, showing warning"),!H())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!H())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Y.next("update-available");return}try{await zn(U.latestVersion,q);let D=await Pw(U.latestVersion),B={from:U.currentVersion,to:U.latestVersion,...D};if(D.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(D){Y.next("update-error")}}catch(z){K.debug("check failed",{error:z})}finally{await XF(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}JA();import{stderr as Oq}from"node:process";function lC4(J){let Z=new aN().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 _o0(Y.force||!1,Y.verbose||!1,"0.0.
|
|
6207
|
+
npm install -g @sourcegraph/amp`;G(Error(D))}},error:(U)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}g0();g0();JA();async function PX0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let G=await fetch(X,{signal:K.signal});if(!G.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let z=await G.json(),F=z.version??z["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=cC4(J,F),W=q<0,U,H;if(z.time){let D=z.time[J],B=z.time[F],N=Date.now();if(D)U=Math.floor((N-new Date(D).getTime())/3600000);if(B)H=Math.floor((N-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:U,latestVersionAge:H}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:U,latestVersionAge:H,source:"npm"}}catch(G){return P.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var tQ3="https://static.ampcode.com/cli/cli-version.txt";async function CX0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${tQ3}?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=cC4(J,X),V=K<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return P.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var eQ3=604800000;function dC4(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>eQ3)return{ageMs:Q};return null}function cC4(J,Z){let Q=(V)=>{let[G,z]=V.split("-");return{parts:G?.split(".").map(Number)||[],label:z}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let G=Y.parts[V]||0,z=X.parts[V]||0;if(G<z)return-1;if(G>z)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function go0(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?PF(Q):void 0;return{sha:Y,age:X}}catch{return null}}w1();function mo0(J,Z,Q={}){let Y=new e1,X=Y.pipe(c6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new kz().scoped("update"),V=Q.startDelayMs??0;if(V>0)await XF(V);let G=X.subscribe({next:(z)=>{K.debug("emit new state",z)}});try{let z=process.env.AMP_TEST_UPDATE_STATUS;if(z){K.debug("using fake update status for testing",{status:z}),await XF(500),Y.next(z);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){K.debug("checking disabled");return}let q=await IX0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await CX0(J):await PX0(J,bj());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let H=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let D=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(D)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:D}),!0}return!1};if(!F)F=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:F});if(q==="brew"){if(!H())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==vo0()){if(K.debug("non-standard binary path, showing warning"),!H())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!H())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Y.next("update-available");return}try{await zn(U.latestVersion,q);let D=await Pw(U.latestVersion),B={from:U.currentVersion,to:U.latestVersion,...D};if(D.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(D){Y.next("update-error")}}catch(z){K.debug("check failed",{error:z})}finally{await XF(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}JA();import{stderr as Oq}from"node:process";function lC4(J){let Z=new aN().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 _o0(Y.force||!1,Y.verbose||!1,"0.0.1774542102-g618b9f"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new aN("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 $Y3(Y.targetVersion)});J.addCommand(Q)}async function $Y3(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")Oq.write(c0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
6208
6208
|
|
|
6209
6209
|
`));try{if(!J){Oq.write(c0.blue(`Checking for updates...
|
|
6210
|
-
`));let{hasUpdate:Y,latestVersion:X}=So0()?await CX0("0.0.
|
|
6211
|
-
`));let G=await Pw("0.0.
|
|
6210
|
+
`));let{hasUpdate:Y,latestVersion:X}=So0()?await CX0("0.0.1774542102-g618b9f"):await PX0("0.0.1774542102-g618b9f",bj());if(!Y){let K=go0("0.0.1774542102-g618b9f"),V=K?.age?`released ${K.age} ago`:`built ${PF(new Date("2026-03-26T16:25:35.143Z"))} ago`;Oq.write(c0.green(`✓ Amp is already up to date on version ${"0.0.1774542102-g618b9f"} (${V})
|
|
6211
|
+
`));let G=await Pw("0.0.1774542102-g618b9f");if(G.warning)Oq.write(`
|
|
6212
6212
|
`+c0.yellow(G.warning)+`
|
|
6213
6213
|
`);process.exit(0)}if(!X)Oq.write(c0.yellow("[WARN] could not find latest version")),process.exit(0);J=X}Oq.write(c0.blue(`Updating to version ${J}...
|
|
6214
6214
|
`)),await zn(J,void 0,(Y)=>{Oq.write(c0.dim(`Running: ${Y}
|
|
@@ -7379,7 +7379,7 @@ Ctrl-X, Y, Z to unlock`;if(U){let f=F.text.replace(/`([^`]+)`/g,"$1")+`
|
|
|
7379
7379
|
`),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(`
|
|
7380
7380
|
`))}return new i0({decoration:{color:Q.colorScheme.background,border:d1.all(new h1(Y.app.keybind,1,"rounded"))},child:new a0({padding:C0.symmetric(0,1),child:new J0({text:new C(void 0,void 0,K)})})})}}class X11 extends u${chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=Nz0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new Q11({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 dg4(J,Z,Q,Y,X,K,V){if(K<=0)return null;switch(J){case"horizontal-bar":{let G=Q;return G>=0&&G<K?G:null}case"bar":case"stacked-bar":{let G=V?y9:0,z=Y-G;if(z<=0)return null;let F=Z-G;if(F<0||F>=z)return null;let q=Math.max(1,Math.floor(z/K)),W=Math.floor(F/q);return W>=0&&W<K?W:null}case"line":case"sparkline":case"stacked-area":{let G=V?y9:0,z=Y-G;if(z<=0)return null;let F=Math.max(0,Math.min(z-1,Z-G));if(K===1)return 0;let q=z/(K-1),W=Math.round(F/q);return Math.max(0,Math.min(K-1,W))}default:return null}}function dI3(J,Z,Q,Y,X,K,V,G){if(X<=0||Z<0||Z>=X)return null;let z=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let F=K?y9:0,q=Q-F,W=Y-(K?z:0);if(q<=0||W<=0)return null;let U=Math.max(1,Math.floor(q/X)),H=F+Z*U+Math.floor(U/2),D=G>0?V/G:0,B=Math.round((1-D)*(W-1));return{x:H,y:B}}case"line":case"sparkline":case"stacked-area":{let F=K?y9:0,q=Q-F,W=Y-(K?z:0);if(q<=0||W<=0)return null;let U=X>1?F+Math.round(Z/(X-1)*(q-1)):F+Math.floor(q/2),H=G>0?V/G:0,D=Math.round((1-H)*(W-1));return{x:U,y:D}}default:return null}}function cI3(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 lI3(J,Z,Q,Y,X){if(Q.length<=1){let G=Y(J.value),z=J.meta?` (${J.meta})`:"";return J.label.length+2+G.length+z.length}let K=J.label.length,V=0;for(let G of Q){let z=G.points[Z];if(!z)continue;V+=z.value;let F=2+G.name.length+2+Y(z.value).length;K=Math.max(K,F)}if(X){let G=9+Y(V).length;K=Math.max(K,G)}return K}function iI3(J,Z,Q,Y,X,K,V){let G;try{let D=T1.of(J),B=f0.of(J);G={foreground:D.colorScheme.foreground,background:D.colorScheme.background,border:B.app.keybind}}catch{G={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let z=new g({color:G.foreground,bold:!0}),F=new g({color:G.foreground}),q=new g({color:G.foreground,dim:!0}),W=[],U=new g({color:G.foreground,underline:!0}),H=(D,B)=>new C(B,U,void 0,hX0(D),()=>{t3(J,D)});if(Y.length<=1){if(W.push(new C(`${Z.label}: `,z)),Z.link)W.push(H(Z.link,K(Z.value)));else W.push(new C(K(Z.value),F));if(Z.meta)W.push(new C(` (${Z.meta})`,q))}else{let D=V==="stacked-bar"||V==="stacked-area";W.push(new C(`${Z.label}
|
|
7381
7381
|
`,z));let B=0;for(let N=0;N<Y.length;N++){let w=Y[N],L=w.points[Q];if(!L)continue;B+=L.value;let O=w.color??X[N%X.length]??G.foreground;if(W.push(new C("● ",new g({color:O}))),W.push(new C(`${w.name}: `,q)),L.link)W.push(H(L.link,K(L.value)));else W.push(new C(K(L.value),F));if(N<Y.length-1||D)W.push(new C(`
|
|
7382
|
-
`))}if(D)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),F))}return new i0({decoration:{color:G.background,border:d1.all(new h1(G.border,1,"rounded"))},child:new J0({text:new C(void 0,void 0,W)})})}WE();g0();_2();import{execSync as OP3}from"node:child_process";wE();O$();f3();T7();nd();JA();jV();XJ();eJ();HY();yA();f4();Ym();Qb();w1();var dm4=G4(QU(),1);import{writeFile as bm4}from"fs/promises";import hm4 from"path";g0();XJ();class K11{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.1774539491-g39ae67"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await a40(Z,this.configService)}catch(Z){P.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class DL extends l0{props;constructor(J){super();this.props=J}createState(){return new cg4}}class cg4 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 lg4 extends d0{controller=new Y$;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,G=d1.all(new h1(Q.foreground,1,"solid")),z=new TZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(H)=>{let D=H.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new q1({children:[new i0({decoration:{color:Q.background},child:new J0({text:new C(">",new g({color:Q.foreground}))})}),new k1({child:z})]}),q=new i0({padding:C0.symmetric(1,0),child:new J0({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 J0({text:new C("",void 0,W)})});return new i0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new I0({height:1}),F,new b3,U]})})}}class $o extends l0{props;constructor(J){super();this.props=J}createState(){return new lg4}}import{isDeepStrictEqual as V11}from"node:util";var nI3=/[\\/_ +.#"@[({&]/,aI3=/[\\/_ +.#"@[({&]/g,oI3=/[\s-]/,ig4=/[\s-]/g;function Oz0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let G=`${X},${K}`;if(V[G]!==void 0)return V[G];let z=Y.charAt(K),F=Q.indexOf(z,X),q=0,W,U,H,D;while(F>=0){if(W=Oz0(J,Z,Q,Y,F+1,K+1,V),W>q){if(F===X)W*=1;else if(oI3.test(J.charAt(F-1))){if(W*=0.9,D=J.slice(X,F-1).match(ig4),D&&X>0)W*=0.999**D.length}else if(nI3.test(J.charAt(F-1))){if(W*=0.8,H=J.slice(X,F-1).match(aI3),H&&X>0)W*=0.999**H.length}else if(W*=0.3,X>0)W*=0.999**(F-X);if(J.charAt(F)!==Z.charAt(K))W*=0.9999}if(W<0.1&&(Q.charAt(F-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(F-1)!==Y.charAt(K))){if(U=Oz0(J,Z,Q,Y,F+1,K+2,V),U*0.1>W)W=U*0.1}if(W>q)q=W;F=Q.indexOf(z,F+1)}return V[G]=q,q}function Lz0(J){return J.toLowerCase().replace(ig4," ")}function ng4(J,Z){let Q=Oz0(J,Z,Lz0(J),Lz0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let G of Y){let z=Oz0(J,G,Lz0(J),Lz0(G),0,0,{});if(z===0)return Q;X+=z,K+=G.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class Pv{}class Cv{}class Ez0{}class Mz0{}class ag4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new og4}}class og4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}function rI3(J,Z){if(J==="")return{matches:!0,score:1};let Q=ng4(Z,J);return{matches:Q>0.15,score:Q}}class r2 extends l0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new rg4}}class rg4 extends d0{textController;focusNode;scrollController=new j5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new Y$(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)=>V11(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!V11(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>V11(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 Pv){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 Cv){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 Ez0){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 Mz0)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,...rI3(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;Ev(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=d1.all(new h1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,G=new TZ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:V,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),z=new d$({shortcuts:new Map([[new U4("ArrowDown"),new Pv],[new U4("ArrowUp"),new Cv],[new U4("Tab"),new Pv],[new U4("Tab",{shift:!0}),new Cv],[new U4("n",{ctrl:!0}),new Pv],[new U4("p",{ctrl:!0}),new Cv],[new U4("Enter"),new Ez0],[new U4("Escape"),new Mz0]]),focusNode:this.focusNode,child:G}),F=new O2({actions:new Map([[Pv,new U6(this.invoke)],[Cv,new U6(this.invoke)],[Ez0,new U6(this.invoke)],[Mz0,new U6(this.invoke)]]),child:z}),q=new q1({children:[new i0({decoration:{color:Q.background},child:new J0({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 Z4({child:new J0({text:new C(N,new g({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)W=new k1({child:new Z4({child:new J0({text:new C(this.widget.props.emptyStateText,new g({color:Q.foreground,dim:!0}))})})});else{let N=Y.map((w,L)=>{let O=L===this.selectedIndex,E=this.widget.props.isItemDisabled?.(w)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(w,O,E,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new i0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C(this.widget.props.getLabel(w),new g({color:j,dim:E}))})})}return new ag4(new J4({onClick:(A)=>this.handleItemClick(L,A.clickCount),child:M}),(A)=>{this.itemContexts[L]=A})});W=new x0({children:N,crossAxisAlignment:"start"})}let U=new J4({onScroll:this.handleScroll,opaque:!1,child:new _6({controller:this.scrollController,autofocus:!1,child:W})}),H=[];if(this.widget.props.title){let N=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C(this.widget.props.title,new g({color:Z.app.command,bold:!0}))})});H.push(N)}if(!K)H.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);H.push(new k1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new k1({child:U}),new i0({padding:C0.only({top:1}),child:new Z4({child:w??new I0({height:1})})})]})}))}else H.push(new k1({child:U}));if(this.widget.props.footer)H.push(this.widget.props.footer);return new i0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:H})})}}function sg4(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 G11 extends $4{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)=>sg4(X.pubDate).length));return new r2({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,K,V,G)=>{let z=f0.of(G),{colors:F}=z,q=z.app,W=K?q.selectionBackground:void 0,U=K?q.selectionForeground:F.foreground,H=F.mutedForeground,D=(B,N)=>new I0({width:N,child:q1.end([new J0({text:new C(B,new g({color:H}))})])});return new i0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[new k1({child:new J0({text:new C(X.title,new g({color:U})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),D(sg4(X.pubDate),Q)]})})}})}}class z11 extends l0{createState(){return new tg4}}class tg4 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 J0({text:new C("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function sI3(J){return RY(J,{acceptedHostnames:["ampcode.com","localhost"],allowThreadsPathExtraction:!0})}function tI3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let G=V.relationships.find((z)=>z.role==="child"&&Z.has(z.threadID)&&(z.type==="fork"||z.type==="handoff"));if(G){Y.set(V.id,G.type);let z=G.threadID,F=Q.get(z)||[];F.push(V),Q.set(z,F)}else X.push(V)}return oV0.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 F11(J,Z,Q){return new J0({text:new C(`${J}${Z}`,new g({color:Q})),maxLines:1})}function eI3(J,Z,Q,Y){return[F11("+",J,Y.success),b3.horizontal(1),F11("~",Z,Y.warning),b3.horizontal(1),F11("-",Q,Y.destructive)]}function $P3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class Az0 extends l0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new eg4}}class eg4 extends d0{spinner=new G3;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,K=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((L)=>L.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((L)=>L.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],G=new Set(V),z=Z.currentThreadID,F=[...K].sort((L,O)=>{if(z){if(L.id===z)return-1;if(O.id===z)return 1}let E=V.indexOf(L.id),M=V.indexOf(O.id);if(E!==-1&&M!==-1)return E-M;if(E!==-1)return-1;if(M!==-1)return 1;return 0}),q=tI3(F),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),U=f0.of(J),H=new a0({padding:C0.symmetric(0,1),child:new Z4({child:new J0({text:new C("",new g({color:U.colors.foreground,dim:!0}),[new C("Alt+W/Ctrl+T",new g({color:U.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:U.colors.foreground,dim:!0}))])})})}),D="",B=null,N=(L)=>{if(L!==D)D=L,B=sI3(L);return B};return new r2({items:q,getLabel:(L)=>`${L.title} ${L.id}`,filterItem:(L,O)=>{let E=N(O);if(E)return L.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(L)=>N(L)?"":L,onAccept:async(L,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(L.id,O);if(!$P3(E))return;this.setSwitchingThread(!0);try{await E}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(L)=>{if(Z.previewController){if(L)Z.previewController.select(L.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:H,renderItem:(L,O,E,M)=>{let A=f0.of(M),{app:j,colors:R}=A,k=O?j.selectionBackground:void 0,S=O?j.selectionForeground:R.foreground,u=R.mutedForeground,m=(s,F0)=>new I0({width:F0,child:q1.end([new J0({text:new C(s,new g({color:u}))})])}),x=Z.threadViewStates[L.id],_=[],f=L.relationshipType==="handoff",p=new Pa({connectorColor:R.mutedForeground});if(L.depth>0){let s=[],F0=L.ancestorsAreLast.slice(1);for(let w0 of F0)s.push(new C(p.getAncestorPrefix(w0),new g({color:p.connectorColor,dim:p.connectorDim})));let o=L.isLast?p.elbow:p.tee,q0=p.getConnectorText(o);s.push(new C(q0,new g({color:p.connectorColor,dim:p.connectorDim}))),_.push(new J0({text:new C("",void 0,s)}))}let d=[],h=z===L.id?new C("(current) ",new g({color:R.success})):G.has(L.id)?new C("(visited) ",new g({color:R.foreground,dim:!0})):null;if(h)d.push(new J0({text:h}));if(IN(x))d.push(new z11),d.push(new I0({width:1}));let n=L.title;if(L.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 J0({text:new C("[fork] ",new g({color:R.primary}))}))}else if(f)d.push(new J0({text:new C("[handoff] ",new g({color:R.accent}))}));if(d.push(new k1({child:new J0({text:new C(n,new g({color:S})),overflow:"ellipsis",maxLines:1})})),d.push(new I0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let s=O?{success:u,warning:u,destructive:u}:R;d.push(...eI3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,s)),d.push(new I0({width:2}))}return d.push(m(L.description.timeAgo,W)),new i0({decoration:k?{color:k}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[..._,...d]})})}})}}function $m4(J){return 1-(1-J)**3}function Jm4(J,Z,Q){return J+(Z-J)*Q}function Jo(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=$m4(Y),V=$m4(X);return{x:Jm4(J.startOffset.x,J.targetOffset.x,K),y:Jm4(J.startOffset.y,J.targetOffset.y,V)}}var JP3={nodeWidth:3,horizontalSpacing:3};class _v{options;constructor(J={}){this.options={...JP3,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let K=0,V=(G,z)=>{let F=Z.get(G.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let q={...G,parentID:Q.get(G.id)};if(F.length===0){Y.push({node:q,position:{x:K,y:z}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let W=[];for(let B of F)W.push(V(B,z+1));let U=Math.min(...W),H=Math.max(...W),D=Math.floor((U+H)/2);return Y.push({node:q,position:{x:D,y:z}}),D};for(let G of X)V(G,0);return Y}buildTree(J){let Z=new Set(J.map((K)=>K.id)),Q=[...J].sort((K,V)=>K.id.localeCompare(V.id)),Y=new Map;for(let K of Q){if(!K.parentID||!Z.has(K.parentID)){Y.set(K.id,void 0);continue}let V=!1,G=K.parentID;while(G){if(G===K.id){V=!0;break}G=Y.get(G)}Y.set(K.id,V?void 0:K.parentID)}let X=new Map;for(let K of J){let V=Y.get(K.id);if(!X.has(V))X.set(V,[]);X.get(V).push(K)}return{childrenMap:X,resolvedParent:Y}}}var ZP3={nodeWidth:3,nodeHeight:2};class Tv{options;constructor(J={}){this.options={...ZP3,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let K=this.calculateConnectorLine(X.position,Y.position);Z.push({points:K,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,K=Z.x+Q,V=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:V});let G=V+1;if(Y.push({x:X,y:G}),X!==K)Y.push({x:K,y:G});let z=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:z}),Y}}var QP3={nodeWidth:3,nodeHeight:2},YP3={x:0,y:0};class Rz0{options;constructor(J={}){this.options={...QP3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=YP3,X,K,V,G){let z=G?f0.of(G):null,F=z?.colors,q=z?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new J0({text:new C("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),D=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let k=[],S=0;for(let u of R){if(u.position.x>S)k.push(new I0({width:u.position.x-S}));let m=u.node.id===Q,x=V?.(u.node.data)??!1,_=K?.activeFlashOn??!1,f=u.node.id===K?.copyFlashNodeId;k.push(this.renderNode(m,x,_,f,q,F)),S=u.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:k})),j>0){let u=J.filter((_)=>_.position.y===j-1),m=R,x=this.renderConnectors(u,m,Z,D,F,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(U+1)*B,M=[new I0({width:D,height:E}),new $5({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,k=L+A.position.x+this.options.nodeWidth+1,S=O+R*B+1,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new $5({left:k,top:S,child:this.renderInfoBox(j,u,F,q)}))}return new i0({padding:C0.horizontal(2),child:new gG(new z5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",G="└─┘",z=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,F=!1;if(Y)z=X?.threadGraphNodeSelected??K?.primary??z,V="┏━┓",G="┗━┛",F=!0;else if(Z&&Q)z=X?.toolSuccess??K?.primary??z,V="┏━┓",G="┗━┛";return new x0({crossAxisAlignment:"start",children:[new J0({text:new C(V,new g({color:z,bold:F}))}),new J0({text:new C(G,new g({color:z,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),K=Math.min(Z,Math.max(1,...X.map((U)=>U.length))),V=K+2,G="┌"+"─".repeat(V)+"┐",z="└"+"─".repeat(V)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,W=[new J0({text:new C(G,new g({color:F}))})];for(let U of X){let H=" ".repeat(K-U.length);W.push(new J0({text:new C("│ ",new g({color:F}),[new C(U+H,new g({color:q??F})),new C(" │",new g({color:F}))])}))}return W.push(new J0({text:new C(z,new g({color:F}))})),new x0({crossAxisAlignment:"start",children:W})}renderConnectors(J,Z,Q,Y,X,K){let V=[],G=Math.floor(this.options.nodeWidth/2),z=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of Z){let H=U.position.x+G;if(H>=0&&H<Y)F[H]="▲"}V.push(new J0({text:new C(F.join(""),new g({color:z}))}));let q=Array(Y).fill(" ");for(let U of J){let H=Z.filter((L)=>L.node.parentID===U.node.id);if(H.length===0)continue;let D=U.position.x+G,B=H.map((L)=>L.position.x+G),N=Math.min(...B),w=Math.max(...B);for(let L=N;L<=w;L++)if(L>=0&&L<Y){if(L===D)if(H.length===1&&B[0]===D)q[L]="│";else if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┬";else if(B.includes(L))if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┴";else if(q[L]===" ")q[L]="─"}}V.push(new J0({text:new C(q.join(""),new g({color:z}))}));let W=Array(Y).fill(" ");for(let U of J){if(Z.filter((B)=>B.node.parentID===U.node.id).length===0)continue;let D=U.position.x+G;if(D>=0&&D<Y)W[D]="│"}return V.push(new J0({text:new C(W.join(""),new g({color:z}))})),V}}var XP3={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},KP3={x:0,y:0};class q11{options;constructor(J={}){this.options={...XP3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=KP3,X,K,V,G){let z=G?f0.of(G):null,F=z?.colors,q=z?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new J0({text:new C("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),D=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let k=[],S=0;for(let u of R){if(u.position.x>S)k.push(new I0({width:u.position.x-S}));let m=u.node.id===Q,x=V?.(u.node.data)??!1,_=K?.activeFlashOn??!1;k.push(this.renderNode(m,x,_,q,F)),S=u.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:k})),j>0){let u=J.filter((_)=>_.position.y===j-1),m=R,x=this.renderConnectors(u,m,Z,D,F,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(U+1)*B,M=[new I0({width:D,height:E}),new $5({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,k=L+A.position.x+this.options.nodeWidth+1,S=O+R*B,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new $5({left:k,top:S,child:this.renderInfoBox(j,u,F)}))}return new i0({padding:C0.horizontal(2),child:new gG(new z5({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 J0({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 J0({text:new C(V,new g({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:K})}renderConnectors(J,Z,Q,Y,X,K){let V=[],G=Math.floor(this.options.nodeWidth/2),z=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let q of J){let W=Z.filter((N)=>N.node.parentID===q.node.id);if(W.length===0)continue;let U=q.position.x+G,H=W.map((N)=>N.position.x+G),D=Math.min(...H),B=Math.max(...H);for(let N=D;N<=B;N++)if(N>=0&&N<Y){let w=N===U,L=H.includes(N);if(w&&L)if(W.length===1)F[N]="│";else if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┼";else if(w)if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┬";else if(L)if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┴";else if(F[N]===" ")F[N]="─"}}return V.push(new J0({text:new C(F.join(""),new g({color:z}))})),V}}class Zo extends o3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new Zm4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class Zm4 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 vR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Xm4}}var Qm4=400,Ym4=300,VP3=16;class Xm4 extends d0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new _v({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new Tv;renderer=new q11;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((z)=>z.id)),Q=new Set(this.widget.props.threads.map((z)=>z.id));if(Z.size!==Q.size||[...Z].some((z)=>!Q.has(z)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,K=this.widget.props.initialSelectedThreadID;if(X!==K&&K){let F=this.widget.props.threads.find((q)=>q.id===K);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((z)=>z.isActive),G=this.widget.props.threads.some((z)=>z.isActive);if(V!==G){if(this.stopActiveFlashTimer(),G)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:Qm4,durationY:Ym4};let Z=Math.max(Qm4,Ym4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=Jo(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},VP3)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),K=Math.floor(this.viewportWidth/2)-J-Y,V=Q-Z,G=2,z=Math.floor(this.viewportHeight/2),q=Math.floor(z/2)-V;return{x:K,y:q}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((K)=>K.node.parentID===Q.node.id);if(X.length>0){X.sort((V,G)=>V.position.x-G.position.x);let K=Math.floor(X.length/2);Y=X[K]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x<Q.position.x);if(X.length>0)X.sort((K,V)=>V.position.x-K.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x>Q.position.x);if(X.length>0)X.sort((K,V)=>K.position.x-V.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let q=(this.selectedNodeId?this.positionedNodes.find((W)=>W.node.id===this.selectedNodeId):null)??this.positionedNodes.find((W)=>!W.node.parentID);if(q){let W=Math.max(...this.positionedNodes.map((U)=>U.position.y));this.currentOffset=this.calculateCenterOffset(q.position.x,q.position.y,W)}}let X=this.widget.props.showTitle??!0,K=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+K},G=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),z=new Zo({onWidth:(F)=>{if(this.viewportWidth!==F)this.viewportWidth=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(F)=>{if(this.viewportHeight!==F)this.viewportHeight=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:G});return new s4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:z})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class Vm4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Gm4}}class Gm4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}var Km4=30,GP3=30;class Sv{}class kv{}class Iz0{}class Pz0{}class W11 extends l0{props;constructor(J){super();this.props=J}createState(){return new zm4}}class zm4 extends d0{highlightedIndex=0;controller=new Y$;focusNode;scrollController=new j5;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;Ev(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 Sv){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof kv){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof Iz0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof Pz0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,G=V4.of(J).size.width>=GP3+Km4,z=d1.all(new h1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,q=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C("Select a cluster",new g({color:X.command,bold:!0}))})}),W=new TZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),U=new d$({shortcuts:new Map([[new U4("ArrowDown"),new Sv],[new U4("ArrowUp"),new kv],[new U4("Tab"),new Sv],[new U4("Tab",{shift:!0}),new kv],[new U4("n",{ctrl:!0}),new Sv],[new U4("p",{ctrl:!0}),new kv],[new U4("Enter"),new Iz0],[new U4("Escape"),new Pz0]]),focusNode:this.focusNode,child:W}),H=new O2({actions:new Map([[Sv,new U6(this.invoke)],[kv,new U6(this.invoke)],[Iz0,new U6(this.invoke)],[Pz0,new U6(this.invoke)]]),child:U}),D=new q1({children:[new i0({decoration:{color:Y.background},child:new J0({text:new C(">",new g({color:Y.foreground}))})}),new k1({child:H})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,R=Z?M.threads.some((m)=>m.id===Z):!1,k=j?X.selectionBackground:void 0,S=j?X.selectionForeground:Y.foreground,u=[new C(M.label,new g({color:S})),new C(` (${M.threads.length})`,new g({color:S,dim:!0}))];if(R)u.push(new C(" (current)",new g({color:j?X.selectionForeground:Y.success})));return new Vm4(new J4({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new i0({decoration:k?{color:k}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C("",void 0,u)})})}),(m)=>{this.itemContexts[A]=m})}),N=new x0({children:B,crossAxisAlignment:"start"}),w=new k1({child:new J4({onScroll:this.handleScroll,child:new _6({controller:this.scrollController,autofocus:!1,child:N})})}),L=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],O=F?new i0({padding:C0.all(1),child:new vR({threads:L,autofocus:!1,offsetY:2})}):null,E;if(G){let M=O?new k1({child:O}):new I0({width:Km4});E=new q1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,M]})}else{let M=[new k1({child:new J4({onScroll:this.handleScroll,child:new _6({controller:this.scrollController,autofocus:!1,child:N})})})];if(O)M.push(new k1({child:O}));E=new x0({crossAxisAlignment:"stretch",children:M})}return new i0({decoration:{border:z,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[q,D,new I0({height:1}),new k1({child:E})]})})}}class vJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!vJ._instance)vJ._instance=new vJ;return vJ._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 Fm4 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){P.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){P.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(),z=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...V];return new r2({title:"Add Label",items:z,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 H=q?Q.selectionBackground:void 0,D=q?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in F&&F.__isCreateMarker){let N=this.currentQuery.trim().toLowerCase();return new i0({decoration:H?{color:H}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C("",void 0,[new C("Create new label: ",new g({color:D})),new C(N,new g({color:D,bold:!0}))])})})}return new i0({decoration:H?{color:H}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C(F.name,new g({color:D}))})})},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,H="__isCreateMarker"in q.item&&q.item.__isCreateMarker;if(U&&!H)return-1;if(!U&&H)return 1;return q.score-F.score}})}}class U11 extends l0{props;constructor(J){super();this.props=J}createState(){return new Fm4}}class aG extends l0{props;constructor(J){super();this.props=J}createState(){return new qm4}}class qm4 extends d0{_spinner=new G3;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=d1.all(new h1(Q.foreground,1,"solid")),K=this._spinner.toBraille(),V=new J0({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}))])}),z=[new k1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[V]})})];if(this.widget.props.onAbort)z.push(new I0({height:2,child:new i0({padding:C0.symmetric(2,0),child:new J0({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:z})})});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 Qo={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"}},Cz0=["workspace","global","flag","default","external","skill","other"];function zP3(J){return Array.from(new Set(J))}function Wm4(J){return zP3([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function yv(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 Wm4(J).length>0?"skill":"other"}function H11(J){return yv(J)==="skill"}function Um4(J){let Z=Wm4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=yv(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${Qo[Y].description}: ${Q}`}function Hm4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}var Dm4=process.platform==="win32"?" ":"█",Bm4=process.platform==="win32"?"░":"█";class L9 extends l0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=Dm4,thumbChar:K=Bm4,showTrack:V=!0,thumbColor:G,trackColor:z}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=G,this.trackColor=z}createState(){return new Nm4}}class Nm4 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),G=Math.max(1,X*V),z=Math.max(0,Math.min(1,K.scrollOffset/(Z-Q))),F=X-G,q=Math.max(0,F*z),W=q+G;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,G=Math.min(1,Q/Z),z=Math.max(1,K*G),F=K-z;if(F<=0)return;let q=Z-Q,W=F/q,U=V/W,H=Math.max(0,Math.min(q,this._dragStartOffset+U));this.widget.controller.jumpTo(H)};_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 G=Math.min(1,Y/Q),z=Math.max(1,V*G),F=Q-Y,q=V-z,W=Math.max(0,Math.min(1,X/(Q-Y))),U=Math.max(0,q*W),H=U+z;if(Z>=U&&Z<=H)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 J4({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?p5.POINTER:p5.DEFAULT,child:new wm4({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 wm4 extends By{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=Dm4,thumbChar:K=Bm4,showTrack:V=!0,thumbColor:G,trackColor:z}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=G,this.trackColor=z}createRenderObject(){return new Lm4(this)}updateRenderObject(J){J.updateWidget(this)}}class Lm4 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,G=this._widget.thumbColor,z=process.platform==="win32",F=Y,q=Y+X;if(!z){let W=["▁","▂","▃","▄","▅","▆","▇","█"];for(let U=0;U<this.size.height;U++){let H="█",D=!0;if(U===Math.floor(F)){let B=1-(F-U),N=Math.floor(B*8);H=W[N]||"█",D=!1}else if(U===Math.floor(q)){let B=1-(q-U),N=Math.floor(B*8);H=W[N]||"█"}else if(U>F&&U<q)D=!1;J.setChar(Z,Q+U,H,{fg:G,bg:V,reverse:D},1)}return}for(let W=0;W<this.size.height;W++){let U=W+0.5,H=U>=F&&U<q,D=H?this._widget.thumbChar:this._widget.trackChar;J.setChar(Z,Q+W,D,{fg:H?G: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),G=Y-V;return{thumbStartFloat:Math.max(0,G*X),thumbSizeFloat:V,showScrollbar:!0}}}class xR extends l0{props;constructor(J){super();this.props=J}createState(){return new Om4}}class Om4 extends d0{scrollController=new j5;scrollAreaKey=new e7("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 o2}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=Zz0(Q);return{title:q.title,type:q.type,description:q.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,K=d1.all(new h1(Z.colors.border,1,"solid")),V=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C(Y.title,new g({color:X,bold:!0}))})}),G=this.isWidgetMessage(Q)?Q.widget:new J0({text:new C(Y.description,new g({color:Z.colors.foreground})),selectable:!0}),z=new k1({child:new c$({child:new i0({padding:C0.symmetric(1,0),child:new q1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new k1({child:new _6({controller:this.scrollController,autofocus:!0,child:G})}),new L9({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let q=this.scrollController.maxScrollExtent,W=this.scrollController.offset,U=this.getViewportHeight(),H=q+U;return{totalContentHeight:Math.max(H,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(W,0)}}})]})})})}),F=new i0({padding:C0.symmetric(1,0),child:new J0({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}),z,F]})})})}}_2();class Em4 extends l0{props;constructor(J){super();this.props=J}createState(){return new Mm4}}class Mm4 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=S9.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 J0({text:new C("No plugins found.",new g({dim:!0}))});let Y=[],X=this.plugins.length,K=this.plugins.filter((z)=>z.status==="active").length,V=this.plugins.reduce((z,F)=>z+F.registeredCommands.length,0),G=this.plugins.reduce((z,F)=>z+F.registeredTools.length,0);if(Y.push(new C(`${K}/${X} ${d4(X,"plugin")} active`,new g({bold:!0}))),V>0||G>0)Y.push(new C(` (${V} ${d4(V,"command")}, ${G} ${d4(G,"tool")})`,new g({dim:!0})));Y.push(new C(`
|
|
7382
|
+
`))}if(D)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),F))}return new i0({decoration:{color:G.background,border:d1.all(new h1(G.border,1,"rounded"))},child:new J0({text:new C(void 0,void 0,W)})})}WE();g0();_2();import{execSync as OP3}from"node:child_process";wE();O$();f3();T7();nd();JA();jV();XJ();eJ();HY();yA();f4();Ym();Qb();w1();var dm4=G4(QU(),1);import{writeFile as bm4}from"fs/promises";import hm4 from"path";g0();XJ();class K11{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.1774542102-g618b9f"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await a40(Z,this.configService)}catch(Z){P.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class DL extends l0{props;constructor(J){super();this.props=J}createState(){return new cg4}}class cg4 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 lg4 extends d0{controller=new Y$;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,G=d1.all(new h1(Q.foreground,1,"solid")),z=new TZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(H)=>{let D=H.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new q1({children:[new i0({decoration:{color:Q.background},child:new J0({text:new C(">",new g({color:Q.foreground}))})}),new k1({child:z})]}),q=new i0({padding:C0.symmetric(1,0),child:new J0({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 J0({text:new C("",void 0,W)})});return new i0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new I0({height:1}),F,new b3,U]})})}}class $o extends l0{props;constructor(J){super();this.props=J}createState(){return new lg4}}import{isDeepStrictEqual as V11}from"node:util";var nI3=/[\\/_ +.#"@[({&]/,aI3=/[\\/_ +.#"@[({&]/g,oI3=/[\s-]/,ig4=/[\s-]/g;function Oz0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let G=`${X},${K}`;if(V[G]!==void 0)return V[G];let z=Y.charAt(K),F=Q.indexOf(z,X),q=0,W,U,H,D;while(F>=0){if(W=Oz0(J,Z,Q,Y,F+1,K+1,V),W>q){if(F===X)W*=1;else if(oI3.test(J.charAt(F-1))){if(W*=0.9,D=J.slice(X,F-1).match(ig4),D&&X>0)W*=0.999**D.length}else if(nI3.test(J.charAt(F-1))){if(W*=0.8,H=J.slice(X,F-1).match(aI3),H&&X>0)W*=0.999**H.length}else if(W*=0.3,X>0)W*=0.999**(F-X);if(J.charAt(F)!==Z.charAt(K))W*=0.9999}if(W<0.1&&(Q.charAt(F-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(F-1)!==Y.charAt(K))){if(U=Oz0(J,Z,Q,Y,F+1,K+2,V),U*0.1>W)W=U*0.1}if(W>q)q=W;F=Q.indexOf(z,F+1)}return V[G]=q,q}function Lz0(J){return J.toLowerCase().replace(ig4," ")}function ng4(J,Z){let Q=Oz0(J,Z,Lz0(J),Lz0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let G of Y){let z=Oz0(J,G,Lz0(J),Lz0(G),0,0,{});if(z===0)return Q;X+=z,K+=G.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class Pv{}class Cv{}class Ez0{}class Mz0{}class ag4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new og4}}class og4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}function rI3(J,Z){if(J==="")return{matches:!0,score:1};let Q=ng4(Z,J);return{matches:Q>0.15,score:Q}}class r2 extends l0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new rg4}}class rg4 extends d0{textController;focusNode;scrollController=new j5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new Y$(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)=>V11(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!V11(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>V11(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 Pv){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 Cv){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 Ez0){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 Mz0)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,...rI3(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;Ev(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=d1.all(new h1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,G=new TZ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:V,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),z=new d$({shortcuts:new Map([[new U4("ArrowDown"),new Pv],[new U4("ArrowUp"),new Cv],[new U4("Tab"),new Pv],[new U4("Tab",{shift:!0}),new Cv],[new U4("n",{ctrl:!0}),new Pv],[new U4("p",{ctrl:!0}),new Cv],[new U4("Enter"),new Ez0],[new U4("Escape"),new Mz0]]),focusNode:this.focusNode,child:G}),F=new O2({actions:new Map([[Pv,new U6(this.invoke)],[Cv,new U6(this.invoke)],[Ez0,new U6(this.invoke)],[Mz0,new U6(this.invoke)]]),child:z}),q=new q1({children:[new i0({decoration:{color:Q.background},child:new J0({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 Z4({child:new J0({text:new C(N,new g({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)W=new k1({child:new Z4({child:new J0({text:new C(this.widget.props.emptyStateText,new g({color:Q.foreground,dim:!0}))})})});else{let N=Y.map((w,L)=>{let O=L===this.selectedIndex,E=this.widget.props.isItemDisabled?.(w)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(w,O,E,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new i0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C(this.widget.props.getLabel(w),new g({color:j,dim:E}))})})}return new ag4(new J4({onClick:(A)=>this.handleItemClick(L,A.clickCount),child:M}),(A)=>{this.itemContexts[L]=A})});W=new x0({children:N,crossAxisAlignment:"start"})}let U=new J4({onScroll:this.handleScroll,opaque:!1,child:new _6({controller:this.scrollController,autofocus:!1,child:W})}),H=[];if(this.widget.props.title){let N=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C(this.widget.props.title,new g({color:Z.app.command,bold:!0}))})});H.push(N)}if(!K)H.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);H.push(new k1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new k1({child:U}),new i0({padding:C0.only({top:1}),child:new Z4({child:w??new I0({height:1})})})]})}))}else H.push(new k1({child:U}));if(this.widget.props.footer)H.push(this.widget.props.footer);return new i0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:H})})}}function sg4(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 G11 extends $4{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)=>sg4(X.pubDate).length));return new r2({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,K,V,G)=>{let z=f0.of(G),{colors:F}=z,q=z.app,W=K?q.selectionBackground:void 0,U=K?q.selectionForeground:F.foreground,H=F.mutedForeground,D=(B,N)=>new I0({width:N,child:q1.end([new J0({text:new C(B,new g({color:H}))})])});return new i0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[new k1({child:new J0({text:new C(X.title,new g({color:U})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),D(sg4(X.pubDate),Q)]})})}})}}class z11 extends l0{createState(){return new tg4}}class tg4 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 J0({text:new C("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function sI3(J){return RY(J,{acceptedHostnames:["ampcode.com","localhost"],allowThreadsPathExtraction:!0})}function tI3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let G=V.relationships.find((z)=>z.role==="child"&&Z.has(z.threadID)&&(z.type==="fork"||z.type==="handoff"));if(G){Y.set(V.id,G.type);let z=G.threadID,F=Q.get(z)||[];F.push(V),Q.set(z,F)}else X.push(V)}return oV0.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 F11(J,Z,Q){return new J0({text:new C(`${J}${Z}`,new g({color:Q})),maxLines:1})}function eI3(J,Z,Q,Y){return[F11("+",J,Y.success),b3.horizontal(1),F11("~",Z,Y.warning),b3.horizontal(1),F11("-",Q,Y.destructive)]}function $P3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class Az0 extends l0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new eg4}}class eg4 extends d0{spinner=new G3;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,K=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((L)=>L.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((L)=>L.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],G=new Set(V),z=Z.currentThreadID,F=[...K].sort((L,O)=>{if(z){if(L.id===z)return-1;if(O.id===z)return 1}let E=V.indexOf(L.id),M=V.indexOf(O.id);if(E!==-1&&M!==-1)return E-M;if(E!==-1)return-1;if(M!==-1)return 1;return 0}),q=tI3(F),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),U=f0.of(J),H=new a0({padding:C0.symmetric(0,1),child:new Z4({child:new J0({text:new C("",new g({color:U.colors.foreground,dim:!0}),[new C("Alt+W/Ctrl+T",new g({color:U.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:U.colors.foreground,dim:!0}))])})})}),D="",B=null,N=(L)=>{if(L!==D)D=L,B=sI3(L);return B};return new r2({items:q,getLabel:(L)=>`${L.title} ${L.id}`,filterItem:(L,O)=>{let E=N(O);if(E)return L.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(L)=>N(L)?"":L,onAccept:async(L,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(L.id,O);if(!$P3(E))return;this.setSwitchingThread(!0);try{await E}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(L)=>{if(Z.previewController){if(L)Z.previewController.select(L.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:H,renderItem:(L,O,E,M)=>{let A=f0.of(M),{app:j,colors:R}=A,k=O?j.selectionBackground:void 0,S=O?j.selectionForeground:R.foreground,u=R.mutedForeground,m=(s,F0)=>new I0({width:F0,child:q1.end([new J0({text:new C(s,new g({color:u}))})])}),x=Z.threadViewStates[L.id],_=[],f=L.relationshipType==="handoff",p=new Pa({connectorColor:R.mutedForeground});if(L.depth>0){let s=[],F0=L.ancestorsAreLast.slice(1);for(let w0 of F0)s.push(new C(p.getAncestorPrefix(w0),new g({color:p.connectorColor,dim:p.connectorDim})));let o=L.isLast?p.elbow:p.tee,q0=p.getConnectorText(o);s.push(new C(q0,new g({color:p.connectorColor,dim:p.connectorDim}))),_.push(new J0({text:new C("",void 0,s)}))}let d=[],h=z===L.id?new C("(current) ",new g({color:R.success})):G.has(L.id)?new C("(visited) ",new g({color:R.foreground,dim:!0})):null;if(h)d.push(new J0({text:h}));if(IN(x))d.push(new z11),d.push(new I0({width:1}));let n=L.title;if(L.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 J0({text:new C("[fork] ",new g({color:R.primary}))}))}else if(f)d.push(new J0({text:new C("[handoff] ",new g({color:R.accent}))}));if(d.push(new k1({child:new J0({text:new C(n,new g({color:S})),overflow:"ellipsis",maxLines:1})})),d.push(new I0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let s=O?{success:u,warning:u,destructive:u}:R;d.push(...eI3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,s)),d.push(new I0({width:2}))}return d.push(m(L.description.timeAgo,W)),new i0({decoration:k?{color:k}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[..._,...d]})})}})}}function $m4(J){return 1-(1-J)**3}function Jm4(J,Z,Q){return J+(Z-J)*Q}function Jo(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=$m4(Y),V=$m4(X);return{x:Jm4(J.startOffset.x,J.targetOffset.x,K),y:Jm4(J.startOffset.y,J.targetOffset.y,V)}}var JP3={nodeWidth:3,horizontalSpacing:3};class _v{options;constructor(J={}){this.options={...JP3,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let K=0,V=(G,z)=>{let F=Z.get(G.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let q={...G,parentID:Q.get(G.id)};if(F.length===0){Y.push({node:q,position:{x:K,y:z}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let W=[];for(let B of F)W.push(V(B,z+1));let U=Math.min(...W),H=Math.max(...W),D=Math.floor((U+H)/2);return Y.push({node:q,position:{x:D,y:z}}),D};for(let G of X)V(G,0);return Y}buildTree(J){let Z=new Set(J.map((K)=>K.id)),Q=[...J].sort((K,V)=>K.id.localeCompare(V.id)),Y=new Map;for(let K of Q){if(!K.parentID||!Z.has(K.parentID)){Y.set(K.id,void 0);continue}let V=!1,G=K.parentID;while(G){if(G===K.id){V=!0;break}G=Y.get(G)}Y.set(K.id,V?void 0:K.parentID)}let X=new Map;for(let K of J){let V=Y.get(K.id);if(!X.has(V))X.set(V,[]);X.get(V).push(K)}return{childrenMap:X,resolvedParent:Y}}}var ZP3={nodeWidth:3,nodeHeight:2};class Tv{options;constructor(J={}){this.options={...ZP3,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let K=this.calculateConnectorLine(X.position,Y.position);Z.push({points:K,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,K=Z.x+Q,V=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:V});let G=V+1;if(Y.push({x:X,y:G}),X!==K)Y.push({x:K,y:G});let z=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:z}),Y}}var QP3={nodeWidth:3,nodeHeight:2},YP3={x:0,y:0};class Rz0{options;constructor(J={}){this.options={...QP3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=YP3,X,K,V,G){let z=G?f0.of(G):null,F=z?.colors,q=z?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new J0({text:new C("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),D=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let k=[],S=0;for(let u of R){if(u.position.x>S)k.push(new I0({width:u.position.x-S}));let m=u.node.id===Q,x=V?.(u.node.data)??!1,_=K?.activeFlashOn??!1,f=u.node.id===K?.copyFlashNodeId;k.push(this.renderNode(m,x,_,f,q,F)),S=u.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:k})),j>0){let u=J.filter((_)=>_.position.y===j-1),m=R,x=this.renderConnectors(u,m,Z,D,F,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(U+1)*B,M=[new I0({width:D,height:E}),new $5({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,k=L+A.position.x+this.options.nodeWidth+1,S=O+R*B+1,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new $5({left:k,top:S,child:this.renderInfoBox(j,u,F,q)}))}return new i0({padding:C0.horizontal(2),child:new gG(new z5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",G="└─┘",z=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,F=!1;if(Y)z=X?.threadGraphNodeSelected??K?.primary??z,V="┏━┓",G="┗━┛",F=!0;else if(Z&&Q)z=X?.toolSuccess??K?.primary??z,V="┏━┓",G="┗━┛";return new x0({crossAxisAlignment:"start",children:[new J0({text:new C(V,new g({color:z,bold:F}))}),new J0({text:new C(G,new g({color:z,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),K=Math.min(Z,Math.max(1,...X.map((U)=>U.length))),V=K+2,G="┌"+"─".repeat(V)+"┐",z="└"+"─".repeat(V)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,W=[new J0({text:new C(G,new g({color:F}))})];for(let U of X){let H=" ".repeat(K-U.length);W.push(new J0({text:new C("│ ",new g({color:F}),[new C(U+H,new g({color:q??F})),new C(" │",new g({color:F}))])}))}return W.push(new J0({text:new C(z,new g({color:F}))})),new x0({crossAxisAlignment:"start",children:W})}renderConnectors(J,Z,Q,Y,X,K){let V=[],G=Math.floor(this.options.nodeWidth/2),z=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of Z){let H=U.position.x+G;if(H>=0&&H<Y)F[H]="▲"}V.push(new J0({text:new C(F.join(""),new g({color:z}))}));let q=Array(Y).fill(" ");for(let U of J){let H=Z.filter((L)=>L.node.parentID===U.node.id);if(H.length===0)continue;let D=U.position.x+G,B=H.map((L)=>L.position.x+G),N=Math.min(...B),w=Math.max(...B);for(let L=N;L<=w;L++)if(L>=0&&L<Y){if(L===D)if(H.length===1&&B[0]===D)q[L]="│";else if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┬";else if(B.includes(L))if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┴";else if(q[L]===" ")q[L]="─"}}V.push(new J0({text:new C(q.join(""),new g({color:z}))}));let W=Array(Y).fill(" ");for(let U of J){if(Z.filter((B)=>B.node.parentID===U.node.id).length===0)continue;let D=U.position.x+G;if(D>=0&&D<Y)W[D]="│"}return V.push(new J0({text:new C(W.join(""),new g({color:z}))})),V}}var XP3={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},KP3={x:0,y:0};class q11{options;constructor(J={}){this.options={...XP3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=KP3,X,K,V,G){let z=G?f0.of(G):null,F=z?.colors,q=z?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new J0({text:new C("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),D=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let k=[],S=0;for(let u of R){if(u.position.x>S)k.push(new I0({width:u.position.x-S}));let m=u.node.id===Q,x=V?.(u.node.data)??!1,_=K?.activeFlashOn??!1;k.push(this.renderNode(m,x,_,q,F)),S=u.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:k})),j>0){let u=J.filter((_)=>_.position.y===j-1),m=R,x=this.renderConnectors(u,m,Z,D,F,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(U+1)*B,M=[new I0({width:D,height:E}),new $5({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,k=L+A.position.x+this.options.nodeWidth+1,S=O+R*B,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new $5({left:k,top:S,child:this.renderInfoBox(j,u,F)}))}return new i0({padding:C0.horizontal(2),child:new gG(new z5({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 J0({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 J0({text:new C(V,new g({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:K})}renderConnectors(J,Z,Q,Y,X,K){let V=[],G=Math.floor(this.options.nodeWidth/2),z=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let q of J){let W=Z.filter((N)=>N.node.parentID===q.node.id);if(W.length===0)continue;let U=q.position.x+G,H=W.map((N)=>N.position.x+G),D=Math.min(...H),B=Math.max(...H);for(let N=D;N<=B;N++)if(N>=0&&N<Y){let w=N===U,L=H.includes(N);if(w&&L)if(W.length===1)F[N]="│";else if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┼";else if(w)if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┬";else if(L)if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┴";else if(F[N]===" ")F[N]="─"}}return V.push(new J0({text:new C(F.join(""),new g({color:z}))})),V}}class Zo extends o3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new Zm4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class Zm4 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 vR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Xm4}}var Qm4=400,Ym4=300,VP3=16;class Xm4 extends d0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new _v({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new Tv;renderer=new q11;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((z)=>z.id)),Q=new Set(this.widget.props.threads.map((z)=>z.id));if(Z.size!==Q.size||[...Z].some((z)=>!Q.has(z)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,K=this.widget.props.initialSelectedThreadID;if(X!==K&&K){let F=this.widget.props.threads.find((q)=>q.id===K);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((z)=>z.isActive),G=this.widget.props.threads.some((z)=>z.isActive);if(V!==G){if(this.stopActiveFlashTimer(),G)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:Qm4,durationY:Ym4};let Z=Math.max(Qm4,Ym4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=Jo(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},VP3)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),K=Math.floor(this.viewportWidth/2)-J-Y,V=Q-Z,G=2,z=Math.floor(this.viewportHeight/2),q=Math.floor(z/2)-V;return{x:K,y:q}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((K)=>K.node.parentID===Q.node.id);if(X.length>0){X.sort((V,G)=>V.position.x-G.position.x);let K=Math.floor(X.length/2);Y=X[K]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x<Q.position.x);if(X.length>0)X.sort((K,V)=>V.position.x-K.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x>Q.position.x);if(X.length>0)X.sort((K,V)=>K.position.x-V.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let q=(this.selectedNodeId?this.positionedNodes.find((W)=>W.node.id===this.selectedNodeId):null)??this.positionedNodes.find((W)=>!W.node.parentID);if(q){let W=Math.max(...this.positionedNodes.map((U)=>U.position.y));this.currentOffset=this.calculateCenterOffset(q.position.x,q.position.y,W)}}let X=this.widget.props.showTitle??!0,K=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+K},G=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),z=new Zo({onWidth:(F)=>{if(this.viewportWidth!==F)this.viewportWidth=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(F)=>{if(this.viewportHeight!==F)this.viewportHeight=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:G});return new s4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:z})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class Vm4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Gm4}}class Gm4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}var Km4=30,GP3=30;class Sv{}class kv{}class Iz0{}class Pz0{}class W11 extends l0{props;constructor(J){super();this.props=J}createState(){return new zm4}}class zm4 extends d0{highlightedIndex=0;controller=new Y$;focusNode;scrollController=new j5;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;Ev(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 Sv){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof kv){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof Iz0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof Pz0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,G=V4.of(J).size.width>=GP3+Km4,z=d1.all(new h1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,q=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C("Select a cluster",new g({color:X.command,bold:!0}))})}),W=new TZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),U=new d$({shortcuts:new Map([[new U4("ArrowDown"),new Sv],[new U4("ArrowUp"),new kv],[new U4("Tab"),new Sv],[new U4("Tab",{shift:!0}),new kv],[new U4("n",{ctrl:!0}),new Sv],[new U4("p",{ctrl:!0}),new kv],[new U4("Enter"),new Iz0],[new U4("Escape"),new Pz0]]),focusNode:this.focusNode,child:W}),H=new O2({actions:new Map([[Sv,new U6(this.invoke)],[kv,new U6(this.invoke)],[Iz0,new U6(this.invoke)],[Pz0,new U6(this.invoke)]]),child:U}),D=new q1({children:[new i0({decoration:{color:Y.background},child:new J0({text:new C(">",new g({color:Y.foreground}))})}),new k1({child:H})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,R=Z?M.threads.some((m)=>m.id===Z):!1,k=j?X.selectionBackground:void 0,S=j?X.selectionForeground:Y.foreground,u=[new C(M.label,new g({color:S})),new C(` (${M.threads.length})`,new g({color:S,dim:!0}))];if(R)u.push(new C(" (current)",new g({color:j?X.selectionForeground:Y.success})));return new Vm4(new J4({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new i0({decoration:k?{color:k}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C("",void 0,u)})})}),(m)=>{this.itemContexts[A]=m})}),N=new x0({children:B,crossAxisAlignment:"start"}),w=new k1({child:new J4({onScroll:this.handleScroll,child:new _6({controller:this.scrollController,autofocus:!1,child:N})})}),L=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],O=F?new i0({padding:C0.all(1),child:new vR({threads:L,autofocus:!1,offsetY:2})}):null,E;if(G){let M=O?new k1({child:O}):new I0({width:Km4});E=new q1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,M]})}else{let M=[new k1({child:new J4({onScroll:this.handleScroll,child:new _6({controller:this.scrollController,autofocus:!1,child:N})})})];if(O)M.push(new k1({child:O}));E=new x0({crossAxisAlignment:"stretch",children:M})}return new i0({decoration:{border:z,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[q,D,new I0({height:1}),new k1({child:E})]})})}}class vJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!vJ._instance)vJ._instance=new vJ;return vJ._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 Fm4 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){P.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){P.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(),z=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...V];return new r2({title:"Add Label",items:z,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 H=q?Q.selectionBackground:void 0,D=q?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in F&&F.__isCreateMarker){let N=this.currentQuery.trim().toLowerCase();return new i0({decoration:H?{color:H}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C("",void 0,[new C("Create new label: ",new g({color:D})),new C(N,new g({color:D,bold:!0}))])})})}return new i0({decoration:H?{color:H}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C(F.name,new g({color:D}))})})},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,H="__isCreateMarker"in q.item&&q.item.__isCreateMarker;if(U&&!H)return-1;if(!U&&H)return 1;return q.score-F.score}})}}class U11 extends l0{props;constructor(J){super();this.props=J}createState(){return new Fm4}}class aG extends l0{props;constructor(J){super();this.props=J}createState(){return new qm4}}class qm4 extends d0{_spinner=new G3;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=d1.all(new h1(Q.foreground,1,"solid")),K=this._spinner.toBraille(),V=new J0({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}))])}),z=[new k1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[V]})})];if(this.widget.props.onAbort)z.push(new I0({height:2,child:new i0({padding:C0.symmetric(2,0),child:new J0({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:z})})});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 Qo={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"}},Cz0=["workspace","global","flag","default","external","skill","other"];function zP3(J){return Array.from(new Set(J))}function Wm4(J){return zP3([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function yv(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 Wm4(J).length>0?"skill":"other"}function H11(J){return yv(J)==="skill"}function Um4(J){let Z=Wm4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=yv(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${Qo[Y].description}: ${Q}`}function Hm4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}var Dm4=process.platform==="win32"?" ":"█",Bm4=process.platform==="win32"?"░":"█";class L9 extends l0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=Dm4,thumbChar:K=Bm4,showTrack:V=!0,thumbColor:G,trackColor:z}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=G,this.trackColor=z}createState(){return new Nm4}}class Nm4 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),G=Math.max(1,X*V),z=Math.max(0,Math.min(1,K.scrollOffset/(Z-Q))),F=X-G,q=Math.max(0,F*z),W=q+G;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,G=Math.min(1,Q/Z),z=Math.max(1,K*G),F=K-z;if(F<=0)return;let q=Z-Q,W=F/q,U=V/W,H=Math.max(0,Math.min(q,this._dragStartOffset+U));this.widget.controller.jumpTo(H)};_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 G=Math.min(1,Y/Q),z=Math.max(1,V*G),F=Q-Y,q=V-z,W=Math.max(0,Math.min(1,X/(Q-Y))),U=Math.max(0,q*W),H=U+z;if(Z>=U&&Z<=H)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 J4({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?p5.POINTER:p5.DEFAULT,child:new wm4({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 wm4 extends By{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=Dm4,thumbChar:K=Bm4,showTrack:V=!0,thumbColor:G,trackColor:z}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=G,this.trackColor=z}createRenderObject(){return new Lm4(this)}updateRenderObject(J){J.updateWidget(this)}}class Lm4 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,G=this._widget.thumbColor,z=process.platform==="win32",F=Y,q=Y+X;if(!z){let W=["▁","▂","▃","▄","▅","▆","▇","█"];for(let U=0;U<this.size.height;U++){let H="█",D=!0;if(U===Math.floor(F)){let B=1-(F-U),N=Math.floor(B*8);H=W[N]||"█",D=!1}else if(U===Math.floor(q)){let B=1-(q-U),N=Math.floor(B*8);H=W[N]||"█"}else if(U>F&&U<q)D=!1;J.setChar(Z,Q+U,H,{fg:G,bg:V,reverse:D},1)}return}for(let W=0;W<this.size.height;W++){let U=W+0.5,H=U>=F&&U<q,D=H?this._widget.thumbChar:this._widget.trackChar;J.setChar(Z,Q+W,D,{fg:H?G: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),G=Y-V;return{thumbStartFloat:Math.max(0,G*X),thumbSizeFloat:V,showScrollbar:!0}}}class xR extends l0{props;constructor(J){super();this.props=J}createState(){return new Om4}}class Om4 extends d0{scrollController=new j5;scrollAreaKey=new e7("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 o2}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=Zz0(Q);return{title:q.title,type:q.type,description:q.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,K=d1.all(new h1(Z.colors.border,1,"solid")),V=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C(Y.title,new g({color:X,bold:!0}))})}),G=this.isWidgetMessage(Q)?Q.widget:new J0({text:new C(Y.description,new g({color:Z.colors.foreground})),selectable:!0}),z=new k1({child:new c$({child:new i0({padding:C0.symmetric(1,0),child:new q1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new k1({child:new _6({controller:this.scrollController,autofocus:!0,child:G})}),new L9({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let q=this.scrollController.maxScrollExtent,W=this.scrollController.offset,U=this.getViewportHeight(),H=q+U;return{totalContentHeight:Math.max(H,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(W,0)}}})]})})})}),F=new i0({padding:C0.symmetric(1,0),child:new J0({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}),z,F]})})})}}_2();class Em4 extends l0{props;constructor(J){super();this.props=J}createState(){return new Mm4}}class Mm4 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=S9.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 J0({text:new C("No plugins found.",new g({dim:!0}))});let Y=[],X=this.plugins.length,K=this.plugins.filter((z)=>z.status==="active").length,V=this.plugins.reduce((z,F)=>z+F.registeredCommands.length,0),G=this.plugins.reduce((z,F)=>z+F.registeredTools.length,0);if(Y.push(new C(`${K}/${X} ${d4(X,"plugin")} active`,new g({bold:!0}))),V>0||G>0)Y.push(new C(` (${V} ${d4(V,"command")}, ${G} ${d4(G,"tool")})`,new g({dim:!0})));Y.push(new C(`
|
|
7383
7383
|
|
|
7384
7384
|
`));for(let z of this.plugins){let{icon:F,color:q}=this.statusIcon(z.status),W=this.getRelativePath(z.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(` ${z.status}`,new g({dim:!0}))),Y.push(new C(`
|
|
7385
7385
|
`)),z.status==="active"&&z.registeredEvents.length>0)Y.push(new C(" Events: ",new g({dim:!0}))),Y.push(new C(z.registeredEvents.join(", "),new g({color:Q.link}))),Y.push(new C(`
|
|
@@ -7608,7 +7608,7 @@ ${Y0.content||""}`:Y0.content||"",$1=[],U1=Y0.baseDir.startsWith("file://")?WF0(
|
|
|
7608
7608
|
`),process.exit(1)}process.stdout.write(await tS3(z.result.displayText)+`
|
|
7609
7609
|
`),process.exit(0)})}JA();import{stdout as eS3}from"node:process";function $k3({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${PF(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function ql4(J){eS3.write(`${$k3(J)}
|
|
7610
7610
|
`)}function Wl4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{ql4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{ql4(Z),process.exit(0)})}var Ef3=xL.join(tZ,"logs","headless.log"),m51=xL.join(Dy,"device-id.json");async function Mf3(){for(let J of OE)try{if((await J.listConfigs()).length>0)return J}catch(Z){P.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => G4(Gx(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){R7.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
7611
|
-
`)}function Af3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",G=!1;J.warn(K,{name:V,code:Y})}}function t2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")sJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")sJ("experimental.agentMode",Z.mode)}function ca4(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 jf3(J){try{return await pa4(J,"utf-8")}catch{return J}}async function p51(J,Z,Q){let Y=ca4(J,Z);if(!Y)return;let X=m6(Q)?Q.features:[],K=m6(Q)?Q.user.email:void 0;if(!n51(X,S7.HARNESS_SYSTEM_PROMPT)&&!la4(K))throw new P1("You are not allowed to do this.",1);sJ("systemPrompt",await jf3(Y))}function la4(J){return!!(J&&m10(J))}function n51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function d51(J){return(J.userEmail?rJ(J.userEmail):!1)||n51(J.features,S7.DTW_TUI)}function va4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new P1("This TUI mode is not enabled for your user;",1)}function c51(J,Z){if(typeof J==="boolean")return J;if(!m6(Z))return!1;return d51({userEmail:Z.user.email,features:Z.features})}function l51(J){if(!m6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Rf3(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 Zq0(J){let Y=Rf3(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 P1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function xa4(J){if(!K5.write(J))await Nf3(K5,"drain")}var fa4=[{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??fK,description:`Custom settings file path (overrides the default location ${fK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${tA})`},{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:n2(),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:hz.SMART.key,description:`Set the agent mode (${gz().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:gz().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"threadActors",long:"thread-actors",type:"switch",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],ua4=(J)=>("deprecated"in J)&&J.deprecated===!0,If3=(J)=>("hidden"in J)&&J.hidden===!0,Pf3=(J)=>("default"in J),Cf3=(J)=>("default"in J)?J.default:void 0,ia4=[{name:"toggle-skills-count",entryPoint:Er0}];function _f3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((G)=>Q.includes(G)||G.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new P1(M3.unknownCommand(Q),1,V)}}async function a51(J){return{...J,getThreadEnvironment:wZ,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new mV(J.fileSystem),generateThreadTitle:H90,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>QQ(J.configService),pluginService:J.pluginService}}function na4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:wZ,filesystem:J.fileSystem,threadService:J.threadService}}var Qq0=Y1.file(da4.homedir()),i51=process.env.XDG_CONFIG_HOME?Y1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(Qq0,".config");function Tf3(J){return YU4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){QU4(Z);let Q=DK0(),Y=fr0();if((!Q||Y||rT4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(RH("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(RH("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(DK0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function Sf3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function e9(J,Z,Q){let Y=Q?.deferAuth??!1;Ju1("0.0.
|
|
7611
|
+
`)}function Af3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",G=!1;J.warn(K,{name:V,code:Y})}}function t2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")sJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")sJ("experimental.agentMode",Z.mode)}function ca4(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 jf3(J){try{return await pa4(J,"utf-8")}catch{return J}}async function p51(J,Z,Q){let Y=ca4(J,Z);if(!Y)return;let X=m6(Q)?Q.features:[],K=m6(Q)?Q.user.email:void 0;if(!n51(X,S7.HARNESS_SYSTEM_PROMPT)&&!la4(K))throw new P1("You are not allowed to do this.",1);sJ("systemPrompt",await jf3(Y))}function la4(J){return!!(J&&m10(J))}function n51(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function d51(J){return(J.userEmail?rJ(J.userEmail):!1)||n51(J.features,S7.DTW_TUI)}function va4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new P1("This TUI mode is not enabled for your user;",1)}function c51(J,Z){if(typeof J==="boolean")return J;if(!m6(Z))return!1;return d51({userEmail:Z.user.email,features:Z.features})}function l51(J){if(!m6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Rf3(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 Zq0(J){let Y=Rf3(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 P1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function xa4(J){if(!K5.write(J))await Nf3(K5,"drain")}var fa4=[{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??fK,description:`Custom settings file path (overrides the default location ${fK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${tA})`},{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:n2(),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:hz.SMART.key,description:`Set the agent mode (${gz().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:gz().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"threadActors",long:"thread-actors",type:"switch",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],ua4=(J)=>("deprecated"in J)&&J.deprecated===!0,If3=(J)=>("hidden"in J)&&J.hidden===!0,Pf3=(J)=>("default"in J),Cf3=(J)=>("default"in J)?J.default:void 0,ia4=[{name:"toggle-skills-count",entryPoint:Er0}];function _f3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((G)=>Q.includes(G)||G.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new P1(M3.unknownCommand(Q),1,V)}}async function a51(J){return{...J,getThreadEnvironment:wZ,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new mV(J.fileSystem),generateThreadTitle:H90,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>QQ(J.configService),pluginService:J.pluginService}}function na4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:wZ,filesystem:J.fileSystem,threadService:J.threadService}}var Qq0=Y1.file(da4.homedir()),i51=process.env.XDG_CONFIG_HOME?Y1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(Qq0,".config");function Tf3(J){return YU4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){QU4(Z);let Q=DK0(),Y=fr0();if((!Q||Y||rT4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(RH("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(RH("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(DK0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function Sf3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function e9(J,Z,Q){let Y=Q?.deferAuth??!1;Ju1("0.0.1774542102-g618b9f");let X=J40({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(Y1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:Qq0,userConfigDir:i51});oT4(X);let K=await X.getLatest();P.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),P.info("API key lookup before login",{found:Boolean(F0),ampURL:J.ampURL,deferAuth:Y}),!F0)if(Y)P.info("No API key found, continuing startup with deferred auth");else{K5.write(`No API key found. Starting login flow...
|
|
7612
7612
|
`);let o=await kf3(J),q0=await J.secrets.get("apiKey",J.ampURL);if(P.info("Login flow completed",{success:o,storedKeyPresent:Boolean(q0),ampURL:J.ampURL}),!o)await JH(),process.exit(1);V=!0}}{let F0=await X.getLatest(),o=F0.settings.url,q0=F0.secrets.isSet?.[o];P.info("Config secrets state after login",{configURL:o,apiKeySet:q0?.apiKey??!1})}let G=M1(QQ(X).pipe(E5((F0)=>F0!=="pending"))),z=Y?"pending":await G;if(!Y)P.info("Server status resolved",{status:"ready",isAuthenticated:m6(z),isError:pW(z),errorMessage:pW(z)?z.error.message:void 0});let{toolService:F,dispose:q}=tW4({configService:X}),W=new Map,U=()=>W.clear(),H=new hT0(X,J.settings.getWorkspaceRootPath()),D=Ye1({configService:X,filesystem:E8}),B=ea1({configService:X,trustStore:H,skillMCPServers:D.skillMCPServers,createOAuthProvider:async(F0,o,q0)=>{let w0=`${F0}:${o}`,z0=W.get(w0);if(z0)return P.debug("Reusing existing OAuth provider for server",{serverName:F0,serverUrl:o}),z0;P.debug("Creating OAuth provider for server",{serverName:F0,serverUrl:o});let $0=(async()=>{let U0=new _E(J.secrets),i=await U0.getClientInfo(F0,o),a=q0?.scopes??i?.scopes,e=_P4();P.info("OAuth headless mode check",{useHeadless:e,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:K5.isTTY});let Z0;if(e)Z0=J.executeMode?CP4():PP4(F0);let Y0=new LI0({storage:U0,serverName:F0,serverUrl:o,clientId:q0?.clientId??i?.clientId,clientSecret:q0?.clientSecret??i?.clientSecret,authUrl:q0?.authUrl??i?.authUrl,tokenUrl:q0?.tokenUrl??i?.tokenUrl,scopes:a,headlessAuthHandler:Z0});return P.debug("OAuth provider created",{serverName:F0,serverUrl:o,hasManualClientId:!!(q0?.clientId??i?.clientId),willUseDCR:!(q0?.clientId??i?.clientId),scopes:a,headlessMode:e,executeMode:J.executeMode}),Y0})();return W.set(w0,$0),$0}}),N=nm0({configService:X,filesystem:E8,spawn:HJ0}),w;if(J.executeMode){let F0=await ZF4({toolService:F,providers:[B,N],initialTimeout:15000});w=F0.registrations;for(let[o,q0]of F0.initErrors)P.warn(`${o} provider initialization slow or failed:`,q0)}else w=am0({toolService:F,providers:[B,N]});if(Z.jetbrains)DE("JetBrains");else if(Z.ide&&UC4())DE("VS Code");else if(Z.ide&&HC4())DE("Neovim");else if(Z.ide){let F0=await Mf3();if(F0){let o=q40(F0.ideName);if(o)DE(o)}}if(J.executeMode)Zu1(!0);let L,O=E$.status.pipe(W1((F0)=>Boolean(F0.connected&&F0.authenticated&&F0.ideName&&cu1(F0.ideName))),y4()).subscribe((F0)=>{if(F0){if(!L)L=F.registerTool(JF4)}else L?.dispose(),L=void 0}),E;if(!J.executeMode){let F0=await J.settings.get("fuzzy.alwaysIncludePaths")??[];E=new rZ0(process.cwd(),{alwaysIncludePaths:F0},!0)}else E=new class extends rZ0{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let M=await Fe1({isDevelopment:!1}),A=new gy0(M,X),j=new Tk0(M,{lazy:!0,maxThreads:200});P.info("Starting Amp background services");let R=Z.takeMeBack?!1:void 0,k=c51(R,z),S=Boolean(k||Z.headless);if(S)P.info("DTW mode enabled: thread sync service disabled");let u=S?Sf3():d04({threadService:A,threadHistoryService:j,configService:X,isExtensionDevelopment:!1}),m;E$.status.subscribe((F0)=>{m=F0});let x=new JR0({workspaceRoots:[Y1.file(process.cwd())],fileSystem:E8,getCurrentFile:()=>{if(!m?.openFile)return;try{return Y1.parse(m.openFile)}catch(F0){P.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((o)=>o!==F0).map((o)=>{try{return Y1.parse(o)}catch(q0){return P.warn("Failed to parse visible file URI",{uri:o,error:q0}),null}}).filter((o)=>o!==null)}}),_=new hr0,f=process.env.PLUGINS??"off",p=Z.headless?yT4():void 0,d=p??new zK0({configService:X}),h=d instanceof zK0?d:void 0;if(h)h.pluginExecutorKind=k?"local":"unknown";let n=JS0({configService:X,fileSystem:E8,platform:d,internalPlugins:ia4,pluginFilter:f}),c=no1({pluginService:n,toolService:F}),s={codebaseContextService:x,configService:X,toolService:F,mcpService:B,skillService:D,toolboxService:N,trustStore:H,threadService:A,threadHistoryService:j,threadSyncService:u,threadStorage:M,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:E,fileSystem:E8,terminal:_,pluginService:n,pluginPlatform:h,headlessPluginPlatform:p,serverStatus:z,serverStatusPromise:G,hasAPIKeyAtStartup:V};return{...s,async asyncDispose(){if(s.mcpService.hasAuthenticatingClients())P.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](),O.unsubscribe(),L?.dispose(),c.dispose(),await s.pluginService.dispose()}}}async function kf3(J){if(!J.executeMode){if(!await KK0("Would you like to log in to Amp? [(y)es, (n)o]: "))return K5.write(`Login cancelled. Run the command again to retry.
|
|
7613
7613
|
`),!1}return await aa4(J)}async function aa4(J){let Z=Bf3(32).toString("hex"),Q=await Ay(J.ampURL,Z),Y=new AbortController;try{await MV(Q,Y.signal)}catch(K){P.error("Error opening browser",{error:K})}let X=await Ay(J.ampURL,Z,!1);K5.write(`If your browser does not open automatically, visit:
|
|
7614
7614
|
|
|
@@ -7616,7 +7616,7 @@ ${c0.blue.bold(X)}
|
|
|
7616
7616
|
|
|
7617
7617
|
`);try{return await WT4(J.ampURL,Z,J.secrets,Y),K5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(K){return P.error("Login failed",{error:K}),R7.write(`
|
|
7618
7618
|
Login failed: ${K instanceof Error?K.message:String(K)}
|
|
7619
|
-
`),!1}}function ba4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function yf3(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 P1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!u9(Y.threadId))throw new P1("Create response did not include a valid thread ID",1);return Y.threadId}function vf3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function xf3(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 P1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!vf3(Q))throw new P1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function ff3(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 uf3(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 P1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function bf3(){let J=new aN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((D)=>{if(D.code==="commander.help"||D.code==="commander.version"||D.exitCode===0)$j(),process.exit(0);let B=D.originalError??D;nw4(B)}),Wl4(J,{version:"0.0.
|
|
7619
|
+
`),!1}}function ba4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function yf3(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 P1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!u9(Y.threadId))throw new P1("Create response did not include a valid thread ID",1);return Y.threadId}function vf3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function xf3(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 P1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!vf3(Q))throw new P1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function ff3(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 uf3(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 P1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function bf3(){let J=new aN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((D)=>{if(D.code==="commander.help"||D.code==="commander.version"||D.exitCode===0)$j(),process.exit(0);let B=D.originalError??D;nw4(B)}),Wl4(J,{version:"0.0.1774542102-g618b9f",buildTimestamp:"2026-03-26T16:25:35.143Z",buildType:"'release'"}),J.addHelpText("after",FC4()),J.configureHelp({formatHelp:qC4}),J.command("logout").description("Log out by removing stored API key").action(async(D,B)=>{let N=B.optsWithGlobals(),w=await m3(N);await lf3(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(D,B)=>{let N=B.optsWithGlobals(),w=await m3(N);await cf3(w,await Oo0(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(D,B,N)=>{let w=N.optsWithGlobals(),L=await m3(w);await LL4(D??"get",L.ampURL,L.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(D,B)=>{let N=B.optsWithGlobals(),w=await m3(N);await OL4(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",`
|
|
7620
7620
|
Actions:
|
|
7621
7621
|
create Create a new DTW thread and print its ID
|
|
7622
7622
|
add-message <message> Send a user message and wait for message_added
|
|
@@ -7680,8 +7680,8 @@ ${E}
|
|
|
7680
7680
|
|
|
7681
7681
|
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 hf3(J){P.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new Ca({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:wZ,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new mV(J.fileSystem),ampURL:J.ampURL,useThreadActors:J.useThreadActors});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw P.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function gf3(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await Cy()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await Cy()).trimEnd(),stdinInput:null}}function mf3(J,Z,Q){if(J.remote&&!Z)throw new P1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new P1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new P1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new P1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new P1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new P1("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 P1("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 P1("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"
|
|
7682
7682
|
Or pipe via stdin: echo "your message" | amp --execute`)}async function Yq0(J,Z,Q){let Y=process.hrtime.bigint(),X=(z0,$0)=>{let U0=Number(process.hrtime.bigint()-$0)/1e6,i=nU4();P.info("Startup phase",{phase:z0,phaseMs:Math.round(U0),sinceMainMs:i===null?void 0:Math.round(i)})},{userInput:K,stdinInput:V}=await gf3(Z),G=!!Z.streamJson||!!Z.streamJsonThinking;mf3({...Z,streamJson:G},J.executeMode,K),t2(Q,Z);let z=process.hrtime.bigint(),F=Boolean(await J.secrets.get("apiKey",J.ampURL)),q=!J.executeMode&&!Z.headless&&!Z.threadActors&&F;P.info("Interactive auth startup mode",{deferInteractiveAuth:q,hasAPIKeyAtStartup:F,executeMode:J.executeMode,headless:Boolean(Z.headless)});let W=await e9(J,Z,{deferAuth:q});X("runMainThread:createThreadDependencies",z),z=process.hrtime.bigint();let U=await a51(W);X("runMainThread:createWorkerDeps",z);let{serverStatus:H}=W;if(!q&&pW(H)){let z0=Ik(Error(H.error.message));if(z0.message===M3.networkOffline||z0.message===M3.networkTimeout)throw Zq0(J.ampURL);throw new P1(M3.invalidAPIKey,1)}let D=m6(H)?H:null,B=D?.user.email,N=la4(B),w=d51({userEmail:B,features:D?.features}),L=Z.takeMeBack?!1:void 0,O=D!==null&&c51(L,D);if(!q)await p51(Q,Z,H);let E=l51(H),M=E?.features??[],A=E?.team??null,j=VK0(Z,E);if(j instanceof Error)p3(j.message);if((J.executeMode||G)&&w8(Z.mode)&&!N)throw new P1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(D&&!NE(Z.mode,B))throw new P1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await fT4(K,V,W.configService),await W.asyncDispose(),process.exit(0);if(Z.headless){if(!B||!rJ(B))throw new P1("Headless DTW mode is only available for Amp employees",1);let z0=await W.secretStorage.get("apiKey",J.ampURL);if(!z0)throw new P1("API key required for headless mode. Please run `amp login` first.",1);let $0=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if($0&&!u9($0))throw new P1(`Invalid thread ID: ${$0}`,1);let U0=$0?void 0:await ef3({dependencies:W,visibility:j??void 0,usesThreadActors:Z.threadActors?!0:void 0}),i=$0??U0?.threadId;if(!i)throw new P1("Failed to resolve headless thread ID",1);let a=await yP4(i);if(a.status==="already-running")await W.asyncDispose(),await JH(),process.exit(0);try{await IP4({ampURL:J.ampURL,apiKey:z0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:i,ownerUserId:U0?.ownerUserId,threadVersion:U0?.threadVersion,agentMode:U0?.agentMode,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,useThreadActors:Z.threadActors?!0:void 0})}finally{await a.release(),await W.asyncDispose()}await JH(),process.exit(0)}let R=J.executeMode?void 0:async(z0)=>oo(z0,"interactive"),k={threadService:W.threadService,workerDeps:U,createThread:async()=>{let z0=q?await W.serverStatusPromise:H,$0=await xZ0(J.settings,process.cwd(),l51(z0),j);if($0 instanceof Error)p3($0.message);return J01(U,{threadMeta:$0?uG($0):void 0,agentMode:Z.mode,onFirstAssistantMessage:R})},validateThreadOwnership:async(z0,$0)=>{if($0?.nonBlockingOwnershipCheck){ha4(z0,W.configService).catch((U0)=>{if(U0 instanceof P1){if($0.onOwnershipError){$0.onOwnershipError(U0,z0);return}Jj(U0,z0);return}P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:U0})});return}try{await ha4(z0,W.configService)}catch(U0){if(U0 instanceof P1)throw U0;P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:U0})}},switchThreadVisibility:j,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:R,handleError:Jj},S=async(z0)=>{try{if(z0==="dtw")return hf3({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,useThreadActors:Z.threadActors?!0:void 0});return cu4(k,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch($0){if($0 instanceof P1)throw $0;throw await Jj($0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")R7.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
7683
|
-
`),await JH(),process.exit(1);let u=(async()=>{if(q){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await W.configService.getLatest(),$0=Ab(z0),U0=await g6.getUserFreeTierStatus({},{config:W.configService,signal:AbortSignal.timeout($0)});if(U0.ok)return P.info("User free tier status:",U0),U0.result;return}catch(z0){P.error("Failed to fetch free tier status:",z0);return}})(),x=!J.executeMode?new ae0:null,_,f=null;if(x)_=x,f=(async()=>{let z0=q?await W.serverStatusPromise:W.serverStatus;await p51(Q,Z,z0);let $0=process.hrtime.bigint(),U0=c51(L,z0),i=m6(z0)?d51({userEmail:z0.user.email,features:z0.features}):!1;va4({dtwEnabled:U0,hasV2TUIAccess:i});let a=await S(U0?"dtw":"worker");if(X("runMainThread:createThreadPool",$0),x.attach(a),K){let e=await M1(a.threadHandles$);if(!e)throw new P1("No active thread is available yet.",1);await e.sendMessage({content:[{type:"text",text:K}]})}})(),f.catch(async(z0)=>{let $0=z0 instanceof Error?z0:Error(String(z0));x.setInitError($0),await Jj(z0,Z.threadId)});else z=process.hrtime.bigint(),va4({dtwEnabled:O,hasV2TUIAccess:w}),_=await S(O?"dtw":"worker"),X("runMainThread:createThreadPool",z);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;z=process.hrtime.bigint();let d=await W.configService.getLatest();if(X("runMainThread:configService.getLatest",z),z=process.hrtime.bigint(),Tf3({configService:W.configService,threadService:W.threadService,config:d,useNotificationsForService:p,threadViewStates$:()=>_.threadHandles$.pipe(W4((z0)=>{if(!z0)return k0.of({});return D5(z0.thread$,z0.threadViewState$).pipe(W1(([$0,U0])=>({[$0.id]:U0})))}))}),X("runMainThread:createCliNotificationService",z),J.executeMode){jT4(W.mcpService,J.settings);let z0={userInput:K,stdinInput:V,dependencies:W,streamJson:G,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},$0=await YL4({threadPool:_,...z0});if(await oo($0,"execute"),Z.archive)await g6.archiveThread({thread:$0,archived:!0},{config:W.configService});await W.asyncDispose(),process.exit(0)}let h=!1,n=!1;if(Z.jetbrains||Z.ide){await ru1();let z0=await ME({jetbrainsOnly:Z.jetbrains});if(z0.length===0){if(Z.jetbrains)h=!await W.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let $0=z0[0];if($0)E$.selectConfig($0)}else n=!0}z=process.hrtime.bigint();let c=mo0("0.0.
|
|
7684
|
-
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Yo1({get:async(G)=>{if(G!==Ng)return;try{let z=await pa4(m51,"utf-8");return JSON.parse(z).installationID}catch{return}},set:async(G,z)=>{if(G!==Ng)return;await ma4(xL.dirname(m51),{recursive:!0}),await wf3(m51,JSON.stringify({installationID:z},null,2),{mode:384})}},{clientType:"cli",platform:uz()});Qu1(Y);let X=await iP4({...J,workspaceTrust:{current:!0,changes:Xb},getHook:process.env.AMP_URL?(G,z)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return z()}:void 0});if(J.mcpConfig){let G=await MT4(J.mcpConfig);X=AT4(X,G)}let K=xL.dirname(X.getSettingsFilePath());ZU4(Dy,K);let V=await X.get("url","global");if(!V)V=V2;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!AV(V))P.info("Targeting custom Amp server",{ampURL:V});return X=nf1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:mT4(await Oo0(J,X))}}function pf3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(G,z)=>z.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}async function df3(){iU4();let J=pf3(process.argv),Z=process.argv.includes("--headless")||process.argv.some((K)=>K.startsWith("--headless="));Xw4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?Ef3: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(Af3(P),P.info("Starting Amp CLI.",{version:"0.0.
|
|
7683
|
+
`),await JH(),process.exit(1);let u=(async()=>{if(q){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await W.configService.getLatest(),$0=Ab(z0),U0=await g6.getUserFreeTierStatus({},{config:W.configService,signal:AbortSignal.timeout($0)});if(U0.ok)return P.info("User free tier status:",U0),U0.result;return}catch(z0){P.error("Failed to fetch free tier status:",z0);return}})(),x=!J.executeMode?new ae0:null,_,f=null;if(x)_=x,f=(async()=>{let z0=q?await W.serverStatusPromise:W.serverStatus;await p51(Q,Z,z0);let $0=process.hrtime.bigint(),U0=c51(L,z0),i=m6(z0)?d51({userEmail:z0.user.email,features:z0.features}):!1;va4({dtwEnabled:U0,hasV2TUIAccess:i});let a=await S(U0?"dtw":"worker");if(X("runMainThread:createThreadPool",$0),x.attach(a),K){let e=await M1(a.threadHandles$);if(!e)throw new P1("No active thread is available yet.",1);await e.sendMessage({content:[{type:"text",text:K}]})}})(),f.catch(async(z0)=>{let $0=z0 instanceof Error?z0:Error(String(z0));x.setInitError($0),await Jj(z0,Z.threadId)});else z=process.hrtime.bigint(),va4({dtwEnabled:O,hasV2TUIAccess:w}),_=await S(O?"dtw":"worker"),X("runMainThread:createThreadPool",z);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;z=process.hrtime.bigint();let d=await W.configService.getLatest();if(X("runMainThread:configService.getLatest",z),z=process.hrtime.bigint(),Tf3({configService:W.configService,threadService:W.threadService,config:d,useNotificationsForService:p,threadViewStates$:()=>_.threadHandles$.pipe(W4((z0)=>{if(!z0)return k0.of({});return D5(z0.thread$,z0.threadViewState$).pipe(W1(([$0,U0])=>({[$0.id]:U0})))}))}),X("runMainThread:createCliNotificationService",z),J.executeMode){jT4(W.mcpService,J.settings);let z0={userInput:K,stdinInput:V,dependencies:W,streamJson:G,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},$0=await YL4({threadPool:_,...z0});if(await oo($0,"execute"),Z.archive)await g6.archiveThread({thread:$0,archived:!0},{config:W.configService});await W.asyncDispose(),process.exit(0)}let h=!1,n=!1;if(Z.jetbrains||Z.ide){await ru1();let z0=await ME({jetbrainsOnly:Z.jetbrains});if(z0.length===0){if(Z.jetbrains)h=!await W.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let $0=z0[0];if($0)E$.selectConfig($0)}else n=!0}z=process.hrtime.bigint();let c=mo0("0.0.1774542102-g618b9f",W.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",z),z=process.hrtime.bigint();let s=new _k0(W.threadStorage);X("runMainThread:createThreadFuzzyIndexer",z),z=process.hrtime.bigint();let F0=new Or0(W.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",z),K&&J.executeMode){let z0=await M1(_.threadHandles$);if(!z0)throw new P1("No active thread is available yet.",1);await z0.sendMessage({content:[{type:"text",text:K}]})}z=process.hrtime.bigint();let o=await qK0();X("runMainThread:loadSessionState",z),P.info("Loaded session state:",o);let q0={...o,launchCount:o.launchCount+1};cj((z0)=>({...z0,launchCount:z0.launchCount+1}));let w0=Z.threadId&&u9(Z.threadId)?Z.threadId:void 0;try{if(z=process.hrtime.bigint(),await yb4({codebaseContextService:W.codebaseContextService,history:new Wl0,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:_,createSystemPromptDeps:async()=>na4(W),ideClient:E$,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:w0,showJetBrainsInstaller:h,showIdePickerHint:n,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:q0,freeTierStatusPromise:u,workspace:A??null,features:M,isDogfooding:N,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-26T16:25:35.143Z"},(z0)=>new H01({...z0,threadPool:z0.threadPool},($0)=>new U61({...$0,threadState:$0.threadState}))),X("runMainThread:mountApp-returned",z),f)await f}finally{}await W.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function m3(J){if(P.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)R7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
7684
|
+
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Yo1({get:async(G)=>{if(G!==Ng)return;try{let z=await pa4(m51,"utf-8");return JSON.parse(z).installationID}catch{return}},set:async(G,z)=>{if(G!==Ng)return;await ma4(xL.dirname(m51),{recursive:!0}),await wf3(m51,JSON.stringify({installationID:z},null,2),{mode:384})}},{clientType:"cli",platform:uz()});Qu1(Y);let X=await iP4({...J,workspaceTrust:{current:!0,changes:Xb},getHook:process.env.AMP_URL?(G,z)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return z()}:void 0});if(J.mcpConfig){let G=await MT4(J.mcpConfig);X=AT4(X,G)}let K=xL.dirname(X.getSettingsFilePath());ZU4(Dy,K);let V=await X.get("url","global");if(!V)V=V2;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!AV(V))P.info("Targeting custom Amp server",{ampURL:V});return X=nf1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:mT4(await Oo0(J,X))}}function pf3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(G,z)=>z.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}async function df3(){iU4();let J=pf3(process.argv),Z=process.argv.includes("--headless")||process.argv.some((K)=>K.startsWith("--headless="));Xw4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?Ef3: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(Af3(P),P.info("Starting Amp CLI.",{version:"0.0.1774542102-g618b9f",buildTimestamp:"2026-03-26T16:25:35.143Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new P1(M3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await bf3().parseAsync(process.argv)}$U4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await df3().catch(Jj)});async function cf3(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"),K5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
7685
7685
|
`);else if(!AV(J.ampURL))K5.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
7686
7686
|
`);let Y=process.env.AMP_API_KEY;if(Y)K5.write(`API key found in environment variable, storing...
|
|
7687
7687
|
`),await Z.set("apiKey",Y,J.ampURL),K5.write(`API key successfully stored.
|