@sourcegraph/amp 0.0.1773691624-gc84dbf → 0.0.1773705849-gda80e7
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
|
@@ -6128,11 +6128,11 @@ ${W}`))}},error:(D)=>{if(!q)q=!0,z(Error(`Failed to spawn brew: ${D.message}`))}
|
|
|
6128
6128
|
${W}`;if(Y==="pnpm"&&W.includes("Unable to find the global bin directory"))H+=`
|
|
6129
6129
|
|
|
6130
6130
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
6131
|
-
npm install -g @sourcegraph/amp`;z(Error(H))}},error:(D)=>{if(!U)U=!0,z(Error(`Failed to spawn ${Y}: ${D.message}`))},complete:()=>{if(!U)U=!0,K()}})})}h0();h0();yj();async function q90(J,Z){let Y=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,V=new AbortController,K=setTimeout(()=>V.abort(),5000);try{let z=await fetch(Y,{signal:V.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),F=G.version??G["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let U=Xz4(J,F),q=U<0,D,W;if(G.time){let H=G.time[J],B=G.time[F],w=Date.now();if(H)D=Math.floor((w-new Date(H).getTime())/3600000);if(B)W=Math.floor((w-new Date(B).getTime())/3600000)}return j.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:U,hasUpdate:q,currentVersionAge:D,latestVersionAge:W}),{hasUpdate:q,latestVersion:F,currentVersion:J,currentVersionAge:D,latestVersionAge:W,source:"npm"}}catch(z){return j.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(K)}}var XP5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function D90(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let X=await fetch(`${XP5}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!X.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let Y=(await X.text()).trim();if(!Y||!/^\d+\.\d+\.\d+/.test(Y))return{hasUpdate:!1,currentVersion:J,source:"bin"};let V=Xz4(J,Y),K=V<0;return j.info("Bin version comparison",{currentVersion:J,latestVersion:Y,compareResult:V,hasUpdate:K}),{hasUpdate:K,latestVersion:Y,currentVersion:J,source:"bin"}}catch(X){return j.debug("Error checking bin version",{error:X}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var YP5=604800000;function Qz4(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>YP5)return{ageMs:Q};return null}function Xz4(J,Z){let Q=(K)=>{let[z,G]=K.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},X=Q(J),Y=Q(Z),V=Math.max(X.parts.length,Y.parts.length);for(let K=0;K<V;K++){let z=X.parts[K]||0,G=Y.parts[K]||0;if(z<G)return-1;if(z>G)return 1}if(X.label===Y.label)return 0;if(!X.label&&Y.label)return 1;if(X.label&&!Y.label)return-1;if(X.label&&Y.label)return X.label<Y.label?-1:1;return 0}function Vf0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,X=Z[2],Y=Q!==0?uD(Q):void 0;return{sha:X,age:Y}}catch{return null}}H1();function Kf0(J,Z,Q={}){let X=new a1,Y=X.pipe(R6({shouldCountRefs:!1}));return setImmediate(async()=>{let V=new CK().scoped("update"),K=Q.startDelayMs??0;if(K>0)await Qz(K);let z=Y.subscribe({next:(G)=>{V.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){V.debug("using fake update status for testing",{status:G}),await Qz(500),X.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){V.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){V.debug("checking disabled");return}let U=await U90(),q=U==="binary"||U==="brew";V.debug("checking",{currentVersion:J,mode:F,packageManager:U,isBinaryDistribution:q});let D=q?await D90(J):await q90(J,$L());if(!(D.latestVersion&&D.hasUpdate)){V.debug("no update available");return}let W=()=>{if(D.currentVersionAge!==void 0&&D.latestVersionAge!==void 0){let H=D.currentVersionAge-D.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return V.debug("versions too close together, suppressing update warning",{currentVersionAge:D.currentVersionAge,latestVersionAge:D.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!F)F=U==="pnpm"?"warn":"auto",V.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:F});if(U==="brew"){if(!W())X.next("update-available-brew");return}if(U==="binary"&&process.execPath!==$f0()){if(V.debug("non-standard binary path, showing warning"),!W())X.next("update-available-unrecognized-path");return}if(F==="warn"){if(!W())X.next("update-available");return}if(!U){if(V.debug("auto-update not supported, falling back to warn mode"),!W())X.next("update-available");return}if(U==="binary"&&process.platform==="win32"){if(V.debug("binary auto-update not supported on Windows, falling back to warn mode"),!W())X.next("update-available");return}try{await Gg(D.latestVersion,U);let H=await wH(D.latestVersion),B={from:D.currentVersion,to:D.latestVersion,...H};if(H.status==="same")V.info("success",B),X.next("updated");else V.warn("success with warning",B),X.next("updated-with-warning")}catch(H){X.next("update-error")}}catch(G){V.debug("check failed",{error:G})}finally{await Qz(5000),X.next("hidden"),z.unsubscribe(),X.complete()}}),{state:Y}}yj();import{stderr as oz}from"node:process";function Yz4(J){let Z=new YH().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(X)=>{await rx0(X.force||!1,X.verbose||!1,"0.0.
|
|
6131
|
+
npm install -g @sourcegraph/amp`;z(Error(H))}},error:(D)=>{if(!U)U=!0,z(Error(`Failed to spawn ${Y}: ${D.message}`))},complete:()=>{if(!U)U=!0,K()}})})}h0();h0();yj();async function q90(J,Z){let Y=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,V=new AbortController,K=setTimeout(()=>V.abort(),5000);try{let z=await fetch(Y,{signal:V.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),F=G.version??G["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let U=Xz4(J,F),q=U<0,D,W;if(G.time){let H=G.time[J],B=G.time[F],w=Date.now();if(H)D=Math.floor((w-new Date(H).getTime())/3600000);if(B)W=Math.floor((w-new Date(B).getTime())/3600000)}return j.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:U,hasUpdate:q,currentVersionAge:D,latestVersionAge:W}),{hasUpdate:q,latestVersion:F,currentVersion:J,currentVersionAge:D,latestVersionAge:W,source:"npm"}}catch(z){return j.debug("Error checking npm version",{error:z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(K)}}var XP5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function D90(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let X=await fetch(`${XP5}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!X.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let Y=(await X.text()).trim();if(!Y||!/^\d+\.\d+\.\d+/.test(Y))return{hasUpdate:!1,currentVersion:J,source:"bin"};let V=Xz4(J,Y),K=V<0;return j.info("Bin version comparison",{currentVersion:J,latestVersion:Y,compareResult:V,hasUpdate:K}),{hasUpdate:K,latestVersion:Y,currentVersion:J,source:"bin"}}catch(X){return j.debug("Error checking bin version",{error:X}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var YP5=604800000;function Qz4(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>YP5)return{ageMs:Q};return null}function Xz4(J,Z){let Q=(K)=>{let[z,G]=K.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},X=Q(J),Y=Q(Z),V=Math.max(X.parts.length,Y.parts.length);for(let K=0;K<V;K++){let z=X.parts[K]||0,G=Y.parts[K]||0;if(z<G)return-1;if(z>G)return 1}if(X.label===Y.label)return 0;if(!X.label&&Y.label)return 1;if(X.label&&!Y.label)return-1;if(X.label&&Y.label)return X.label<Y.label?-1:1;return 0}function Vf0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,X=Z[2],Y=Q!==0?uD(Q):void 0;return{sha:X,age:Y}}catch{return null}}H1();function Kf0(J,Z,Q={}){let X=new a1,Y=X.pipe(R6({shouldCountRefs:!1}));return setImmediate(async()=>{let V=new CK().scoped("update"),K=Q.startDelayMs??0;if(K>0)await Qz(K);let z=Y.subscribe({next:(G)=>{V.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){V.debug("using fake update status for testing",{status:G}),await Qz(500),X.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){V.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){V.debug("checking disabled");return}let U=await U90(),q=U==="binary"||U==="brew";V.debug("checking",{currentVersion:J,mode:F,packageManager:U,isBinaryDistribution:q});let D=q?await D90(J):await q90(J,$L());if(!(D.latestVersion&&D.hasUpdate)){V.debug("no update available");return}let W=()=>{if(D.currentVersionAge!==void 0&&D.latestVersionAge!==void 0){let H=D.currentVersionAge-D.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return V.debug("versions too close together, suppressing update warning",{currentVersionAge:D.currentVersionAge,latestVersionAge:D.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!F)F=U==="pnpm"?"warn":"auto",V.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:F});if(U==="brew"){if(!W())X.next("update-available-brew");return}if(U==="binary"&&process.execPath!==$f0()){if(V.debug("non-standard binary path, showing warning"),!W())X.next("update-available-unrecognized-path");return}if(F==="warn"){if(!W())X.next("update-available");return}if(!U){if(V.debug("auto-update not supported, falling back to warn mode"),!W())X.next("update-available");return}if(U==="binary"&&process.platform==="win32"){if(V.debug("binary auto-update not supported on Windows, falling back to warn mode"),!W())X.next("update-available");return}try{await Gg(D.latestVersion,U);let H=await wH(D.latestVersion),B={from:D.currentVersion,to:D.latestVersion,...H};if(H.status==="same")V.info("success",B),X.next("updated");else V.warn("success with warning",B),X.next("updated-with-warning")}catch(H){X.next("update-error")}}catch(G){V.debug("check failed",{error:G})}finally{await Qz(5000),X.next("hidden"),z.unsubscribe(),X.complete()}}),{state:Y}}yj();import{stderr as oz}from"node:process";function Yz4(J){let Z=new YH().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(X)=>{await rx0(X.force||!1,X.verbose||!1,"0.0.1773705849-gda80e7"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new YH("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(X)=>{await VP5(X.targetVersion)});J.addCommand(Q)}async function VP5(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")oz.write(Z1.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
6132
6132
|
|
|
6133
6133
|
`));try{if(!J){oz.write(Z1.blue(`Checking for updates...
|
|
6134
|
-
`));let{hasUpdate:X,latestVersion:Y}=sx0()?await D90("0.0.
|
|
6135
|
-
`));let z=await wH("0.0.
|
|
6134
|
+
`));let{hasUpdate:X,latestVersion:Y}=sx0()?await D90("0.0.1773705849-gda80e7"):await q90("0.0.1773705849-gda80e7",$L());if(!X){let V=Vf0("0.0.1773705849-gda80e7"),K=V?.age?`released ${V.age} ago`:`built ${uD(new Date("2026-03-17T00:09:44.746Z"))} ago`;oz.write(Z1.green(`✓ Amp is already up to date on version ${"0.0.1773705849-gda80e7"} (${K})
|
|
6135
|
+
`));let z=await wH("0.0.1773705849-gda80e7");if(z.warning)oz.write(`
|
|
6136
6136
|
`+Z1.yellow(z.warning)+`
|
|
6137
6137
|
`);process.exit(0)}if(!Y)oz.write(Z1.yellow("[WARN] could not find latest version")),process.exit(0);J=Y}oz.write(Z1.blue(`Updating to version ${J}...
|
|
6138
6138
|
`)),await Gg(J,void 0,(X)=>{oz.write(Z1.dim(`Running: ${X}
|
|
@@ -7296,7 +7296,7 @@ Ctrl-X, Y, Z to unlock`;if(D){let f=F.text.replace(/`([^`]+)`/g,"$1")+`
|
|
|
7296
7296
|
`),V=[];for(let K=0;K<Y.length;K++){let F=Y[K].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let U of F)if(U.startsWith("\x00")&&U.endsWith("\x01"))V.push(new C(U.slice(1,-1),new h({color:X.app.keybind,bold:!0})));else V.push(new C(U,new h({color:Q.colorScheme.foreground})));if(K<Y.length-1)V.push(new C(`
|
|
7297
7297
|
`))}return new c0({decoration:{color:Q.colorScheme.background,border:x1.all(new v1(X.app.keybind,1,"rounded"))},child:new i0({padding:C0.symmetric(0,1),child:new $0({text:new C(void 0,void 0,V)})})})}}class Np0 extends I2{chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:X=!0,colors:Y=d$0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=X,this.colors=Y}createRenderObject(){return new Bp0({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 MO4(J,Z,Q,X,Y,V,K){if(V<=0)return null;switch(J){case"horizontal-bar":{let z=Q;return z>=0&&z<V?z:null}case"bar":case"stacked-bar":{let z=K?n8:0,G=X-z;if(G<=0)return null;let F=Z-z;if(F<0||F>=G)return null;let U=Math.max(1,Math.floor(G/V)),q=Math.floor(F/U);return q>=0&&q<V?q:null}case"line":case"sparkline":case"stacked-area":{let z=K?n8:0,G=X-z;if(G<=0)return null;let F=Math.max(0,Math.min(G-1,Z-z));if(V===1)return 0;let U=G/(V-1),q=Math.round(F/U);return Math.max(0,Math.min(V-1,q))}default:return null}}function Ua5(J,Z,Q,X,Y,V,K,z){if(Y<=0||Z<0||Z>=Y)return null;let G=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let F=V?n8:0,U=Q-F,q=X-(V?G:0);if(U<=0||q<=0)return null;let D=Math.max(1,Math.floor(U/Y)),W=F+Z*D+Math.floor(D/2),H=z>0?K/z:0,B=Math.round((1-H)*(q-1));return{x:W,y:B}}case"line":case"sparkline":case"stacked-area":{let F=V?n8:0,U=Q-F,q=X-(V?G:0);if(U<=0||q<=0)return null;let D=Y>1?F+Math.round(Z/(Y-1)*(U-1)):F+Math.floor(U/2),W=z>0?K/z:0,H=Math.round((1-W)*(q-1));return{x:D,y:H}}default:return null}}function qa5(J){let Z=0;for(let Q of J)for(let X of Q.points)if(X.value>Z)Z=X.value;return Z||1}function Da5(J,Z,Q,X,Y){if(Q.length<=1){let z=X(J.value),G=J.meta?` (${J.meta})`:"";return J.label.length+2+z.length+G.length}let V=J.label.length,K=0;for(let z of Q){let G=z.points[Z];if(!G)continue;K+=G.value;let F=2+z.name.length+2+X(G.value).length;V=Math.max(V,F)}if(Y){let z=9+X(K).length;V=Math.max(V,z)}return V}function Wa5(J,Z,Q,X,Y,V,K){let z;try{let H=I1.of(J),B=f0.of(J);z={foreground:H.colorScheme.foreground,background:H.colorScheme.background,border:B.app.keybind}}catch{z={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let G=new h({color:z.foreground,bold:!0}),F=new h({color:z.foreground}),U=new h({color:z.foreground,dim:!0}),q=[],D=new h({color:z.foreground,underline:!0}),W=(H,B)=>new C(B,D,void 0,T90(H),()=>{w8(J,H)});if(X.length<=1){if(q.push(new C(`${Z.label}: `,G)),Z.link)q.push(W(Z.link,V(Z.value)));else q.push(new C(V(Z.value),F));if(Z.meta)q.push(new C(` (${Z.meta})`,U))}else{let H=K==="stacked-bar"||K==="stacked-area";q.push(new C(`${Z.label}
|
|
7298
7298
|
`,G));let B=0;for(let w=0;w<X.length;w++){let N=X[w],O=N.points[Q];if(!O)continue;B+=O.value;let E=N.color??Y[w%Y.length]??z.foreground;if(q.push(new C("● ",new h({color:E}))),q.push(new C(`${N.name}: `,U)),O.link)q.push(W(O.link,V(O.value)));else q.push(new C(V(O.value),F));if(w<X.length-1||H)q.push(new C(`
|
|
7299
|
-
`))}if(H)q.push(new C(" ",U)),q.push(new C("Total: ",U)),q.push(new C(V(B),F))}return new c0({decoration:{color:z.background,border:x1.all(new v1(z.border,1,"rounded"))},child:new $0({text:new C(void 0,void 0,q)})})}JN();h0();m9();import{execSync as da5}from"node:child_process";DN();C7();w3();P7();Vh();xY();o2();h$();yY();jE();_4();Nx();Ek();H1();var ME4=D4(SF(),1);import{writeFile as wE4}from"fs/promises";import NE4 from"path";h0();o2();class Op0{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.1773691624-gc84dbf"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await ft(Z,this.configService)}catch(Z){j.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class YB extends d0{props;constructor(J){super();this.props=J}createState(){return new AO4}}class AO4 extends p0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class IO4 extends p0{controller=new a7;focusNode=new r4({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:X}=Z,Y=this.widget.props.isRequiredArg??!0,V=this.controller.text.trim().length>0,K=!Y||V,z=x1.all(new v1(Q.foreground,1,"solid")),G=new FJ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(W)=>{let H=W.trim();if(Y&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new U1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:G})]}),U=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,[new C("Command: ",new h({color:Q.foreground})),new C(this.widget.props.commandName,new h({color:X.command,bold:!0}))])})}),q=[];if(K)q.push(new C("Enter",new h({color:X.keybind}))),q.push(new C(" to submit, ",new h({color:Q.foreground,dim:!0})));q.push(new C("Esc",new h({color:X.keybind}))),q.push(new C(" to cancel",new h({color:Q.foreground,dim:!0})));let D=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,q)})});return new c0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new u0({children:[U,new R0({height:1}),F,new K3,D]})})}}class rp extends d0{props;constructor(J){super();this.props=J}createState(){return new IO4}}import{isDeepStrictEqual as Ep0}from"node:util";var Ha5=/[\\/_ +.#"@[({&]/,Ba5=/[\\/_ +.#"@[({&]/g,wa5=/[\s-]/,jO4=/[\s-]/g;function i$0(J,Z,Q,X,Y,V,K){if(V===Z.length){if(Y===J.length)return 1;return 0.99}let z=`${Y},${V}`;if(K[z]!==void 0)return K[z];let G=X.charAt(V),F=Q.indexOf(G,Y),U=0,q,D,W,H;while(F>=0){if(q=i$0(J,Z,Q,X,F+1,V+1,K),q>U){if(F===Y)q*=1;else if(wa5.test(J.charAt(F-1))){if(q*=0.9,H=J.slice(Y,F-1).match(jO4),H&&Y>0)q*=0.999**H.length}else if(Ha5.test(J.charAt(F-1))){if(q*=0.8,W=J.slice(Y,F-1).match(Ba5),W&&Y>0)q*=0.999**W.length}else if(q*=0.3,Y>0)q*=0.999**(F-Y);if(J.charAt(F)!==Z.charAt(V))q*=0.9999}if(q<0.1&&(Q.charAt(F-1)===X.charAt(V+1)||X.charAt(V+1)===X.charAt(V)&&Q.charAt(F-1)!==X.charAt(V))){if(D=i$0(J,Z,Q,X,F+1,V+2,K),D*0.1>q)q=D*0.1}if(q>U)U=q;F=Q.indexOf(G,F+1)}return K[z]=U,U}function l$0(J){return J.toLowerCase().replace(jO4," ")}function RO4(J,Z){let Q=i$0(J,Z,l$0(J),l$0(Z),0,0,{}),X=Z.trim().split(/\s+/);if(X.length>1){let Y=0,V=0;for(let z of X){let G=i$0(J,z,l$0(J),l$0(z),0,0,{});if(G===0)return Q;Y+=G,V+=z.length}let K=Y/X.length*0.95;return Math.max(Q,K)}return Q}class nT{}class aT{}class n$0{}class a$0{}class PO4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new CO4}}class CO4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function Na5(J,Z){if(J==="")return{matches:!0,score:1};let Q=RO4(Z,J);return{matches:Q>0.15,score:Q}}class r9 extends d0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new TO4}}class TO4 extends p0{textController;focusNode;scrollController=new X5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new a7(this.widget.props.controller?.query??""),this.focusNode=new r4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>Ep0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!Ep0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>Ep0(Q,this.widget.props.controller?.selectedItem));if(Z>=0)this.selectedIndex=Z}this.clampSelectedIndex(),this.ensureSelectedItemVisible(),this.syncSelection()}}dispose(){this.widget.props.onSelectionChange?.(null),this.textController.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof nT){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof aT){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof n$0){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length){let Q=Z[this.selectedIndex];if(Q){if(!(this.widget.props.isItemDisabled?.(Q)??!1))this.widget.props.onAccept(Q,{hasUserInteracted:this.hasUserInteracted})}}return"handled"}if(J instanceof a$0)return this.widget.props.onDismiss?.(),"handled";return"ignored"};syncSelection(){let Z=this.cachedFiltered[this.selectedIndex]??null;if(this.widget.props.controller)this.widget.props.controller.selectedItem=Z;this.widget.props.onSelectionChange?.(Z)}clampSelectedIndex(){let J=this.cachedFiltered.length-1;if(J<0){this.selectedIndex=0;return}this.selectedIndex=Math.max(0,Math.min(this.selectedIndex,J))}recomputeFilteredItems(){let J=this.textController.text,Z=this.widget.props.items,Q=this.widget.props.normalizeQuery?.(J)??J,X=Z.filter((Y)=>!this.widget.props.filterItem||this.widget.props.filterItem(Y,J)).map((Y)=>({item:Y,...Na5(Q,this.widget.props.getLabel(Y))})).filter((Y)=>Y.matches).sort(this.widget.props.sortItems?(Y,V)=>this.widget.props.sortItems(Y,V,J):(Y,V)=>V.score-Y.score).map((Y)=>Y.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?X.slice(0,this.widget.props.maxRenderItems):X}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,X=Z.size.height;gT(J,{top:Q,bottom:X},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let X=Q[J],Y=X?this.widget.props.isItemDisabled?.(X)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!Y){if(X)this.hasUserInteracted=!0,this.widget.props.onAccept(X,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,X=this.getFilteredItems(),Y=x1.all(new v1(Q.foreground,1,"solid")),V=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,K=this.widget.props.enabled??!0,z=new FJ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:K,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),G=new T2({shortcuts:new Map([[new Y4("ArrowDown"),new nT],[new Y4("ArrowUp"),new aT],[new Y4("Tab"),new nT],[new Y4("Tab",{shift:!0}),new aT],[new Y4("n",{ctrl:!0}),new nT],[new Y4("p",{ctrl:!0}),new aT],[new Y4("Enter"),new n$0],[new Y4("Escape"),new a$0]]),focusNode:this.focusNode,child:z}),F=new k9({actions:new Map([[nT,new s4(this.invoke)],[aT,new s4(this.invoke)],[n$0,new s4(this.invoke)],[a$0,new s4(this.invoke)]]),child:G}),U=new U1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:F})]});this.itemContexts=[];let q;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";q=new R0({height:10,child:new l1({child:new $0({text:new C(w,new h({color:Q.foreground}))})})})}else if(X.length===0&&this.widget.props.emptyStateText)q=new T1({child:new l1({child:new $0({text:new C(this.widget.props.emptyStateText,new h({color:Q.foreground,dim:!0}))})})});else{let w=X.map((N,O)=>{let E=O===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(N,E,L,J);else{let A=E?Z.app.selectionBackground:void 0,I=E?Z.app.selectionForeground:Q.foreground;M=new c0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(this.widget.props.getLabel(N),new h({color:I,dim:L}))})})}return new PO4(new n1({onClick:(A)=>this.handleItemClick(O,A.clickCount),child:M}),(A)=>{this.itemContexts[O]=A})});q=new u0({children:w,crossAxisAlignment:"start"})}let D=new n1({onScroll:this.handleScroll,opaque:!1,child:new j6({controller:this.scrollController,autofocus:!1,child:q})}),W=[];if(this.widget.props.title){let w=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(this.widget.props.title,new h({color:Z.app.command,bold:!0}))})});W.push(w)}if(!V)W.push(U,new R0({height:1}));if(this.textController.text!==""){let w=X.length>0?X[this.selectedIndex]:void 0,N=w&&this.widget.props.buildDisabledReasonWidget?.(w,J);W.push(new T1({child:new u0({mainAxisAlignment:"spaceBetween",children:[new T1({child:D}),new c0({padding:C0.only({top:1}),child:new l1({child:N??new R0({height:1})})})]})}))}else W.push(new T1({child:D}));if(this.widget.props.footer)W.push(this.widget.props.footer);return new c0({decoration:{border:Y,color:Q.background},padding:C0.symmetric(1,0),child:new u0({children:W})})}}function _O4(J){let Q=new Date().getTime()-J.getTime(),X=Math.floor(Q/60000),Y=Math.floor(Q/3600000),V=Math.floor(Q/86400000);if(X<1)return"just now";if(X<60)return`${X}m ago`;if(Y<24)return`${Y}h ago`;if(V<7)return`${V}d ago`;return J.toLocaleDateString()}class Lp0 extends c1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((Y,V)=>V.pubDate.getTime()-Y.pubDate.getTime()),Q=Math.max(0,...Z.map((Y)=>_O4(Y.pubDate).length));return new r9({items:Z,getLabel:(Y)=>Y.title,onAccept:(Y)=>this.props.onSelect?.(Y),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(Y,V,K,z)=>{let G=f0.of(z),{colors:F}=G,U=G.app,q=V?U.selectionBackground:void 0,D=V?U.selectionForeground:F.foreground,W=F.mutedForeground,H=(B,w)=>new R0({width:w,child:U1.end([new $0({text:new C(B,new h({color:W}))})])});return new c0({decoration:q?{color:q}:void 0,padding:C0.symmetric(2,0),child:new U1({children:[new T1({child:new $0({text:new C(Y.title,new h({color:D})),overflow:"ellipsis",maxLines:1})}),new R0({width:2}),H(_O4(Y.pubDate),Q)]})})}})}}_4();class Mp0 extends d0{createState(){return new SO4}}class SO4 extends p0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new $0({text:new C("●",new h({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}var Oa5=/\/threads\/(T-[^/?#\s<>]+)/i;function Ea5(J){let Z=J.trim(),X=Z.match(Oa5)?.[1];if(X&&W8(X))return X;let Y=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(W8(Y))return Y;return null}function La5(J){let Z=new Map,Q=new Map,X=new Map,Y=[];for(let K of J)Z.set(K.id,K);for(let K of J){let z=K.relationships.find((G)=>G.role==="child"&&Z.has(G.threadID)&&(G.type==="fork"||G.type==="handoff"));if(z){X.set(K.id,z.type);let G=z.threadID,F=Q.get(G)||[];F.push(K),Q.set(G,F)}else Y.push(K)}return N20.flatten(Y,(K)=>Q.get(K.id)).map((K)=>({...K.item,depth:K.depth,isLast:K.isLast,ancestorsAreLast:K.ancestorsAreLast,relationshipType:X.get(K.item.id)}))}function Ap0(J,Z,Q){return new $0({text:new C(`${J}${Z}`,new h({color:Q})),maxLines:1})}function Ma5(J,Z,Q,X){return[Ap0("+",J,X.success),K3.horizontal(1),Ap0("~",Z,X.warning),K3.horizontal(1),Ap0("-",Q,X.destructive)]}function Aa5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class o$0 extends d0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new vO4}}class vO4 extends p0{spinner=new v3;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,X=this.isSwitchingThread?"Switching thread...":"Loading threads...",Y=`${this.spinner.toBraille()} ${X}`,V=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((O)=>O.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)V=V.filter((O)=>O.id!==Z.currentThreadID);let K=Z.recentThreadIDs||[],z=new Set(K),G=Z.currentThreadID,F=[...V].sort((O,E)=>{if(G){if(O.id===G)return-1;if(E.id===G)return 1}let L=K.indexOf(O.id),M=K.indexOf(E.id);if(L!==-1&&M!==-1)return L-M;if(L!==-1)return-1;if(M!==-1)return 1;return 0}),U=La5(F),q=Math.max(0,...U.map((O)=>O.description.timeAgo.length)),D=f0.of(J),W=new i0({padding:C0.symmetric(0,1),child:new l1({child:new $0({text:new C("",new h({color:D.colors.foreground,dim:!0}),[new C("Ctrl+T",new h({color:D.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new h({color:D.colors.foreground,dim:!0}))])})})}),H="",B=null,w=(O)=>{if(O!==H)H=O,B=Ea5(O);return B};return new r9({items:U,getLabel:(O)=>`${O.title} ${O.id}`,filterItem:(O,E)=>{let L=w(E);if(L)return O.id.toLowerCase()===L.toLowerCase();return!0},normalizeQuery:(O)=>w(O)?"":O,onAccept:async(O,E)=>{if(!Z.onSelect||this.isSwitchingThread)return;let L=Z.onSelect(O.id,E);if(!Aa5(L))return;this.setSwitchingThread(!0);try{await L}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(O)=>{if(Z.previewController){if(O)Z.previewController.select(O.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:Y,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:W,renderItem:(O,E,L,M)=>{let A=f0.of(M),{app:I,colors:P}=A,_=E?I.selectionBackground:void 0,S=E?I.selectionForeground:P.foreground,y=P.mutedForeground,m=(s,B0)=>new R0({width:B0,child:U1.end([new $0({text:new C(s,new h({color:y}))})])}),b=Z.threadViewStates[O.id],v=[],f=O.relationshipType==="handoff",g=new Ep({connectorColor:P.mutedForeground});if(O.depth>0){let s=[],B0=O.ancestorsAreLast.slice(1);for(let W0 of B0)s.push(new C(g.getAncestorPrefix(W0),new h({color:g.connectorColor,dim:g.connectorDim})));let o=O.isLast?g.elbow:g.tee,G0=g.getConnectorText(o);s.push(new C(G0,new h({color:g.connectorColor,dim:g.connectorDim}))),v.push(new $0({text:new C("",void 0,s)}))}let d=[],x=G===O.id?new C("(current) ",new h({color:P.success})):z.has(O.id)?new C("(visited) ",new h({color:P.foreground,dim:!0})):null;if(x)d.push(new $0({text:x}));if(nO(b))d.push(new Mp0),d.push(new R0({width:1}));let a=O.title;if(O.relationshipType==="fork"){let s=a.match(/^Forked\((\d+)\): /);if(s)a=a.slice(s[0].length);else while(a.startsWith("Forked: "))a=a.slice(8);d.push(new $0({text:new C("[fork] ",new h({color:P.primary}))}))}else if(f)d.push(new $0({text:new C("[handoff] ",new h({color:P.accent}))}));if(d.push(new T1({child:new $0({text:new C(a,new h({color:S})),overflow:"ellipsis",maxLines:1})})),d.push(new R0({width:2})),O.diffStats&&(O.diffStats.added>0||O.diffStats.changed>0||O.diffStats.deleted>0)){let s=E?{success:y,warning:y,destructive:y}:P;d.push(...Ma5(O.diffStats.added,O.diffStats.changed,O.diffStats.deleted,s)),d.push(new R0({width:2}))}return d.push(m(O.description.timeAgo,q)),new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new U1({children:[...v,...d]})})}})}}function kO4(J){return 1-(1-J)**3}function yO4(J,Z,Q){return J+(Z-J)*Q}function sp(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,X=Math.min(Q/J.durationX,1),Y=Math.min(Q/J.durationY,1),V=kO4(X),K=kO4(Y);return{x:yO4(J.startOffset.x,J.targetOffset.x,V),y:yO4(J.startOffset.y,J.targetOffset.y,K)}}var Ia5={nodeWidth:3,horizontalSpacing:3};class oT{options;constructor(J={}){this.options={...Ia5,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),X=[],Y=Z.get(void 0)??[];if(this.options.comparator)Y.sort(this.options.comparator);let V=0,K=(z,G)=>{let F=Z.get(z.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let U={...z,parentID:Q.get(z.id)};if(F.length===0){X.push({node:U,position:{x:V,y:G}});let B=V;return V+=this.options.nodeWidth+this.options.horizontalSpacing,B}let q=[];for(let B of F)q.push(K(B,G+1));let D=Math.min(...q),W=Math.max(...q),H=Math.floor((D+W)/2);return X.push({node:U,position:{x:H,y:G}}),H};for(let z of Y)K(z,0);return X}buildTree(J){let Z=new Set(J.map((V)=>V.id)),Q=[...J].sort((V,K)=>V.id.localeCompare(K.id)),X=new Map;for(let V of Q){if(!V.parentID||!Z.has(V.parentID)){X.set(V.id,void 0);continue}let K=!1,z=V.parentID;while(z){if(z===V.id){K=!0;break}z=X.get(z)}X.set(V.id,K?void 0:V.parentID)}let Y=new Map;for(let V of J){let K=X.get(V.id);if(!Y.has(K))Y.set(K,[]);Y.get(K).push(V)}return{childrenMap:Y,resolvedParent:X}}}var ja5={nodeWidth:3,nodeHeight:2};class rT{options;constructor(J={}){this.options={...ja5,...J}}calculate(J){let Z=[],Q=new Map;for(let X of J)Q.set(X.node.id,X);for(let X of J){if(!X.node.parentID)continue;let Y=Q.get(X.node.parentID);if(!Y)continue;let V=this.calculateConnectorLine(Y.position,X.position);Z.push({points:V,fromNodeID:Y.node.id,toNodeID:X.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),X=[],Y=J.x+Q,V=Z.x+Q,K=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;X.push({x:Y,y:K});let z=K+1;if(X.push({x:Y,y:z}),Y!==V)X.push({x:V,y:z});let G=Z.y*(this.options.nodeHeight+3)-1;return X.push({x:V,y:G}),X}}var Ra5={nodeWidth:3,nodeHeight:2},Pa5={x:0,y:0};class s$0{options;constructor(J={}){this.options={...Ra5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,X=Pa5,Y,V,K,z){let G=z?f0.of(z):null,F=G?.colors,U=G?.app,q=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:q}))});let D=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,w=[];for(let I=D;I>=0;I--){let P=J.filter((y)=>y.position.y===I);P.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new R0({width:y.position.x-S}));let m=y.node.id===Q,b=K?.(y.node.data)??!1,v=V?.activeFlashOn??!1,f=y.node.id===V?.copyFlashNodeId;_.push(this.renderNode(m,b,v,f,U,F)),S=y.position.x+this.options.nodeWidth}if(w.push(new U1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((v)=>v.position.y===I-1),m=P,b=this.renderConnectors(y,m,Z,H,F,U);w.push(...b)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(X.x),E=Math.round(X.y*B),L=(D+1)*B,M=[new R0({width:H,height:L}),new x6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&Y){let I=Y(A.node.data),P=D-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+P*B+1,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(I,y,F,U)}))}return new c0({padding:C0.horizontal(2),child:new TH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,X,Y,V){let K="┌─┐",z="└─┘",G=J?Y?.threadGraphNodeSelected??V?.primary??V?.foreground:Y?.threadGraphNode??V?.primary??V?.foreground,F=!1;if(X)G=Y?.threadGraphNodeSelected??V?.primary??G,K="┏━┓",z="┗━┛",F=!0;else if(Z&&Q)G=Y?.toolSuccess??V?.primary??G,K="┏━┓",z="┗━┛";return new u0({crossAxisAlignment:"start",children:[new $0({text:new C(K,new h({color:G,bold:F}))}),new $0({text:new C(z,new h({color:G,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),X=[],Y="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(Y.length===0)Y=V;else if(Y.length+1+V.length<=Z)Y+=" "+V;else X.push(Y),Y=V}if(Y.length>0)X.push(Y);return X}renderInfoBox(J,Z=30,Q,X){let Y=this.wrapText(J,Z),V=Math.min(Z,Math.max(1,...Y.map((D)=>D.length))),K=V+2,z="┌"+"─".repeat(K)+"┐",G="└"+"─".repeat(K)+"┘",F=Q?.border??X?.threadGraphConnector??Q?.foreground,U=Q?.foreground,q=[new $0({text:new C(z,new h({color:F}))})];for(let D of Y){let W=" ".repeat(V-D.length);q.push(new $0({text:new C("│ ",new h({color:F}),[new C(D+W,new h({color:U??F})),new C(" │",new h({color:F}))])}))}return q.push(new $0({text:new C(G,new h({color:F}))})),new u0({crossAxisAlignment:"start",children:q})}renderConnectors(J,Z,Q,X,Y,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??Y?.primary??Y?.foreground,F=Array(X).fill(" ");for(let D of Z){let W=D.position.x+z;if(W>=0&&W<X)F[W]="▲"}K.push(new $0({text:new C(F.join(""),new h({color:G}))}));let U=Array(X).fill(" ");for(let D of J){let W=Z.filter((O)=>O.node.parentID===D.node.id);if(W.length===0)continue;let H=D.position.x+z,B=W.map((O)=>O.position.x+z),w=Math.min(...B),N=Math.max(...B);for(let O=w;O<=N;O++)if(O>=0&&O<X){if(O===H)if(W.length===1&&B[0]===H)U[O]="│";else if(O===w)U[O]="└";else if(O===N)U[O]="┘";else U[O]="┬";else if(B.includes(O))if(O===w)U[O]="└";else if(O===N)U[O]="┘";else U[O]="┴";else if(U[O]===" ")U[O]="─"}}K.push(new $0({text:new C(U.join(""),new h({color:G}))}));let q=Array(X).fill(" ");for(let D of J){if(Z.filter((B)=>B.node.parentID===D.node.id).length===0)continue;let H=D.position.x+z;if(H>=0&&H<X)q[H]="│"}return K.push(new $0({text:new C(q.join(""),new h({color:G}))})),K}}var Ca5={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},Ta5={x:0,y:0};class Ip0{options;constructor(J={}){this.options={...Ca5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,X=Ta5,Y,V,K,z){let G=z?f0.of(z):null,F=G?.colors,U=G?.app,q=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:q}))});let D=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,w=[];for(let I=D;I>=0;I--){let P=J.filter((y)=>y.position.y===I);P.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new R0({width:y.position.x-S}));let m=y.node.id===Q,b=K?.(y.node.data)??!1,v=V?.activeFlashOn??!1;_.push(this.renderNode(m,b,v,U,F)),S=y.position.x+this.options.nodeWidth}if(w.push(new U1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((v)=>v.position.y===I-1),m=P,b=this.renderConnectors(y,m,Z,H,F,U);w.push(...b)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(X.x),E=Math.round(X.y*B),L=(D+1)*B,M=[new R0({width:H,height:L}),new x6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&Y){let I=Y(A.node.data),P=D-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+P*B,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(I,y,F)}))}return new c0({padding:C0.horizontal(2),child:new TH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,X,Y){let V=J?this.options.selectedIcon:this.options.nodeIcon,K=J?X?.threadGraphNodeSelected??Y?.primary??Y?.foreground:X?.threadGraphNode??Y?.primary??Y?.foreground;if(Z&&Q)K=X?.toolSuccess??Y?.primary??K,V="■";return new $0({text:new C(V,new h({color:K}))})}wrapText(J,Z){let Q=J.split(" "),X=[],Y="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(Y.length===0)Y=V;else if(Y.length+1+V.length<=Z)Y+=" "+V;else X.push(Y),Y=V}if(Y.length>0)X.push(Y);return X}renderInfoBox(J,Z=30,Q){let X=this.wrapText(J,Z),Y=Q?.foreground,V=[];for(let K of X)V.push(new $0({text:new C(K,new h({color:Y??Q?.primary??Q?.foreground}))}));return new u0({crossAxisAlignment:"start",children:V})}renderConnectors(J,Z,Q,X,Y,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??Y?.primary??Y?.foreground,F=Array(X).fill(" ");for(let U of J){let q=Z.filter((w)=>w.node.parentID===U.node.id);if(q.length===0)continue;let D=U.position.x+z,W=q.map((w)=>w.position.x+z),H=Math.min(...W),B=Math.max(...W);for(let w=H;w<=B;w++)if(w>=0&&w<X){let N=w===D,O=W.includes(w);if(N&&O)if(q.length===1)F[w]="│";else if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┼";else if(N)if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┬";else if(O)if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┴";else if(F[w]===" ")F[w]="─"}}return K.push(new $0({text:new C(F.join(""),new h({color:G}))})),K}}class tp extends E3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new uO4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class uO4 extends A4{onWidth;onHeight;constructor(J,Z){super();this.onWidth=J,this.onHeight=Z}performLayout(){let J=this._lastConstraints,Z=Number.isFinite(J.maxWidth)?J.maxWidth:80,Q=Number.isFinite(J.maxHeight)?J.maxHeight:24;this.onWidth(Z),this.onHeight?.(Q);let X=this.children[0];if(X)X.layout(J),this.setSize(X.size.width,X.size.height);else this.setSize(J.minWidth,J.minHeight)}paint(J,Z,Q){for(let X of this.children)X.paint(J,Z,Q)}}class iL extends d0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new bO4}}var xO4=400,fO4=300,_a5=16;class bO4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",X=Z.data.updatedAt??"";return Q.localeCompare(X)};layoutEngine=new oT({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new rT;renderer=new Ip0;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((X)=>X.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((G)=>G.id)),Q=new Set(this.widget.props.threads.map((G)=>G.id));if(Z.size!==Q.size||[...Z].some((G)=>!Q.has(G)))this.stopAnimation(),this.currentOffset={x:0,y:0};let Y=J.props.initialSelectedThreadID,V=this.widget.props.initialSelectedThreadID;if(Y!==V&&V){let F=this.widget.props.threads.find((U)=>U.id===V);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let K=J.props.threads.some((G)=>G.isActive),z=this.widget.props.threads.some((G)=>G.isActive);if(K!==z){if(this.stopActiveFlashTimer(),z)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:xO4,durationY:fO4};let Z=Math.max(xO4,fO4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=sp(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},_a5)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let X=Math.floor(this.renderer.getNodeWidth()/2),V=Math.floor(this.viewportWidth/2)-J-X,K=Q-Z,z=2,G=Math.floor(this.viewportHeight/2),U=Math.floor(G/2)-K;return{x:V,y:U}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((Y)=>Y.position.y)),X=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(X)}}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((Y)=>Y.node.id===this.selectedNodeId);if(!Q)return"ignored";let X;switch(J.key){case"ArrowUp":{let Y=Z.filter((V)=>V.node.parentID===Q.node.id);if(Y.length>0){Y.sort((K,z)=>K.position.x-z.position.x);let V=Math.floor(Y.length/2);X=Y[V]}break}case"ArrowDown":{X=Z.find((Y)=>Y.node.id===Q.node.parentID);break}case"ArrowLeft":{let Y=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x<Q.position.x);if(Y.length>0)Y.sort((V,K)=>K.position.x-V.position.x),X=Y[0];break}case"ArrowRight":{let Y=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x>Q.position.x);if(Y.length>0)Y.sort((V,K)=>V.position.x-K.position.x),X=Y[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(X)return this.selectedNodeId=X.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(X)),this.animateToNode(X.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let U=(this.selectedNodeId?this.positionedNodes.find((q)=>q.node.id===this.selectedNodeId):null)??this.positionedNodes.find((q)=>!q.node.parentID);if(U){let q=Math.max(...this.positionedNodes.map((D)=>D.position.y));this.currentOffset=this.calculateCenterOffset(U.position.x,U.position.y,q)}}let Y=this.widget.props.showTitle??!0,V=this.widget.props.offsetY??0,K={x:this.currentOffset.x,y:this.currentOffset.y+V},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,K,Y?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),G=new tp({onWidth:(F)=>{if(this.viewportWidth!==F)this.viewportWidth=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(F)=>{if(this.viewportHeight!==F)this.viewportHeight=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new k4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:G})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class mO4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new gO4}}class gO4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var hO4=30,Sa5=30;class sT{}class tT{}class t$0{}class e$0{}class jp0 extends d0{props;constructor(J){super();this.props=J}createState(){return new pO4}}class pO4 extends p0{highlightedIndex=0;controller=new a7;focusNode;scrollController=new X5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new r4({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,X=Z.size.height;gT(J,{top:Q,bottom:X},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Z}=this.widget.props;if(!J)this.filteredClusters=[...Z];else this.filteredClusters=Z.filter((Q)=>Q.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof sT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof tT){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof t$0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof e$0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:X,app:Y}=Q,z=t1.of(J).size.width>=Sa5+hO4,G=x1.all(new v1(X.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,U=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("Select a cluster",new h({color:Y.command,bold:!0}))})}),q=new FJ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:X.foreground,border:null},maxLines:1}),D=new T2({shortcuts:new Map([[new Y4("ArrowDown"),new sT],[new Y4("ArrowUp"),new tT],[new Y4("Tab"),new sT],[new Y4("Tab",{shift:!0}),new tT],[new Y4("n",{ctrl:!0}),new sT],[new Y4("p",{ctrl:!0}),new tT],[new Y4("Enter"),new t$0],[new Y4("Escape"),new e$0]]),focusNode:this.focusNode,child:q}),W=new k9({actions:new Map([[sT,new s4(this.invoke)],[tT,new s4(this.invoke)],[t$0,new s4(this.invoke)],[e$0,new s4(this.invoke)]]),child:D}),H=new U1({children:[new c0({decoration:{color:X.background},child:new $0({text:new C(">",new h({color:X.foreground}))})}),new T1({child:W})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let I=A===this.highlightedIndex,P=Z?M.threads.some((m)=>m.id===Z):!1,_=I?Y.selectionBackground:void 0,S=I?Y.selectionForeground:X.foreground,y=[new C(M.label,new h({color:S})),new C(` (${M.threads.length})`,new h({color:S,dim:!0}))];if(P)y.push(new C(" (current)",new h({color:I?Y.selectionForeground:X.success})));return new mO4(new n1({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,y)})})}),(m)=>{this.itemContexts[A]=m})}),w=new u0({children:B,crossAxisAlignment:"start"}),N=new T1({child:new n1({onScroll:this.handleScroll,child:new j6({controller:this.scrollController,autofocus:!1,child:w})})}),O=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],E=F?new c0({padding:C0.all(1),child:new iL({threads:O,autofocus:!1,offsetY:2})}):null,L;if(z){let M=E?new T1({child:E}):new R0({width:hO4});L=new U1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,M]})}else{let M=[new T1({child:new n1({onScroll:this.handleScroll,child:new j6({controller:this.scrollController,autofocus:!1,child:w})})})];if(E)M.push(new T1({child:E}));L=new u0({crossAxisAlignment:"stretch",children:M})}return new c0({decoration:{border:G,color:X.background},padding:C0.symmetric(1,0),child:new u0({children:[U,H,new R0({height:1}),new T1({child:L})]})})}}class UJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!UJ._instance)UJ._instance=new UJ;return UJ._instance}get allExpanded(){return this._allExpanded}setAllExpanded(J){if(this._allExpanded===J)return;this._allExpanded=J,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(J){return this._listeners.add(J),()=>this.removeListener(J)}removeListener(J){this._listeners.delete(J)}_notifyListeners(){for(let J of this._listeners)J()}}h0();class dO4 extends p0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){j.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){j.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],X=this.labels.some((V)=>V.name===Z),Y=Q.includes(Z);return!X&&!Y}build(J){let Z=f0.of(J),{app:Q,colors:X}=Z,Y=this.currentQuery.trim().toLowerCase(),V=Y.length>0?this.getValidationError(Y):null,K=this.getAvailableLabels(),G=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...K];return new r9({title:"Add Label",items:G,getLabel:(F)=>{if("__isCreateMarker"in F)return this.currentQuery.trim().toLowerCase();return F.name},onAccept:(F)=>{if("__isCreateMarker"in F)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(F.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:V||"Type to create a new label",renderItem:(F,U,q,D)=>{let W=U?Q.selectionBackground:void 0,H=U?Q.selectionForeground:X.foreground;if("__isCreateMarker"in F&&F.__isCreateMarker){let w=this.currentQuery.trim().toLowerCase();return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,[new C("Create new label: ",new h({color:H})),new C(w,new h({color:H,bold:!0}))])})})}return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(F.name,new h({color:H}))})})},filterItem:(F,U)=>{if(this.currentQuery!==U)this.currentQuery=U,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in F&&F.__isCreateMarker)return this.shouldShowCreateMarker(U);let D=U.trim().toLowerCase();return D.length===0||F.name.includes(D)},sortItems:(F,U,q)=>{let D="__isCreateMarker"in F.item&&F.item.__isCreateMarker,W="__isCreateMarker"in U.item&&U.item.__isCreateMarker;if(D&&!W)return-1;if(!D&&W)return 1;return U.score-F.score}})}}class Rp0 extends d0{props;constructor(J){super();this.props=J}createState(){return new dO4}}class lV extends d0{props;constructor(J){super();this.props=J}createState(){return new cO4}}class cO4 extends p0{_spinner=new v3;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:X}=Z,Y=x1.all(new v1(Q.foreground,1,"solid")),V=this._spinner.toBraille(),K=new $0({textAlign:"center",text:new C("",void 0,[new C(V,new h({color:X.processing})),new C(" ",void 0),new C(this.widget.props.message,new h({color:Q.foreground}))])}),G=[new T1({child:new u0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[K]})})];if(this.widget.props.onAbort)G.push(new R0({height:2,child:new c0({padding:C0.symmetric(2,0),child:new $0({text:new C("",new h({dim:!0}),[new C("Press ",new h({color:Q.foreground})),new C("Esc",new h({color:Q.info})),new C(" to cancel",new h({color:Q.foreground}))])})})}));let F=new c0({decoration:new v4(Q.background,Y),child:new R0({width:60,height:7,child:new u0({mainAxisAlignment:"start",children:G})})});if(this.widget.props.onAbort)return new k4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(U)=>{if(U.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:F});return F}}var ep={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"}},$J0=["workspace","global","flag","default","external","skill","other"];function va5(J){return Array.from(new Set(J))}function lO4(J){return va5([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function eT(J){if(J.isExternal)return"external";switch(J.spec._target){case"workspace":return"workspace";case"global":return"global";case"flag":return"flag";case"default":return"default"}return lO4(J).length>0?"skill":"other"}function Pp0(J){return eT(J)==="skill"}function iO4(J){let Z=lO4(J);if(Z.length===0)return;let Q=Z.join(", "),X=eT(J);if(X==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${ep[X].description}: ${Q}`}function nO4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}var aO4=process.platform==="win32"?" ":"█",oO4=process.platform==="win32"?"░":"█";class u8 extends d0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:X=1,trackChar:Y=aO4,thumbChar:V=oO4,showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=X,this.trackChar=Y,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createState(){return new rO4}}class rO4 extends p0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),Y=this.context.findRenderObject()?.size.height??0;if(Y===0||Z<=Q)return!1;let V=this.widget.getScrollInfo(),K=Math.min(1,Q/Z),z=Math.max(1,Y*K),G=Math.max(0,Math.min(1,V.scrollOffset/(Z-Q))),F=Y-z,U=Math.max(0,F*G),q=U+z;return J>=U&&J<=q}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:X}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=X;let K=J.localPosition.y-this._dragStartY,z=Math.min(1,Q/Z),G=Math.max(1,V*z),F=V-G;if(F<=0)return;let U=Z-Q,q=F/U,D=K/q,W=Math.max(0,Math.min(U,this._dragStartOffset+D));this.widget.controller.jumpTo(W)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:X,scrollOffset:Y}=this.widget.getScrollInfo(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Q<=X)return;let z=Math.min(1,X/Q),G=Math.max(1,K*z),F=Q-X,U=K-G,q=Math.max(0,Math.min(1,Y/(Q-X))),D=Math.max(0,U*q),W=D+G;if(Z>=D&&Z<=W)return;if(Z<D)this.widget.controller.animateTo(Math.max(0,Y-X));else this.widget.controller.animateTo(Math.min(F,Y+X))};build(J){return new n1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?E5.POINTER:E5.DEFAULT,child:new sO4({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 sO4 extends sC{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:X=1,trackChar:Y=aO4,thumbChar:V=oO4,showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=X,this.trackChar=Y,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createRenderObject(){return new tO4(this)}updateRenderObject(J){J.updateWidget(this)}}class tO4 extends A4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;b4(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:X,thumbSizeFloat:Y,showScrollbar:V}=this._calculateScrollbarMetrics();if(!V)return;let K=this._widget.trackColor,z=this._widget.thumbColor,G=process.platform==="win32",F=X,U=X+Y;if(!G){let q=["▁","▂","▃","▄","▅","▆","▇","█"];for(let D=0;D<this.size.height;D++){let W="█",H=!0;if(D===Math.floor(F)){let B=1-(F-D),w=Math.floor(B*8);W=q[w]||"█",H=!1}else if(D===Math.floor(U)){let B=1-(U-D),w=Math.floor(B*8);W=q[w]||"█"}else if(D>F&&D<U)H=!1;J.setChar(Z,Q+D,W,{fg:z,bg:K,reverse:H},1)}return}for(let q=0;q<this.size.height;q++){let D=q+0.5,W=D>=F&&D<U,H=W?this._widget.thumbChar:this._widget.trackChar;J.setChar(Z,Q+q,H,{fg:W?z:K,bg:K,reverse:!1},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),X=this.size.height;if(J<=Z||X<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let Y=Math.max(0,Math.min(1,Q/(J-Z))),V=Math.min(1,Z/J),K=Math.max(1,X*V),z=X-K;return{thumbStartFloat:Math.max(0,z*Y),thumbSizeFloat:K,showScrollbar:!0}}}class nL extends d0{props;constructor(J){super();this.props=J}createState(){return new eO4}}class eO4 extends p0{scrollController=new X5;scrollAreaKey=new d7("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 v2}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,X=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let U=T$0(Q);return{title:U.title,type:U.type,description:U.description}})(),Y=X.type==="error"?Z.app.toolError:Z.app.command,V=x1.all(new v1(Z.colors.border,1,"solid")),K=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(X.title,new h({color:Y,bold:!0}))})}),z=this.isWidgetMessage(Q)?Q.widget:new $0({text:new C(X.description,new h({color:Z.colors.foreground})),selectable:!0}),G=new T1({child:new _2({child:new c0({padding:C0.symmetric(1,0),child:new U1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new j6({controller:this.scrollController,autofocus:!0,child:z})}),new u8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let U=this.scrollController.maxScrollExtent,q=this.scrollController.offset,D=this.getViewportHeight(),W=U+D;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(D,1),scrollOffset:Math.max(q,0)}}})]})})})}),F=new c0({padding:C0.symmetric(1,0),child:new $0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new h({color:Z.colors.foreground,dim:!0})),new C("R",new h({color:Z.app.keybind})),new C(" to retry, ",new h({color:Z.colors.foreground,dim:!0})),new C("Esc",new h({color:Z.app.keybind})),new C(" to cancel",new h({color:Z.colors.foreground,dim:!0}))]);let U=this.resolveFooterStyle(this.widget.props.message);if(U==="none")return new C("",new h({color:Z.colors.foreground,dim:!0}));if(U==="help"){let q=new h({color:Z.app.keybind}),D=new h({color:Z.colors.foreground,dim:!0});return new C("",D,[new C("Press ",D),new C("Escape",q),new C(" to close • Use ",D),new C("↑↓",q),new C(" or ",D),new C("j/k",q),new C(" to scroll",D)])}return new C("Press any key to close",new h({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new k4({onKey:(U)=>{if(this.widget.props.onRetry&&U.key==="r")return this.widget.props.onRetry(),"handled";if(U.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new c0({decoration:{border:V,color:Z.colors.background},padding:C0.all(1),child:new u0({mainAxisAlignment:"center",children:[K,new R0({height:1}),G,F]})})})}}m9();class $E4 extends d0{props;constructor(J){super();this.props=J}createState(){return new JE4}}class JE4 extends p0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((J)=>{this.plugins=J,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(J){let Z=J.startsWith("file://")?J.slice(7):J,Q=this.widget.props.cwd;if(Z.startsWith(Q))return Z.slice(Q.length+1);return Z}statusIcon(J){let Z=l8.default(),{colors:Q,app:X}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:X.toolSuccess};case"error":return{icon:"✗",color:X.toolError}}}build(J){let Z=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new $0({text:new C("No plugins found.",new h({dim:!0}))});let X=[],Y=this.plugins.length,V=this.plugins.filter((G)=>G.status==="active").length,K=this.plugins.reduce((G,F)=>G+F.registeredCommands.length,0),z=this.plugins.reduce((G,F)=>G+F.registeredTools.length,0);if(X.push(new C(`${V}/${Y} ${u4(Y,"plugin")} active`,new h({bold:!0}))),K>0||z>0)X.push(new C(` (${K} ${u4(K,"command")}, ${z} ${u4(z,"tool")})`,new h({dim:!0})));X.push(new C(`
|
|
7299
|
+
`))}if(H)q.push(new C(" ",U)),q.push(new C("Total: ",U)),q.push(new C(V(B),F))}return new c0({decoration:{color:z.background,border:x1.all(new v1(z.border,1,"rounded"))},child:new $0({text:new C(void 0,void 0,q)})})}JN();h0();m9();import{execSync as da5}from"node:child_process";DN();C7();w3();P7();Vh();xY();o2();h$();yY();jE();_4();Nx();Ek();H1();var ME4=D4(SF(),1);import{writeFile as wE4}from"fs/promises";import NE4 from"path";h0();o2();class Op0{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.1773705849-gda80e7"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await ft(Z,this.configService)}catch(Z){j.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class YB extends d0{props;constructor(J){super();this.props=J}createState(){return new AO4}}class AO4 extends p0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class IO4 extends p0{controller=new a7;focusNode=new r4({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:X}=Z,Y=this.widget.props.isRequiredArg??!0,V=this.controller.text.trim().length>0,K=!Y||V,z=x1.all(new v1(Q.foreground,1,"solid")),G=new FJ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(W)=>{let H=W.trim();if(Y&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new U1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:G})]}),U=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,[new C("Command: ",new h({color:Q.foreground})),new C(this.widget.props.commandName,new h({color:X.command,bold:!0}))])})}),q=[];if(K)q.push(new C("Enter",new h({color:X.keybind}))),q.push(new C(" to submit, ",new h({color:Q.foreground,dim:!0})));q.push(new C("Esc",new h({color:X.keybind}))),q.push(new C(" to cancel",new h({color:Q.foreground,dim:!0})));let D=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,q)})});return new c0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new u0({children:[U,new R0({height:1}),F,new K3,D]})})}}class rp extends d0{props;constructor(J){super();this.props=J}createState(){return new IO4}}import{isDeepStrictEqual as Ep0}from"node:util";var Ha5=/[\\/_ +.#"@[({&]/,Ba5=/[\\/_ +.#"@[({&]/g,wa5=/[\s-]/,jO4=/[\s-]/g;function i$0(J,Z,Q,X,Y,V,K){if(V===Z.length){if(Y===J.length)return 1;return 0.99}let z=`${Y},${V}`;if(K[z]!==void 0)return K[z];let G=X.charAt(V),F=Q.indexOf(G,Y),U=0,q,D,W,H;while(F>=0){if(q=i$0(J,Z,Q,X,F+1,V+1,K),q>U){if(F===Y)q*=1;else if(wa5.test(J.charAt(F-1))){if(q*=0.9,H=J.slice(Y,F-1).match(jO4),H&&Y>0)q*=0.999**H.length}else if(Ha5.test(J.charAt(F-1))){if(q*=0.8,W=J.slice(Y,F-1).match(Ba5),W&&Y>0)q*=0.999**W.length}else if(q*=0.3,Y>0)q*=0.999**(F-Y);if(J.charAt(F)!==Z.charAt(V))q*=0.9999}if(q<0.1&&(Q.charAt(F-1)===X.charAt(V+1)||X.charAt(V+1)===X.charAt(V)&&Q.charAt(F-1)!==X.charAt(V))){if(D=i$0(J,Z,Q,X,F+1,V+2,K),D*0.1>q)q=D*0.1}if(q>U)U=q;F=Q.indexOf(G,F+1)}return K[z]=U,U}function l$0(J){return J.toLowerCase().replace(jO4," ")}function RO4(J,Z){let Q=i$0(J,Z,l$0(J),l$0(Z),0,0,{}),X=Z.trim().split(/\s+/);if(X.length>1){let Y=0,V=0;for(let z of X){let G=i$0(J,z,l$0(J),l$0(z),0,0,{});if(G===0)return Q;Y+=G,V+=z.length}let K=Y/X.length*0.95;return Math.max(Q,K)}return Q}class nT{}class aT{}class n$0{}class a$0{}class PO4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new CO4}}class CO4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function Na5(J,Z){if(J==="")return{matches:!0,score:1};let Q=RO4(Z,J);return{matches:Q>0.15,score:Q}}class r9 extends d0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new TO4}}class TO4 extends p0{textController;focusNode;scrollController=new X5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new a7(this.widget.props.controller?.query??""),this.focusNode=new r4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>Ep0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!Ep0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>Ep0(Q,this.widget.props.controller?.selectedItem));if(Z>=0)this.selectedIndex=Z}this.clampSelectedIndex(),this.ensureSelectedItemVisible(),this.syncSelection()}}dispose(){this.widget.props.onSelectionChange?.(null),this.textController.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof nT){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof aT){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof n$0){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length){let Q=Z[this.selectedIndex];if(Q){if(!(this.widget.props.isItemDisabled?.(Q)??!1))this.widget.props.onAccept(Q,{hasUserInteracted:this.hasUserInteracted})}}return"handled"}if(J instanceof a$0)return this.widget.props.onDismiss?.(),"handled";return"ignored"};syncSelection(){let Z=this.cachedFiltered[this.selectedIndex]??null;if(this.widget.props.controller)this.widget.props.controller.selectedItem=Z;this.widget.props.onSelectionChange?.(Z)}clampSelectedIndex(){let J=this.cachedFiltered.length-1;if(J<0){this.selectedIndex=0;return}this.selectedIndex=Math.max(0,Math.min(this.selectedIndex,J))}recomputeFilteredItems(){let J=this.textController.text,Z=this.widget.props.items,Q=this.widget.props.normalizeQuery?.(J)??J,X=Z.filter((Y)=>!this.widget.props.filterItem||this.widget.props.filterItem(Y,J)).map((Y)=>({item:Y,...Na5(Q,this.widget.props.getLabel(Y))})).filter((Y)=>Y.matches).sort(this.widget.props.sortItems?(Y,V)=>this.widget.props.sortItems(Y,V,J):(Y,V)=>V.score-Y.score).map((Y)=>Y.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?X.slice(0,this.widget.props.maxRenderItems):X}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,X=Z.size.height;gT(J,{top:Q,bottom:X},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let X=Q[J],Y=X?this.widget.props.isItemDisabled?.(X)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!Y){if(X)this.hasUserInteracted=!0,this.widget.props.onAccept(X,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,X=this.getFilteredItems(),Y=x1.all(new v1(Q.foreground,1,"solid")),V=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,K=this.widget.props.enabled??!0,z=new FJ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:K,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),G=new T2({shortcuts:new Map([[new Y4("ArrowDown"),new nT],[new Y4("ArrowUp"),new aT],[new Y4("Tab"),new nT],[new Y4("Tab",{shift:!0}),new aT],[new Y4("n",{ctrl:!0}),new nT],[new Y4("p",{ctrl:!0}),new aT],[new Y4("Enter"),new n$0],[new Y4("Escape"),new a$0]]),focusNode:this.focusNode,child:z}),F=new k9({actions:new Map([[nT,new s4(this.invoke)],[aT,new s4(this.invoke)],[n$0,new s4(this.invoke)],[a$0,new s4(this.invoke)]]),child:G}),U=new U1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:F})]});this.itemContexts=[];let q;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";q=new R0({height:10,child:new l1({child:new $0({text:new C(w,new h({color:Q.foreground}))})})})}else if(X.length===0&&this.widget.props.emptyStateText)q=new T1({child:new l1({child:new $0({text:new C(this.widget.props.emptyStateText,new h({color:Q.foreground,dim:!0}))})})});else{let w=X.map((N,O)=>{let E=O===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(N,E,L,J);else{let A=E?Z.app.selectionBackground:void 0,I=E?Z.app.selectionForeground:Q.foreground;M=new c0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(this.widget.props.getLabel(N),new h({color:I,dim:L}))})})}return new PO4(new n1({onClick:(A)=>this.handleItemClick(O,A.clickCount),child:M}),(A)=>{this.itemContexts[O]=A})});q=new u0({children:w,crossAxisAlignment:"start"})}let D=new n1({onScroll:this.handleScroll,opaque:!1,child:new j6({controller:this.scrollController,autofocus:!1,child:q})}),W=[];if(this.widget.props.title){let w=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(this.widget.props.title,new h({color:Z.app.command,bold:!0}))})});W.push(w)}if(!V)W.push(U,new R0({height:1}));if(this.textController.text!==""){let w=X.length>0?X[this.selectedIndex]:void 0,N=w&&this.widget.props.buildDisabledReasonWidget?.(w,J);W.push(new T1({child:new u0({mainAxisAlignment:"spaceBetween",children:[new T1({child:D}),new c0({padding:C0.only({top:1}),child:new l1({child:N??new R0({height:1})})})]})}))}else W.push(new T1({child:D}));if(this.widget.props.footer)W.push(this.widget.props.footer);return new c0({decoration:{border:Y,color:Q.background},padding:C0.symmetric(1,0),child:new u0({children:W})})}}function _O4(J){let Q=new Date().getTime()-J.getTime(),X=Math.floor(Q/60000),Y=Math.floor(Q/3600000),V=Math.floor(Q/86400000);if(X<1)return"just now";if(X<60)return`${X}m ago`;if(Y<24)return`${Y}h ago`;if(V<7)return`${V}d ago`;return J.toLocaleDateString()}class Lp0 extends c1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((Y,V)=>V.pubDate.getTime()-Y.pubDate.getTime()),Q=Math.max(0,...Z.map((Y)=>_O4(Y.pubDate).length));return new r9({items:Z,getLabel:(Y)=>Y.title,onAccept:(Y)=>this.props.onSelect?.(Y),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(Y,V,K,z)=>{let G=f0.of(z),{colors:F}=G,U=G.app,q=V?U.selectionBackground:void 0,D=V?U.selectionForeground:F.foreground,W=F.mutedForeground,H=(B,w)=>new R0({width:w,child:U1.end([new $0({text:new C(B,new h({color:W}))})])});return new c0({decoration:q?{color:q}:void 0,padding:C0.symmetric(2,0),child:new U1({children:[new T1({child:new $0({text:new C(Y.title,new h({color:D})),overflow:"ellipsis",maxLines:1})}),new R0({width:2}),H(_O4(Y.pubDate),Q)]})})}})}}_4();class Mp0 extends d0{createState(){return new SO4}}class SO4 extends p0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new $0({text:new C("●",new h({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}var Oa5=/\/threads\/(T-[^/?#\s<>]+)/i;function Ea5(J){let Z=J.trim(),X=Z.match(Oa5)?.[1];if(X&&W8(X))return X;let Y=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(W8(Y))return Y;return null}function La5(J){let Z=new Map,Q=new Map,X=new Map,Y=[];for(let K of J)Z.set(K.id,K);for(let K of J){let z=K.relationships.find((G)=>G.role==="child"&&Z.has(G.threadID)&&(G.type==="fork"||G.type==="handoff"));if(z){X.set(K.id,z.type);let G=z.threadID,F=Q.get(G)||[];F.push(K),Q.set(G,F)}else Y.push(K)}return N20.flatten(Y,(K)=>Q.get(K.id)).map((K)=>({...K.item,depth:K.depth,isLast:K.isLast,ancestorsAreLast:K.ancestorsAreLast,relationshipType:X.get(K.item.id)}))}function Ap0(J,Z,Q){return new $0({text:new C(`${J}${Z}`,new h({color:Q})),maxLines:1})}function Ma5(J,Z,Q,X){return[Ap0("+",J,X.success),K3.horizontal(1),Ap0("~",Z,X.warning),K3.horizontal(1),Ap0("-",Q,X.destructive)]}function Aa5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class o$0 extends d0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new vO4}}class vO4 extends p0{spinner=new v3;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,X=this.isSwitchingThread?"Switching thread...":"Loading threads...",Y=`${this.spinner.toBraille()} ${X}`,V=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((O)=>O.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)V=V.filter((O)=>O.id!==Z.currentThreadID);let K=Z.recentThreadIDs||[],z=new Set(K),G=Z.currentThreadID,F=[...V].sort((O,E)=>{if(G){if(O.id===G)return-1;if(E.id===G)return 1}let L=K.indexOf(O.id),M=K.indexOf(E.id);if(L!==-1&&M!==-1)return L-M;if(L!==-1)return-1;if(M!==-1)return 1;return 0}),U=La5(F),q=Math.max(0,...U.map((O)=>O.description.timeAgo.length)),D=f0.of(J),W=new i0({padding:C0.symmetric(0,1),child:new l1({child:new $0({text:new C("",new h({color:D.colors.foreground,dim:!0}),[new C("Ctrl+T",new h({color:D.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new h({color:D.colors.foreground,dim:!0}))])})})}),H="",B=null,w=(O)=>{if(O!==H)H=O,B=Ea5(O);return B};return new r9({items:U,getLabel:(O)=>`${O.title} ${O.id}`,filterItem:(O,E)=>{let L=w(E);if(L)return O.id.toLowerCase()===L.toLowerCase();return!0},normalizeQuery:(O)=>w(O)?"":O,onAccept:async(O,E)=>{if(!Z.onSelect||this.isSwitchingThread)return;let L=Z.onSelect(O.id,E);if(!Aa5(L))return;this.setSwitchingThread(!0);try{await L}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(O)=>{if(Z.previewController){if(O)Z.previewController.select(O.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:Y,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:W,renderItem:(O,E,L,M)=>{let A=f0.of(M),{app:I,colors:P}=A,_=E?I.selectionBackground:void 0,S=E?I.selectionForeground:P.foreground,y=P.mutedForeground,m=(s,B0)=>new R0({width:B0,child:U1.end([new $0({text:new C(s,new h({color:y}))})])}),b=Z.threadViewStates[O.id],v=[],f=O.relationshipType==="handoff",g=new Ep({connectorColor:P.mutedForeground});if(O.depth>0){let s=[],B0=O.ancestorsAreLast.slice(1);for(let W0 of B0)s.push(new C(g.getAncestorPrefix(W0),new h({color:g.connectorColor,dim:g.connectorDim})));let o=O.isLast?g.elbow:g.tee,G0=g.getConnectorText(o);s.push(new C(G0,new h({color:g.connectorColor,dim:g.connectorDim}))),v.push(new $0({text:new C("",void 0,s)}))}let d=[],x=G===O.id?new C("(current) ",new h({color:P.success})):z.has(O.id)?new C("(visited) ",new h({color:P.foreground,dim:!0})):null;if(x)d.push(new $0({text:x}));if(nO(b))d.push(new Mp0),d.push(new R0({width:1}));let a=O.title;if(O.relationshipType==="fork"){let s=a.match(/^Forked\((\d+)\): /);if(s)a=a.slice(s[0].length);else while(a.startsWith("Forked: "))a=a.slice(8);d.push(new $0({text:new C("[fork] ",new h({color:P.primary}))}))}else if(f)d.push(new $0({text:new C("[handoff] ",new h({color:P.accent}))}));if(d.push(new T1({child:new $0({text:new C(a,new h({color:S})),overflow:"ellipsis",maxLines:1})})),d.push(new R0({width:2})),O.diffStats&&(O.diffStats.added>0||O.diffStats.changed>0||O.diffStats.deleted>0)){let s=E?{success:y,warning:y,destructive:y}:P;d.push(...Ma5(O.diffStats.added,O.diffStats.changed,O.diffStats.deleted,s)),d.push(new R0({width:2}))}return d.push(m(O.description.timeAgo,q)),new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new U1({children:[...v,...d]})})}})}}function kO4(J){return 1-(1-J)**3}function yO4(J,Z,Q){return J+(Z-J)*Q}function sp(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,X=Math.min(Q/J.durationX,1),Y=Math.min(Q/J.durationY,1),V=kO4(X),K=kO4(Y);return{x:yO4(J.startOffset.x,J.targetOffset.x,V),y:yO4(J.startOffset.y,J.targetOffset.y,K)}}var Ia5={nodeWidth:3,horizontalSpacing:3};class oT{options;constructor(J={}){this.options={...Ia5,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),X=[],Y=Z.get(void 0)??[];if(this.options.comparator)Y.sort(this.options.comparator);let V=0,K=(z,G)=>{let F=Z.get(z.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let U={...z,parentID:Q.get(z.id)};if(F.length===0){X.push({node:U,position:{x:V,y:G}});let B=V;return V+=this.options.nodeWidth+this.options.horizontalSpacing,B}let q=[];for(let B of F)q.push(K(B,G+1));let D=Math.min(...q),W=Math.max(...q),H=Math.floor((D+W)/2);return X.push({node:U,position:{x:H,y:G}}),H};for(let z of Y)K(z,0);return X}buildTree(J){let Z=new Set(J.map((V)=>V.id)),Q=[...J].sort((V,K)=>V.id.localeCompare(K.id)),X=new Map;for(let V of Q){if(!V.parentID||!Z.has(V.parentID)){X.set(V.id,void 0);continue}let K=!1,z=V.parentID;while(z){if(z===V.id){K=!0;break}z=X.get(z)}X.set(V.id,K?void 0:V.parentID)}let Y=new Map;for(let V of J){let K=X.get(V.id);if(!Y.has(K))Y.set(K,[]);Y.get(K).push(V)}return{childrenMap:Y,resolvedParent:X}}}var ja5={nodeWidth:3,nodeHeight:2};class rT{options;constructor(J={}){this.options={...ja5,...J}}calculate(J){let Z=[],Q=new Map;for(let X of J)Q.set(X.node.id,X);for(let X of J){if(!X.node.parentID)continue;let Y=Q.get(X.node.parentID);if(!Y)continue;let V=this.calculateConnectorLine(Y.position,X.position);Z.push({points:V,fromNodeID:Y.node.id,toNodeID:X.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),X=[],Y=J.x+Q,V=Z.x+Q,K=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;X.push({x:Y,y:K});let z=K+1;if(X.push({x:Y,y:z}),Y!==V)X.push({x:V,y:z});let G=Z.y*(this.options.nodeHeight+3)-1;return X.push({x:V,y:G}),X}}var Ra5={nodeWidth:3,nodeHeight:2},Pa5={x:0,y:0};class s$0{options;constructor(J={}){this.options={...Ra5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,X=Pa5,Y,V,K,z){let G=z?f0.of(z):null,F=G?.colors,U=G?.app,q=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:q}))});let D=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,w=[];for(let I=D;I>=0;I--){let P=J.filter((y)=>y.position.y===I);P.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new R0({width:y.position.x-S}));let m=y.node.id===Q,b=K?.(y.node.data)??!1,v=V?.activeFlashOn??!1,f=y.node.id===V?.copyFlashNodeId;_.push(this.renderNode(m,b,v,f,U,F)),S=y.position.x+this.options.nodeWidth}if(w.push(new U1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((v)=>v.position.y===I-1),m=P,b=this.renderConnectors(y,m,Z,H,F,U);w.push(...b)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(X.x),E=Math.round(X.y*B),L=(D+1)*B,M=[new R0({width:H,height:L}),new x6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&Y){let I=Y(A.node.data),P=D-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+P*B+1,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(I,y,F,U)}))}return new c0({padding:C0.horizontal(2),child:new TH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,X,Y,V){let K="┌─┐",z="└─┘",G=J?Y?.threadGraphNodeSelected??V?.primary??V?.foreground:Y?.threadGraphNode??V?.primary??V?.foreground,F=!1;if(X)G=Y?.threadGraphNodeSelected??V?.primary??G,K="┏━┓",z="┗━┛",F=!0;else if(Z&&Q)G=Y?.toolSuccess??V?.primary??G,K="┏━┓",z="┗━┛";return new u0({crossAxisAlignment:"start",children:[new $0({text:new C(K,new h({color:G,bold:F}))}),new $0({text:new C(z,new h({color:G,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),X=[],Y="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(Y.length===0)Y=V;else if(Y.length+1+V.length<=Z)Y+=" "+V;else X.push(Y),Y=V}if(Y.length>0)X.push(Y);return X}renderInfoBox(J,Z=30,Q,X){let Y=this.wrapText(J,Z),V=Math.min(Z,Math.max(1,...Y.map((D)=>D.length))),K=V+2,z="┌"+"─".repeat(K)+"┐",G="└"+"─".repeat(K)+"┘",F=Q?.border??X?.threadGraphConnector??Q?.foreground,U=Q?.foreground,q=[new $0({text:new C(z,new h({color:F}))})];for(let D of Y){let W=" ".repeat(V-D.length);q.push(new $0({text:new C("│ ",new h({color:F}),[new C(D+W,new h({color:U??F})),new C(" │",new h({color:F}))])}))}return q.push(new $0({text:new C(G,new h({color:F}))})),new u0({crossAxisAlignment:"start",children:q})}renderConnectors(J,Z,Q,X,Y,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??Y?.primary??Y?.foreground,F=Array(X).fill(" ");for(let D of Z){let W=D.position.x+z;if(W>=0&&W<X)F[W]="▲"}K.push(new $0({text:new C(F.join(""),new h({color:G}))}));let U=Array(X).fill(" ");for(let D of J){let W=Z.filter((O)=>O.node.parentID===D.node.id);if(W.length===0)continue;let H=D.position.x+z,B=W.map((O)=>O.position.x+z),w=Math.min(...B),N=Math.max(...B);for(let O=w;O<=N;O++)if(O>=0&&O<X){if(O===H)if(W.length===1&&B[0]===H)U[O]="│";else if(O===w)U[O]="└";else if(O===N)U[O]="┘";else U[O]="┬";else if(B.includes(O))if(O===w)U[O]="└";else if(O===N)U[O]="┘";else U[O]="┴";else if(U[O]===" ")U[O]="─"}}K.push(new $0({text:new C(U.join(""),new h({color:G}))}));let q=Array(X).fill(" ");for(let D of J){if(Z.filter((B)=>B.node.parentID===D.node.id).length===0)continue;let H=D.position.x+z;if(H>=0&&H<X)q[H]="│"}return K.push(new $0({text:new C(q.join(""),new h({color:G}))})),K}}var Ca5={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},Ta5={x:0,y:0};class Ip0{options;constructor(J={}){this.options={...Ca5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,X=Ta5,Y,V,K,z){let G=z?f0.of(z):null,F=G?.colors,U=G?.app,q=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:q}))});let D=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,w=[];for(let I=D;I>=0;I--){let P=J.filter((y)=>y.position.y===I);P.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new R0({width:y.position.x-S}));let m=y.node.id===Q,b=K?.(y.node.data)??!1,v=V?.activeFlashOn??!1;_.push(this.renderNode(m,b,v,U,F)),S=y.position.x+this.options.nodeWidth}if(w.push(new U1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((v)=>v.position.y===I-1),m=P,b=this.renderConnectors(y,m,Z,H,F,U);w.push(...b)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(X.x),E=Math.round(X.y*B),L=(D+1)*B,M=[new R0({width:H,height:L}),new x6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&Y){let I=Y(A.node.data),P=D-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+P*B,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(I,y,F)}))}return new c0({padding:C0.horizontal(2),child:new TH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,X,Y){let V=J?this.options.selectedIcon:this.options.nodeIcon,K=J?X?.threadGraphNodeSelected??Y?.primary??Y?.foreground:X?.threadGraphNode??Y?.primary??Y?.foreground;if(Z&&Q)K=X?.toolSuccess??Y?.primary??K,V="■";return new $0({text:new C(V,new h({color:K}))})}wrapText(J,Z){let Q=J.split(" "),X=[],Y="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(Y.length===0)Y=V;else if(Y.length+1+V.length<=Z)Y+=" "+V;else X.push(Y),Y=V}if(Y.length>0)X.push(Y);return X}renderInfoBox(J,Z=30,Q){let X=this.wrapText(J,Z),Y=Q?.foreground,V=[];for(let K of X)V.push(new $0({text:new C(K,new h({color:Y??Q?.primary??Q?.foreground}))}));return new u0({crossAxisAlignment:"start",children:V})}renderConnectors(J,Z,Q,X,Y,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??Y?.primary??Y?.foreground,F=Array(X).fill(" ");for(let U of J){let q=Z.filter((w)=>w.node.parentID===U.node.id);if(q.length===0)continue;let D=U.position.x+z,W=q.map((w)=>w.position.x+z),H=Math.min(...W),B=Math.max(...W);for(let w=H;w<=B;w++)if(w>=0&&w<X){let N=w===D,O=W.includes(w);if(N&&O)if(q.length===1)F[w]="│";else if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┼";else if(N)if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┬";else if(O)if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┴";else if(F[w]===" ")F[w]="─"}}return K.push(new $0({text:new C(F.join(""),new h({color:G}))})),K}}class tp extends E3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new uO4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class uO4 extends A4{onWidth;onHeight;constructor(J,Z){super();this.onWidth=J,this.onHeight=Z}performLayout(){let J=this._lastConstraints,Z=Number.isFinite(J.maxWidth)?J.maxWidth:80,Q=Number.isFinite(J.maxHeight)?J.maxHeight:24;this.onWidth(Z),this.onHeight?.(Q);let X=this.children[0];if(X)X.layout(J),this.setSize(X.size.width,X.size.height);else this.setSize(J.minWidth,J.minHeight)}paint(J,Z,Q){for(let X of this.children)X.paint(J,Z,Q)}}class iL extends d0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new bO4}}var xO4=400,fO4=300,_a5=16;class bO4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",X=Z.data.updatedAt??"";return Q.localeCompare(X)};layoutEngine=new oT({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new rT;renderer=new Ip0;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((X)=>X.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((G)=>G.id)),Q=new Set(this.widget.props.threads.map((G)=>G.id));if(Z.size!==Q.size||[...Z].some((G)=>!Q.has(G)))this.stopAnimation(),this.currentOffset={x:0,y:0};let Y=J.props.initialSelectedThreadID,V=this.widget.props.initialSelectedThreadID;if(Y!==V&&V){let F=this.widget.props.threads.find((U)=>U.id===V);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let K=J.props.threads.some((G)=>G.isActive),z=this.widget.props.threads.some((G)=>G.isActive);if(K!==z){if(this.stopActiveFlashTimer(),z)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:xO4,durationY:fO4};let Z=Math.max(xO4,fO4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=sp(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},_a5)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let X=Math.floor(this.renderer.getNodeWidth()/2),V=Math.floor(this.viewportWidth/2)-J-X,K=Q-Z,z=2,G=Math.floor(this.viewportHeight/2),U=Math.floor(G/2)-K;return{x:V,y:U}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((Y)=>Y.position.y)),X=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(X)}}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((Y)=>Y.node.id===this.selectedNodeId);if(!Q)return"ignored";let X;switch(J.key){case"ArrowUp":{let Y=Z.filter((V)=>V.node.parentID===Q.node.id);if(Y.length>0){Y.sort((K,z)=>K.position.x-z.position.x);let V=Math.floor(Y.length/2);X=Y[V]}break}case"ArrowDown":{X=Z.find((Y)=>Y.node.id===Q.node.parentID);break}case"ArrowLeft":{let Y=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x<Q.position.x);if(Y.length>0)Y.sort((V,K)=>K.position.x-V.position.x),X=Y[0];break}case"ArrowRight":{let Y=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x>Q.position.x);if(Y.length>0)Y.sort((V,K)=>V.position.x-K.position.x),X=Y[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(X)return this.selectedNodeId=X.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(X)),this.animateToNode(X.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let U=(this.selectedNodeId?this.positionedNodes.find((q)=>q.node.id===this.selectedNodeId):null)??this.positionedNodes.find((q)=>!q.node.parentID);if(U){let q=Math.max(...this.positionedNodes.map((D)=>D.position.y));this.currentOffset=this.calculateCenterOffset(U.position.x,U.position.y,q)}}let Y=this.widget.props.showTitle??!0,V=this.widget.props.offsetY??0,K={x:this.currentOffset.x,y:this.currentOffset.y+V},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,K,Y?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),G=new tp({onWidth:(F)=>{if(this.viewportWidth!==F)this.viewportWidth=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(F)=>{if(this.viewportHeight!==F)this.viewportHeight=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new k4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:G})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class mO4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new gO4}}class gO4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var hO4=30,Sa5=30;class sT{}class tT{}class t$0{}class e$0{}class jp0 extends d0{props;constructor(J){super();this.props=J}createState(){return new pO4}}class pO4 extends p0{highlightedIndex=0;controller=new a7;focusNode;scrollController=new X5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new r4({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,X=Z.size.height;gT(J,{top:Q,bottom:X},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Z}=this.widget.props;if(!J)this.filteredClusters=[...Z];else this.filteredClusters=Z.filter((Q)=>Q.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof sT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof tT){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof t$0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof e$0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:X,app:Y}=Q,z=t1.of(J).size.width>=Sa5+hO4,G=x1.all(new v1(X.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,U=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("Select a cluster",new h({color:Y.command,bold:!0}))})}),q=new FJ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:X.foreground,border:null},maxLines:1}),D=new T2({shortcuts:new Map([[new Y4("ArrowDown"),new sT],[new Y4("ArrowUp"),new tT],[new Y4("Tab"),new sT],[new Y4("Tab",{shift:!0}),new tT],[new Y4("n",{ctrl:!0}),new sT],[new Y4("p",{ctrl:!0}),new tT],[new Y4("Enter"),new t$0],[new Y4("Escape"),new e$0]]),focusNode:this.focusNode,child:q}),W=new k9({actions:new Map([[sT,new s4(this.invoke)],[tT,new s4(this.invoke)],[t$0,new s4(this.invoke)],[e$0,new s4(this.invoke)]]),child:D}),H=new U1({children:[new c0({decoration:{color:X.background},child:new $0({text:new C(">",new h({color:X.foreground}))})}),new T1({child:W})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let I=A===this.highlightedIndex,P=Z?M.threads.some((m)=>m.id===Z):!1,_=I?Y.selectionBackground:void 0,S=I?Y.selectionForeground:X.foreground,y=[new C(M.label,new h({color:S})),new C(` (${M.threads.length})`,new h({color:S,dim:!0}))];if(P)y.push(new C(" (current)",new h({color:I?Y.selectionForeground:X.success})));return new mO4(new n1({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,y)})})}),(m)=>{this.itemContexts[A]=m})}),w=new u0({children:B,crossAxisAlignment:"start"}),N=new T1({child:new n1({onScroll:this.handleScroll,child:new j6({controller:this.scrollController,autofocus:!1,child:w})})}),O=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],E=F?new c0({padding:C0.all(1),child:new iL({threads:O,autofocus:!1,offsetY:2})}):null,L;if(z){let M=E?new T1({child:E}):new R0({width:hO4});L=new U1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,M]})}else{let M=[new T1({child:new n1({onScroll:this.handleScroll,child:new j6({controller:this.scrollController,autofocus:!1,child:w})})})];if(E)M.push(new T1({child:E}));L=new u0({crossAxisAlignment:"stretch",children:M})}return new c0({decoration:{border:G,color:X.background},padding:C0.symmetric(1,0),child:new u0({children:[U,H,new R0({height:1}),new T1({child:L})]})})}}class UJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!UJ._instance)UJ._instance=new UJ;return UJ._instance}get allExpanded(){return this._allExpanded}setAllExpanded(J){if(this._allExpanded===J)return;this._allExpanded=J,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(J){return this._listeners.add(J),()=>this.removeListener(J)}removeListener(J){this._listeners.delete(J)}_notifyListeners(){for(let J of this._listeners)J()}}h0();class dO4 extends p0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){j.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){j.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],X=this.labels.some((V)=>V.name===Z),Y=Q.includes(Z);return!X&&!Y}build(J){let Z=f0.of(J),{app:Q,colors:X}=Z,Y=this.currentQuery.trim().toLowerCase(),V=Y.length>0?this.getValidationError(Y):null,K=this.getAvailableLabels(),G=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...K];return new r9({title:"Add Label",items:G,getLabel:(F)=>{if("__isCreateMarker"in F)return this.currentQuery.trim().toLowerCase();return F.name},onAccept:(F)=>{if("__isCreateMarker"in F)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(F.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:V||"Type to create a new label",renderItem:(F,U,q,D)=>{let W=U?Q.selectionBackground:void 0,H=U?Q.selectionForeground:X.foreground;if("__isCreateMarker"in F&&F.__isCreateMarker){let w=this.currentQuery.trim().toLowerCase();return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,[new C("Create new label: ",new h({color:H})),new C(w,new h({color:H,bold:!0}))])})})}return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(F.name,new h({color:H}))})})},filterItem:(F,U)=>{if(this.currentQuery!==U)this.currentQuery=U,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in F&&F.__isCreateMarker)return this.shouldShowCreateMarker(U);let D=U.trim().toLowerCase();return D.length===0||F.name.includes(D)},sortItems:(F,U,q)=>{let D="__isCreateMarker"in F.item&&F.item.__isCreateMarker,W="__isCreateMarker"in U.item&&U.item.__isCreateMarker;if(D&&!W)return-1;if(!D&&W)return 1;return U.score-F.score}})}}class Rp0 extends d0{props;constructor(J){super();this.props=J}createState(){return new dO4}}class lV extends d0{props;constructor(J){super();this.props=J}createState(){return new cO4}}class cO4 extends p0{_spinner=new v3;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:X}=Z,Y=x1.all(new v1(Q.foreground,1,"solid")),V=this._spinner.toBraille(),K=new $0({textAlign:"center",text:new C("",void 0,[new C(V,new h({color:X.processing})),new C(" ",void 0),new C(this.widget.props.message,new h({color:Q.foreground}))])}),G=[new T1({child:new u0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[K]})})];if(this.widget.props.onAbort)G.push(new R0({height:2,child:new c0({padding:C0.symmetric(2,0),child:new $0({text:new C("",new h({dim:!0}),[new C("Press ",new h({color:Q.foreground})),new C("Esc",new h({color:Q.info})),new C(" to cancel",new h({color:Q.foreground}))])})})}));let F=new c0({decoration:new v4(Q.background,Y),child:new R0({width:60,height:7,child:new u0({mainAxisAlignment:"start",children:G})})});if(this.widget.props.onAbort)return new k4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(U)=>{if(U.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:F});return F}}var ep={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"}},$J0=["workspace","global","flag","default","external","skill","other"];function va5(J){return Array.from(new Set(J))}function lO4(J){return va5([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function eT(J){if(J.isExternal)return"external";switch(J.spec._target){case"workspace":return"workspace";case"global":return"global";case"flag":return"flag";case"default":return"default"}return lO4(J).length>0?"skill":"other"}function Pp0(J){return eT(J)==="skill"}function iO4(J){let Z=lO4(J);if(Z.length===0)return;let Q=Z.join(", "),X=eT(J);if(X==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${ep[X].description}: ${Q}`}function nO4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}var aO4=process.platform==="win32"?" ":"█",oO4=process.platform==="win32"?"░":"█";class u8 extends d0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:X=1,trackChar:Y=aO4,thumbChar:V=oO4,showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=X,this.trackChar=Y,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createState(){return new rO4}}class rO4 extends p0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),Y=this.context.findRenderObject()?.size.height??0;if(Y===0||Z<=Q)return!1;let V=this.widget.getScrollInfo(),K=Math.min(1,Q/Z),z=Math.max(1,Y*K),G=Math.max(0,Math.min(1,V.scrollOffset/(Z-Q))),F=Y-z,U=Math.max(0,F*G),q=U+z;return J>=U&&J<=q}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:X}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=X;let K=J.localPosition.y-this._dragStartY,z=Math.min(1,Q/Z),G=Math.max(1,V*z),F=V-G;if(F<=0)return;let U=Z-Q,q=F/U,D=K/q,W=Math.max(0,Math.min(U,this._dragStartOffset+D));this.widget.controller.jumpTo(W)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:X,scrollOffset:Y}=this.widget.getScrollInfo(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Q<=X)return;let z=Math.min(1,X/Q),G=Math.max(1,K*z),F=Q-X,U=K-G,q=Math.max(0,Math.min(1,Y/(Q-X))),D=Math.max(0,U*q),W=D+G;if(Z>=D&&Z<=W)return;if(Z<D)this.widget.controller.animateTo(Math.max(0,Y-X));else this.widget.controller.animateTo(Math.min(F,Y+X))};build(J){return new n1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?E5.POINTER:E5.DEFAULT,child:new sO4({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 sO4 extends sC{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:X=1,trackChar:Y=aO4,thumbChar:V=oO4,showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=X,this.trackChar=Y,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createRenderObject(){return new tO4(this)}updateRenderObject(J){J.updateWidget(this)}}class tO4 extends A4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;b4(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:X,thumbSizeFloat:Y,showScrollbar:V}=this._calculateScrollbarMetrics();if(!V)return;let K=this._widget.trackColor,z=this._widget.thumbColor,G=process.platform==="win32",F=X,U=X+Y;if(!G){let q=["▁","▂","▃","▄","▅","▆","▇","█"];for(let D=0;D<this.size.height;D++){let W="█",H=!0;if(D===Math.floor(F)){let B=1-(F-D),w=Math.floor(B*8);W=q[w]||"█",H=!1}else if(D===Math.floor(U)){let B=1-(U-D),w=Math.floor(B*8);W=q[w]||"█"}else if(D>F&&D<U)H=!1;J.setChar(Z,Q+D,W,{fg:z,bg:K,reverse:H},1)}return}for(let q=0;q<this.size.height;q++){let D=q+0.5,W=D>=F&&D<U,H=W?this._widget.thumbChar:this._widget.trackChar;J.setChar(Z,Q+q,H,{fg:W?z:K,bg:K,reverse:!1},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),X=this.size.height;if(J<=Z||X<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let Y=Math.max(0,Math.min(1,Q/(J-Z))),V=Math.min(1,Z/J),K=Math.max(1,X*V),z=X-K;return{thumbStartFloat:Math.max(0,z*Y),thumbSizeFloat:K,showScrollbar:!0}}}class nL extends d0{props;constructor(J){super();this.props=J}createState(){return new eO4}}class eO4 extends p0{scrollController=new X5;scrollAreaKey=new d7("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 v2}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,X=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let U=T$0(Q);return{title:U.title,type:U.type,description:U.description}})(),Y=X.type==="error"?Z.app.toolError:Z.app.command,V=x1.all(new v1(Z.colors.border,1,"solid")),K=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(X.title,new h({color:Y,bold:!0}))})}),z=this.isWidgetMessage(Q)?Q.widget:new $0({text:new C(X.description,new h({color:Z.colors.foreground})),selectable:!0}),G=new T1({child:new _2({child:new c0({padding:C0.symmetric(1,0),child:new U1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new j6({controller:this.scrollController,autofocus:!0,child:z})}),new u8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let U=this.scrollController.maxScrollExtent,q=this.scrollController.offset,D=this.getViewportHeight(),W=U+D;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(D,1),scrollOffset:Math.max(q,0)}}})]})})})}),F=new c0({padding:C0.symmetric(1,0),child:new $0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new h({color:Z.colors.foreground,dim:!0})),new C("R",new h({color:Z.app.keybind})),new C(" to retry, ",new h({color:Z.colors.foreground,dim:!0})),new C("Esc",new h({color:Z.app.keybind})),new C(" to cancel",new h({color:Z.colors.foreground,dim:!0}))]);let U=this.resolveFooterStyle(this.widget.props.message);if(U==="none")return new C("",new h({color:Z.colors.foreground,dim:!0}));if(U==="help"){let q=new h({color:Z.app.keybind}),D=new h({color:Z.colors.foreground,dim:!0});return new C("",D,[new C("Press ",D),new C("Escape",q),new C(" to close • Use ",D),new C("↑↓",q),new C(" or ",D),new C("j/k",q),new C(" to scroll",D)])}return new C("Press any key to close",new h({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new k4({onKey:(U)=>{if(this.widget.props.onRetry&&U.key==="r")return this.widget.props.onRetry(),"handled";if(U.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new c0({decoration:{border:V,color:Z.colors.background},padding:C0.all(1),child:new u0({mainAxisAlignment:"center",children:[K,new R0({height:1}),G,F]})})})}}m9();class $E4 extends d0{props;constructor(J){super();this.props=J}createState(){return new JE4}}class JE4 extends p0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((J)=>{this.plugins=J,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(J){let Z=J.startsWith("file://")?J.slice(7):J,Q=this.widget.props.cwd;if(Z.startsWith(Q))return Z.slice(Q.length+1);return Z}statusIcon(J){let Z=l8.default(),{colors:Q,app:X}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:X.toolSuccess};case"error":return{icon:"✗",color:X.toolError}}}build(J){let Z=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new $0({text:new C("No plugins found.",new h({dim:!0}))});let X=[],Y=this.plugins.length,V=this.plugins.filter((G)=>G.status==="active").length,K=this.plugins.reduce((G,F)=>G+F.registeredCommands.length,0),z=this.plugins.reduce((G,F)=>G+F.registeredTools.length,0);if(X.push(new C(`${V}/${Y} ${u4(Y,"plugin")} active`,new h({bold:!0}))),K>0||z>0)X.push(new C(` (${K} ${u4(K,"command")}, ${z} ${u4(z,"tool")})`,new h({dim:!0})));X.push(new C(`
|
|
7300
7300
|
|
|
7301
7301
|
`));for(let G of this.plugins){let{icon:F,color:U}=this.statusIcon(G.status),q=this.getRelativePath(G.uri.toString());if(X.push(new C(`${F} `,new h({color:U}))),X.push(new C(q,new h({bold:!0}))),X.push(new C(` ${G.status}`,new h({dim:!0}))),X.push(new C(`
|
|
7302
7302
|
`)),G.status==="active"&&G.registeredEvents.length>0)X.push(new C(" Events: ",new h({dim:!0}))),X.push(new C(G.registeredEvents.join(", "),new h({color:Q.link}))),X.push(new C(`
|
|
@@ -7512,7 +7512,7 @@ ${Q0.content||""}`:Q0.content||"",a0=[],F1=Q0.baseDir.startsWith("file://")?fJ0(
|
|
|
7512
7512
|
`)}function uA4(J,Z){J.command("usage").description("Show your current Amp usage and credit balance").action(async(Q,X)=>{let Y=X.optsWithGlobals(),V=await Z(Y),K=await V.settings.get("proxy"),z=Sj1({settings:{url:V.ampURL,proxy:K},secrets:{getToken:(F,U)=>V.secrets.get(F,U)}}),G=await A6.userDisplayBalanceInfo({},{config:z});if(!G.ok){if(G.error.code==="auth-required")process.stderr.write(Z1.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(Z1.red("Error: ")+G.error.message+`
|
|
7513
7513
|
`),process.exit(1)}process.stdout.write(await Ge5(G.result.displayText)+`
|
|
7514
7514
|
`),process.exit(0)})}var _63=jB.join(y$,"logs","headless.log"),rl0=jB.join(mC,"device-id.json");async function S63(){for(let J of HN)try{if((await J.listConfigs()).length>0)return J}catch(Z){j.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => D4(R_(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){E7.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
7515
|
-
`)}function v63(J){process.emitWarning=(Z,Q,X,Y)=>{let V=typeof Z==="string"?Z:Z.message||String(Z),K=Q||"Warning",z=!1;J.warn(V,{name:K,code:X})}}function e9(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")u$("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")u$("experimental.agentMode",Z.mode)}function WP4(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 k63(J){try{return await qP4(J,"utf-8")}catch{return J}}async function sl0(J,Z,Q){let X=WP4(J,Z);if(!X)return;let Y=_6(Q)?Q.features:[],V=_6(Q)?Q.user.email:void 0;if(!Zi0(Y,_7.HARNESS_SYSTEM_PROMPT)&&!HP4(V))throw new k1("You are not allowed to do this.",1);u$("systemPrompt",await k63(X))}function HP4(J){return!!(J&&vo(J))}function Zi0(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function tl0(J){return(J.userEmail?vZ(J.userEmail):!1)||Zi0(J.features,_7.DTW_TUI)}function QP4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new k1("This TUI mode is not enabled for your user;",1)}function el0(J,Z){if(typeof J==="boolean")return J;if(!_6(Z))return!1;return tl0({userEmail:Z.user.email,features:Z.features})}function $i0(J){if(!_6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function y63(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 PZ0(J){let X=y63(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 k1(`Couldn't connect to the Amp server at ${J}.`,1,X)}async function XP4(J){if(!f6.write(J))await R63(f6,"drain")}var YP4=[{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??cX,description:`Custom settings file path (overrides the default location ${cX})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${cE})`},{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:o9(),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:uK.SMART.key,description:`Set the agent mode (${SY().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:SY().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],VP4=(J)=>("deprecated"in J)&&J.deprecated===!0,u63=(J)=>("hidden"in J)&&J.hidden===!0,x63=(J)=>("default"in J),f63=(J)=>("default"in J)?J.default:void 0,BP4=[{name:"toggle-skills-count",entryPoint:Bf0}];function b63(J,Z){let Q=Z.args[0],X=Z.commands.map((V)=>V.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let V=X.filter((z)=>Q.includes(z)||z.includes(Q)),K="Run amp --help for a list of available commands.";if(V.length>0)K=`Did you mean: ${V.join(", ")}? Or run amp --help for all commands.`;throw new k1(Y3.unknownCommand(Q),1,K)}}async function Qi0(J){return{...J,getThreadEnvironment:$J,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new eY(J.fileSystem),generateThreadTitle:Y10,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>nJ(J.configService),pluginService:J.pluginService}}function wP4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:$J,filesystem:J.fileSystem,threadService:J.threadService}}var CZ0=V1.file(DP4.homedir()),Ji0=process.env.XDG_CONFIG_HOME?V1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(CZ0,".config");function h63(J){return z$4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){K$4(Z);let Q=f90(),X=ff0();if((!Q||X||KG4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(_U("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(_U("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(f90()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function m63(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>v0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function F9(J,Z,Q){let X=Q?.deferAuth??!1;Ij1("0.0.
|
|
7515
|
+
`)}function v63(J){process.emitWarning=(Z,Q,X,Y)=>{let V=typeof Z==="string"?Z:Z.message||String(Z),K=Q||"Warning",z=!1;J.warn(V,{name:K,code:X})}}function e9(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")u$("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")u$("experimental.agentMode",Z.mode)}function WP4(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 k63(J){try{return await qP4(J,"utf-8")}catch{return J}}async function sl0(J,Z,Q){let X=WP4(J,Z);if(!X)return;let Y=_6(Q)?Q.features:[],V=_6(Q)?Q.user.email:void 0;if(!Zi0(Y,_7.HARNESS_SYSTEM_PROMPT)&&!HP4(V))throw new k1("You are not allowed to do this.",1);u$("systemPrompt",await k63(X))}function HP4(J){return!!(J&&vo(J))}function Zi0(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function tl0(J){return(J.userEmail?vZ(J.userEmail):!1)||Zi0(J.features,_7.DTW_TUI)}function QP4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new k1("This TUI mode is not enabled for your user;",1)}function el0(J,Z){if(typeof J==="boolean")return J;if(!_6(Z))return!1;return tl0({userEmail:Z.user.email,features:Z.features})}function $i0(J){if(!_6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function y63(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 PZ0(J){let X=y63(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 k1(`Couldn't connect to the Amp server at ${J}.`,1,X)}async function XP4(J){if(!f6.write(J))await R63(f6,"drain")}var YP4=[{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??cX,description:`Custom settings file path (overrides the default location ${cX})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${cE})`},{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:o9(),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:uK.SMART.key,description:`Set the agent mode (${SY().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:SY().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],VP4=(J)=>("deprecated"in J)&&J.deprecated===!0,u63=(J)=>("hidden"in J)&&J.hidden===!0,x63=(J)=>("default"in J),f63=(J)=>("default"in J)?J.default:void 0,BP4=[{name:"toggle-skills-count",entryPoint:Bf0}];function b63(J,Z){let Q=Z.args[0],X=Z.commands.map((V)=>V.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let V=X.filter((z)=>Q.includes(z)||z.includes(Q)),K="Run amp --help for a list of available commands.";if(V.length>0)K=`Did you mean: ${V.join(", ")}? Or run amp --help for all commands.`;throw new k1(Y3.unknownCommand(Q),1,K)}}async function Qi0(J){return{...J,getThreadEnvironment:$J,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new eY(J.fileSystem),generateThreadTitle:Y10,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>nJ(J.configService),pluginService:J.pluginService}}function wP4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:$J,filesystem:J.fileSystem,threadService:J.threadService}}var CZ0=V1.file(DP4.homedir()),Ji0=process.env.XDG_CONFIG_HOME?V1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(CZ0,".config");function h63(J){return z$4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){K$4(Z);let Q=f90(),X=ff0();if((!Q||X||KG4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(_U("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(_U("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(f90()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function m63(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>v0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function F9(J,Z,Q){let X=Q?.deferAuth??!1;Ij1("0.0.1773705849-gda80e7");let Y=Mr({storage:J.settings,secretStorage:J.secrets,workspaceRoots:v0.of([V1.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:CZ0,userConfigDir:Ji0});ZG4(Y);let V=await Y.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(V.settings)});let{toolService:K,dispose:z}=Z$4({configService:Y}),G=new Map,F=()=>G.clear(),U=new GM0(Y,J.settings.getWorkspaceRootPath()),q=Im1({configService:Y,filesystem:r6}),D=Ux1({configService:Y,trustStore:U,skillMCPServers:q.skillMCPServers,createOAuthProvider:async(B0,o,G0)=>{let W0=`${B0}:${o}`,F0=G.get(W0);if(F0)return j.debug("Reusing existing OAuth provider for server",{serverName:B0,serverUrl:o}),F0;j.debug("Creating OAuth provider for server",{serverName:B0,serverUrl:o});let J0=(async()=>{let q0=new xN(J.secrets),i=await q0.getClientInfo(B0,o),n=G0?.scopes??i?.scopes,e=cV4();j.info("OAuth headless mode check",{useHeadless:e,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:f6.isTTY});let Z0;if(e)Z0=J.executeMode?dV4():pV4(B0);let Q0=new PL0({storage:q0,serverName:B0,serverUrl:o,clientId:G0?.clientId??i?.clientId,clientSecret:G0?.clientSecret??i?.clientSecret,authUrl:G0?.authUrl??i?.authUrl,tokenUrl:G0?.tokenUrl??i?.tokenUrl,scopes:n,headlessAuthHandler:Z0});return j.debug("OAuth provider created",{serverName:B0,serverUrl:o,hasManualClientId:!!(G0?.clientId??i?.clientId),willUseDCR:!(G0?.clientId??i?.clientId),scopes:n,headlessMode:e,executeMode:J.executeMode}),Q0})();return G.set(W0,J0),J0}}),W=Uk0({configService:Y,filesystem:r6,spawn:G30}),H;if(J.executeMode){let B0=await X94({toolService:K,providers:[D,W],initialTimeout:15000});H=B0.registrations;for(let[o,G0]of B0.initErrors)j.warn(`${o} provider initialization slow or failed:`,G0)}else H=qk0({toolService:K,providers:[D,W]});if(Z.jetbrains)UN("JetBrains");else if(Z.ide&&RK4())UN("VS Code");else if(Z.ide&&PK4())UN("Neovim");else if(Z.ide){let B0=await S63();if(B0){let o=Sr(B0.ideName);if(o)UN(o)}}if(J.executeMode)jj1(!0);let B,w=m8.status.pipe(D1((B0)=>Boolean(B0.connected&&B0.authenticated&&B0.ideName&&QR1(B0.ideName))),M4()).subscribe((B0)=>{if(B0){if(!B)B=K.registerTool(Q94)}else B?.dispose(),B=void 0}),N;if(!J.executeMode){let B0=await J.settings.get("fuzzy.alwaysIncludePaths")??[];N=new l80(process.cwd(),{alwaysIncludePaths:B0},!0)}else N=new class extends l80{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let O=!1;{let B0=await J.secrets.get("apiKey",J.ampURL);if(O=Boolean(B0),j.info("API key lookup before login",{found:Boolean(B0),ampURL:J.ampURL,deferAuth:X}),!B0)if(X)j.info("No API key found, continuing startup with deferred auth");else{f6.write(`No API key found. Starting login flow...
|
|
7516
7516
|
`);let o=await g63(J),G0=await J.secrets.get("apiKey",J.ampURL);if(j.info("Login flow completed",{success:o,storedKeyPresent:Boolean(G0),ampURL:J.ampURL}),!o)await jU(),process.exit(1);O=!0}}{let B0=await Y.getLatest(),o=B0.settings.url,G0=B0.secrets.isSet?.[o];j.info("Config secrets state after login",{configURL:o,apiKeySet:G0?.apiKey??!1})}let E=E1(nJ(Y).pipe(F5((B0)=>B0!=="pending"))),L=await _m1({isDevelopment:!1}),M=X?"pending":await E;if(!X)j.info("Server status resolved",{status:"ready",isAuthenticated:_6(M),isError:RF(M),errorMessage:RF(M)?M.error.message:void 0});let A=new Fj0(L,Y),I=new QI0(L,{lazy:!0,maxThreads:200});j.info("Starting Amp background services");let P=Z.takeMeBack?!1:void 0,_=el0(P,M),S=Boolean(_||Z.headless);if(S)j.info("DTW mode enabled: thread sync service disabled");let y=S?m63():$p1({threadService:A,threadHistoryService:I,configService:Y,isExtensionDevelopment:!1}),m;m8.status.subscribe((B0)=>{m=B0});let b=new Iw0({workspaceRoots:[V1.file(process.cwd())],fileSystem:Z.jetbrains||Z.ide?lt:r6,getCurrentFile:()=>{if(!m?.openFile)return;try{return V1.parse(m.openFile)}catch(B0){j.warn("Failed to parse current file URI",{uri:m.openFile,error:B0});return}},getOpenFiles:()=>{if(!m?.visibleFiles?.length)return[];let B0=m.openFile;return m.visibleFiles.filter((o)=>o!==B0).map((o)=>{try{return V1.parse(o)}catch(G0){return j.warn("Failed to parse visible file URI",{uri:o,error:G0}),null}}).filter((o)=>o!==null)}}),v=new mf0,f=process.env.PLUGINS??"off",g=Z.headless?pz4():void 0,d=g??new O90({configService:Y}),x=d instanceof O90?d:void 0;if(x)x.pluginExecutorKind=_?"local":"unknown";let a=CM0({configService:Y,fileSystem:Z.jetbrains||Z.ide?lt:r6,platform:d,internalPlugins:BP4,pluginFilter:f}),l=Df1({pluginService:a,toolService:K}),s={codebaseContextService:b,configService:Y,toolService:K,mcpService:D,skillService:q,toolboxService:W,trustStore:U,threadService:A,threadHistoryService:I,threadSyncService:y,threadStorage:L,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:N,fileSystem:Z.jetbrains||Z.ide?lt:r6,terminal:v,pluginService:a,pluginPlatform:x,headlessPluginPlatform:g,serverStatus:M,serverStatusPromise:E,hasAPIKeyAtStartup:O};return{...s,async asyncDispose(){if(s.mcpService.hasAuthenticatingClients())j.info("Waiting for OAuth authentication to complete before exit..."),await s.mcpService.waitForAuthentication();for(let B0 of H.values())B0.dispose();await s.mcpService.dispose(),F(),await s.threadService.asyncDispose(),s.configService.unsubscribe(),z(),s.fuzzyServer.dispose(),s.threadSyncService.dispose(),s.settingsStorage[Symbol.dispose](),w.unsubscribe(),B?.dispose(),l.dispose(),await s.pluginService.dispose()}}}async function g63(J){if(!J.executeMode){if(!await B90("Would you like to log in to Amp? [(y)es, (n)o]: "))return f6.write(`Login cancelled. Run the command again to retry.
|
|
7517
7517
|
`),!1}return await NP4(J)}async function NP4(J){let Z=j63(32).toString("hex"),Q=await dC(J.ampURL,Z),X=new AbortController;try{await uY(Q,X.signal)}catch(V){j.error("Error opening browser",{error:V})}let Y=await dC(J.ampURL,Z,!1);f6.write(`If your browser does not open automatically, visit:
|
|
7518
7518
|
|
|
@@ -7520,7 +7520,7 @@ ${Z1.blue.bold(Y)}
|
|
|
7520
7520
|
|
|
7521
7521
|
`);try{return await Lz4(J.ampURL,Z,J.secrets,X),f6.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(V){return j.error("Login failed",{error:V}),E7.write(`
|
|
7522
7522
|
Login failed: ${V instanceof Error?V.message:String(V)}
|
|
7523
|
-
`),!1}}function KP4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function p63(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 Y=await Q.text();throw new k1(`Create request failed (${Q.status}): ${Y}`,1)}let X=await Q.json();if(!X.threadId||!W8(X.threadId))throw new k1("Create response did not include a valid thread ID",1);return X.threadId}function d63(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 c63(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 k1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function l63(){let J=new YH().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)nE(),process.exit(0);let B=H.originalError??H;oY4(B)}),J.option("-V, --version","Print the version number and exit",()=>{let B;try{B=`, ${uD(new Date("2026-03-
|
|
7523
|
+
`),!1}}function KP4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function p63(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 Y=await Q.text();throw new k1(`Create request failed (${Q.status}): ${Y}`,1)}let X=await Q.json();if(!X.threadId||!W8(X.threadId))throw new k1("Create response did not include a valid thread ID",1);return X.threadId}function d63(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 c63(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 k1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function l63(){let J=new YH().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)nE(),process.exit(0);let B=H.originalError??H;oY4(B)}),J.option("-V, --version","Print the version number and exit",()=>{let B;try{B=`, ${uD(new Date("2026-03-17T00:09:44.746Z"))} ago`}catch{}f6.write(`0.0.1773705849-gda80e7 (released 2026-03-17T00:09:44.746Z${B??""})
|
|
7524
7524
|
`),process.exit(0)}),J.addHelpText("after",AK4()),J.configureHelp({formatHelp:IK4}),J.command("logout").description("Log out by removing stored API key").action(async(H,B)=>{let w=B.optsWithGlobals(),N=await F3(w);await t63(N)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(H,B)=>{let w=B.optsWithGlobals(),N=await F3(w);await s63(N,await px0(w,N.settings))}),J.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(H,B,w)=>{let N=w.optsWithGlobals(),O=await F3(N);await LV4(H??"get",O.ampURL,O.secrets),process.exit(process.exitCode??0)}),J.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(H,B)=>{let w=B.optsWithGlobals(),N=await F3(w);await MV4(N.ampURL,N.secrets),process.exit(process.exitCode??0)}),J.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
|
|
7525
7525
|
Actions:
|
|
7526
7526
|
create Create a new DTW thread and print its ID
|
|
@@ -7586,8 +7586,8 @@ ${L}
|
|
|
7586
7586
|
|
|
7587
7587
|
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 i63(J){j.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new Tg({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized]).then(()=>{return}),toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:$J,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new eY(J.fileSystem),ampURL:J.ampURL});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw j.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function n63(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await aC()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await aC()).trimEnd(),stdinInput:null}}function a63(J,Z,Q){if(J.remote&&!Z)throw new k1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new k1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new k1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new k1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new k1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new k1("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 k1("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"}]}}' | amp --execute --stream-json --stream-json-input`);if(Z&&Q===""&&!J.streamJsonInput&&!J.headless)throw new k1("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"
|
|
7588
7588
|
Or pipe via stdin: echo "your message" | amp --execute`)}async function TZ0(J,Z,Q){let X=process.hrtime.bigint(),Y=(W0,F0)=>{let J0=Number(process.hrtime.bigint()-F0)/1e6,q0=s$4();j.info("Startup phase",{phase:W0,phaseMs:Math.round(J0),sinceMainMs:q0===null?void 0:Math.round(q0)})},{userInput:V,stdinInput:K}=await n63(Z),z=!!Z.streamJson||!!Z.streamJsonThinking;a63({...Z,streamJson:z},J.executeMode,V),e9(Q,Z);let G=process.hrtime.bigint(),F=Boolean(await J.secrets.get("apiKey",J.ampURL)),U=!J.executeMode&&!Z.headless&&F;j.info("Interactive auth startup mode",{deferInteractiveAuth:U,hasAPIKeyAtStartup:F,executeMode:J.executeMode,headless:Boolean(Z.headless)});let q=await F9(J,Z,{deferAuth:U});Y("runMainThread:createThreadDependencies",G),G=process.hrtime.bigint();let D=await Qi0(q);Y("runMainThread:createWorkerDeps",G);let{serverStatus:W}=q;if(!U&&RF(W)){let W0=kC(Error(W.error.message));if(W0.message===Y3.networkOffline||W0.message===Y3.networkTimeout)throw PZ0(J.ampURL);throw new k1(Y3.invalidAPIKey,1)}let H=_6(W)?W:null,B=H?.user.email,w=HP4(B),N=tl0({userEmail:B,features:H?.features}),O=Z.takeMeBack?!1:void 0,E=H!==null&&el0(O,H);if(!U)await sl0(Q,Z,W);let L=$i0(W),M=L?.features??[],A=L?.team??null,I=w90(Z,L);if(I instanceof Error)U3(I.message);if((J.executeMode||z)&&m3(Z.mode)&&!w)throw new k1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(H&&!JD(Z.mode,B))throw new k1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await lz4(V,K,q.configService),await q.asyncDispose(),process.exit(0);if(Z.headless){if(!B||!vZ(B))throw new k1("Headless DTW mode is only available for Amp employees",1);let W0=await q.secretStorage.get("apiKey",J.ampURL);if(!W0)throw new k1("API key required for headless mode. Please run `amp login` first.",1);let F0=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if(F0&&!W8(F0))throw new k1(`Invalid thread ID: ${F0}`,1);let J0=F0??await V53({dependencies:q,visibility:I??void 0}),q0=await aV4(J0);if(q0.status==="already-running")await q.asyncDispose(),await jU(),process.exit(0);try{await gV4({ampURL:J.ampURL,apiKey:W0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:J0,initialToolDiscovery:Promise.all([q.mcpService.initialized,q.toolboxService.initialized]).then(()=>{return}),configService:q.configService,mcpService:q.mcpService,toolService:q.toolService,skillService:q.skillService,fileSystem:q.fileSystem,pluginService:q.pluginService,pluginPlatform:q.headlessPluginPlatform})}finally{await q0.release(),await q.asyncDispose()}await jU(),process.exit(0)}let P={threadService:q.threadService,workerDeps:D,createThread:async()=>{let W0=U?await q.serverStatusPromise:W,F0=await T80(J.settings,process.cwd(),$i0(W0),I);if(F0 instanceof Error)U3(F0.message);return $g0(D,{threadMeta:F0?kV(F0):void 0,agentMode:Z.mode,onFirstAssistantMessage:zP4})},validateThreadOwnership:async(W0,F0)=>{if(F0?.nonBlockingOwnershipCheck){GP4(W0,q.configService).catch((J0)=>{if(J0 instanceof k1){if(F0.onOwnershipError){F0.onOwnershipError(J0,W0);return}yC(J0,W0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:J0})});return}try{await GP4(W0,q.configService)}catch(J0){if(J0 instanceof k1)throw J0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:J0})}},switchThreadVisibility:I,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:zP4},_=async(W0)=>{try{if(W0==="dtw")return i63({ampURL:J.ampURL,configService:q.configService,threadService:q.threadService,mcpService:q.mcpService,toolboxService:q.toolboxService,toolService:q.toolService,skillService:q.skillService,fileSystem:q.fileSystem,threadId:Z.threadId});return zB4(P,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(F0){if(F0 instanceof k1)throw F0;throw await yC(F0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")E7.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
7589
|
-
`),await jU(),process.exit(1);let S=(async()=>{if(U){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let W0=await q.configService.getLatest(),F0=hk(W0),J0=await A6.getUserFreeTierStatus({},{config:q.configService,signal:AbortSignal.timeout(F0)});if(J0.ok)return j.info("User free tier status:",J0),J0.result;return}catch(W0){j.error("Failed to fetch free tier status:",W0);return}})(),m=!J.executeMode?new rf0:null,b,v=null;if(m)b=m,v=(async()=>{let W0=U?await q.serverStatusPromise:q.serverStatus;await sl0(Q,Z,W0);let F0=process.hrtime.bigint(),J0=el0(O,W0),q0=_6(W0)?tl0({userEmail:W0.user.email,features:W0.features}):!1;QP4({dtwEnabled:J0,hasV2TUIAccess:q0});let i=await _(J0?"dtw":"worker");if(Y("runMainThread:createThreadPool",F0),m.attach(i),V){let n=await E1(i.threadHandles$);if(!n)throw new k1("No active thread is available yet.",1);await n.sendMessage({content:[{type:"text",text:V}]})}})(),v.catch(async(W0)=>{let F0=W0 instanceof Error?W0:Error(String(W0));m.setInitError(F0),await yC(W0,Z.threadId)});else G=process.hrtime.bigint(),QP4({dtwEnabled:E,hasV2TUIAccess:N}),b=await _(E?"dtw":"worker"),Y("runMainThread:createThreadPool",G);let f=Z.notifications!==void 0?Z.notifications:!J.executeMode;G=process.hrtime.bigint();let g=await q.configService.getLatest();if(Y("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),h63({configService:q.configService,threadService:q.threadService,config:g,useNotificationsForService:f,threadViewStates$:()=>b.threadHandles$.pipe(Q4((W0)=>{if(!W0)return v0.of({});return Y5(W0.thread$,W0.threadViewState$).pipe(D1(([F0,J0])=>({[F0.id]:J0})))}))}),Y("runMainThread:createCliNotificationService",G),J.executeMode){kz4(q.mcpService,J.settings);let W0={userInput:V,stdinInput:K,dependencies:q,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},F0=await VV4({threadPool:b,...W0});if(Z.archive)await A6.archiveThread({thread:F0,archived:!0},{config:q.configService});await q.asyncDispose(),process.exit(0)}let d=!1,x=!1;if(Z.jetbrains||Z.ide){await GR1();let W0=await wN({jetbrainsOnly:Z.jetbrains});if(W0.length===0){if(Z.jetbrains)d=!await q.configService.get("jetbrains.skipInstall")}else if(W0.length===1){let F0=W0[0];if(F0)m8.selectConfig(F0)}else x=!0}G=process.hrtime.bigint();let a=Kf0("0.0.
|
|
7590
|
-
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let X=await wx1({get:async(z)=>{if(z!==vu)return;try{let G=await qP4(rl0,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==vu)return;await UP4(jB.dirname(rl0),{recursive:!0}),await P63(rl0,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:mK()});Rj1(X);let Y=await KK4({...J,workspaceTrust:{current:!0,changes:Mk},getHook:process.env.AMP_URL?(z,G)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let z=await Sz4(J.mcpConfig);Y=vz4(Y,z)}let V=jB.dirname(Y.getSettingsFilePath());V$4(mC,V);let K=await Y.get("url","global");if(!K)K=Z7;if(j.info("Resolved Amp URL",{ampURL:K,settingsFile:Y.getSettingsFilePath(),workspaceRoot:Y.getWorkspaceRootPath()}),!qD(K))j.info("Targeting custom Amp server",{ampURL:K});return Y=Bj1(Y),{executeMode:Z,isTTY:Q,ampURL:K,settings:Y,secrets:rz4(await px0(J,Y))}}function o63(J){let Z={};for(let Q=0;Q<J.length;Q++){let X=J[Q];if(X?.startsWith("--")){let V=X.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),K=J[Q+1];if(K&&!K.startsWith("--"))Z[V]=K,Q++}}return Z}async function r63(){r$4();let J=o63(process.argv),Z=process.argv.includes("--headless")||process.argv.some((V)=>V.startsWith("--headless="));GY4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?_63:void 0)});let Q=process.argv.includes("--no-color"),X=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!X&&!Y)Z1.level=0;if(v63(j),j.info("Starting Amp CLI.",{version:"0.0.
|
|
7589
|
+
`),await jU(),process.exit(1);let S=(async()=>{if(U){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let W0=await q.configService.getLatest(),F0=hk(W0),J0=await A6.getUserFreeTierStatus({},{config:q.configService,signal:AbortSignal.timeout(F0)});if(J0.ok)return j.info("User free tier status:",J0),J0.result;return}catch(W0){j.error("Failed to fetch free tier status:",W0);return}})(),m=!J.executeMode?new rf0:null,b,v=null;if(m)b=m,v=(async()=>{let W0=U?await q.serverStatusPromise:q.serverStatus;await sl0(Q,Z,W0);let F0=process.hrtime.bigint(),J0=el0(O,W0),q0=_6(W0)?tl0({userEmail:W0.user.email,features:W0.features}):!1;QP4({dtwEnabled:J0,hasV2TUIAccess:q0});let i=await _(J0?"dtw":"worker");if(Y("runMainThread:createThreadPool",F0),m.attach(i),V){let n=await E1(i.threadHandles$);if(!n)throw new k1("No active thread is available yet.",1);await n.sendMessage({content:[{type:"text",text:V}]})}})(),v.catch(async(W0)=>{let F0=W0 instanceof Error?W0:Error(String(W0));m.setInitError(F0),await yC(W0,Z.threadId)});else G=process.hrtime.bigint(),QP4({dtwEnabled:E,hasV2TUIAccess:N}),b=await _(E?"dtw":"worker"),Y("runMainThread:createThreadPool",G);let f=Z.notifications!==void 0?Z.notifications:!J.executeMode;G=process.hrtime.bigint();let g=await q.configService.getLatest();if(Y("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),h63({configService:q.configService,threadService:q.threadService,config:g,useNotificationsForService:f,threadViewStates$:()=>b.threadHandles$.pipe(Q4((W0)=>{if(!W0)return v0.of({});return Y5(W0.thread$,W0.threadViewState$).pipe(D1(([F0,J0])=>({[F0.id]:J0})))}))}),Y("runMainThread:createCliNotificationService",G),J.executeMode){kz4(q.mcpService,J.settings);let W0={userInput:V,stdinInput:K,dependencies:q,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},F0=await VV4({threadPool:b,...W0});if(Z.archive)await A6.archiveThread({thread:F0,archived:!0},{config:q.configService});await q.asyncDispose(),process.exit(0)}let d=!1,x=!1;if(Z.jetbrains||Z.ide){await GR1();let W0=await wN({jetbrainsOnly:Z.jetbrains});if(W0.length===0){if(Z.jetbrains)d=!await q.configService.get("jetbrains.skipInstall")}else if(W0.length===1){let F0=W0[0];if(F0)m8.selectConfig(F0)}else x=!0}G=process.hrtime.bigint();let a=Kf0("0.0.1773705849-gda80e7",q.settingsStorage,{startDelayMs:3000});Y("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let l=new ZI0(q.threadStorage);Y("runMainThread:createThreadFuzzyIndexer",G),G=process.hrtime.bigint();let s=new Hf0(q.mcpService,J.settings.getWorkspaceRootPath());if(Y("runMainThread:createMcpTrustHandler",G),V&&J.executeMode){let W0=await E1(b.threadHandles$);if(!W0)throw new k1("No active thread is available yet.",1);await W0.sendMessage({content:[{type:"text",text:V}]})}G=process.hrtime.bigint();let B0=await sz();Y("runMainThread:loadSessionState",G),j.info("Loaded session state:",B0);let o={...B0,launchCount:B0.launchCount+1};tz(o);let G0=Z.threadId&&W8(Z.threadId)?Z.threadId:void 0;try{if(G=process.hrtime.bigint(),await Bw4({codebaseContextService:q.codebaseContextService,history:new jx0,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadHistoryService:q.threadHistoryService,threadFuzzyIndexer:l,skillService:q.skillService,configService:q.configService,secretStorage:q.secretStorage,internalAPIClient:A6,threadPool:b,createSystemPromptDeps:async()=>wP4(q),ideClient:m8,mcpService:q.mcpService,toolboxService:q.toolboxService,mcpTrustHandler:s,updateService:a,pluginPlatform:q.pluginPlatform,pluginService:q.pluginService},{initialServerStatus:q.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:q.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:G0,showJetBrainsInstaller:d,showIdePickerHint:x,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:o,freeTierStatusPromise:S,workspace:A??null,features:M,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-17T00:09:44.746Z"},(W0)=>new Rg0({...W0,threadPool:W0.threadPool},(F0)=>new Mc0({...F0,threadState:F0.threadState}))),Y("runMainThread:mountApp-returned",G),v)await v}finally{}await q.asyncDispose(),Y("runMainThread:dependencies.asyncDispose",X),process.exit(0)}async function F3(J){if(j.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)E7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
7590
|
+
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let X=await wx1({get:async(z)=>{if(z!==vu)return;try{let G=await qP4(rl0,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==vu)return;await UP4(jB.dirname(rl0),{recursive:!0}),await P63(rl0,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:mK()});Rj1(X);let Y=await KK4({...J,workspaceTrust:{current:!0,changes:Mk},getHook:process.env.AMP_URL?(z,G)=>{if(z==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(J.mcpConfig){let z=await Sz4(J.mcpConfig);Y=vz4(Y,z)}let V=jB.dirname(Y.getSettingsFilePath());V$4(mC,V);let K=await Y.get("url","global");if(!K)K=Z7;if(j.info("Resolved Amp URL",{ampURL:K,settingsFile:Y.getSettingsFilePath(),workspaceRoot:Y.getWorkspaceRootPath()}),!qD(K))j.info("Targeting custom Amp server",{ampURL:K});return Y=Bj1(Y),{executeMode:Z,isTTY:Q,ampURL:K,settings:Y,secrets:rz4(await px0(J,Y))}}function o63(J){let Z={};for(let Q=0;Q<J.length;Q++){let X=J[Q];if(X?.startsWith("--")){let V=X.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),K=J[Q+1];if(K&&!K.startsWith("--"))Z[V]=K,Q++}}return Z}async function r63(){r$4();let J=o63(process.argv),Z=process.argv.includes("--headless")||process.argv.some((V)=>V.startsWith("--headless="));GY4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?_63:void 0)});let Q=process.argv.includes("--no-color"),X=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!X&&!Y)Z1.level=0;if(v63(j),j.info("Starting Amp CLI.",{version:"0.0.1773705849-gda80e7",buildTimestamp:"2026-03-17T00:09:44.746Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new k1(Y3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await l63().parseAsync(process.argv)}X$4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await r63().catch(yC)});async function s63(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"),f6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
7591
7591
|
`);else if(!qD(J.ampURL))f6.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
7592
7592
|
`);let X=process.env.AMP_API_KEY;if(X)f6.write(`API key found in environment variable, storing...
|
|
7593
7593
|
`),await Z.set("apiKey",X,J.ampURL),f6.write(`API key successfully stored.
|