@sourcegraph/amp 0.0.1773425987-gff03c8 → 0.0.1773432280-gcd86a7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +9 -9
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -6119,11 +6119,11 @@ ${W}`))}},error:(D)=>{if(!q)q=!0,z(Error(`Failed to spawn brew: ${D.message}`))}
6119
6119
  ${W}`;if(X==="pnpm"&&W.includes("Unable to find the global bin directory"))H+=`
6120
6120
 
6121
6121
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
6122
- npm install -g @sourcegraph/amp`;z(Error(H))}},error:(D)=>{if(!U)U=!0,z(Error(`Failed to spawn ${X}: ${D.message}`))},complete:()=>{if(!U)U=!0,K()}})})}h0();h0();Rj();async function e80(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,V=new AbortController,K=setTimeout(()=>V.abort(),5000);try{let z=await fetch(X,{signal:V.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),F=G.version??G["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let U=SK4(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 ZR5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function $90(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${ZR5}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let V=SK4(J,X),K=V<0;return j.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:V,hasUpdate:K}),{hasUpdate:K,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return j.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var QR5=604800000;function _K4(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>QR5)return{ageMs:Q};return null}function SK4(J,Z){let Q=(K)=>{let[z,G]=K.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),V=Math.max(Y.parts.length,X.parts.length);for(let K=0;K<V;K++){let z=Y.parts[K]||0,G=X.parts[K]||0;if(z<G)return-1;if(z>G)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function lx0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?PD(Q):void 0;return{sha:Y,age:X}}catch{return null}}H1();function ix0(J,Z,Q={}){let Y=new s1,X=Y.pipe(R6({shouldCountRefs:!1}));return setImmediate(async()=>{let V=new TK().scoped("update"),K=Q.startDelayMs??0;if(K>0)await Yz(K);let z=X.subscribe({next:(G)=>{V.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){V.debug("using fake update status for testing",{status:G}),await Yz(500),Y.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){V.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){V.debug("checking disabled");return}let U=await t80(),q=U==="binary"||U==="brew";V.debug("checking",{currentVersion:J,mode:F,packageManager:U,isBinaryDistribution:q});let D=q?await $90(J):await e80(J,aE());if(!(D.latestVersion&&D.hasUpdate)){V.debug("no update available");return}let W=()=>{if(D.currentVersionAge!==void 0&&D.latestVersionAge!==void 0){let H=D.currentVersionAge-D.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return V.debug("versions too close together, suppressing update warning",{currentVersionAge:D.currentVersionAge,latestVersionAge:D.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!F)F=U==="pnpm"?"warn":"auto",V.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:F});if(U==="brew"){if(!W())Y.next("update-available-brew");return}if(U==="binary"&&process.execPath!==hx0()){if(V.debug("non-standard binary path, showing warning"),!W())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!W())Y.next("update-available");return}if(!U){if(V.debug("auto-update not supported, falling back to warn mode"),!W())Y.next("update-available");return}if(U==="binary"&&process.platform==="win32"){if(V.debug("binary auto-update not supported on Windows, falling back to warn mode"),!W())Y.next("update-available");return}try{await Qg(D.latestVersion,U);let H=await FH(D.latestVersion),B={from:D.currentVersion,to:D.latestVersion,...H};if(H.status==="same")V.info("success",B),Y.next("updated");else V.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(G){V.debug("check failed",{error:G})}finally{await Yz(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}Rj();import{stderr as az}from"node:process";function vK4(J){let Z=new sW().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Y)=>{await ux0(Y.force||!1,Y.verbose||!1,"0.0.1773425987-gff03c8"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new sW("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await YR5(Y.targetVersion)});J.addCommand(Q)}async function YR5(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")az.write(Z1.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6122
+ npm install -g @sourcegraph/amp`;z(Error(H))}},error:(D)=>{if(!U)U=!0,z(Error(`Failed to spawn ${X}: ${D.message}`))},complete:()=>{if(!U)U=!0,K()}})})}h0();h0();Rj();async function e80(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,V=new AbortController,K=setTimeout(()=>V.abort(),5000);try{let z=await fetch(X,{signal:V.signal});if(!z.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=await z.json(),F=G.version??G["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let U=SK4(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 ZR5="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function $90(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${ZR5}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let V=SK4(J,X),K=V<0;return j.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:V,hasUpdate:K}),{hasUpdate:K,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return j.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var QR5=604800000;function _K4(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>QR5)return{ageMs:Q};return null}function SK4(J,Z){let Q=(K)=>{let[z,G]=K.split("-");return{parts:z?.split(".").map(Number)||[],label:G}},Y=Q(J),X=Q(Z),V=Math.max(Y.parts.length,X.parts.length);for(let K=0;K<V;K++){let z=Y.parts[K]||0,G=X.parts[K]||0;if(z<G)return-1;if(z>G)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function lx0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?PD(Q):void 0;return{sha:Y,age:X}}catch{return null}}H1();function ix0(J,Z,Q={}){let Y=new s1,X=Y.pipe(R6({shouldCountRefs:!1}));return setImmediate(async()=>{let V=new TK().scoped("update"),K=Q.startDelayMs??0;if(K>0)await Yz(K);let z=X.subscribe({next:(G)=>{V.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){V.debug("using fake update status for testing",{status:G}),await Yz(500),Y.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){V.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){V.debug("checking disabled");return}let U=await t80(),q=U==="binary"||U==="brew";V.debug("checking",{currentVersion:J,mode:F,packageManager:U,isBinaryDistribution:q});let D=q?await $90(J):await e80(J,aE());if(!(D.latestVersion&&D.hasUpdate)){V.debug("no update available");return}let W=()=>{if(D.currentVersionAge!==void 0&&D.latestVersionAge!==void 0){let H=D.currentVersionAge-D.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return V.debug("versions too close together, suppressing update warning",{currentVersionAge:D.currentVersionAge,latestVersionAge:D.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!F)F=U==="pnpm"?"warn":"auto",V.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:F});if(U==="brew"){if(!W())Y.next("update-available-brew");return}if(U==="binary"&&process.execPath!==hx0()){if(V.debug("non-standard binary path, showing warning"),!W())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!W())Y.next("update-available");return}if(!U){if(V.debug("auto-update not supported, falling back to warn mode"),!W())Y.next("update-available");return}if(U==="binary"&&process.platform==="win32"){if(V.debug("binary auto-update not supported on Windows, falling back to warn mode"),!W())Y.next("update-available");return}try{await Qg(D.latestVersion,U);let H=await FH(D.latestVersion),B={from:D.currentVersion,to:D.latestVersion,...H};if(H.status==="same")V.info("success",B),Y.next("updated");else V.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(G){V.debug("check failed",{error:G})}finally{await Yz(5000),Y.next("hidden"),z.unsubscribe(),Y.complete()}}),{state:X}}Rj();import{stderr as az}from"node:process";function vK4(J){let Z=new sW().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Y)=>{await ux0(Y.force||!1,Y.verbose||!1,"0.0.1773432280-gcd86a7"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new sW("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await YR5(Y.targetVersion)});J.addCommand(Q)}async function YR5(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")az.write(Z1.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6123
6123
 
6124
6124
  `));try{if(!J){az.write(Z1.blue(`Checking for updates...
6125
- `));let{hasUpdate:Y,latestVersion:X}=xx0()?await $90("0.0.1773425987-gff03c8"):await e80("0.0.1773425987-gff03c8",aE());if(!Y){let V=lx0("0.0.1773425987-gff03c8"),K=V?.age?`released ${V.age} ago`:`built ${PD(new Date("2026-03-13T18:25:24.718Z"))} ago`;az.write(Z1.green(`✓ Amp is already up to date on version ${"0.0.1773425987-gff03c8"} (${K})
6126
- `));let z=await FH("0.0.1773425987-gff03c8");if(z.warning)az.write(`
6125
+ `));let{hasUpdate:Y,latestVersion:X}=xx0()?await $90("0.0.1773432280-gcd86a7"):await e80("0.0.1773432280-gcd86a7",aE());if(!Y){let V=lx0("0.0.1773432280-gcd86a7"),K=V?.age?`released ${V.age} ago`:`built ${PD(new Date("2026-03-13T20:10:28.325Z"))} ago`;az.write(Z1.green(`✓ Amp is already up to date on version ${"0.0.1773432280-gcd86a7"} (${K})
6126
+ `));let z=await FH("0.0.1773432280-gcd86a7");if(z.warning)az.write(`
6127
6127
  `+Z1.yellow(z.warning)+`
6128
6128
  `);process.exit(0)}if(!X)az.write(Z1.yellow("[WARN] could not find latest version")),process.exit(0);J=X}az.write(Z1.blue(`Updating to version ${J}...
6129
6129
  `)),await Qg(J,void 0,(Y)=>{az.write(Z1.dim(`Running: ${Y}
@@ -7286,7 +7286,7 @@ Ctrl-X, Y, Z to unlock`;if(D){let b=F.text.replace(/`([^`]+)`/g,"$1")+`
7286
7286
  `),V=[];for(let K=0;K<X.length;K++){let F=X[K].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let U of F)if(U.startsWith("\x00")&&U.endsWith("\x01"))V.push(new C(U.slice(1,-1),new h({color:Y.app.keybind,bold:!0})));else V.push(new C(U,new h({color:Q.colorScheme.foreground})));if(K<X.length-1)V.push(new C(`
7287
7287
  `))}return new c0({decoration:{color:Q.colorScheme.background,border:u1.all(new v1(Y.app.keybind,1,"rounded"))},child:new i0({padding:C0.symmetric(0,1),child:new $0({text:new C(void 0,void 0,V)})})})}}class eg0 extends A2{chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=_$0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new sg0({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 bN4(J,Z,Q,Y,X,V,K){if(V<=0)return null;switch(J){case"horizontal-bar":{let z=Q;return z>=0&&z<V?z:null}case"bar":case"stacked-bar":{let z=K?i8:0,G=Y-z;if(G<=0)return null;let F=Z-z;if(F<0||F>=G)return null;let U=Math.max(1,Math.floor(G/V)),q=Math.floor(F/U);return q>=0&&q<V?q:null}case"line":case"sparkline":case"stacked-area":{let z=K?i8:0,G=Y-z;if(G<=0)return null;let F=Math.max(0,Math.min(G-1,Z-z));if(V===1)return 0;let U=G/(V-1),q=Math.round(F/U);return Math.max(0,Math.min(V-1,q))}default:return null}}function _i5(J,Z,Q,Y,X,V,K,z){if(X<=0||Z<0||Z>=X)return null;let G=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let F=V?i8:0,U=Q-F,q=Y-(V?G:0);if(U<=0||q<=0)return null;let D=Math.max(1,Math.floor(U/X)),W=F+Z*D+Math.floor(D/2),H=z>0?K/z:0,B=Math.round((1-H)*(q-1));return{x:W,y:B}}case"line":case"sparkline":case"stacked-area":{let F=V?i8:0,U=Q-F,q=Y-(V?G:0);if(U<=0||q<=0)return null;let D=X>1?F+Math.round(Z/(X-1)*(U-1)):F+Math.floor(U/2),W=z>0?K/z:0,H=Math.round((1-W)*(q-1));return{x:D,y:H}}default:return null}}function Si5(J){let Z=0;for(let Q of J)for(let Y of Q.points)if(Y.value>Z)Z=Y.value;return Z||1}function vi5(J,Z,Q,Y,X){if(Q.length<=1){let z=Y(J.value),G=J.meta?` (${J.meta})`:"";return J.label.length+2+z.length+G.length}let V=J.label.length,K=0;for(let z of Q){let G=z.points[Z];if(!G)continue;K+=G.value;let F=2+z.name.length+2+Y(G.value).length;V=Math.max(V,F)}if(X){let z=9+Y(K).length;V=Math.max(V,z)}return V}function ki5(J,Z,Q,Y,X,V,K){let z;try{let H=I1.of(J),B=f0.of(J);z={foreground:H.colorScheme.foreground,background:H.colorScheme.background,border:B.app.keybind}}catch{z={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let G=new h({color:z.foreground,bold:!0}),F=new h({color:z.foreground}),U=new h({color:z.foreground,dim:!0}),q=[],D=new h({color:z.foreground,underline:!0}),W=(H,B)=>new C(B,D,void 0,D90(H),()=>{w8(J,H)});if(Y.length<=1){if(q.push(new C(`${Z.label}: `,G)),Z.link)q.push(W(Z.link,V(Z.value)));else q.push(new C(V(Z.value),F));if(Z.meta)q.push(new C(` (${Z.meta})`,U))}else{let H=K==="stacked-bar"||K==="stacked-area";q.push(new C(`${Z.label}
7288
7288
  `,G));let B=0;for(let w=0;w<Y.length;w++){let N=Y[w],O=N.points[Q];if(!O)continue;B+=O.value;let E=N.color??X[w%X.length]??z.foreground;if(q.push(new C("● ",new h({color:E}))),q.push(new C(`${N.name}: `,U)),O.link)q.push(W(O.link,V(O.value)));else q.push(new C(V(O.value),F));if(w<Y.length-1||H)q.push(new C(`
7289
- `))}if(H)q.push(new C(" ",U)),q.push(new C("Total: ",U)),q.push(new C(V(B),F))}return new c0({decoration:{color:z.background,border:u1.all(new v1(z.border,1,"rounded"))},child:new $0({text:new C(void 0,void 0,q)})})}ow();h0();e9();import{execSync as zn5}from"node:child_process";KN();C7();H3();P7();sb();bX();a2();h$();xX();OE();_4();Gx();qk();H1();var xO4=D4(CF(),1);import{writeFile as SO4}from"fs/promises";import vO4 from"path";h0();a2();class $p0{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.1773425987-gff03c8"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await Ct(Z,this.configService)}catch(Z){j.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class sH extends d0{props;constructor(J){super();this.props=J}createState(){return new hN4}}class hN4 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 mN4 extends p0{controller=new i7;focusNode=new r4({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,V=this.controller.text.trim().length>0,K=!X||V,z=u1.all(new v1(Q.foreground,1,"solid")),G=new FJ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(W)=>{let H=W.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new U1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:G})]}),U=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,[new C("Command: ",new h({color:Q.foreground})),new C(this.widget.props.commandName,new h({color:Y.command,bold:!0}))])})}),q=[];if(K)q.push(new C("Enter",new h({color:Y.keybind}))),q.push(new C(" to submit, ",new h({color:Q.foreground,dim:!0})));q.push(new C("Esc",new h({color:Y.keybind}))),q.push(new C(" to cancel",new h({color:Q.foreground,dim:!0})));let D=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,q)})});return new c0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new u0({children:[U,new R0({height:1}),F,new V3,D]})})}}class dp extends d0{props;constructor(J){super();this.props=J}createState(){return new mN4}}import{isDeepStrictEqual as Jp0}from"node:util";var yi5=/[\\/_ +.#"@[({&]/,ui5=/[\\/_ +.#"@[({&]/g,xi5=/[\s-]/,gN4=/[\s-]/g;function k$0(J,Z,Q,Y,X,V,K){if(V===Z.length){if(X===J.length)return 1;return 0.99}let z=`${X},${V}`;if(K[z]!==void 0)return K[z];let G=Y.charAt(V),F=Q.indexOf(G,X),U=0,q,D,W,H;while(F>=0){if(q=k$0(J,Z,Q,Y,F+1,V+1,K),q>U){if(F===X)q*=1;else if(xi5.test(J.charAt(F-1))){if(q*=0.9,H=J.slice(X,F-1).match(gN4),H&&X>0)q*=0.999**H.length}else if(yi5.test(J.charAt(F-1))){if(q*=0.8,W=J.slice(X,F-1).match(ui5),W&&X>0)q*=0.999**W.length}else if(q*=0.3,X>0)q*=0.999**(F-X);if(J.charAt(F)!==Z.charAt(V))q*=0.9999}if(q<0.1&&(Q.charAt(F-1)===Y.charAt(V+1)||Y.charAt(V+1)===Y.charAt(V)&&Q.charAt(F-1)!==Y.charAt(V))){if(D=k$0(J,Z,Q,Y,F+1,V+2,K),D*0.1>q)q=D*0.1}if(q>U)U=q;F=Q.indexOf(G,F+1)}return K[z]=U,U}function v$0(J){return J.toLowerCase().replace(gN4," ")}function pN4(J,Z){let Q=k$0(J,Z,v$0(J),v$0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,V=0;for(let z of Y){let G=k$0(J,z,v$0(J),v$0(z),0,0,{});if(G===0)return Q;X+=G,V+=z.length}let K=X/Y.length*0.95;return Math.max(Q,K)}return Q}class hT{}class mT{}class y$0{}class u$0{}class dN4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new cN4}}class cN4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function fi5(J,Z){if(J==="")return{matches:!0,score:1};let Q=pN4(Z,J);return{matches:Q>0.15,score:Q}}class o9 extends d0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new lN4}}class lN4 extends p0{textController;focusNode;scrollController=new Y5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new i7(this.widget.props.controller?.query??""),this.focusNode=new r4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>Jp0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!Jp0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>Jp0(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 hT){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 mT){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 y$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 u$0)return this.widget.props.onDismiss?.(),"handled";return"ignored"};syncSelection(){let Z=this.cachedFiltered[this.selectedIndex]??null;if(this.widget.props.controller)this.widget.props.controller.selectedItem=Z;this.widget.props.onSelectionChange?.(Z)}clampSelectedIndex(){let J=this.cachedFiltered.length-1;if(J<0){this.selectedIndex=0;return}this.selectedIndex=Math.max(0,Math.min(this.selectedIndex,J))}recomputeFilteredItems(){let J=this.textController.text,Z=this.widget.props.items,Q=this.widget.props.normalizeQuery?.(J)??J,Y=Z.filter((X)=>!this.widget.props.filterItem||this.widget.props.filterItem(X,J)).map((X)=>({item:X,...fi5(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,V)=>this.widget.props.sortItems(X,V,J):(X,V)=>V.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Z=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Z)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;kT(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=u1.all(new v1(Q.foreground,1,"solid")),V=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,K=this.widget.props.enabled??!0,z=new FJ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:K,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),G=new C2({shortcuts:new Map([[new Y4("ArrowDown"),new hT],[new Y4("ArrowUp"),new mT],[new Y4("Tab"),new hT],[new Y4("Tab",{shift:!0}),new mT],[new Y4("n",{ctrl:!0}),new hT],[new Y4("p",{ctrl:!0}),new mT],[new Y4("Enter"),new y$0],[new Y4("Escape"),new u$0]]),focusNode:this.focusNode,child:z}),F=new S9({actions:new Map([[hT,new s4(this.invoke)],[mT,new s4(this.invoke)],[y$0,new s4(this.invoke)],[u$0,new s4(this.invoke)]]),child:G}),U=new U1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:F})]});this.itemContexts=[];let q;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";q=new R0({height:10,child:new l1({child:new $0({text:new C(w,new h({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)q=new T1({child:new l1({child:new $0({text:new C(this.widget.props.emptyStateText,new h({color:Q.foreground,dim:!0}))})})});else{let w=Y.map((N,O)=>{let E=O===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(N,E,L,J);else{let A=E?Z.app.selectionBackground:void 0,I=E?Z.app.selectionForeground:Q.foreground;M=new c0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(this.widget.props.getLabel(N),new h({color:I,dim:L}))})})}return new dN4(new n1({onClick:(A)=>this.handleItemClick(O,A.clickCount),child:M}),(A)=>{this.itemContexts[O]=A})});q=new u0({children:w,crossAxisAlignment:"start"})}let D=new n1({onScroll:this.handleScroll,opaque:!1,child:new j6({controller:this.scrollController,autofocus:!1,child:q})}),W=[];if(this.widget.props.title){let w=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(this.widget.props.title,new h({color:Z.app.command,bold:!0}))})});W.push(w)}if(!V)W.push(U,new R0({height:1}));if(this.textController.text!==""){let w=Y.length>0?Y[this.selectedIndex]:void 0,N=w&&this.widget.props.buildDisabledReasonWidget?.(w,J);W.push(new T1({child:new u0({mainAxisAlignment:"spaceBetween",children:[new T1({child:D}),new c0({padding:C0.only({top:1}),child:new l1({child:N??new R0({height:1})})})]})}))}else W.push(new T1({child:D}));if(this.widget.props.footer)W.push(this.widget.props.footer);return new c0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new u0({children:W})})}}function iN4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),V=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(V<7)return`${V}d ago`;return J.toLocaleDateString()}class Zp0 extends d1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,V)=>V.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>iN4(X.pubDate).length));return new o9({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,V,K,z)=>{let G=f0.of(z),{colors:F}=G,U=G.app,q=V?U.selectionBackground:void 0,D=V?U.selectionForeground:F.foreground,W=F.mutedForeground,H=(B,w)=>new R0({width:w,child:U1.end([new $0({text:new C(B,new h({color:W}))})])});return new c0({decoration:q?{color:q}:void 0,padding:C0.symmetric(2,0),child:new U1({children:[new T1({child:new $0({text:new C(X.title,new h({color:D})),overflow:"ellipsis",maxLines:1})}),new R0({width:2}),H(iN4(X.pubDate),Q)]})})}})}}_4();class Qp0 extends d0{createState(){return new nN4}}class nN4 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 bi5=/\/threads\/(T-[^/?#\s<>]+)/i;function hi5(J){let Z=J.trim(),Y=Z.match(bi5)?.[1];if(Y&&D8(Y))return Y;let X=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(D8(X))return X;return null}function mi5(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let K of J)Z.set(K.id,K);for(let K of J){let z=K.relationships.find((G)=>G.role==="child"&&Z.has(G.threadID)&&(G.type==="fork"||G.type==="handoff"));if(z){Y.set(K.id,z.type);let G=z.threadID,F=Q.get(G)||[];F.push(K),Q.set(G,F)}else X.push(K)}return X20.flatten(X,(K)=>Q.get(K.id)).map((K)=>({...K.item,depth:K.depth,isLast:K.isLast,ancestorsAreLast:K.ancestorsAreLast,relationshipType:Y.get(K.item.id)}))}function Yp0(J,Z,Q){return new $0({text:new C(`${J}${Z}`,new h({color:Q})),maxLines:1})}function gi5(J,Z,Q,Y){return[Yp0("+",J,Y.success),V3.horizontal(1),Yp0("~",Z,Y.warning),V3.horizontal(1),Yp0("-",Q,Y.destructive)]}function pi5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class x$0 extends d0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new aN4}}class aN4 extends p0{spinner=new S3;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,V=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((O)=>O.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)V=V.filter((O)=>O.id!==Z.currentThreadID);let K=Z.recentThreadIDs||[],z=new Set(K),G=Z.currentThreadID,F=[...V].sort((O,E)=>{if(G){if(O.id===G)return-1;if(E.id===G)return 1}let L=K.indexOf(O.id),M=K.indexOf(E.id);if(L!==-1&&M!==-1)return L-M;if(L!==-1)return-1;if(M!==-1)return 1;return 0}),U=mi5(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=hi5(O);return B};return new o9({items:U,getLabel:(O)=>`${O.title} ${O.id}`,filterItem:(O,E)=>{let L=w(E);if(L)return O.id.toLowerCase()===L.toLowerCase();return!0},normalizeQuery:(O)=>w(O)?"":O,onAccept:async(O,E)=>{if(!Z.onSelect||this.isSwitchingThread)return;let L=Z.onSelect(O.id,E);if(!pi5(L))return;this.setSwitchingThread(!0);try{await L}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(O)=>{if(Z.previewController){if(O)Z.previewController.select(O.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:W,renderItem:(O,E,L,M)=>{let A=f0.of(M),{app:I,colors:P}=A,_=E?I.selectionBackground:void 0,S=E?I.selectionForeground:P.foreground,y=P.mutedForeground,m=(s,w0)=>new R0({width:w0,child:U1.end([new $0({text:new C(s,new h({color:y}))})])}),b=Z.threadViewStates[O.id],k=[],f=O.relationshipType==="handoff",p=new qp({connectorColor:P.mutedForeground});if(O.depth>0){let s=[],w0=O.ancestorsAreLast.slice(1);for(let z0 of w0)s.push(new C(p.getAncestorPrefix(z0),new h({color:p.connectorColor,dim:p.connectorDim})));let a=O.isLast?p.elbow:p.tee,F0=p.getConnectorText(a);s.push(new C(F0,new h({color:p.connectorColor,dim:p.connectorDim}))),k.push(new $0({text:new C("",void 0,s)}))}let l=[],x=G===O.id?new C("(current) ",new h({color:P.success})):z.has(O.id)?new C("(visited) ",new h({color:P.foreground,dim:!0})):null;if(x)l.push(new $0({text:x}));if(gO(b))l.push(new Qp0),l.push(new R0({width:1}));let r=O.title;if(O.relationshipType==="fork"){let s=r.match(/^Forked\((\d+)\): /);if(s)r=r.slice(s[0].length);else while(r.startsWith("Forked: "))r=r.slice(8);l.push(new $0({text:new C("[fork] ",new h({color:P.primary}))}))}else if(f)l.push(new $0({text:new C("[handoff] ",new h({color:P.accent}))}));if(l.push(new T1({child:new $0({text:new C(r,new h({color:S})),overflow:"ellipsis",maxLines:1})})),l.push(new R0({width:2})),O.diffStats&&(O.diffStats.added>0||O.diffStats.changed>0||O.diffStats.deleted>0)){let s=E?{success:y,warning:y,destructive:y}:P;l.push(...gi5(O.diffStats.added,O.diffStats.changed,O.diffStats.deleted,s)),l.push(new R0({width:2}))}return l.push(m(O.description.timeAgo,q)),new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new U1({children:[...k,...l]})})}})}}function oN4(J){return 1-(1-J)**3}function rN4(J,Z,Q){return J+(Z-J)*Q}function cp(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),V=oN4(Y),K=oN4(X);return{x:rN4(J.startOffset.x,J.targetOffset.x,V),y:rN4(J.startOffset.y,J.targetOffset.y,K)}}var di5={nodeWidth:3,horizontalSpacing:3};class gT{options;constructor(J={}){this.options={...di5,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let V=0,K=(z,G)=>{let F=Z.get(z.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let U={...z,parentID:Q.get(z.id)};if(F.length===0){Y.push({node:U,position:{x:V,y:G}});let B=V;return V+=this.options.nodeWidth+this.options.horizontalSpacing,B}let q=[];for(let B of F)q.push(K(B,G+1));let D=Math.min(...q),W=Math.max(...q),H=Math.floor((D+W)/2);return Y.push({node:U,position:{x:H,y:G}}),H};for(let z of X)K(z,0);return Y}buildTree(J){let Z=new Set(J.map((V)=>V.id)),Q=[...J].sort((V,K)=>V.id.localeCompare(K.id)),Y=new Map;for(let V of Q){if(!V.parentID||!Z.has(V.parentID)){Y.set(V.id,void 0);continue}let K=!1,z=V.parentID;while(z){if(z===V.id){K=!0;break}z=Y.get(z)}Y.set(V.id,K?void 0:V.parentID)}let X=new Map;for(let V of J){let K=Y.get(V.id);if(!X.has(K))X.set(K,[]);X.get(K).push(V)}return{childrenMap:X,resolvedParent:Y}}}var ci5={nodeWidth:3,nodeHeight:2};class pT{options;constructor(J={}){this.options={...ci5,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let V=this.calculateConnectorLine(X.position,Y.position);Z.push({points:V,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,V=Z.x+Q,K=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:K});let z=K+1;if(Y.push({x:X,y:z}),X!==V)Y.push({x:V,y:z});let G=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:V,y:G}),Y}}var li5={nodeWidth:3,nodeHeight:2},ii5={x:0,y:0};class b$0{options;constructor(J={}){this.options={...li5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=ii5,X,V,K,z){let G=z?f0.of(z):null,F=G?.colors,U=G?.app,q=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:q}))});let D=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,w=[];for(let I=D;I>=0;I--){let P=J.filter((y)=>y.position.y===I);P.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new R0({width:y.position.x-S}));let m=y.node.id===Q,b=K?.(y.node.data)??!1,k=V?.activeFlashOn??!1,f=y.node.id===V?.copyFlashNodeId;_.push(this.renderNode(m,b,k,f,U,F)),S=y.position.x+this.options.nodeWidth}if(w.push(new U1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((k)=>k.position.y===I-1),m=P,b=this.renderConnectors(y,m,Z,H,F,U);w.push(...b)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(D+1)*B,M=[new R0({width:H,height:L}),new x6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&X){let I=X(A.node.data),P=D-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+P*B+1,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(I,y,F,U)}))}return new c0({padding:C0.horizontal(2),child:new LH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,V){let K="┌─┐",z="└─┘",G=J?X?.threadGraphNodeSelected??V?.primary??V?.foreground:X?.threadGraphNode??V?.primary??V?.foreground,F=!1;if(Y)G=X?.threadGraphNodeSelected??V?.primary??G,K="┏━┓",z="┗━┛",F=!0;else if(Z&&Q)G=X?.toolSuccess??V?.primary??G,K="┏━┓",z="┗━┛";return new u0({crossAxisAlignment:"start",children:[new $0({text:new C(K,new h({color:G,bold:F}))}),new $0({text:new C(z,new h({color:G,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(X.length===0)X=V;else if(X.length+1+V.length<=Z)X+=" "+V;else Y.push(X),X=V}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),V=Math.min(Z,Math.max(1,...X.map((D)=>D.length))),K=V+2,z="┌"+"─".repeat(K)+"┐",G="└"+"─".repeat(K)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,U=Q?.foreground,q=[new $0({text:new C(z,new h({color:F}))})];for(let D of X){let W=" ".repeat(V-D.length);q.push(new $0({text:new C("│ ",new h({color:F}),[new C(D+W,new h({color:U??F})),new C(" │",new h({color:F}))])}))}return q.push(new $0({text:new C(G,new h({color:F}))})),new u0({crossAxisAlignment:"start",children:q})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let D of Z){let W=D.position.x+z;if(W>=0&&W<Y)F[W]="▲"}K.push(new $0({text:new C(F.join(""),new h({color:G}))}));let U=Array(Y).fill(" ");for(let D of J){let W=Z.filter((O)=>O.node.parentID===D.node.id);if(W.length===0)continue;let H=D.position.x+z,B=W.map((O)=>O.position.x+z),w=Math.min(...B),N=Math.max(...B);for(let O=w;O<=N;O++)if(O>=0&&O<Y){if(O===H)if(W.length===1&&B[0]===H)U[O]="│";else if(O===w)U[O]="└";else if(O===N)U[O]="┘";else U[O]="┬";else if(B.includes(O))if(O===w)U[O]="└";else if(O===N)U[O]="┘";else U[O]="┴";else if(U[O]===" ")U[O]="─"}}K.push(new $0({text:new C(U.join(""),new h({color:G}))}));let q=Array(Y).fill(" ");for(let D of J){if(Z.filter((B)=>B.node.parentID===D.node.id).length===0)continue;let H=D.position.x+z;if(H>=0&&H<Y)q[H]="│"}return K.push(new $0({text:new C(q.join(""),new h({color:G}))})),K}}var ni5={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},ai5={x:0,y:0};class Xp0{options;constructor(J={}){this.options={...ni5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=ai5,X,V,K,z){let G=z?f0.of(z):null,F=G?.colors,U=G?.app,q=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:q}))});let D=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,w=[];for(let I=D;I>=0;I--){let P=J.filter((y)=>y.position.y===I);P.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new R0({width:y.position.x-S}));let m=y.node.id===Q,b=K?.(y.node.data)??!1,k=V?.activeFlashOn??!1;_.push(this.renderNode(m,b,k,U,F)),S=y.position.x+this.options.nodeWidth}if(w.push(new U1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((k)=>k.position.y===I-1),m=P,b=this.renderConnectors(y,m,Z,H,F,U);w.push(...b)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(D+1)*B,M=[new R0({width:H,height:L}),new x6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&X){let I=X(A.node.data),P=D-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+P*B,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(I,y,F)}))}return new c0({padding:C0.horizontal(2),child:new LH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let V=J?this.options.selectedIcon:this.options.nodeIcon,K=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)K=Y?.toolSuccess??X?.primary??K,V="■";return new $0({text:new C(V,new h({color:K}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(X.length===0)X=V;else if(X.length+1+V.length<=Z)X+=" "+V;else Y.push(X),X=V}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,V=[];for(let K of Y)V.push(new $0({text:new C(K,new h({color:X??Q?.primary??Q?.foreground}))}));return new u0({crossAxisAlignment:"start",children:V})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of J){let q=Z.filter((w)=>w.node.parentID===U.node.id);if(q.length===0)continue;let D=U.position.x+z,W=q.map((w)=>w.position.x+z),H=Math.min(...W),B=Math.max(...W);for(let w=H;w<=B;w++)if(w>=0&&w<Y){let N=w===D,O=W.includes(w);if(N&&O)if(q.length===1)F[w]="│";else if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┼";else if(N)if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┬";else if(O)if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┴";else if(F[w]===" ")F[w]="─"}}return K.push(new $0({text:new C(F.join(""),new h({color:G}))})),K}}class lp extends N3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new sN4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class sN4 extends A4{onWidth;onHeight;constructor(J,Z){super();this.onWidth=J,this.onHeight=Z}performLayout(){let J=this._lastConstraints,Z=Number.isFinite(J.maxWidth)?J.maxWidth:80,Q=Number.isFinite(J.maxHeight)?J.maxHeight:24;this.onWidth(Z),this.onHeight?.(Q);let Y=this.children[0];if(Y)Y.layout(J),this.setSize(Y.size.width,Y.size.height);else this.setSize(J.minWidth,J.minHeight)}paint(J,Z,Q){for(let Y of this.children)Y.paint(J,Z,Q)}}class bL extends d0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new $O4}}var tN4=400,eN4=300,oi5=16;class $O4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new gT({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new pT;renderer=new Xp0;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((G)=>G.id)),Q=new Set(this.widget.props.threads.map((G)=>G.id));if(Z.size!==Q.size||[...Z].some((G)=>!Q.has(G)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,V=this.widget.props.initialSelectedThreadID;if(X!==V&&V){let F=this.widget.props.threads.find((U)=>U.id===V);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let K=J.props.threads.some((G)=>G.isActive),z=this.widget.props.threads.some((G)=>G.isActive);if(K!==z){if(this.stopActiveFlashTimer(),z)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:tN4,durationY:eN4};let Z=Math.max(tN4,eN4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=cp(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},oi5)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),V=Math.floor(this.viewportWidth/2)-J-Y,K=Q-Z,z=2,G=Math.floor(this.viewportHeight/2),U=Math.floor(G/2)-K;return{x:V,y:U}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((V)=>V.node.parentID===Q.node.id);if(X.length>0){X.sort((K,z)=>K.position.x-z.position.x);let V=Math.floor(X.length/2);Y=X[V]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x<Q.position.x);if(X.length>0)X.sort((V,K)=>K.position.x-V.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x>Q.position.x);if(X.length>0)X.sort((V,K)=>V.position.x-K.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let U=(this.selectedNodeId?this.positionedNodes.find((q)=>q.node.id===this.selectedNodeId):null)??this.positionedNodes.find((q)=>!q.node.parentID);if(U){let q=Math.max(...this.positionedNodes.map((D)=>D.position.y));this.currentOffset=this.calculateCenterOffset(U.position.x,U.position.y,q)}}let X=this.widget.props.showTitle??!0,V=this.widget.props.offsetY??0,K={x:this.currentOffset.x,y:this.currentOffset.y+V},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,K,X?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),G=new lp({onWidth:(F)=>{if(this.viewportWidth!==F)this.viewportWidth=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(F)=>{if(this.viewportHeight!==F)this.viewportHeight=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new k4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:G})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class ZO4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new QO4}}class QO4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var JO4=30,ri5=30;class dT{}class cT{}class h$0{}class m$0{}class Vp0 extends d0{props;constructor(J){super();this.props=J}createState(){return new YO4}}class YO4 extends p0{highlightedIndex=0;controller=new i7;focusNode;scrollController=new Y5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new r4({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;kT(J,{top:Q,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Z}=this.widget.props;if(!J)this.filteredClusters=[...Z];else this.filteredClusters=Z.filter((Q)=>Q.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof dT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof cT){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof h$0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof m$0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,z=t1.of(J).size.width>=ri5+JO4,G=u1.all(new v1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,U=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("Select a cluster",new h({color:X.command,bold:!0}))})}),q=new FJ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),D=new C2({shortcuts:new Map([[new Y4("ArrowDown"),new dT],[new Y4("ArrowUp"),new cT],[new Y4("Tab"),new dT],[new Y4("Tab",{shift:!0}),new cT],[new Y4("n",{ctrl:!0}),new dT],[new Y4("p",{ctrl:!0}),new cT],[new Y4("Enter"),new h$0],[new Y4("Escape"),new m$0]]),focusNode:this.focusNode,child:q}),W=new S9({actions:new Map([[dT,new s4(this.invoke)],[cT,new s4(this.invoke)],[h$0,new s4(this.invoke)],[m$0,new s4(this.invoke)]]),child:D}),H=new U1({children:[new c0({decoration:{color:Y.background},child:new $0({text:new C(">",new h({color:Y.foreground}))})}),new T1({child:W})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let I=A===this.highlightedIndex,P=Z?M.threads.some((m)=>m.id===Z):!1,_=I?X.selectionBackground:void 0,S=I?X.selectionForeground:Y.foreground,y=[new C(M.label,new h({color:S})),new C(` (${M.threads.length})`,new h({color:S,dim:!0}))];if(P)y.push(new C(" (current)",new h({color:I?X.selectionForeground:Y.success})));return new ZO4(new n1({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,y)})})}),(m)=>{this.itemContexts[A]=m})}),w=new u0({children:B,crossAxisAlignment:"start"}),N=new T1({child:new n1({onScroll:this.handleScroll,child:new j6({controller:this.scrollController,autofocus:!1,child:w})})}),O=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],E=F?new c0({padding:C0.all(1),child:new bL({threads:O,autofocus:!1,offsetY:2})}):null,L;if(z){let M=E?new T1({child:E}):new R0({width:JO4});L=new U1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,M]})}else{let M=[new T1({child:new n1({onScroll:this.handleScroll,child:new j6({controller:this.scrollController,autofocus:!1,child:w})})})];if(E)M.push(new T1({child:E}));L=new u0({crossAxisAlignment:"stretch",children:M})}return new c0({decoration:{border:G,color:Y.background},padding:C0.symmetric(1,0),child:new u0({children:[U,H,new R0({height:1}),new T1({child:L})]})})}}class UJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!UJ._instance)UJ._instance=new UJ;return UJ._instance}get allExpanded(){return this._allExpanded}setAllExpanded(J){if(this._allExpanded===J)return;this._allExpanded=J,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(J){return this._listeners.add(J),()=>this.removeListener(J)}removeListener(J){this._listeners.delete(J)}_notifyListeners(){for(let J of this._listeners)J()}}h0();class XO4 extends p0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){j.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){j.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((V)=>V.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=f0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),V=X.length>0?this.getValidationError(X):null,K=this.getAvailableLabels(),G=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...K];return new o9({title:"Add Label",items:G,getLabel:(F)=>{if("__isCreateMarker"in F)return this.currentQuery.trim().toLowerCase();return F.name},onAccept:(F)=>{if("__isCreateMarker"in F)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(F.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:V||"Type to create a new label",renderItem:(F,U,q,D)=>{let W=U?Q.selectionBackground:void 0,H=U?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in F&&F.__isCreateMarker){let w=this.currentQuery.trim().toLowerCase();return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,[new C("Create new label: ",new h({color:H})),new C(w,new h({color:H,bold:!0}))])})})}return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(F.name,new h({color:H}))})})},filterItem:(F,U)=>{if(this.currentQuery!==U)this.currentQuery=U,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in F&&F.__isCreateMarker)return this.shouldShowCreateMarker(U);let D=U.trim().toLowerCase();return D.length===0||F.name.includes(D)},sortItems:(F,U,q)=>{let D="__isCreateMarker"in F.item&&F.item.__isCreateMarker,W="__isCreateMarker"in U.item&&U.item.__isCreateMarker;if(D&&!W)return-1;if(!D&&W)return 1;return U.score-F.score}})}}class Kp0 extends d0{props;constructor(J){super();this.props=J}createState(){return new XO4}}class iV extends d0{props;constructor(J){super();this.props=J}createState(){return new VO4}}class VO4 extends p0{_spinner=new S3;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=u1.all(new v1(Q.foreground,1,"solid")),V=this._spinner.toBraille(),K=new $0({textAlign:"center",text:new C("",void 0,[new C(V,new h({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new h({color:Q.foreground}))])}),G=[new T1({child:new u0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[K]})})];if(this.widget.props.onAbort)G.push(new R0({height:2,child:new c0({padding:C0.symmetric(2,0),child:new $0({text:new C("",new h({dim:!0}),[new C("Press ",new h({color:Q.foreground})),new C("Esc",new h({color:Q.info})),new C(" to cancel",new h({color:Q.foreground}))])})})}));let F=new c0({decoration:new v4(Q.background,X),child:new R0({width:60,height:7,child:new u0({mainAxisAlignment:"start",children:G})})});if(this.widget.props.onAbort)return new k4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(U)=>{if(U.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:F});return F}}var ip={workspace:{label:"Workspace",pathHint:".amp/settings.json",description:"workspace config"},global:{label:"Global",pathHint:"~/.config/amp/settings.json",description:"global config"},flag:{label:"Flag",pathHint:"CLI flags",description:"flag config"},default:{label:"Default",pathHint:"built-in defaults",description:"default config"},external:{label:"External",pathHint:"extensions / external",description:"external source"},skill:{label:"Skills",pathHint:".agents/skills/",description:"skill source"},other:{label:"Other",pathHint:"",description:"other source"}},g$0=["workspace","global","flag","default","external","skill","other"];function si5(J){return Array.from(new Set(J))}function KO4(J){return si5([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function lT(J){if(J.isExternal)return"external";switch(J.spec._target){case"workspace":return"workspace";case"global":return"global";case"flag":return"flag";case"default":return"default"}return KO4(J).length>0?"skill":"other"}function zp0(J){return lT(J)==="skill"}function zO4(J){let Z=KO4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=lT(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${ip[Y].description}: ${Q}`}function GO4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}class u8 extends d0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:V="█",showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createState(){return new FO4}}class FO4 extends p0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),X=this.context.findRenderObject()?.size.height??0;if(X===0||Z<=Q)return!1;let V=this.widget.getScrollInfo(),K=Math.min(1,Q/Z),z=Math.max(1,X*K),G=Math.max(0,Math.min(1,V.scrollOffset/(Z-Q))),F=X-z,U=Math.max(0,F*G),q=U+z;return J>=U&&J<=q}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let K=J.localPosition.y-this._dragStartY,z=Math.min(1,Q/Z),G=Math.max(1,V*z),F=V-G;if(F<=0)return;let U=Z-Q,q=F/U,D=K/q,W=Math.max(0,Math.min(U,this._dragStartOffset+D));this.widget.controller.jumpTo(W)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Q<=Y)return;let z=Math.min(1,Y/Q),G=Math.max(1,K*z),F=Q-Y,U=K-G,q=Math.max(0,Math.min(1,X/(Q-Y))),D=Math.max(0,U*q),W=D+G;if(Z>=D&&Z<=W)return;if(Z<D)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(F,X+Y))};build(J){return new n1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?E5.POINTER:E5.DEFAULT,child:new UO4({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 UO4 extends dC{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:V="█",showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createRenderObject(){return new qO4(this)}updateRenderObject(J){J.updateWidget(this)}}class qO4 extends A4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;f4(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:V}=this._calculateScrollbarMetrics();if(!V)return;let K=this._widget.trackColor,z=this._widget.thumbColor,G=["▁","▂","▃","▄","▅","▆","▇","█"],F=Y,U=Y+X;for(let q=0;q<this.size.height;q++){let D="█",W=!0;if(q===Math.floor(F)){let H=1-(F-q),B=Math.floor(H*8);D=G[B]||"█",W=!1}else if(q===Math.floor(U)){let H=1-(U-q),B=Math.floor(H*8);D=G[B]||"█"}else if(q>F&&q<U)W=!1;J.setChar(Z,Q+q,D,{fg:z,bg:K,reverse:W},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),V=Math.min(1,Z/J),K=Math.max(1,Y*V),z=Y-K;return{thumbStartFloat:Math.max(0,z*X),thumbSizeFloat:K,showScrollbar:!0}}}class hL extends d0{props;constructor(J){super();this.props=J}createState(){return new DO4}}class DO4 extends p0{scrollController=new Y5;scrollAreaKey=new g7("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(J){return J instanceof S2}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=f0.of(J),Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let U=B$0(Q);return{title:U.title,type:U.type,description:U.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,V=u1.all(new v1(Z.colors.border,1,"solid")),K=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(Y.title,new h({color:X,bold:!0}))})}),z=this.isWidgetMessage(Q)?Q.widget:new $0({text:new C(Y.description,new h({color:Z.colors.foreground})),selectable:!0}),G=new T1({child:new T2({child:new c0({padding:C0.symmetric(1,0),child:new U1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new j6({controller:this.scrollController,autofocus:!0,child:z})}),new u8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let U=this.scrollController.maxScrollExtent,q=this.scrollController.offset,D=this.getViewportHeight(),W=U+D;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(D,1),scrollOffset:Math.max(q,0)}}})]})})})}),F=new c0({padding:C0.symmetric(1,0),child:new $0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new h({color:Z.colors.foreground,dim:!0})),new C("R",new h({color:Z.app.keybind})),new C(" to retry, ",new h({color:Z.colors.foreground,dim:!0})),new C("Esc",new h({color:Z.app.keybind})),new C(" to cancel",new h({color:Z.colors.foreground,dim:!0}))]);let U=this.resolveFooterStyle(this.widget.props.message);if(U==="none")return new C("",new h({color:Z.colors.foreground,dim:!0}));if(U==="help"){let q=new h({color:Z.app.keybind}),D=new h({color:Z.colors.foreground,dim:!0});return new C("",D,[new C("Press ",D),new C("Escape",q),new C(" to close • Use ",D),new C("↑↓",q),new C(" or ",D),new C("j/k",q),new C(" to scroll",D)])}return new C("Press any key to close",new h({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new k4({onKey:(U)=>{if(this.widget.props.onRetry&&U.key==="r")return this.widget.props.onRetry(),"handled";if(U.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new c0({decoration:{border:V,color:Z.colors.background},padding:C0.all(1),child:new u0({mainAxisAlignment:"center",children:[K,new R0({height:1}),G,F]})})})}}e9();class WO4 extends d0{props;constructor(J){super();this.props=J}createState(){return new HO4}}class HO4 extends p0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((J)=>{this.plugins=J,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(J){let Z=J.startsWith("file://")?J.slice(7):J,Q=this.widget.props.cwd;if(Z.startsWith(Q))return Z.slice(Q.length+1);return Z}statusIcon(J){let Z=c8.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new $0({text:new C("No plugins found.",new h({dim:!0}))});let Y=[],X=this.plugins.length,V=this.plugins.filter((G)=>G.status==="active").length,K=this.plugins.reduce((G,F)=>G+F.registeredCommands.length,0),z=this.plugins.reduce((G,F)=>G+F.registeredTools.length,0);if(Y.push(new C(`${V}/${X} ${m4(X,"plugin")} active`,new h({bold:!0}))),K>0||z>0)Y.push(new C(` (${K} ${m4(K,"command")}, ${z} ${m4(z,"tool")})`,new h({dim:!0})));Y.push(new C(`
7289
+ `))}if(H)q.push(new C(" ",U)),q.push(new C("Total: ",U)),q.push(new C(V(B),F))}return new c0({decoration:{color:z.background,border:u1.all(new v1(z.border,1,"rounded"))},child:new $0({text:new C(void 0,void 0,q)})})}ow();h0();e9();import{execSync as zn5}from"node:child_process";KN();C7();H3();P7();sb();bX();a2();h$();xX();OE();_4();Gx();qk();H1();var xO4=D4(CF(),1);import{writeFile as SO4}from"fs/promises";import vO4 from"path";h0();a2();class $p0{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.1773432280-gcd86a7"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await Ct(Z,this.configService)}catch(Z){j.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class sH extends d0{props;constructor(J){super();this.props=J}createState(){return new hN4}}class hN4 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 mN4 extends p0{controller=new i7;focusNode=new r4({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,V=this.controller.text.trim().length>0,K=!X||V,z=u1.all(new v1(Q.foreground,1,"solid")),G=new FJ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(W)=>{let H=W.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new U1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:G})]}),U=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,[new C("Command: ",new h({color:Q.foreground})),new C(this.widget.props.commandName,new h({color:Y.command,bold:!0}))])})}),q=[];if(K)q.push(new C("Enter",new h({color:Y.keybind}))),q.push(new C(" to submit, ",new h({color:Q.foreground,dim:!0})));q.push(new C("Esc",new h({color:Y.keybind}))),q.push(new C(" to cancel",new h({color:Q.foreground,dim:!0})));let D=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("",void 0,q)})});return new c0({decoration:{border:z,color:Q.background},padding:C0.all(1),child:new u0({children:[U,new R0({height:1}),F,new V3,D]})})}}class dp extends d0{props;constructor(J){super();this.props=J}createState(){return new mN4}}import{isDeepStrictEqual as Jp0}from"node:util";var yi5=/[\\/_ +.#"@[({&]/,ui5=/[\\/_ +.#"@[({&]/g,xi5=/[\s-]/,gN4=/[\s-]/g;function k$0(J,Z,Q,Y,X,V,K){if(V===Z.length){if(X===J.length)return 1;return 0.99}let z=`${X},${V}`;if(K[z]!==void 0)return K[z];let G=Y.charAt(V),F=Q.indexOf(G,X),U=0,q,D,W,H;while(F>=0){if(q=k$0(J,Z,Q,Y,F+1,V+1,K),q>U){if(F===X)q*=1;else if(xi5.test(J.charAt(F-1))){if(q*=0.9,H=J.slice(X,F-1).match(gN4),H&&X>0)q*=0.999**H.length}else if(yi5.test(J.charAt(F-1))){if(q*=0.8,W=J.slice(X,F-1).match(ui5),W&&X>0)q*=0.999**W.length}else if(q*=0.3,X>0)q*=0.999**(F-X);if(J.charAt(F)!==Z.charAt(V))q*=0.9999}if(q<0.1&&(Q.charAt(F-1)===Y.charAt(V+1)||Y.charAt(V+1)===Y.charAt(V)&&Q.charAt(F-1)!==Y.charAt(V))){if(D=k$0(J,Z,Q,Y,F+1,V+2,K),D*0.1>q)q=D*0.1}if(q>U)U=q;F=Q.indexOf(G,F+1)}return K[z]=U,U}function v$0(J){return J.toLowerCase().replace(gN4," ")}function pN4(J,Z){let Q=k$0(J,Z,v$0(J),v$0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,V=0;for(let z of Y){let G=k$0(J,z,v$0(J),v$0(z),0,0,{});if(G===0)return Q;X+=G,V+=z.length}let K=X/Y.length*0.95;return Math.max(Q,K)}return Q}class hT{}class mT{}class y$0{}class u$0{}class dN4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new cN4}}class cN4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}function fi5(J,Z){if(J==="")return{matches:!0,score:1};let Q=pN4(Z,J);return{matches:Q>0.15,score:Q}}class o9 extends d0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new lN4}}class lN4 extends p0{textController;focusNode;scrollController=new Y5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new i7(this.widget.props.controller?.query??""),this.focusNode=new r4({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>Jp0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!Jp0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>Jp0(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 hT){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 mT){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 y$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 u$0)return this.widget.props.onDismiss?.(),"handled";return"ignored"};syncSelection(){let Z=this.cachedFiltered[this.selectedIndex]??null;if(this.widget.props.controller)this.widget.props.controller.selectedItem=Z;this.widget.props.onSelectionChange?.(Z)}clampSelectedIndex(){let J=this.cachedFiltered.length-1;if(J<0){this.selectedIndex=0;return}this.selectedIndex=Math.max(0,Math.min(this.selectedIndex,J))}recomputeFilteredItems(){let J=this.textController.text,Z=this.widget.props.items,Q=this.widget.props.normalizeQuery?.(J)??J,Y=Z.filter((X)=>!this.widget.props.filterItem||this.widget.props.filterItem(X,J)).map((X)=>({item:X,...fi5(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,V)=>this.widget.props.sortItems(X,V,J):(X,V)=>V.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Z=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Z)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;kT(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=u1.all(new v1(Q.foreground,1,"solid")),V=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,K=this.widget.props.enabled??!0,z=new FJ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:K,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),G=new C2({shortcuts:new Map([[new Y4("ArrowDown"),new hT],[new Y4("ArrowUp"),new mT],[new Y4("Tab"),new hT],[new Y4("Tab",{shift:!0}),new mT],[new Y4("n",{ctrl:!0}),new hT],[new Y4("p",{ctrl:!0}),new mT],[new Y4("Enter"),new y$0],[new Y4("Escape"),new u$0]]),focusNode:this.focusNode,child:z}),F=new S9({actions:new Map([[hT,new s4(this.invoke)],[mT,new s4(this.invoke)],[y$0,new s4(this.invoke)],[u$0,new s4(this.invoke)]]),child:G}),U=new U1({children:[new c0({decoration:{color:Q.background},child:new $0({text:new C(">",new h({color:Q.foreground}))})}),new T1({child:F})]});this.itemContexts=[];let q;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";q=new R0({height:10,child:new l1({child:new $0({text:new C(w,new h({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)q=new T1({child:new l1({child:new $0({text:new C(this.widget.props.emptyStateText,new h({color:Q.foreground,dim:!0}))})})});else{let w=Y.map((N,O)=>{let E=O===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(N,E,L,J);else{let A=E?Z.app.selectionBackground:void 0,I=E?Z.app.selectionForeground:Q.foreground;M=new c0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(this.widget.props.getLabel(N),new h({color:I,dim:L}))})})}return new dN4(new n1({onClick:(A)=>this.handleItemClick(O,A.clickCount),child:M}),(A)=>{this.itemContexts[O]=A})});q=new u0({children:w,crossAxisAlignment:"start"})}let D=new n1({onScroll:this.handleScroll,opaque:!1,child:new j6({controller:this.scrollController,autofocus:!1,child:q})}),W=[];if(this.widget.props.title){let w=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(this.widget.props.title,new h({color:Z.app.command,bold:!0}))})});W.push(w)}if(!V)W.push(U,new R0({height:1}));if(this.textController.text!==""){let w=Y.length>0?Y[this.selectedIndex]:void 0,N=w&&this.widget.props.buildDisabledReasonWidget?.(w,J);W.push(new T1({child:new u0({mainAxisAlignment:"spaceBetween",children:[new T1({child:D}),new c0({padding:C0.only({top:1}),child:new l1({child:N??new R0({height:1})})})]})}))}else W.push(new T1({child:D}));if(this.widget.props.footer)W.push(this.widget.props.footer);return new c0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new u0({children:W})})}}function iN4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),V=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(V<7)return`${V}d ago`;return J.toLocaleDateString()}class Zp0 extends d1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,V)=>V.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>iN4(X.pubDate).length));return new o9({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,V,K,z)=>{let G=f0.of(z),{colors:F}=G,U=G.app,q=V?U.selectionBackground:void 0,D=V?U.selectionForeground:F.foreground,W=F.mutedForeground,H=(B,w)=>new R0({width:w,child:U1.end([new $0({text:new C(B,new h({color:W}))})])});return new c0({decoration:q?{color:q}:void 0,padding:C0.symmetric(2,0),child:new U1({children:[new T1({child:new $0({text:new C(X.title,new h({color:D})),overflow:"ellipsis",maxLines:1})}),new R0({width:2}),H(iN4(X.pubDate),Q)]})})}})}}_4();class Qp0 extends d0{createState(){return new nN4}}class nN4 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 bi5=/\/threads\/(T-[^/?#\s<>]+)/i;function hi5(J){let Z=J.trim(),Y=Z.match(bi5)?.[1];if(Y&&D8(Y))return Y;let X=Z.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(D8(X))return X;return null}function mi5(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let K of J)Z.set(K.id,K);for(let K of J){let z=K.relationships.find((G)=>G.role==="child"&&Z.has(G.threadID)&&(G.type==="fork"||G.type==="handoff"));if(z){Y.set(K.id,z.type);let G=z.threadID,F=Q.get(G)||[];F.push(K),Q.set(G,F)}else X.push(K)}return X20.flatten(X,(K)=>Q.get(K.id)).map((K)=>({...K.item,depth:K.depth,isLast:K.isLast,ancestorsAreLast:K.ancestorsAreLast,relationshipType:Y.get(K.item.id)}))}function Yp0(J,Z,Q){return new $0({text:new C(`${J}${Z}`,new h({color:Q})),maxLines:1})}function gi5(J,Z,Q,Y){return[Yp0("+",J,Y.success),V3.horizontal(1),Yp0("~",Z,Y.warning),V3.horizontal(1),Yp0("-",Q,Y.destructive)]}function pi5(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class x$0 extends d0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new aN4}}class aN4 extends p0{spinner=new S3;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,V=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((O)=>O.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)V=V.filter((O)=>O.id!==Z.currentThreadID);let K=Z.recentThreadIDs||[],z=new Set(K),G=Z.currentThreadID,F=[...V].sort((O,E)=>{if(G){if(O.id===G)return-1;if(E.id===G)return 1}let L=K.indexOf(O.id),M=K.indexOf(E.id);if(L!==-1&&M!==-1)return L-M;if(L!==-1)return-1;if(M!==-1)return 1;return 0}),U=mi5(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=hi5(O);return B};return new o9({items:U,getLabel:(O)=>`${O.title} ${O.id}`,filterItem:(O,E)=>{let L=w(E);if(L)return O.id.toLowerCase()===L.toLowerCase();return!0},normalizeQuery:(O)=>w(O)?"":O,onAccept:async(O,E)=>{if(!Z.onSelect||this.isSwitchingThread)return;let L=Z.onSelect(O.id,E);if(!pi5(L))return;this.setSwitchingThread(!0);try{await L}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(O)=>{if(Z.previewController){if(O)Z.previewController.select(O.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:W,renderItem:(O,E,L,M)=>{let A=f0.of(M),{app:I,colors:P}=A,_=E?I.selectionBackground:void 0,S=E?I.selectionForeground:P.foreground,y=P.mutedForeground,m=(s,w0)=>new R0({width:w0,child:U1.end([new $0({text:new C(s,new h({color:y}))})])}),b=Z.threadViewStates[O.id],k=[],f=O.relationshipType==="handoff",p=new qp({connectorColor:P.mutedForeground});if(O.depth>0){let s=[],w0=O.ancestorsAreLast.slice(1);for(let z0 of w0)s.push(new C(p.getAncestorPrefix(z0),new h({color:p.connectorColor,dim:p.connectorDim})));let a=O.isLast?p.elbow:p.tee,F0=p.getConnectorText(a);s.push(new C(F0,new h({color:p.connectorColor,dim:p.connectorDim}))),k.push(new $0({text:new C("",void 0,s)}))}let l=[],x=G===O.id?new C("(current) ",new h({color:P.success})):z.has(O.id)?new C("(visited) ",new h({color:P.foreground,dim:!0})):null;if(x)l.push(new $0({text:x}));if(gO(b))l.push(new Qp0),l.push(new R0({width:1}));let r=O.title;if(O.relationshipType==="fork"){let s=r.match(/^Forked\((\d+)\): /);if(s)r=r.slice(s[0].length);else while(r.startsWith("Forked: "))r=r.slice(8);l.push(new $0({text:new C("[fork] ",new h({color:P.primary}))}))}else if(f)l.push(new $0({text:new C("[handoff] ",new h({color:P.accent}))}));if(l.push(new T1({child:new $0({text:new C(r,new h({color:S})),overflow:"ellipsis",maxLines:1})})),l.push(new R0({width:2})),O.diffStats&&(O.diffStats.added>0||O.diffStats.changed>0||O.diffStats.deleted>0)){let s=E?{success:y,warning:y,destructive:y}:P;l.push(...gi5(O.diffStats.added,O.diffStats.changed,O.diffStats.deleted,s)),l.push(new R0({width:2}))}return l.push(m(O.description.timeAgo,q)),new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new U1({children:[...k,...l]})})}})}}function oN4(J){return 1-(1-J)**3}function rN4(J,Z,Q){return J+(Z-J)*Q}function cp(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),V=oN4(Y),K=oN4(X);return{x:rN4(J.startOffset.x,J.targetOffset.x,V),y:rN4(J.startOffset.y,J.targetOffset.y,K)}}var di5={nodeWidth:3,horizontalSpacing:3};class gT{options;constructor(J={}){this.options={...di5,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let V=0,K=(z,G)=>{let F=Z.get(z.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let U={...z,parentID:Q.get(z.id)};if(F.length===0){Y.push({node:U,position:{x:V,y:G}});let B=V;return V+=this.options.nodeWidth+this.options.horizontalSpacing,B}let q=[];for(let B of F)q.push(K(B,G+1));let D=Math.min(...q),W=Math.max(...q),H=Math.floor((D+W)/2);return Y.push({node:U,position:{x:H,y:G}}),H};for(let z of X)K(z,0);return Y}buildTree(J){let Z=new Set(J.map((V)=>V.id)),Q=[...J].sort((V,K)=>V.id.localeCompare(K.id)),Y=new Map;for(let V of Q){if(!V.parentID||!Z.has(V.parentID)){Y.set(V.id,void 0);continue}let K=!1,z=V.parentID;while(z){if(z===V.id){K=!0;break}z=Y.get(z)}Y.set(V.id,K?void 0:V.parentID)}let X=new Map;for(let V of J){let K=Y.get(V.id);if(!X.has(K))X.set(K,[]);X.get(K).push(V)}return{childrenMap:X,resolvedParent:Y}}}var ci5={nodeWidth:3,nodeHeight:2};class pT{options;constructor(J={}){this.options={...ci5,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let V=this.calculateConnectorLine(X.position,Y.position);Z.push({points:V,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,V=Z.x+Q,K=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:K});let z=K+1;if(Y.push({x:X,y:z}),X!==V)Y.push({x:V,y:z});let G=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:V,y:G}),Y}}var li5={nodeWidth:3,nodeHeight:2},ii5={x:0,y:0};class b$0{options;constructor(J={}){this.options={...li5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=ii5,X,V,K,z){let G=z?f0.of(z):null,F=G?.colors,U=G?.app,q=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:q}))});let D=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,w=[];for(let I=D;I>=0;I--){let P=J.filter((y)=>y.position.y===I);P.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new R0({width:y.position.x-S}));let m=y.node.id===Q,b=K?.(y.node.data)??!1,k=V?.activeFlashOn??!1,f=y.node.id===V?.copyFlashNodeId;_.push(this.renderNode(m,b,k,f,U,F)),S=y.position.x+this.options.nodeWidth}if(w.push(new U1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((k)=>k.position.y===I-1),m=P,b=this.renderConnectors(y,m,Z,H,F,U);w.push(...b)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(D+1)*B,M=[new R0({width:H,height:L}),new x6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&X){let I=X(A.node.data),P=D-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+P*B+1,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(I,y,F,U)}))}return new c0({padding:C0.horizontal(2),child:new LH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,V){let K="┌─┐",z="└─┘",G=J?X?.threadGraphNodeSelected??V?.primary??V?.foreground:X?.threadGraphNode??V?.primary??V?.foreground,F=!1;if(Y)G=X?.threadGraphNodeSelected??V?.primary??G,K="┏━┓",z="┗━┛",F=!0;else if(Z&&Q)G=X?.toolSuccess??V?.primary??G,K="┏━┓",z="┗━┛";return new u0({crossAxisAlignment:"start",children:[new $0({text:new C(K,new h({color:G,bold:F}))}),new $0({text:new C(z,new h({color:G,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(X.length===0)X=V;else if(X.length+1+V.length<=Z)X+=" "+V;else Y.push(X),X=V}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),V=Math.min(Z,Math.max(1,...X.map((D)=>D.length))),K=V+2,z="┌"+"─".repeat(K)+"┐",G="└"+"─".repeat(K)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,U=Q?.foreground,q=[new $0({text:new C(z,new h({color:F}))})];for(let D of X){let W=" ".repeat(V-D.length);q.push(new $0({text:new C("│ ",new h({color:F}),[new C(D+W,new h({color:U??F})),new C(" │",new h({color:F}))])}))}return q.push(new $0({text:new C(G,new h({color:F}))})),new u0({crossAxisAlignment:"start",children:q})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let D of Z){let W=D.position.x+z;if(W>=0&&W<Y)F[W]="▲"}K.push(new $0({text:new C(F.join(""),new h({color:G}))}));let U=Array(Y).fill(" ");for(let D of J){let W=Z.filter((O)=>O.node.parentID===D.node.id);if(W.length===0)continue;let H=D.position.x+z,B=W.map((O)=>O.position.x+z),w=Math.min(...B),N=Math.max(...B);for(let O=w;O<=N;O++)if(O>=0&&O<Y){if(O===H)if(W.length===1&&B[0]===H)U[O]="│";else if(O===w)U[O]="└";else if(O===N)U[O]="┘";else U[O]="┬";else if(B.includes(O))if(O===w)U[O]="└";else if(O===N)U[O]="┘";else U[O]="┴";else if(U[O]===" ")U[O]="─"}}K.push(new $0({text:new C(U.join(""),new h({color:G}))}));let q=Array(Y).fill(" ");for(let D of J){if(Z.filter((B)=>B.node.parentID===D.node.id).length===0)continue;let H=D.position.x+z;if(H>=0&&H<Y)q[H]="│"}return K.push(new $0({text:new C(q.join(""),new h({color:G}))})),K}}var ni5={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},ai5={x:0,y:0};class Xp0{options;constructor(J={}){this.options={...ni5,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=ai5,X,V,K,z){let G=z?f0.of(z):null,F=G?.colors,U=G?.app,q=F?.mutedForeground??F?.foreground;if(J.length===0)return new $0({text:new C("No nodes",new h({color:q}))});let D=Math.max(...J.map((I)=>I.position.y)),H=Math.max(...J.map((I)=>I.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,w=[];for(let I=D;I>=0;I--){let P=J.filter((y)=>y.position.y===I);P.sort((y,m)=>y.position.x-m.position.x);let _=[],S=0;for(let y of P){if(y.position.x>S)_.push(new R0({width:y.position.x-S}));let m=y.node.id===Q,b=K?.(y.node.data)??!1,k=V?.activeFlashOn??!1;_.push(this.renderNode(m,b,k,U,F)),S=y.position.x+this.options.nodeWidth}if(w.push(new U1({crossAxisAlignment:"start",children:_})),I>0){let y=J.filter((k)=>k.position.y===I-1),m=P,b=this.renderConnectors(y,m,Z,H,F,U);w.push(...b)}}let N=new u0({crossAxisAlignment:"start",children:w}),O=Math.round(Y.x),E=Math.round(Y.y*B),L=(D+1)*B,M=[new R0({width:H,height:L}),new x6({left:O,top:E,child:N})],A=Q?J.find((I)=>I.node.id===Q):void 0;if(A&&X){let I=X(A.node.data),P=D-A.position.y,_=O+A.position.x+this.options.nodeWidth+1,S=E+P*B,y=30;if(V?.maxTitleWidthPercent&&V.viewportWidth)y=Math.floor(V.viewportWidth*V.maxTitleWidthPercent/100);M.push(new x6({left:_,top:S,child:this.renderInfoBox(I,y,F)}))}return new c0({padding:C0.horizontal(2),child:new LH(new i6({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let V=J?this.options.selectedIcon:this.options.nodeIcon,K=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)K=Y?.toolSuccess??X?.primary??K,V="■";return new $0({text:new C(V,new h({color:K}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let V of Q){if(V.length>Z)V=V.slice(0,Z-1)+"…";if(X.length===0)X=V;else if(X.length+1+V.length<=Z)X+=" "+V;else Y.push(X),X=V}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,V=[];for(let K of Y)V.push(new $0({text:new C(K,new h({color:X??Q?.primary??Q?.foreground}))}));return new u0({crossAxisAlignment:"start",children:V})}renderConnectors(J,Z,Q,Y,X,V){let K=[],z=Math.floor(this.options.nodeWidth/2),G=V?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of J){let q=Z.filter((w)=>w.node.parentID===U.node.id);if(q.length===0)continue;let D=U.position.x+z,W=q.map((w)=>w.position.x+z),H=Math.min(...W),B=Math.max(...W);for(let w=H;w<=B;w++)if(w>=0&&w<Y){let N=w===D,O=W.includes(w);if(N&&O)if(q.length===1)F[w]="│";else if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┼";else if(N)if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┬";else if(O)if(w===H)F[w]="└";else if(w===B)F[w]="┘";else F[w]="┴";else if(F[w]===" ")F[w]="─"}}return K.push(new $0({text:new C(F.join(""),new h({color:G}))})),K}}class lp extends N3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new sN4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class sN4 extends A4{onWidth;onHeight;constructor(J,Z){super();this.onWidth=J,this.onHeight=Z}performLayout(){let J=this._lastConstraints,Z=Number.isFinite(J.maxWidth)?J.maxWidth:80,Q=Number.isFinite(J.maxHeight)?J.maxHeight:24;this.onWidth(Z),this.onHeight?.(Q);let Y=this.children[0];if(Y)Y.layout(J),this.setSize(Y.size.width,Y.size.height);else this.setSize(J.minWidth,J.minHeight)}paint(J,Z,Q){for(let Y of this.children)Y.paint(J,Z,Q)}}class bL extends d0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new $O4}}var tN4=400,eN4=300,oi5=16;class $O4 extends p0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new gT({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new pT;renderer=new Xp0;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((G)=>G.id)),Q=new Set(this.widget.props.threads.map((G)=>G.id));if(Z.size!==Q.size||[...Z].some((G)=>!Q.has(G)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,V=this.widget.props.initialSelectedThreadID;if(X!==V&&V){let F=this.widget.props.threads.find((U)=>U.id===V);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let K=J.props.threads.some((G)=>G.isActive),z=this.widget.props.threads.some((G)=>G.isActive);if(K!==z){if(this.stopActiveFlashTimer(),z)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:tN4,durationY:eN4};let Z=Math.max(tN4,eN4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=cp(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},oi5)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),V=Math.floor(this.viewportWidth/2)-J-Y,K=Q-Z,z=2,G=Math.floor(this.viewportHeight/2),U=Math.floor(G/2)-K;return{x:V,y:U}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((V)=>V.node.parentID===Q.node.id);if(X.length>0){X.sort((K,z)=>K.position.x-z.position.x);let V=Math.floor(X.length/2);Y=X[V]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x<Q.position.x);if(X.length>0)X.sort((V,K)=>K.position.x-V.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((V)=>V.position.y===Q.position.y&&V.position.x>Q.position.x);if(X.length>0)X.sort((V,K)=>V.position.x-K.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let U=(this.selectedNodeId?this.positionedNodes.find((q)=>q.node.id===this.selectedNodeId):null)??this.positionedNodes.find((q)=>!q.node.parentID);if(U){let q=Math.max(...this.positionedNodes.map((D)=>D.position.y));this.currentOffset=this.calculateCenterOffset(U.position.x,U.position.y,q)}}let X=this.widget.props.showTitle??!0,V=this.widget.props.offsetY??0,K={x:this.currentOffset.x,y:this.currentOffset.y+V},z=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,K,X?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),G=new lp({onWidth:(F)=>{if(this.viewportWidth!==F)this.viewportWidth=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(F)=>{if(this.viewportHeight!==F)this.viewportHeight=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:z});return new k4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:G})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class ZO4 extends d0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new QO4}}class QO4 extends p0{build(J){return this.widget.onContext(J),this.widget.child}}var JO4=30,ri5=30;class dT{}class cT{}class h$0{}class m$0{}class Vp0 extends d0{props;constructor(J){super();this.props=J}createState(){return new YO4}}class YO4 extends p0{highlightedIndex=0;controller=new i7;focusNode;scrollController=new Y5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new r4({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;kT(J,{top:Q,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Z}=this.widget.props;if(!J)this.filteredClusters=[...Z];else this.filteredClusters=Z.filter((Q)=>Q.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof dT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof cT){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof h$0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof m$0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),H6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,z=t1.of(J).size.width>=ri5+JO4,G=u1.all(new v1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,U=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C("Select a cluster",new h({color:X.command,bold:!0}))})}),q=new FJ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),D=new C2({shortcuts:new Map([[new Y4("ArrowDown"),new dT],[new Y4("ArrowUp"),new cT],[new Y4("Tab"),new dT],[new Y4("Tab",{shift:!0}),new cT],[new Y4("n",{ctrl:!0}),new dT],[new Y4("p",{ctrl:!0}),new cT],[new Y4("Enter"),new h$0],[new Y4("Escape"),new m$0]]),focusNode:this.focusNode,child:q}),W=new S9({actions:new Map([[dT,new s4(this.invoke)],[cT,new s4(this.invoke)],[h$0,new s4(this.invoke)],[m$0,new s4(this.invoke)]]),child:D}),H=new U1({children:[new c0({decoration:{color:Y.background},child:new $0({text:new C(">",new h({color:Y.foreground}))})}),new T1({child:W})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let I=A===this.highlightedIndex,P=Z?M.threads.some((m)=>m.id===Z):!1,_=I?X.selectionBackground:void 0,S=I?X.selectionForeground:Y.foreground,y=[new C(M.label,new h({color:S})),new C(` (${M.threads.length})`,new h({color:S,dim:!0}))];if(P)y.push(new C(" (current)",new h({color:I?X.selectionForeground:Y.success})));return new ZO4(new n1({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new c0({decoration:_?{color:_}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,y)})})}),(m)=>{this.itemContexts[A]=m})}),w=new u0({children:B,crossAxisAlignment:"start"}),N=new T1({child:new n1({onScroll:this.handleScroll,child:new j6({controller:this.scrollController,autofocus:!1,child:w})})}),O=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],E=F?new c0({padding:C0.all(1),child:new bL({threads:O,autofocus:!1,offsetY:2})}):null,L;if(z){let M=E?new T1({child:E}):new R0({width:JO4});L=new U1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,M]})}else{let M=[new T1({child:new n1({onScroll:this.handleScroll,child:new j6({controller:this.scrollController,autofocus:!1,child:w})})})];if(E)M.push(new T1({child:E}));L=new u0({crossAxisAlignment:"stretch",children:M})}return new c0({decoration:{border:G,color:Y.background},padding:C0.symmetric(1,0),child:new u0({children:[U,H,new R0({height:1}),new T1({child:L})]})})}}class UJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!UJ._instance)UJ._instance=new UJ;return UJ._instance}get allExpanded(){return this._allExpanded}setAllExpanded(J){if(this._allExpanded===J)return;this._allExpanded=J,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(J){return this._listeners.add(J),()=>this.removeListener(J)}removeListener(J){this._listeners.delete(J)}_notifyListeners(){for(let J of this._listeners)J()}}h0();class XO4 extends p0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){j.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){j.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((V)=>V.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=f0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),V=X.length>0?this.getValidationError(X):null,K=this.getAvailableLabels(),G=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...K];return new o9({title:"Add Label",items:G,getLabel:(F)=>{if("__isCreateMarker"in F)return this.currentQuery.trim().toLowerCase();return F.name},onAccept:(F)=>{if("__isCreateMarker"in F)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(F.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:V||"Type to create a new label",renderItem:(F,U,q,D)=>{let W=U?Q.selectionBackground:void 0,H=U?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in F&&F.__isCreateMarker){let w=this.currentQuery.trim().toLowerCase();return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C("",void 0,[new C("Create new label: ",new h({color:H})),new C(w,new h({color:H,bold:!0}))])})})}return new c0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new $0({text:new C(F.name,new h({color:H}))})})},filterItem:(F,U)=>{if(this.currentQuery!==U)this.currentQuery=U,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in F&&F.__isCreateMarker)return this.shouldShowCreateMarker(U);let D=U.trim().toLowerCase();return D.length===0||F.name.includes(D)},sortItems:(F,U,q)=>{let D="__isCreateMarker"in F.item&&F.item.__isCreateMarker,W="__isCreateMarker"in U.item&&U.item.__isCreateMarker;if(D&&!W)return-1;if(!D&&W)return 1;return U.score-F.score}})}}class Kp0 extends d0{props;constructor(J){super();this.props=J}createState(){return new XO4}}class iV extends d0{props;constructor(J){super();this.props=J}createState(){return new VO4}}class VO4 extends p0{_spinner=new S3;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=u1.all(new v1(Q.foreground,1,"solid")),V=this._spinner.toBraille(),K=new $0({textAlign:"center",text:new C("",void 0,[new C(V,new h({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new h({color:Q.foreground}))])}),G=[new T1({child:new u0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[K]})})];if(this.widget.props.onAbort)G.push(new R0({height:2,child:new c0({padding:C0.symmetric(2,0),child:new $0({text:new C("",new h({dim:!0}),[new C("Press ",new h({color:Q.foreground})),new C("Esc",new h({color:Q.info})),new C(" to cancel",new h({color:Q.foreground}))])})})}));let F=new c0({decoration:new v4(Q.background,X),child:new R0({width:60,height:7,child:new u0({mainAxisAlignment:"start",children:G})})});if(this.widget.props.onAbort)return new k4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(U)=>{if(U.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:F});return F}}var ip={workspace:{label:"Workspace",pathHint:".amp/settings.json",description:"workspace config"},global:{label:"Global",pathHint:"~/.config/amp/settings.json",description:"global config"},flag:{label:"Flag",pathHint:"CLI flags",description:"flag config"},default:{label:"Default",pathHint:"built-in defaults",description:"default config"},external:{label:"External",pathHint:"extensions / external",description:"external source"},skill:{label:"Skills",pathHint:".agents/skills/",description:"skill source"},other:{label:"Other",pathHint:"",description:"other source"}},g$0=["workspace","global","flag","default","external","skill","other"];function si5(J){return Array.from(new Set(J))}function KO4(J){return si5([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function lT(J){if(J.isExternal)return"external";switch(J.spec._target){case"workspace":return"workspace";case"global":return"global";case"flag":return"flag";case"default":return"default"}return KO4(J).length>0?"skill":"other"}function zp0(J){return lT(J)==="skill"}function zO4(J){let Z=KO4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=lT(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${ip[Y].description}: ${Q}`}function GO4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}class u8 extends d0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:V="█",showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createState(){return new FO4}}class FO4 extends p0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),X=this.context.findRenderObject()?.size.height??0;if(X===0||Z<=Q)return!1;let V=this.widget.getScrollInfo(),K=Math.min(1,Q/Z),z=Math.max(1,X*K),G=Math.max(0,Math.min(1,V.scrollOffset/(Z-Q))),F=X-z,U=Math.max(0,F*G),q=U+z;return J>=U&&J<=q}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let K=J.localPosition.y-this._dragStartY,z=Math.min(1,Q/Z),G=Math.max(1,V*z),F=V-G;if(F<=0)return;let U=Z-Q,q=F/U,D=K/q,W=Math.max(0,Math.min(U,this._dragStartOffset+D));this.widget.controller.jumpTo(W)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Q<=Y)return;let z=Math.min(1,Y/Q),G=Math.max(1,K*z),F=Q-Y,U=K-G,q=Math.max(0,Math.min(1,X/(Q-Y))),D=Math.max(0,U*q),W=D+G;if(Z>=D&&Z<=W)return;if(Z<D)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(F,X+Y))};build(J){return new n1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?E5.POINTER:E5.DEFAULT,child:new UO4({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 UO4 extends dC{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X="█",thumbChar:V="█",showTrack:K=!0,thumbColor:z,trackColor:G}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=V,this.showTrack=K,this.thumbColor=z,this.trackColor=G}createRenderObject(){return new qO4(this)}updateRenderObject(J){J.updateWidget(this)}}class qO4 extends A4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;f4(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:V}=this._calculateScrollbarMetrics();if(!V)return;let K=this._widget.trackColor,z=this._widget.thumbColor,G=["▁","▂","▃","▄","▅","▆","▇","█"],F=Y,U=Y+X;for(let q=0;q<this.size.height;q++){let D="█",W=!0;if(q===Math.floor(F)){let H=1-(F-q),B=Math.floor(H*8);D=G[B]||"█",W=!1}else if(q===Math.floor(U)){let H=1-(U-q),B=Math.floor(H*8);D=G[B]||"█"}else if(q>F&&q<U)W=!1;J.setChar(Z,Q+q,D,{fg:z,bg:K,reverse:W},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),V=Math.min(1,Z/J),K=Math.max(1,Y*V),z=Y-K;return{thumbStartFloat:Math.max(0,z*X),thumbSizeFloat:K,showScrollbar:!0}}}class hL extends d0{props;constructor(J){super();this.props=J}createState(){return new DO4}}class DO4 extends p0{scrollController=new Y5;scrollAreaKey=new g7("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(J){return J instanceof S2}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=f0.of(J),Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let U=B$0(Q);return{title:U.title,type:U.type,description:U.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,V=u1.all(new v1(Z.colors.border,1,"solid")),K=new c0({padding:C0.symmetric(1,0),child:new $0({text:new C(Y.title,new h({color:X,bold:!0}))})}),z=this.isWidgetMessage(Q)?Q.widget:new $0({text:new C(Y.description,new h({color:Z.colors.foreground})),selectable:!0}),G=new T1({child:new T2({child:new c0({padding:C0.symmetric(1,0),child:new U1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new j6({controller:this.scrollController,autofocus:!0,child:z})}),new u8({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let U=this.scrollController.maxScrollExtent,q=this.scrollController.offset,D=this.getViewportHeight(),W=U+D;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(D,1),scrollOffset:Math.max(q,0)}}})]})})})}),F=new c0({padding:C0.symmetric(1,0),child:new $0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new h({color:Z.colors.foreground,dim:!0})),new C("R",new h({color:Z.app.keybind})),new C(" to retry, ",new h({color:Z.colors.foreground,dim:!0})),new C("Esc",new h({color:Z.app.keybind})),new C(" to cancel",new h({color:Z.colors.foreground,dim:!0}))]);let U=this.resolveFooterStyle(this.widget.props.message);if(U==="none")return new C("",new h({color:Z.colors.foreground,dim:!0}));if(U==="help"){let q=new h({color:Z.app.keybind}),D=new h({color:Z.colors.foreground,dim:!0});return new C("",D,[new C("Press ",D),new C("Escape",q),new C(" to close • Use ",D),new C("↑↓",q),new C(" or ",D),new C("j/k",q),new C(" to scroll",D)])}return new C("Press any key to close",new h({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new k4({onKey:(U)=>{if(this.widget.props.onRetry&&U.key==="r")return this.widget.props.onRetry(),"handled";if(U.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new c0({decoration:{border:V,color:Z.colors.background},padding:C0.all(1),child:new u0({mainAxisAlignment:"center",children:[K,new R0({height:1}),G,F]})})})}}e9();class WO4 extends d0{props;constructor(J){super();this.props=J}createState(){return new HO4}}class HO4 extends p0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((J)=>{this.plugins=J,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(J){let Z=J.startsWith("file://")?J.slice(7):J,Q=this.widget.props.cwd;if(Z.startsWith(Q))return Z.slice(Q.length+1);return Z}statusIcon(J){let Z=c8.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new $0({text:new C("No plugins found.",new h({dim:!0}))});let Y=[],X=this.plugins.length,V=this.plugins.filter((G)=>G.status==="active").length,K=this.plugins.reduce((G,F)=>G+F.registeredCommands.length,0),z=this.plugins.reduce((G,F)=>G+F.registeredTools.length,0);if(Y.push(new C(`${V}/${X} ${m4(X,"plugin")} active`,new h({bold:!0}))),K>0||z>0)Y.push(new C(` (${K} ${m4(K,"command")}, ${z} ${m4(z,"tool")})`,new h({dim:!0})));Y.push(new C(`
7290
7290
 
7291
7291
  `));for(let G of this.plugins){let{icon:F,color:U}=this.statusIcon(G.status),q=this.getRelativePath(G.uri.toString());if(Y.push(new C(`${F} `,new h({color:U}))),Y.push(new C(q,new h({bold:!0}))),Y.push(new C(` ${G.status}`,new h({dim:!0}))),Y.push(new C(`
7292
7292
  `)),G.status==="active"&&G.registeredEvents.length>0)Y.push(new C(" Events: ",new h({dim:!0}))),Y.push(new C(G.registeredEvents.join(", "),new h({color:Q.link}))),Y.push(new C(`
@@ -7497,12 +7497,12 @@ ${O0.join(`
7497
7497
  ---
7498
7498
 
7499
7499
  ${Z0.content||""}`:Z0.content||"",a0=[],F1=Z0.baseDir.startsWith("file://")?IJ0(Z0.baseDir):Z0.baseDir,a1=(Z0.files||[]).filter((V1)=>!V1.toLowerCase().endsWith("skill.md"));if(!K0){a0.push(new R0({height:1})),a0.push(new $0({text:new C("─".repeat(P-4),q)})),a0.push(new R0({height:1})),a0.push(new $0({text:new C("Files:",q)})),a0.push(new n1({cursor:"pointer",onClick:()=>{w8(J,`${Z0.baseDir}/SKILL.md`)},child:new $0({text:new C(" SKILL.md",new h({color:Q.primary}))})}));for(let V1 of a1){let t0=kM4(F1,V1),A1=V1.startsWith("/")?`file://${V1}`:`${Z0.baseDir}/${V1}`;a0.push(new n1({cursor:"pointer",onClick:()=>{w8(J,A1)},child:new $0({text:new C(` ${t0}`,new h({color:Q.primary}))})}))}}let o1=K0?new $0({text:new C("SKILL.md",q)}):new n1({cursor:"pointer",onClick:()=>{w8(J,`${Z0.baseDir}/SKILL.md`)},child:new $0({text:new C("SKILL.md",new h({color:Q.primary}))})}),m0=new u0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[o1,new R0({height:1}),...e0?[new $0({text:new C(e0,U)})]:[],...a0]});q0=new c0({constraints:new M1({minWidth:P,maxWidth:P}),decoration:new v4(void 0,new u1(void 0,void 0,void 0,new v1(Q.border,1))),padding:C0.only({left:2}),child:new u0({crossAxisAlignment:"stretch",children:[D0,new R0({height:1}),new T1({child:new U1({crossAxisAlignment:"stretch",children:[new T1({child:new j6({controller:this.detailScrollController,child:m0})}),new u8({controller:this.detailScrollController,thumbColor:X.scrollbarThumb,trackColor:X.scrollbarTrack,getScrollInfo:()=>{let V1=this.detailScrollController.maxScrollExtent,t0=this.detailScrollController.offset;return{totalContentHeight:Math.max(V1+20,0),viewportHeight:20,scrollOffset:Math.max(t0,0)}}})]})})]})})}let Q0=new T1({child:new i0({padding:A?C0.only({right:1}):C0.all(0),child:new U1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new j6({controller:this.listScrollController,child:z0})}),new u8({controller:this.listScrollController,thumbColor:X.scrollbarThumb,trackColor:X.scrollbarTrack,getScrollInfo:()=>{let Z0=this.getViewportHeight(),K0=this.listScrollController.maxScrollExtent,t=this.listScrollController.offset;return{totalContentHeight:Math.max(K0+Z0,0),viewportHeight:Z0,scrollOffset:Math.max(t,0)}}})]})})}),H0=new l1({child:new $0({text:new C("",N,[new C("Escape",B),new C(" to close",N)])})}),i=new T1({child:new c0({padding:C0.symmetric(1,0),child:new U1({crossAxisAlignment:"stretch",children:[Q0]})})}),e=[new T1({child:new u0({crossAxisAlignment:"stretch",children:[s,new R0({height:1}),i,new R0({height:1}),H0]})})];if(q0)e.push(q0);let J0=new U1({crossAxisAlignment:"stretch",children:e});return new k4({autofocus:!0,focusNode:this.focusNode,onKey:this.handleKeyEvent,child:new l1({child:new c0({constraints:new M1(I,I,0,M),decoration:new v4(Q.background,u1.all(new v1(Q.primary,1,"rounded"))),child:new i0({padding:C0.all(1),child:J0})})})})}}class sd0 extends d0{props;constructor(J){super();this.props=J}createState(){return new uM4}}class uM4 extends p0{_scrollController=new Y5;_viewportHeight=0;getOptions(){return[{value:"remove",label:"Remove skill"},{value:"close",label:"Close"}]}handleSelect=(J)=>{if(!J){this.widget.props.onDismiss();return}switch(J){case"remove":this.widget.props.onRemove();break;case"close":this.widget.props.onDismiss();break}};dispose(){this._scrollController.dispose(),super.dispose()}build(J){let{pendingSkill:Z,skill:Q}=this.widget.props,Y=I1.of(J).colorScheme,X=f0.of(J),V=t1.sizeOf(J),K=V.width,z=V.height,G=Math.min(K-12,80),F=Math.min(z-4,30),U=16,q=F-16,D=[];if(Q?.description){if(D.push(new $0({text:new C(Q.description,new h({color:Y.foreground}))})),D.push(new R0({height:1})),Q.content&&q>2){D.push(new $0({text:new C("─".repeat(G-6),new h({color:Y.foreground,dim:!0}))})),D.push(new R0({height:1}));let H=Q.content.split(`
7500
- `).length,B=Math.max(Math.min(H,q),3);this._viewportHeight=B;let w=new a3({markdown:Q.content}),N=new c0({constraints:new M1({maxHeight:B}),child:new U1({crossAxisAlignment:"stretch",children:[new T1({child:new j6({controller:this._scrollController,autofocus:!1,child:w})}),new u8({controller:this._scrollController,thumbColor:X.app.scrollbarThumb,trackColor:X.app.scrollbarTrack,getScrollInfo:()=>{let O=this._scrollController.maxScrollExtent,E=this._scrollController.offset,L=this._viewportHeight,M=O+L;return{totalContentHeight:Math.max(M,0),viewportHeight:Math.max(L,1),scrollOffset:Math.max(E,0)}}})]})});D.push(N),D.push(new R0({height:1}))}}else D.push(new $0({text:new C("(Loading skill details...)",new h({color:Y.foreground,dim:!0,italic:!0}))})),D.push(new R0({height:1}));if(Z.arguments)D.push(new $0({text:new C("",void 0,[new C("Arguments: ",new h({color:Y.foreground,dim:!0})),new C(Z.arguments,new h({color:Y.foreground}))])})),D.push(new R0({height:1}));let W=new u0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new $0({text:new C("",void 0,[new C(Z.name,new h({bold:!0,color:Y.success,underline:!0}))])}),new R0({height:1}),...D,new c7({options:this.getOptions(),onSelect:this.handleSelect,autofocus:!0,showDismissalMessage:!1,enableMouseInteraction:!0})]});return new k4({onKey:(H)=>{if(H.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"},child:new l1({child:new LH(new c0({constraints:new M1(G,G,0,F),decoration:{color:Y.background,border:u1.all(new v1(Y.success,1,"rounded"))},padding:C0.symmetric(2,1),child:W}))})})}}function Ns5(J,Z){if(J===Z)return!0;let Q=Object.keys(J),Y=Object.keys(Z);if(Q.length!==Y.length)return!1;for(let X of Q){if(!(X in Z))return!1;if(!Object.is(J[X],Z[X]))return!1}return!0}class td0 extends d0{stableProps;arePropsEqual;constructor({key:J,stableProps:Z,arePropsEqual:Q}){super(J?{key:J}:{});this.stableProps=Z,this.arePropsEqual=Q??Ns5}createState(){return new jJ0}}class jJ0 extends p0{cachedChild=null;build(J){let{stableProps:Z,arePropsEqual:Q}=this.widget,Y=this.cachedChild;if(Y&&Q(Y.props,Z))return Y.widget;let X=this.widget.buildStableChild(Z);return this.cachedChild={props:Z,widget:X},X}dispose(){this.cachedChild=null}}class ed0 extends td0{constructor(J){super({stableProps:J})}createState(){return new xM4}buildStableChild(J){let{threadID:Z,...Q}=J;return new qd({...Q,key:Z?new $3(`message-view-${Z}`):void 0})}}class xM4 extends jJ0{build(J){return super.build(J)}}H1();function Os5(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/3600000),X=Math.floor(Y/24),V=Math.floor(X/7),K=Math.floor(X/30);if(Y<1)return"Just now";if(Y<24)return`${Y}h ago`;if(X<7)return`${X}d ago`;if(V<=4)return`${V}w ago`;return`${K}mo ago`}class $c0{threadHistoryService;constructor(J){this.threadHistoryService=J}async fetchThreadSummaries(J="",Z){try{let Q=await new Promise((Y)=>{let X=this.threadHistoryService.observeThreadList(Z).subscribe((V)=>{X.unsubscribe(),Y(V)})});return{ok:!0,threads:this.formatThreadSummaries(Q,J,Z)}}catch(Q){return{ok:!1,errorMsg:Q instanceof Error?Q.message:"An unexpected error occurred"}}}observeThreadSummaries(J="",Z={}){return this.threadHistoryService.observeHistory().pipe(D1((Q)=>this.formatThreadSummaries(Q,J,Z)))}formatThreadSummaries(J,Z,Q={}){return J.filter((X)=>{if(X.mainThreadID)return!1;if(!Q.includeArchived&&X.archived)return!1;if(!Z.trim())return!0;let V=X.title?.toLowerCase()||"untitled",K=X.id.toLowerCase(),z=Z.toLowerCase();return V.includes(z)||K.includes(z)}).map((X)=>{let V=new Date(X.userLastInteractedAt),K=Os5(V),z=X.id.slice(-8),G=X.env?.initial.trees?.[0]?.uri;return{id:X.id,title:X.title||"Untitled",updatedAt:new Date(X.userLastInteractedAt).toISOString(),description:{timeAgo:K,title:X.title||"Untitled",shortThreadID:z},diffStats:X.summaryStats?.diffStats,workspaceURI:G,relationships:X.relationships,agentMode:X.agentMode,details:{messageCount:X.summaryStats?.messageCount},archived:X.archived}})}}h0();_4();_4();function fM4(J){let Z=fI1(J),Q=Array.from(Z.entries()).map(([V,K])=>({path:V,diffStats:K})),X=K2(J)?.totalInputTokens??0;return{filesAffected:Q,totalTokens:X}}class Jc0{currentId=null;current=null;statsCache=new Map;subscribeTimer=null;subscription=null;listeners=[];threadService=null;scrollController=new Y5;constructor(){}setThreadService(J){this.threadService=J}async select(J){if(!this.threadService){j.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId===J)return;this.cancelTimerAndSubscription(),this.currentId=J;let Z=await this.threadService.get(J);if(Z){if(this.currentId===J)this.current=Z,this.notifyListeners()}this.subscribeTimer=setTimeout(()=>{this.subscribeLive(J)},1000)}clear(){this.cancelTimerAndSubscription(),this.currentId=null,this.current=null,this.notifyListeners()}addListener(J){this.listeners.push(J)}removeListener(J){let Z=this.listeners.indexOf(J);if(Z!==-1)this.listeners.splice(Z,1)}getCurrentThread(){return this.current}getCurrentStats(){if(!this.current)return null;let J=this.statsCache.get(this.current.id);if(J&&J.version===this.current.v)return J.stats;let Z=fM4(this.current);return this.statsCache.set(this.current.id,{stats:Z,version:this.current.v}),Z}clearStatsCache(){this.statsCache.clear()}dispose(){this.cancelTimerAndSubscription(),this.clearStatsCache(),this.scrollController.dispose(),this.listeners=[]}subscribeLive(J){if(!this.threadService){j.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId!==J)return;this.subscription=this.threadService.observePatches(J).pipe(Qr()).subscribe((Z)=>{if(this.currentId===J)this.current=Z,this.notifyListeners()})}cancelTimerAndSubscription(){if(this.subscribeTimer)clearTimeout(this.subscribeTimer),this.subscribeTimer=null;if(this.subscription)this.subscription.unsubscribe(),this.subscription=null}notifyListeners(){for(let J of this.listeners)J(this.current)}}class Zc0 extends d0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new bM4}}class bM4 extends p0{build(J){let Q=f0.of(J).colors,{todos:Y,title:X="TODOs"}=this.widget.props;if(!Array.isArray(Y)||Y.length===0)return new R0({width:0,height:0});let V=Y.map((K)=>this.buildTodoItem(K,Q));return new c0({child:new i0({padding:C0.symmetric(1,0),child:new u0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new $0({text:new C(X,new h({bold:!0,color:Q.foreground}))}),...V]})})})}buildTodoItem(J,Z){let Q=this.getStatusIcon(J.status),Y=J.status==="completed",X=new h({bold:J.status==="in-progress",color:Z.foreground,dim:Y}),V=new h({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Z.foreground,dim:Y});return new U1({crossAxisAlignment:"start",children:[new $0({text:new C(Q,X)}),new R0({width:1}),new T1({child:new $0({text:new C(J.content,V)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}function hM4(J,Z){switch(J){case"update-available":return[new C("A newer Amp is available. Run ",new h({color:Z.foreground,dim:!0})),new C("amp update",new h({color:Z.warning}))];case"update-available-unrecognized-path":return[new C("A newer Amp is available.",new h({color:Z.foreground,dim:!0}))];case"update-available-brew":return[new C("A newer Amp is available. Run ",new h({color:Z.foreground,dim:!0})),new C("brew upgrade ampcode",new h({color:Z.warning}))];case"updated":return null;case"updated-with-warning":return[new C("Update complete, run ",new h({color:Z.foreground,dim:!0})),new C("amp update",new h({color:Z.warning})),new C(" to see warnings",new h({color:Z.foreground,dim:!0}))];case"update-error":return[new C("Update failed, run ",new h({color:Z.foreground,dim:!0})),new C("amp update",new h({color:Z.warning})),new C(" to see warnings",new h({color:Z.foreground,dim:!0}))];case"hidden":return null}}async function Ps5(J){return new Promise((Z)=>{Es5("git",["branch","--show-current"],{cwd:J},(Q,Y)=>{if(Q){Z(null);return}let X=Y.trim();Z(X||null)})})}function pM4(J){return"interrupt"in J&&J.interrupt===!0}class Qc0 extends d0{dependencies;constructor(J){super();this.dependencies=J}createState(){return new RJ0}}class RJ0 extends p0{get tuiContext(){return DZ.require(this.context)}debugThreadViewState=process.env.AMP_DEBUG_THREAD_VIEW==="1";lastThreadStatusDebugSignature=null;themeColors=null;themeApp=null;ideStatus=null;randomAd=null;adSubscription=null;adsDisabledBySetting=!1;adReadinessTimeout=null;threadLoadSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();hasShownWinPasteHookRecoveryWarning=!1;winPasteHookImageUnsubscribe=null;winPasteHookStateUnsubscribe=null;isConfirmingExit=!1;isExiting=!1;isConfirmingClearInput=!1;isConfirmingCancelProcessing=!1;statusMessage=null;statusMessageTimer=null;isShowingHelp=!1;isShowingShortcutsHelp=!1;isShowingContextAnalyzeModal=!1;isShowingSkillListModal=!1;skillListData=null;shortcutsHintUsed=!1;deepReasoningEffort="high";anthropicSpeed=void 0;openAISpeed=void 0;deepReasoningEffortSubscription=null;anthropicSpeedSubscription=null;openAISpeedSubscription=null;sessionState=bC;isShowingConsoleOverlay=!1;isShowingMCPStatusModal=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingContextDetailOverlay=!1;threadCostInfo=void 0;threadCostInfoThreadID=void 0;lastInferenceState=void 0;elapsedTimeTimer=null;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;cancelProcessingConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];pendingSkills=[];pendingSkillsSubscription=null;skillListSubscription=null;skillWarningsSubscription=null;skillErrorsSubscription=null;availableSkillCount=0;availableSkillCountReady=!1;showSkillsCountInPromptBar=!0;showSkillsCountInPromptBarSubscription=null;skillWarningCount=0;skillErrorCount=0;pendingApprovals=[];pendingApprovalsSubscription=null;submitOnEnter=!0;submitOnEnterSubscription=null;displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;isShowingPalette=!1;isShowingPromptHistoryPicker=!1;paletteShowOptions=null;paletteOnThreadMentionSelected=null;threadsForPicker=[];parentThreadTitles=new Map;parentThreadTitleLoadsInFlight=new Set;clustersForPicker=[];isLoadingThreads=!1;threadPreviewController=new Jc0;previewThread=null;todoScrollController=(()=>{let J=new Y5;return J.followMode=!1,J})();contextAnalyzeDeps=null;contextAnalyzeFromDTW=null;openContextAnalyzeModal=()=>{if(this.widget.dependencies.threadPool.isDTWMode?.()){let J=this.widget.dependencies.threadState.mainThread;if(!J)return;this.contextAnalyzeDeps=null,this.contextAnalyzeFromDTW=(Z)=>g30({ampURL:this.tuiContext.ampURL,configService:this.widget.dependencies.configService,threadID:J.id,workerURL:process.env.AMP_WORKER_URL,signal:Z}),this.setState(()=>{this.isShowingContextAnalyzeModal=!0});return}this.contextAnalyzeFromDTW=null,this.widget.dependencies.createSystemPromptDeps().then((J)=>{this.contextAnalyzeDeps=J,this.setState(()=>{this.isShowingContextAnalyzeModal=!0})})};filterThreadPickerByWorkspace=!0;currentGitBranch=null;messageViewFocusNode=new r4({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new r4({debugLabel:"AutocompleteFocus"});autocompleteFocusNodeListener=null;isTextfieldAndAutocompleteFocused=!1;hasReplayedEarlyInput=!1;submitDisabledHint=null;submitDisabledHintTimer=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;imagePreview=null;fileImagePreviewPath=null;painterImagePreview=null;painterSaveDialog=null;messageViewController=new AJ0;previewMessageViewController=new AJ0;handleMainMessageViewCopy=(J,Z)=>{this._handleTextCopy(J,Z)};handleMainMessageViewDismissFocus=()=>{if(this.setState(()=>{this.isMessageViewInSelectionMode=!1,this.imagePreview=null}),!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()};messageViewControllerUnsubscribe=null;lastEditingMessageOrdinal=null;skillPreview=null;cachedSkillForPreview=null;adActionModal=null;adInfoModal=null;adModalStack=[];newsFeedReader=null;newsFeedEntries=[];newsFeedSubscription=null;bottomGridUserHeight=void 0;bottomGridDragStartY=null;bottomGridDragStartHeight=null;parentThreadLinkAnchor=new hp;previousThreadIdForHint=null;handoffController=null;handoffState={isInHandoffMode:!1,isGeneratingHandoff:!1,isConfirmingAbortHandoff:!1,pendingHandoffPrompt:null,spinner:null,countdownSeconds:null};isInQueueMode=!1;pendingMCPServers=[];mcpTrustSubscription=null;pendingOAuthRequest=null;pendingAuthLogin=null;authStatus="pending";authStatusSubscription=null;authModalKeyInterceptorUnsubscribe=null;isCreatingAuthLoginSession=!1;queuedPromptAfterAuth=null;pendingInputDialog=null;pendingConfirmDialog=null;mcpServers=[];mcpServersSubscription=null;pluginInfos=[];pluginInfosSubscription=null;agentModeController=null;freeTierStatus={canUseAmpFree:!1,isDailyGrantEnabled:!1};agentModePulseSeq=0;lastEffectiveAgentMode="smart";deepModeEffortHintController=new vg0({getDeepReasoningEffort:()=>this.deepReasoningEffort,getEffectiveAgentMode:()=>this.getEffectiveAgentMode(),canShowHintInCurrentThread:()=>{let J=this.widget.dependencies.threadState.mainThread;return!!J&&W3(J)===0},requestRender:()=>{if(!this.mounted)return;this.setState(()=>{})},isMounted:()=>this.mounted});updateState="hidden";updateServiceSubscription=null;toastController=new x70;isMessageViewInSelectionMode=!1;threadBackStack=[];threadForwardStack=[];isShowingForkDeprecationModal=!1;mysteriousMessage=null;isShowingMysteriousMessageModal=!1;mysteriousMessageSubscription=null;mysterySequenceManager=null;mysterySequenceProgress=null;mysteryKeyInterceptorUnsubscribe=null;static MYSTERY_SEQUENCE=["ctrl+x","y","z"];splashOrbExplosion=null;splashOrbExplosionSeq=0;freeTierStatusSubscription=null;allConnectedThreadActivityStatusesSubscription=null;threadInitializationStatusSubscription=null;allConnectedThreadActivityStatuses={};threadInitializationMessage=null;threadTitlesSubscription=null;threadTitles={};pendingNavigationSubscription=null;pendingNavigationInFlightThreadID=null;pluginCommands=[];pluginCommandsSubscription=null;async initNewsFeed(){let J=async(Q)=>{return p3(Q,void 0,this.widget.dependencies.configService)},Z=Bm1();this.newsFeedReader=new Tg0(Z,J,"/news.rss"),this.newsFeedSubscription=this.newsFeedReader.stream().subscribe({next:(Q)=>{if(Q.length>0)this.setState(()=>{this.newsFeedEntries=[...Q,...this.newsFeedEntries]})},error:(Q)=>{j.error("News feed error:",Q)}})}bringAdModalToFront(J){this.adModalStack=this.adModalStack.filter((Z)=>Z!==J),this.adModalStack.push(J)}removeAdModalFromStack(J){this.adModalStack=this.adModalStack.filter((Z)=>Z!==J)}getTopAdModal(){for(let J=this.adModalStack.length-1;J>=0;J--){let Z=this.adModalStack[J];if(Z==="adAction"&&this.adActionModal)return Z;if(Z==="adInfo"&&this.adInfoModal)return Z}return null}dismissTopAdModal(){let J=this.getTopAdModal();if(!J)return!1;return this.setState(()=>{if(J==="adAction")this.adActionModal=null;if(J==="adInfo")this.adInfoModal=null;this.removeAdModalFromStack(J)}),!0}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}navigateBack=async()=>{if(this.threadBackStack.length===0)return;let J=this.widget.dependencies.threadState.mainThread?.id;if(!J)return;let Z=this.threadBackStack.pop();this.threadForwardStack.push(J),await this.switchToExistingThread(Z,{recordInNavigationHistory:!1})};navigateForward=async()=>{if(this.threadForwardStack.length===0)return;let J=this.widget.dependencies.threadState.mainThread?.id;if(!J)return;let Z=this.threadForwardStack.pop();this.threadBackStack.push(J),await this.switchToExistingThread(Z,{recordInNavigationHistory:!1})};onThreadSwitch(){this.handoffController?.resetUIState(),this.exitQueueMode(),this.isMessageViewInSelectionMode=!1,this.imagePreview=null}canInterruptQueuedInference(){let{activeThreadHandle:J,threadPool:Z,threadState:Q}=this.widget.dependencies,Y=Q.mainThread?.queuedMessages?.some((X)=>!pM4(X))??!1;return Z.queueOnSubmitByDefault&&Boolean(J.interruptQueuedMessage)&&Y&&gO(Q.viewState)}interruptNextQueuedMessage=async()=>{let{activeThreadHandle:J,threadState:Z}=this.widget.dependencies,Q=Z.mainThread?.queuedMessages?.find((Y)=>!pM4(Y))?.id;if(!Q||!J.interruptQueuedMessage)return;await J.interruptQueuedMessage(Q)};startAndSwitchToNewThread=async()=>{let J=this.widget.dependencies.threadState.mainThread?.id;if(J)this.recordNavigation(J);await this.widget.dependencies.threadPool.createThread(),this.setState(()=>{this.onThreadSwitch(),this.previousThreadIdForHint=J??null})};canChangeAgentModeInPromptEditor(){return(this.messageViewController.editingMessageOrdinal===0||this.handoffState.isInHandoffMode)&&!this.handoffState.isGeneratingHandoff}getEffectiveAgentMode(){if(!this.agentModeController)return"smart";return(this.canChangeAgentModeInPromptEditor()?this.agentModeController.getMode():null)??this.agentModeController.getEffectiveMode()}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(J.viewState.interactionState==="handoff")return!0;if(Boolean(J.viewState.inferenceState==="running"))return!0;return J.items.filter((Y)=>Y.type==="toolResult").filter((Y)=>Y.toolResult.run.status==="in-progress"||Y.toolResult.run.status==="queued").length>0}showSubmitDisabledHint(J){if(this.submitDisabledHintTimer)clearTimeout(this.submitDisabledHintTimer);this.setState(()=>{this.submitDisabledHint=J}),this.submitDisabledHintTimer=setTimeout(()=>{this.setState(()=>{this.submitDisabledHint=null}),this.submitDisabledHintTimer=null},3000)}getUIHint(){let J=this.themeColors?.colorScheme;if(!J)return null;let Z=this.themeApp;if(!Z)return null;if(this.submitDisabledHint)return new C(this.submitDisabledHint,new h({color:J.foreground,dim:!0}));if(this.isExiting)return new C("Exiting...",new h({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new C("",void 0,[new C("Ctrl+C",new h({color:Z.keybind})),new C(" again to exit",new h({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new C("",void 0,[new C("Esc",new h({color:Z.keybind})),new C(" again to clear input",new h({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new C("",void 0,[new C("Escape",new h({color:Z.keybind})),new C(" to close help",new h({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let U=this.getEffectiveAgentMode(),q=rg(U);return new C("",void 0,[new C("Images aren't supported in ",new h({color:J.warning,dim:!1})),new C(U,new h({color:q})),new C(" mode.",new h({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0){if(this.isConfirmingCancelProcessing)return new C("",void 0,[new C("Esc",new h({color:Z.keybind})),new C(" again to cancel",new h({color:J.foreground,dim:!0}))]);if(this.canInterruptQueuedInference())return new C("",void 0,[new C("Enter",new h({color:Z.keybind})),new C(" to interject",new h({color:J.foreground,dim:!0}))]);return new C("",void 0,[new C("Esc",new h({color:Z.keybind})),new C(" to cancel",new h({color:J.foreground,dim:!0}))])}let{threadState:Q}=this.widget.dependencies;if(this.statusMessage){if(this.debugThreadViewState)j.info("[tui-ui] footer status override",{source:"statusMessage",statusMessage:this.statusMessage,inferenceState:Q.viewState.state==="active"?Q.viewState.inferenceState:void 0});return new C(this.statusMessage,new h({color:J.foreground,dim:!0}))}let Y=hM4(this.updateState,J);if(Y){if(this.debugThreadViewState)j.info("[tui-ui] footer status override",{source:"updateState",inferenceState:Q.viewState.state==="active"?Q.viewState.inferenceState:void 0});return new C("",void 0,Y)}let X=this.getCurrentConfirmation(),V=dM4(Q),K=this.widget.dependencies.threadPool.getCompactionStatus?.(),z=new pp({threadViewState:Q.viewState,tokenUsage:V,thread:Q.mainThread??void 0,compactionState:K?.compactionState??"idle",waitingForConfirmation:!!X,showingEphemeralError:Boolean(Q.viewState.state==="active"&&Q.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandNoun:this.executingCommand?.noun??null,executingCommandVerb:this.executingCommand?.verb??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),G=gp(z);if(this.debugThreadViewState){let U=JSON.stringify({inferenceState:Q.viewState.state==="active"?Q.viewState.inferenceState:void 0,interactionState:Q.viewState.interactionState,statusType:G.type});if(U!==this.lastThreadStatusDebugSignature)this.lastThreadStatusDebugSignature=U,j.info("[tui-ui] footer thread status",JSON.parse(U))}let F=!this.shortcutsHintUsed||this.sessionState.launchCount<10;if(G.type==="none"&&!this.isShowingShortcutsHelp&&this.textController.text===""&&F)return new C("",void 0,[new C("?",new h({color:Z.keybind})),new C(" for shortcuts",new h({color:J.foreground,dim:!0}))]);return null}getParentThreadInfo(){let J=this.previewThread??this.widget.dependencies.threadState.mainThread;if(!J)return null;let Z=ck(J).filter((K)=>K.type==="fork"||K.type==="handoff");if(Z.length===0)return null;let Q=Z[0],Y=Q.threadID,X=this.threadsForPicker.find((K)=>K.id===Y);if(!X?.title)this.ensureParentThreadTitleLoaded(Y);let V=X?.title??this.parentThreadTitles.get(Y)??Y.slice(-8);return{type:Q.type==="handoff"?"handoff":"fork",title:V,threadID:Y}}ensureParentThreadTitleLoaded(J){if(this.parentThreadTitles.has(J)||this.parentThreadTitleLoadsInFlight.has(J))return;this.parentThreadTitleLoadsInFlight.add(J),this.widget.dependencies.threadService.getPrimitiveProperty(J,"title").then((Z)=>{if(!this.mounted||!Z)return;this.setState(()=>{this.parentThreadTitles.set(J,Z)})}).catch((Z)=>{j.debug("Failed to load parent thread title",{threadID:J,error:Z})}).finally(()=>{this.parentThreadTitleLoadsInFlight.delete(J)})}getThreadClusterForMinimap=(J)=>{let Z=this.clustersForPicker.find((Q)=>Q.threads.some((Y)=>Y.id===J));if(!Z||Z.threads.length<2)return null;return Z.threads.map((Q)=>({id:Q.id,title:Q.title,parentID:Q.parentID,updatedAt:Q.updatedAt,isActive:this.isThreadActivelyWorking(Q.id)}))};getCurrentThreadClusterForMinimap=()=>{let J=this.previewThread??this.widget.dependencies.threadState.mainThread;if(!J)return null;return this.getThreadClusterForMinimap(J.id)};enrichClustersWithActiveState=(J)=>{return J.map((Z)=>({...Z,threads:Z.threads.map((Q)=>({...Q,isActive:this.isThreadActivelyWorking(Q.id)}))}))};areRecordValuesEqual(J,Z){if(J===Z)return!0;let Q=Object.entries(J),Y=Object.entries(Z);if(Q.length!==Y.length)return!1;for(let[X,V]of Q){if(!Object.hasOwn(Z,X))return!1;if(!Object.is(V,Z[X]))return!1}return!0}getThreadViewStatesSnapshot(){let J={...this.allConnectedThreadActivityStatuses},Z=this.widget.dependencies.threadState.mainThread;if(Z)J[Z.id]=this.widget.dependencies.threadState.viewState;return J}isThreadActivelyWorking(J){return gO(this.allConnectedThreadActivityStatuses[J])}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}isStartupThreadLoading(){if(!this.tuiContext.startupThreadID)return!1;let{threadPool:J}=this.widget.dependencies;return J.hasPendingInitialization?.()===!0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Z,activeThreadHandle:Q}=this.widget.dependencies;if(!Z.mainThread?.id)return;let X=Z.mainThread?.messages.findIndex((V)=>V===J);if(X===void 0||X===-1)return;try{this.cancelBashInvocations(),await Q.cancelTurn(),await Q.restoreTo(X),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(V){j.error("Failed to edit message:",V)}};showForkDeprecationMessage=()=>{this.setState(()=>{this.isShowingForkDeprecationModal=!0})};dismissForkDeprecationModal=()=>{this.setState(()=>{this.isShowingForkDeprecationModal=!1})};handleMessageEditSubmit=async(J,Z,Q)=>{let{threadState:Y,activeThreadHandle:X}=this.widget.dependencies,V=Y.mainThread;if(!V)return;let K=V.messages.findIndex((F)=>F.messageId!==void 0&&F.messageId===J.messageId);if(K===-1)return;let z=K===0,G=z?this.agentModeController?.getMode()??V.agentMode??this.getEffectiveAgentMode():V.agentMode;if(this.shouldRequireAuthForPromptSubmit()){this.showSubmitDisabledHint("Sign in required before editing and resubmitting messages"),this.ensureAuthLoginSession();return}try{this.cancelBashInvocations(),await X.cancelTurn(),this.widget.dependencies.history.add(Z,process.cwd());let F=aH(Z);if(F&&X.invokeBashTool)await X.restoreTo(K),this.invokeBashCommand(F.cmd,{visibility:F.visibility});else{let U=[{type:"text",text:Z}];if(Q.length>0)U.push(...Q);let q=G;if(V.agentMode&&!z&&q!==V.agentMode){j.error(`Cannot edit message: This thread uses ${V.agentMode} mode. To change mode, create a new thread.`);return}await X.sendMessage({content:U,agentMode:q,editIndex:K})}this.scrollMessageViewToBottom()}catch(F){j.error("Failed to edit message:",F)}};getAffectedFiles=async(J)=>{let{activeThreadHandle:Z,threadState:Q}=this.widget.dependencies;try{let Y=Q.mainThread;if(!Y)return[];let X=Y.messages.findIndex((K)=>K===J);if(X===-1)return[];return(await Z.getFilesAffectedByTruncation(X)).map(b9)}catch(Y){return j.error("Failed to get affected files:",Y),[]}};textController=new i7;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new Y5);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Z=J.mainThread?.id;if(!Z)return;this.getMessageScrollController(Z).scrollToBottom()}_handleSelectionChanged=(J)=>{this.setState(()=>{})};updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Z=J.mainThread?.title;if(Z!==this.currentTitle){this.currentTitle=Z;let Q=process.cwd().replace(process.env.HOME||"","~"),Y=Z?`amp - ${Z} - ${Q}`:"";process.stdout.write(B90(Y))}}_handleTextCopy(J,Z){if(J&&J.length>0){let Q=Z?"Selection copied to clipboard":"Failed to copy selection to clipboard",Y=Z?"success":"error";this.toastController.show(Q,Y,2000)}}textFieldKey=new $3("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;paletteCommands;paletteConfig;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text;if(J==="")this.textController.resetScrollOffset();if(J!=="")this.deepModeEffortHintController.dismissForInteraction();if(this.handoffState.countdownSeconds!==null)this.handoffController?.stopCountdown();if(J==="/"&&!this.handoffState.isGeneratingHandoff){this.showCommandPalette(),this.textController.clear(),this.toastController.show("Use [[Ctrl-O]] to open the command palette","warning");return}let Z=aH(J),Q=J===""&&this.bottomGridUserHeight!==void 0,Y=this.handoffState.isInHandoffMode||!this.widget.dependencies.activeThreadHandle.invokeBashTool?void 0:Z?.visibility;this.setState(()=>{if(this.currentShellModeStatus=Y,Q)this.bottomGridUserHeight=void 0})};navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!1}),H6.instance.addPostFrameCallback(()=>{this.autocompleteFocusNode.requestFocus()})};handleIdeSelection=async(J,Z)=>{let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q&&this.isSameIdeConfig(Q,J)){this.dismissIdePicker();return}try{await this.connectToSelectedIde(J,Z)}catch(Y){let X=Y instanceof Error?Y.message:String(Y);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.dismissIdePicker()};isSameIdeConfig(J,Z){if(J.connection!==Z.connection||J.ideName!==Z.ideName||J.pid!==Z.pid||J.port!==Z.port||J.authToken!==Z.authToken||J.workspaceId!==Z.workspaceId)return!1;if(J.workspaceFolders.length!==Z.workspaceFolders.length)return!1;return J.workspaceFolders.every((Q)=>Z.workspaceFolders.includes(Q))}async connectToSelectedIde(J,Z){await this.widget.dependencies.ideClient.start(J,!0,Z)}previewControllerListener=(J)=>{this.setState(()=>{this.previewThread=J})};showStandaloneThreadPicker=()=>{this.showCommandPalette({type:"standalone",commandId:"continue",onSubmit:()=>{this.threadPreviewController.clear(),this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null}),H6.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette)this.autocompleteFocusNode.requestFocus()})},onCancel:()=>{this.exitApplication()}})};toggleThreadPickerWorkspaceFilter=()=>{this.setState(()=>{this.filterThreadPickerByWorkspace=!this.filterThreadPickerByWorkspace})};handleDoubleAtTrigger=(J)=>{let{text:Z,cursorPosition:Q}=J,X=Z.slice(0,Q).lastIndexOf("@@"),V=J!==this.textController;if(j.info("[handleDoubleAtTrigger] called",{isEditingPreviousMessage:V,text:Z,cursor:Q,atAtIndex:X}),V)this.setState(()=>{this.paletteOnThreadMentionSelected=(K)=>{let z=this.messageViewController.editingController;if(!z){j.warn("[paletteOnThreadMentionSelected] no editing controller found");return}this.insertThreadMention(z,K)}});else this.setState(()=>{this.paletteOnThreadMentionSelected=null});this.showCommandPalette({type:"standalone",commandId:"mention-thread",onBeforeExecute:V?void 0:()=>{if(X!==-1){let K=J.text,z=K.slice(0,X)+K.slice(X+2);J.text=z,J.cursorPosition=X}},onSubmit:()=>{this.setState(()=>{this.paletteOnThreadMentionSelected=null}),this.dismissPalette()},onCancel:()=>{this.setState(()=>{this.paletteOnThreadMentionSelected=null}),this.dismissPalette()}})};insertThreadMention(J,Z){let{text:Q,cursorPosition:Y}=J,V=Q.slice(0,Y).lastIndexOf("@@");if(V!==-1){let K=Q.slice(Y),z=K.length===0,G=`@${Z}${z?" ":""}`,F=Q.slice(0,V)+G+K,U=V+G.length;J.text=F,J.cursorPosition=U}else J.insertText(`@${Z} `)}showCommandPalette(J){if(this.handoffState.isGeneratingHandoff)return;let Z=!this.isShowingPalette;if(this.setState(()=>{if(this.isShowingPalette=Z,this.paletteShowOptions=Z?J??null:null,!Z)this.threadsForPicker=[],this.clustersForPicker=[],this.isLoadingThreads=!1}),Z)this.loadThreadsForPicker();else this.unloadThreadsForPicker()}isShowingStandalonePalette(){return this.isShowingPalette&&this.paletteShowOptions?.type==="standalone"}getPaletteCommands(){if(!this.paletteCommands){if(!this.paletteConfig)throw Error("Config not yet available");this.paletteCommands=new Np0(this.widget.dependencies.configService,(J)=>{this.setState(()=>{this.executingCommand=J})},()=>{this.setState(()=>{this.executingCommand=null})},this.paletteConfig)}return this.paletteCommands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new Lp0(this.widget.dependencies.fuzzyServer);return this.completionBuilder}unloadThreadsForPicker(){if(this.threadLoadSubscription)this.threadLoadSubscription.unsubscribe(),this.threadLoadSubscription=null;this.threadPreviewController.clearStatsCache(),this.widget.dependencies.threadHistoryService.resetCache()}dismissPalette=()=>{if(this.isExiting)return;this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.threadsForPicker=[],this.clustersForPicker=[],this.isLoadingThreads=!1}),this.unloadThreadsForPicker()};lastRootContext;getCommandPaletteContext=(J)=>{let{threadState:Z,recentThreadIDs:Q}=this.widget.dependencies;if(!Z.mainThread)return null;let Y=J??this.lastRootContext;if(!Y)return null;let X=K1.file(process.cwd()),V=g1(X);return{recentThreadIDs:Q,currentThreadID:Z.mainThread.id,contextFallback:Y,context:J,threadPool:this.widget.dependencies.threadPool,createSystemPromptDeps:this.widget.dependencies.createSystemPromptDeps,activeThreadHandle:this.widget.dependencies.activeThreadHandle,editorState:this.textController,isProcessing:this.isProcessing(),thread:Z.mainThread,ampURL:this.tuiContext.ampURL,threadService:this.widget.dependencies.threadService,configService:this.widget.dependencies.configService,skillService:this.widget.dependencies.skillService,openInEditor:this.openInEditor,takeImageAttachments:()=>{let K=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),K},setImageAttachments:(K)=>{this.setState(()=>{this.imageAttachments=K})},editorDispatch:(K)=>{switch(K.type){case"set-input":this.textController.clear(),this.textController.insertText(K.input);break;case"set-input-with-cursor":this.textController.clear(),this.textController.insertText(K.input),this.textController.cursorPosition=K.cursorPosition;break;case"insert-text":this.textController.insertText(K.text);break;case"clear":this.textController.clear();break}},submitMessage:(K)=>{this.onTextSubmitted(K).catch((z)=>{this.handleSubmitFlowError(z)})},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},openContextAnalyze:()=>{this.openContextAnalyzeModal()},openSkillList:()=>{this.setState(()=>{this.isShowingSkillListModal=!0})},settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.tuiContext.clientId,mcpService:this.widget.dependencies.mcpService,toolboxService:this.widget.dependencies.toolboxService,createThread:async()=>{await this.startAndSwitchToNewThread()},navigateBack:this.navigateBack,navigateForward:this.navigateForward,canNavigateBack:this.threadBackStack.length>0,canNavigateForward:this.threadForwardStack.length>0,canUseAmpFree:this.freeTierStatus.canUseAmpFree,isDailyGrantEnabled:this.freeTierStatus.isDailyGrantEnabled,switchToThread:async(K)=>{await this.switchToExistingThread(K),this.setState(()=>{this.isMessageViewInSelectionMode=!1,this.imagePreview=null});return},handleHandoff:async(K,z)=>{let{goal:G,images:F}=z;if(!G)return{ok:!1,error:Error("Goal is required")};try{let U=this.widget.dependencies.threadState.mainThread;if(!U)return{ok:!1,error:Error("No active thread")};let q=setTimeout(()=>K.abort(new uT("Handoff took too long and was aborted (timeout: 60s)")),60000);try{let D=await this.widget.dependencies.threadPool.createHandoff(U.id,{goal:G,images:F,agentMode:U.agentMode,queuedMessages:U.queuedMessages?[...U.queuedMessages]:void 0,signal:K.signal});return clearTimeout(q),await this.switchToExistingThread(D),{ok:!0}}catch(D){if(clearTimeout(q),D instanceof Error&&(D.name==="AbortError"||D.message.includes("aborted")))throw K.signal.reason;throw D}}catch(U){return j.error("Failed to create handoff thread",{error:U}),{ok:!1,error:U instanceof Error?U:Error(String(U))}}},getGuidanceFiles:(K)=>{return this.widget.dependencies.activeThreadHandle.getGuidanceFiles(K)},openIdePicker:()=>{this.openIdePicker()},openPromptHistoryPicker:()=>{this.setState(()=>{this.isShowingPromptHistoryPicker=!0})},getAgentMode:()=>{return this.agentModeController?.getMode()??null},setAgentMode:(K)=>{this.agentModeController?.setMode(K)},toggleAgentMode:this.toggleAgentMode,toggleDeepReasoningEffort:this.toggleDeepReasoningEffort,getEffectiveAgentMode:()=>this.getEffectiveAgentMode(),getEditorText:()=>this.textController.text,userEmail:y6(this.authStatus)?this.authStatus.user.email:void 0,workspace:this.tuiContext.workspace??null,completionBuilder:this.getCompletionBuilder(),threads:this.threadsForPicker,clusters:this.enrichClustersWithActiveState(this.clustersForPicker),previewController:this.threadPreviewController,isLoadingThreads:this.isLoadingThreads,filterByWorkspace:this.filterThreadPickerByWorkspace,currentWorkspace:V,threadViewStates:this.getThreadViewStatesSnapshot(),newsFeedEntries:this.newsFeedEntries,showMCPStatusModal:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!0})},internalAPIClient:this.widget.dependencies.internalAPIClient,features:y6(this.authStatus)?this.authStatus.features:this.tuiContext.features,showStatusMessage:(K,z=2000)=>{this.showStatusMessage(K,z)},showToast:(K,z="success",G)=>{this.toastController.show(K,z,G)},getThemeName:()=>LB4(Y).themeName,isMessageViewInteractionActive:this.isMessageViewInSelectionMode||this.messageViewController.editingMessageOrdinal!==null,enterHandoffMode:this.enterHandoffMode,isInHandoffMode:this.handoffState.isInHandoffMode,enterQueueMode:this.enterQueueMode,submitQueue:this.submitQueue,isInQueueMode:this.isInQueueMode,addPendingSkill:(K)=>{this.widget.dependencies.activeThreadHandle.addPendingSkill(K)},onThreadMentionSelected:this.paletteOnThreadMentionSelected??void 0,canChangeAgentModeInPromptEditor:()=>this.canChangeAgentModeInPromptEditor(),pluginCommands:this.pluginCommands,executePluginCommand:this.widget.dependencies.pluginService?(K,z,G)=>this.widget.dependencies.pluginService.commands.execute(K,z,{threadID:G}):void 0,reloadPlugins:this.widget.dependencies.pluginService?()=>this.widget.dependencies.pluginService.reload():void 0,pluginService:this.widget.dependencies.pluginService}};loadThreadsForPicker(){if(this.threadLoadSubscription)return;this.setState(()=>{this.isLoadingThreads=!0});let J=new $c0(this.widget.dependencies.threadHistoryService);this.threadLoadSubscription=J.observeThreadSummaries("",{includeArchived:!0}).subscribe({next:(Z)=>{this.setState(()=>{this.threadsForPicker=Z,this.clustersForPicker=_O4(Z),this.isLoadingThreads=!1})},error:()=>{this.setState(()=>{this.isLoadingThreads=!1})}})}updateGitBranch=async()=>{let J=await Ps5(process.cwd());this.setState(()=>{this.currentGitBranch=J})};removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Z)=>Z.id!==J)})};invokeBashCommand=(J,{visibility:Z})=>{if(!this.widget.dependencies.activeThreadHandle.invokeBashTool)return;let Q=Date.now(),Y=`bash-${Q}-${Math.random().toString(36).substring(7)}`,X={cmd:J},V=new AbortController;this.widget.dependencies.activeThreadHandle.invokeBashTool(X,{hidden:Z===nH,abortController:V}).subscribe({next:(K)=>{this.setState(()=>{if(this.bashInvocations.find((G)=>G.id===Y))this.bashInvocations=this.bashInvocations.map((G)=>G.id===Y?{...G,toolRun:K}:G);else{let G={id:Y,args:X,toolRun:K,startTime:Q,abortController:V,hidden:Z===nH};this.bashInvocations=[...this.bashInvocations,G]}})},error:()=>this.removeBashInvocation(Y),complete:()=>this.removeBashInvocation(Y)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Z)=>Z.toolRun.status==="in-progress");if(J)J.abortController.abort()};showContextDetailOverlay=()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!0}),this.fetchThreadCostInfo()};fetchThreadCostInfo=uB4(()=>{let J=this.widget.dependencies.threadState.mainThread?.id;if(!J)return;this.widget.dependencies.internalAPIClient.threadDisplayCostInfo({threadID:J},{config:this.widget.dependencies.configService}).then((Z)=>{if(Z.ok)this.setState(()=>{this.threadCostInfo=Z.result,this.threadCostInfoThreadID=J})}).catch(()=>{this.setState(()=>{this.threadCostInfo=void 0,this.threadCostInfoThreadID=J})})},150);maybeRefetchThreadCostInfo=(J)=>{let Z=this.lastInferenceState==="running",Q=J==="running",Y=J==="idle"&&Z,X=Q&&!Z;if(Y)this.fetchThreadCostInfo();if(X)this.startElapsedTimeTimer();else if(Z&&!Q)this.stopElapsedTimeTimer();this.lastInferenceState=J};startElapsedTimeTimer=()=>{if(this.elapsedTimeTimer)return;this.elapsedTimeTimer=setInterval(()=>{let J=this.widget.dependencies.threadState.viewState;if(!(J.state==="active"&&J.inferenceState==="running")){this.stopElapsedTimeTimer();return}this.setState(()=>{})},1000)};stopElapsedTimeTimer=()=>{if(this.elapsedTimeTimer)clearInterval(this.elapsedTimeTimer),this.elapsedTimeTimer=null};toggleAgentMode=()=>{if(!this.agentModeController)return;if(this.handoffState.isGeneratingHandoff)return;let J=this.canChangeAgentModeInPromptEditor();if(this.agentModeController.toggle(J))this.setState(()=>{this.showImageUnsupportedHint=!1,this.agentModePulseSeq++})};handleMessageViewControllerUpdate=()=>{let J=this.messageViewController.editingMessageOrdinal;if(J===this.lastEditingMessageOrdinal)return;if(this.lastEditingMessageOrdinal===0&&J!==0){let Y=this.agentModeController;if(!Y){this.lastEditingMessageOrdinal=J,this.setState(()=>{});return}if(Y.getMode()!==null)Y.setMode(null)}this.lastEditingMessageOrdinal=J,this.setState(()=>{})};showStatusMessage(J,Z=2000){if(this.statusMessageTimer)clearTimeout(this.statusMessageTimer);this.setState(()=>{this.statusMessage=J}),this.statusMessageTimer=setTimeout(()=>{this.setState(()=>{this.statusMessage=null}),this.statusMessageTimer=null},Z)}applyDeepReasoningEffort(J){this.deepReasoningEffort=J,u$("agent.deepReasoningEffort",J)}commitDeepReasoningEffort(J){let Z=this.deepReasoningEffort;if(this.applyDeepReasoningEffort(J),J===Z)return Promise.resolve(!0);return this.widget.dependencies.configService.updateSettings("agent.deepReasoningEffort",J,"global").then(()=>!0).catch((Q)=>{return this.applyDeepReasoningEffort(Z),j.error("Failed to persist deep reasoning setting",{error:Q}),this.showStatusMessage("Failed to save deep reasoning effort"),!1})}getNextDeepReasoningEffort(J){return J==="medium"?"high":J==="high"?"xhigh":"medium"}toggleDeepReasoningEffort=async()=>{if(this.deepModeEffortHintController.dismissForInteraction(),this.getEffectiveAgentMode()!=="deep"){this.showStatusMessage("Deep reasoning effort is only available in deep mode");return}let Z=this.widget.dependencies.threadState.mainThread;if(!Z)return;if(W3(Z)>0){this.showStatusMessage("Deep reasoning effort can only be toggled before the first message");return}let Q=this.getNextDeepReasoningEffort(this.deepReasoningEffort);if(!await this.commitDeepReasoningEffort(Q))return;this.showStatusMessage(`Deep reasoning effort: ${Q}`),this.setState(()=>{this.agentModePulseSeq++})};formatAgentModeLabel(J){if(J!=="deep")return J;if(this.deepReasoningEffort==="high")return"deep²";if(this.deepReasoningEffort==="xhigh")return"deep³";return"deep"}handleInsertImage=async(J)=>{let Z=this.getEffectiveAgentMode();if(!vk(Z)){if(this.imageUnsupportedHintTimer)clearTimeout(this.imageUnsupportedHintTimer);return this.setState(()=>{this.showImageUnsupportedHint=!0}),this.imageUnsupportedHintTimer=setTimeout(()=>{this.setState(()=>{this.showImageUnsupportedHint=!1}),this.imageUnsupportedHintTimer=null},5000),!1}if(this.imageAttachments.length>=BI)return!1;let Q=await vT(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q]}),!1;return this.setState(()=>{this.displayMessage=Error(`Failed to attach image: ${Q}`)}),!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};handleImageClick=(J)=>{let Z=this.imageAttachments[J];if(Z)this.setState(()=>{this.imagePreview={image:Z,index:J,onRemove:()=>{let Q=this.imageAttachments.indexOf(Z);if(Q!==-1)this.setState(()=>{this.imageAttachments=this.imageAttachments.filter((Y,X)=>X!==Q),this.imagePreview=null})}}})};handleImagePreviewDismiss=()=>{this.setState(()=>{this.imagePreview=null})};handleShowFileImagePreview=(J)=>{this.setState(()=>{this.fileImagePreviewPath=J})};handleFileImagePreviewDismiss=()=>{this.setState(()=>{this.fileImagePreviewPath=null})};handleShowPainterImagePreview=(J,Z)=>{this.setState(()=>{this.painterImagePreview={image:J,filePath:Z}})};handlePainterImagePreviewDismiss=()=>{this.setState(()=>{this.painterImagePreview=null})};handleShowPainterSaveDialog=(J,Z)=>{this.setState(()=>{this.painterSaveDialog={image:J,filePath:Z}})};handlePainterSaveDialogDismiss=()=>{this.setState(()=>{this.painterSaveDialog=null})};handleSkillClick=(J)=>{let Z=this.pendingSkills[J];if(Z)this.setState(()=>{this.cachedSkillForPreview=null,this.skillPreview={skillIndex:J,onRemove:()=>{this.widget.dependencies.activeThreadHandle.removePendingSkill(Z.name),this.setState(()=>{this.skillPreview=null,this.cachedSkillForPreview=null})}}}),this.widget.dependencies.skillService.getSkills().then((Q)=>{let Y=Q.find((X)=>X.name===Z.name)??null;if(this.skillPreview!==null)this.setState(()=>{this.cachedSkillForPreview=Y})})};handleSkillPreviewDismiss=()=>{this.setState(()=>{this.skillPreview=null,this.cachedSkillForPreview=null})};handleShowEditingImagePreview=(J,Z,Q)=>{this.setState(()=>{this.imagePreview={image:J,index:Z,onRemove:Q}})};handleImagePreviewRemove=()=>{if(this.imagePreview)this.imagePreview.onRemove(),this.setState(()=>{this.imagePreview=null})};handleShowMysteryModal=()=>{if(this.mysteriousMessage)this.setState(()=>{this.isShowingMysteriousMessageModal=!0})};handleSplashOrbExplode=(J)=>{this.splashOrbExplosionSeq+=1,this.setState(()=>{this.splashOrbExplosion={seq:this.splashOrbExplosionSeq,originX:J.x,originY:J.y}})};handleSplashOrbExplosionComplete=()=>{if(!this.splashOrbExplosion)return;this.setState(()=>{this.splashOrbExplosion=null})};handleDestructMysteriousMessage=()=>{if(!this.mysteriousMessage)return;let J=this.mysteriousMessage.id;this.widget.dependencies.internalAPIClient.markAsReadMysteriousMessage({messageId:J},{config:this.widget.dependencies.configService}).then((Z)=>{if(!Z.ok)j.error("Failed to destruct mysterious message",Z.error);else this.setState(()=>{this.mysteriousMessage=null,this.isShowingMysteriousMessageModal=!1})}).catch((Z)=>{j.error("Failed to destruct mysterious message",Z)})};exitMessageViewInteraction=()=>{this.messageViewController.setSelectedUserMessageOrdinal(null),this.messageViewController.setIsShowingRestoreConfirmation(!1),this.messageViewController.setIsShowingEditConfirmation(!1),this.messageViewController.setPendingEditText(null),this.messageViewController.setPendingEditImageAttachments([]),this.messageViewController.setAffectedFiles([]),this.messageViewController.stopEditing(),this.setState(()=>{this.isMessageViewInSelectionMode=!1,this.imagePreview=null}),this.scrollMessageViewToBottom(),H6.instance.addPostFrameCallback(()=>{if(!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})};enterHandoffMode=()=>{this.dismissPalette(),this.exitMessageViewInteraction(),this.handoffController?.enter()};exitHandoffMode=()=>{this.handoffController?.exit()};submitHandoff=async(J)=>{let Z=this.imageAttachments;if(this.resetHistory(),!this.handoffController){this.showSubmitDisabledHint("Handoff controller not initialized");return}let Q=await this.handoffController.submit(J,Z,this.agentModeController?.getMode()??null);if(!Q.ok&&Q.error.message!=="Cancelled")this.displayMessage=Q.error,this.setState(()=>{});else if(Q.ok)this.setState(()=>{this.imageAttachments=[]}),setTimeout(()=>{this.handoffController?.startCountdown(()=>{this.autoSubmitHandoffDraft().catch((Y)=>{this.handleSubmitFlowError(Y)})})},0)};autoSubmitHandoffDraft=async()=>{let J=this.textController.text;if(J.trim())this.textController.clear(),await this.sendUserMessage(J)};enterQueueMode=()=>{this.dismissPalette(),this.exitMessageViewInteraction(),this.setState(()=>{this.isInQueueMode=!0})};exitQueueMode=()=>{this.setState(()=>{this.isInQueueMode=!1})};submitQueue=(J)=>{this.exitMessageViewInteraction();let{threadState:Z}=this.widget.dependencies;if((Z.mainThread?.queuedMessages?.length??0)>=l00){this.toastController.show(`Queue is full (max ${l00} messages)`,"error",3000);return}let Y=this.imageAttachments;this.resetHistory(),this.setState(()=>{this.imageAttachments=[]}),this.textController.clear();let X=[{type:"text",text:J}];if(Y.length>0)X.push(...Y);this.widget.dependencies.activeThreadHandle.queueMessage(X),this.exitQueueMode()};isAuthRequiredStatus(J){if(!RD(J))return!1;let Z=J.error.message.toLowerCase();return Z.includes("user not found")||Z.includes("auth-required")||Z.includes("unauthorized")||Z.includes("forbidden")||Z.includes("401")||Z.includes("403")||Z.includes("api key")||Z.includes("access token")}shouldRequireAuthForPromptSubmit(){if(!this.tuiContext.hasAPIKeyAtStartup&&!y6(this.authStatus))return!0;return this.isAuthRequiredStatus(this.authStatus)&&!y6(this.authStatus)}queuePromptUntilAuthenticated(J,Z=[...this.imageAttachments],Q){if(this.queuedPromptAfterAuth={text:J,images:Z},Q?.clearInput??!0)this.textController.clear(),this.textController.resetScrollOffset(),this.resetHistory(),this.setState(()=>{this.imageAttachments=[]});this.showStatusMessage("Sign in required. Prompt queued and will send after login.",2500),this.ensureAuthLoginSession()}ensureAuthLoginSession=async()=>{if(this.pendingAuthLogin||this.isCreatingAuthLoginSession||y6(this.authStatus))return;this.isCreatingAuthLoginSession=!0;try{let J=mM4(32).toString("hex"),Z=await yC(this.tuiContext.ampURL,J),Q=await yC(this.tuiContext.ampURL,J,!1),Y=new AbortController;this.setState(()=>{this.pendingAuthLogin={authToken:J,browserURL:Z,manualURL:Q,abortController:Y,isOpeningBrowser:!1,isAuthenticating:!0,errorMessage:null}}),uK4(this.tuiContext.ampURL,J,this.widget.dependencies.secretStorage,Y).then(()=>{this.showStatusMessage("Login successful",2000),this.checkAuthStatusAfterLogin()}).catch((X)=>{if(Y.signal.aborted)return;let V=X instanceof Error?X.message:"Login failed. Please try again.";this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage=V,this.pendingAuthLogin.isAuthenticating=!1})})}catch(J){let Z=J instanceof Error?J.message:"Unable to start login flow. Please try again.";this.setState(()=>{if(!this.pendingAuthLogin){this.displayMessage=Error(Z);return}this.pendingAuthLogin.errorMessage=Z,this.pendingAuthLogin.isAuthenticating=!1})}finally{this.isCreatingAuthLoginSession=!1}};openAuthLoginBrowser=async()=>{if(!this.pendingAuthLogin)return;let J=this.pendingAuthLogin.browserURL,Z=this.pendingAuthLogin.abortController;this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.isOpeningBrowser=!0,this.pendingAuthLogin.errorMessage=null});try{await fX(J,Z.signal)}catch(Q){let Y=Q instanceof Error?Q.message:"Unable to open browser. Copy the manual link.";this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage=Y})}finally{this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.isOpeningBrowser=!1})}};copyAuthLoginLink=async()=>{let J=this.pendingAuthLogin?.manualURL;if(!J)return;try{await l4.instance.tuiInstance.clipboard.writeText(J),this.showStatusMessage("Login link copied to clipboard",2000)}catch(Z){j.error("Failed to copy login link",{error:Z}),this.showStatusMessage("Failed to copy login link",2000)}};checkAuthStatusAfterLogin=async()=>{try{let J=await this.widget.dependencies.configService.getLatest(),Z=_k(J),Q=await this.widget.dependencies.internalAPIClient.getUserInfo({},{config:this.widget.dependencies.configService,signal:AbortSignal.timeout(Z)});if(!Q.ok){this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage="Still waiting for login confirmation. Finish login in your browser, then press I again."});return}this.setState(()=>{this.authStatus={user:Q.result,features:Q.result.features,workspace:Q.result.team,mysteriousMessage:Q.result.mysteriousMessage},this.pendingAuthLogin=null}),await this.maybeResumeQueuedPromptAfterAuth()}catch(J){j.error("Failed to verify login state",{error:J}),this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage="Unable to verify login yet. Press I again in a moment."})}};cancelAuthLoginSession=()=>{if(this.pendingAuthLogin)this.pendingAuthLogin.abortController.abort(Error("Authentication cancelled"));this.setState(()=>{this.pendingAuthLogin=null})};maybeResumeQueuedPromptAfterAuth=async()=>{if(!y6(this.authStatus))return;let J=this.queuedPromptAfterAuth;if(!J)return;this.queuedPromptAfterAuth=null,await this.proceedWithUserMessage(J.text,J.images)};handleAuthModalKey=(J)=>{if(!this.pendingAuthLogin||this.pendingInputDialog)return!1;let Z=J.key.length===1?J.key.toLowerCase():J.key;if(Z==="Enter"||Z==="o")return this.openAuthLoginBrowser(),!0;if(Z==="c")return this.copyAuthLoginLink(),!0;if(Z==="i")return this.checkAuthStatusAfterLogin(),!0;if(Z==="p")return this.promptForAuthLoginCode(),!0;return!1};promptForAuthLoginCode=async()=>{if(!this.pendingAuthLogin)return;let{authToken:J,abortController:Z}=this.pendingAuthLogin,Q=await new Promise((Y)=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.pendingInputDialog={options:{title:"Paste Login Code",helpText:"Paste the login code from the browser page. This is not your API key.",submitButtonText:"Verify"},resolve:Y}})});if(!Q||!this.pendingAuthLogin)return;try{let{accessToken:Y}=nx0(Q,J);await this.widget.dependencies.secretStorage.set("apiKey",Y,this.tuiContext.ampURL),Z.abort(Error("Authentication completed from pasted code")),this.showStatusMessage("Login code accepted",2000),await this.checkAuthStatusAfterLogin()}catch(Y){let X=Y instanceof Error?Y.message:"Invalid login code.";this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage=X,this.pendingAuthLogin.isAuthenticating=!1})}};openInEditor=async(J)=>{try{let Z=await Ls5(wG.join(Rs5(),"amp-edit-")),Q=wG.join(Z,"message.amp.md");await Is5(Q,J,"utf-8"),await oY(Q);try{let Y=await Ms5(Q,"utf-8");this.textController.text=Y}catch(Y){if(Y?.code!=="ENOENT")j.error("Failed to read temporary file",Y)}try{await gM4(Q),await As5(Z)}catch(Y){j.warn("Failed to clean up temporary file",Y)}}catch(Z){j.error("Error opening editor:",Z)}};onTextSubmitted=async(J)=>{if(!J.trim()&&this.imageAttachments.length===0){if(!this.canInterruptQueuedInference())return;try{await this.interruptNextQueuedMessage();return}catch(Y){j.error("Failed to interrupt queued message from empty submit",Y)}return}let Z=J.trim();if(Z===":q"){this.widget.dependencies.setExitNotice?.("Vim reflex detected. Exiting politely."),await this.exitApplication();return}if(Z==="exit"||Z==="quit"){await this.exitApplication();return}if(this.handoffState.isInHandoffMode){await this.submitHandoff(J);return}if(this.isInQueueMode){this.submitQueue(J);return}let Q=aH(J);if(Q&&this.widget.dependencies.activeThreadHandle.invokeBashTool)if(!Q.cmd){this.showSubmitDisabledHint("No command provided");return}else if(this.isProcessing()){this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}else{this.invokeBashCommand(Q.cmd,{visibility:Q.visibility}),this.widget.dependencies.history.add(J,process.cwd()),this.textController.clear(),this.textController.resetScrollOffset(),this.resetHistory();return}if(this.shouldRequireAuthForPromptSubmit()){this.queuePromptUntilAuthenticated(J);return}this.textController.clear(),this.textController.resetScrollOffset(),this.resetHistory(),await this.updateGitBranch(),await this.sendUserMessage(J)};agentModeListener=()=>{let J=this.agentModeController?.getMode(),Z=this.canChangeAgentModeInPromptEditor(),Q=this.widget.dependencies.threadState.mainThread;if(!Q)return;let Y=!Z&&J!==null&&W3(Q)>0&&Q.agentMode!==J;if(this.handoffState.countdownSeconds!==null)this.handoffController?.stopCountdown();if(!Z&&J&&J!==this.sessionState.agentMode)this.persistAgentMode(J);if(Y)this.agentModeController?.setMode(null);let X=this.lastEffectiveAgentMode,V=this.getEffectiveAgentMode();this.lastEffectiveAgentMode=V,this.deepModeEffortHintController.onAgentModeTransition(X,V),this.setState(()=>{})};handoffListener=(J)=>{this.setState(()=>{this.handoffState=J})};handleWinPasteHookImagePaste=async(J)=>{this.lastUserInteractionTime=Date.now();let Z=this.imageAttachments.length;try{await this.handleInsertImage(J.image.tempFile)}catch(Q){j.error("Failed to process win-paste-hook image paste event",{error:Q})}if(this.imageAttachments.length<=Z)await gM4(J.image.tempFile).catch(()=>{})};handleWinPasteHookStateChange=(J)=>{if(J.current!=="disabled_session"||this.hasShownWinPasteHookRecoveryWarning)return;this.hasShownWinPasteHookRecoveryWarning=!0,this.toastController.show('Windows clipboard hook unavailable. Open the command palette (Ctrl+O) and run "paste image from clipboard".',"warning",7000)};initState(){if(OQ.getInstance().interceptConsole(),this.threadPreviewController.setThreadService(this.widget.dependencies.threadService),this.threadPreviewController.addListener(this.previewControllerListener),this.handoffController=new yg0({getActiveThreadHandle:()=>this.widget.dependencies.activeThreadHandle,getThreadPool:()=>this.widget.dependencies.threadPool,switchToThread:(X)=>{return this.textController.clear(),this.switchToExistingThread(X)}}),this.handoffController.addListener(this.handoffListener),this.tuiContext.openThreadSwitcher)this.showStandaloneThreadPicker();l4.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),l4.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),l4.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()});let J=l4.instance.tuiInstance;if(this.winPasteHookImageUnsubscribe=J.onWinPasteHookImagePaste((X)=>{this.handleWinPasteHookImagePaste(X)}),this.winPasteHookStateUnsubscribe=J.onWinPasteHookStateChange((X)=>{this.handleWinPasteHookStateChange(X)}),this.authStatus=this.tuiContext.initialServerStatus,this.authStatusSubscription=nJ(this.widget.dependencies.configService).subscribe((X)=>{if(this.setState(()=>{if(this.authStatus=X,y6(X))this.pendingAuthLogin=null}),this.agentModeController?.updateVisibilityContext({userEmail:y6(X)?X.user.email:void 0}),y6(X)){this.maybeResumeQueuedPromptAfterAuth();return}if(this.isAuthRequiredStatus(X))this.ensureAuthLoginSession()}),this.authModalKeyInterceptorUnsubscribe=l4.instance.addKeyInterceptor((X)=>this.handleAuthModalKey(X)),!this.tuiContext.hasAPIKeyAtStartup)this.ensureAuthLoginSession();this.autocompleteFocusNodeListener=(X)=>{H6.instance.addPostFrameCallback(()=>{if(!this.mounted)return;this.setState(()=>{this.isTextfieldAndAutocompleteFocused=X.hasFocus})},"TuiUIState.autocompleteFocusNodeListener")},this.autocompleteFocusNode.addListener(this.autocompleteFocusNodeListener),this.sessionState=this.tuiContext.sessionState??bC,this.shortcutsHintUsed=this.sessionState.shortcutsHintUsed,this.messageViewControllerUnsubscribe??=this.messageViewController.subscribe(this.handleMessageViewControllerUpdate),Promise.all([this.tuiContext.freeTierStatusPromise??Promise.resolve(void 0),E1(this.widget.dependencies.configService.config)]).then(([X,V])=>{if(X)this.freeTierStatus=X;this.paletteConfig=V;let K=Jy(V.settings),z=V.settings["anthropic.speed"],G=V.settings["openai.speed"];this.showSkillsCountInPromptBar=V.settings["internal.cli.showSkillsCountInPromptBar"]!==!1,this.adsDisabledBySetting=V.settings.newAdsDisplay===!0,this.applyDeepReasoningEffort(K),this.anthropicSpeed=z,this.openAISpeed=G,this.deepReasoningEffortSubscription=this.widget.dependencies.configService.config.pipe(D1((F)=>Jy(F.settings)),M4()).subscribe((F)=>{if(F!==this.deepReasoningEffort)this.applyDeepReasoningEffort(F),this.setState(()=>{this.agentModePulseSeq++})}),this.anthropicSpeedSubscription=this.widget.dependencies.configService.config.pipe(D1((F)=>({settings:F.settings})),M4((F,U)=>F.settings["anthropic.speed"]===U.settings["anthropic.speed"])).subscribe(({settings:F})=>{let U=F["anthropic.speed"];if(U!==this.anthropicSpeed)this.anthropicSpeed=U,this.setState(()=>{this.agentModePulseSeq++})}),this.openAISpeedSubscription=this.widget.dependencies.configService.config.pipe(D1((F)=>({settings:F.settings})),M4((F,U)=>F.settings["openai.speed"]===U.settings["openai.speed"])).subscribe(({settings:F})=>{let U=F["openai.speed"];if(U!==this.openAISpeed)this.openAISpeed=U,this.setState(()=>{this.agentModePulseSeq++})}),this.showSkillsCountInPromptBarSubscription=this.widget.dependencies.configService.config.pipe(D1((F)=>({settings:F.settings})),M4((F,U)=>F.settings["internal.cli.showSkillsCountInPromptBar"]===U.settings["internal.cli.showSkillsCountInPromptBar"])).subscribe(({settings:F})=>{let U=F["internal.cli.showSkillsCountInPromptBar"]!==!1;if(U!==this.showSkillsCountInPromptBar)this.setState(()=>{this.showSkillsCountInPromptBar=U})}),this.submitOnEnter=V.settings.submitOnEnter??!0,this.submitOnEnterSubscription=this.widget.dependencies.configService.config.pipe(D1((F)=>({settings:F.settings})),M4((F,U)=>F.settings.submitOnEnter===U.settings.submitOnEnter)).subscribe(({settings:F})=>{let U=F.submitOnEnter??!0;if(U!==this.submitOnEnter)this.setState(()=>{this.submitOnEnter=U})}),this.agentModeController=new _g0({initialCliMode:this.tuiContext.initialAgentMode,sessionState:this.sessionState,freeTierStatus:this.freeTierStatus,workspace:this.tuiContext.workspace??null,userEmail:y6(this.authStatus)?this.authStatus.user.email:void 0,initialSettings:V.settings,config$:this.widget.dependencies.configService.config,getThread:()=>this.widget.dependencies.threadState.mainThread}),this.agentModeController.addListener(this.agentModeListener),this.lastEffectiveAgentMode=this.getEffectiveAgentMode(),this.deepModeEffortHintController.maybeShowForInitialDeepMode(),this.scheduleAdSubscriptionWithIdeReadiness(),this.setState(()=>{})}),this.updateGitBranch(),this.allConnectedThreadActivityStatusesSubscription=this.widget.dependencies.threadPool.allConnectedThreadActivityStatuses$.subscribe((X)=>{if(this.areRecordValuesEqual(this.allConnectedThreadActivityStatuses,X))return;this.setState(()=>{this.allConnectedThreadActivityStatuses=X})}),this.threadTitlesSubscription=this.widget.dependencies.threadPool.threadTitles$.subscribe((X)=>{if(this.areRecordValuesEqual(this.threadTitles,X))return;this.setState(()=>{this.threadTitles=X})}),this.threadInitializationStatusSubscription=this.widget.dependencies.threadPool.initializationStatus$?.subscribe((X)=>{let V=X.pending?X.message:null;if(V===this.threadInitializationMessage)return;this.setState(()=>{this.threadInitializationMessage=V})})??null,this.pendingNavigationSubscription=this.widget.dependencies.threadPool.threadHandles$.pipe(M4(),Q4((X)=>X?X.thread$:v0.of(null))).subscribe((X)=>{this.checkForPendingNavigation(X);let V=X?.id;if(this.threadCostInfoThreadID!==V){if(this.threadCostInfo=void 0,this.threadCostInfoThreadID=V,V&&W3(X)>0)this.fetchThreadCostInfo()}let K=X?this.widget.dependencies.threadState.viewState:void 0;this.maybeRefetchThreadCostInfo(K?.state==="active"?K.inferenceState:void 0)}),this.freeTierStatusSubscription=Ke1(async()=>{let X=await this.widget.dependencies.configService.getLatest(),V=_k(X),K=await this.widget.dependencies.internalAPIClient.getUserFreeTierStatus({},{config:this.widget.dependencies.configService,signal:AbortSignal.timeout(V)});if(!K.ok)throw K.error;return K.result}).subscribe({next:(X)=>{if(X){let V=this.freeTierStatus.canUseAmpFree;if(this.setState(()=>{this.freeTierStatus=X}),this.agentModeController?.updateVisibilityContext({freeTierStatus:X}),X.canUseAmpFree!==V)if(X.canUseAmpFree){if(!this.adSubscription&&!this.adsDisabledBySetting)this.scheduleAdSubscriptionWithIdeReadiness()}else this.unsubscribeFromAds()}},error:(X)=>{j.debug("Failed to fetch free tier status",X)}});let{mcpTrustHandler:Z}=this.widget.dependencies;if(this.mcpTrustSubscription=Z.pendingServers$.subscribe((X)=>{this.setState(()=>{this.pendingMCPServers=X})}),Ax0((X)=>{this.setState(()=>{this.pendingOAuthRequest=X})}),this.mcpServersSubscription=this.widget.dependencies.mcpService.servers.subscribe((X)=>{this.setState(()=>{this.mcpServers=X})}),this.pendingSkillsSubscription=this.widget.dependencies.activeThreadHandle.pendingSkills$.subscribe((X)=>{this.setState(()=>{this.pendingSkills=X})}),this.widget.dependencies.pluginService){let X=this.widget.dependencies.pluginService;this.pluginCommandsSubscription=_J(X.plugins,X.commands.changed).subscribe(()=>{let V=X.commands.list();this.setState(()=>{this.pluginCommands=V})}),this.pluginInfosSubscription=X.plugins.subscribe((V)=>{this.setState(()=>{this.pluginInfos=V})})}this.skillListSubscription=this.widget.dependencies.skillService.skills.subscribe((X)=>{let V=X.filter((K)=>!K.baseDir.startsWith("builtin://")).length;this.setState(()=>{this.availableSkillCount=V,this.availableSkillCountReady=!0})}),this.skillWarningsSubscription=this.widget.dependencies.skillService.skillWarnings.subscribe((X)=>{this.setState(()=>{this.skillWarningCount=X.length})}),this.skillErrorsSubscription=this.widget.dependencies.skillService.skillErrors.subscribe((X)=>{this.setState(()=>{this.skillErrorCount=X.length})}),this.pendingApprovalsSubscription=this.widget.dependencies.activeThreadHandle.pendingApprovals$.subscribe((X)=>{this.setState(()=>{this.pendingApprovals=X})}),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((X)=>{let V=this.isIdeReadyForAdContext();if(this.setState(()=>{this.ideStatus=X}),!V&&this.isIdeReadyForAdContext()){if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;if(!this.adSubscription&&!this.adsDisabledBySetting)this.subscribeToAds()}}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(X)=>{try{if(!this.widget.dependencies.threadState.mainThread){j.warn("No active thread found to handle IDE message");return}await new Promise((K)=>setTimeout(K,50)),await this.widget.dependencies.activeThreadHandle.sendMessage({content:[{type:"text",text:X}]}),j.debug("Message sent from IDE to agent",{message:X.slice(0,100)})}catch(V){this.handleSubmitFlowError(V)}}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((X)=>{this.textController.insertText(X),j.debug("Appended text to CLI prompt from IDE",{text:X.slice(0,100)})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((X)=>{this.setState(()=>{this.updateState=X})}),this.mysteriousMessageSubscription=nJ(this.widget.dependencies.configService).pipe(F5((X)=>X!=="pending"),D1((X)=>y6(X)?X.mysteriousMessage??null:null),M4((X,V)=>X?.id===V?.id)).subscribe((X)=>{this.setState(()=>{if(X?.id!==this.mysteriousMessage?.id)this.isShowingMysteriousMessageModal=!1;if(this.mysteriousMessage=X,X&&!this.mysterySequenceManager)this.mysterySequenceManager=new E20(new Map([[new O20(RJ0.MYSTERY_SEQUENCE),new Pp]])),this.mysteryKeyInterceptorUnsubscribe=l4.instance.addKeyInterceptor((V)=>{if(!this.mysterySequenceManager)return!1;if(this.isShowingMysteriousMessageModal)return!1;let K=this.mysterySequenceManager.handleKeyEvent(V);if(K.consumed){if(K.intent)this.handleShowMysteryModal();return this.setState(()=>{this.mysterySequenceProgress=K.progress}),!0}else if(this.mysterySequenceProgress)this.setState(()=>{this.mysterySequenceProgress=null});return!1});else if(!X)this.mysteryKeyInterceptorUnsubscribe?.(),this.mysteryKeyInterceptorUnsubscribe=null,this.mysterySequenceManager?.dispose(),this.mysterySequenceManager=null,this.mysterySequenceProgress=null})}),this.textController.addListener(this.textChangeListener),l4.instance.addKeyInterceptor((X)=>{if(X.key==="?"){if(this.textController.text===""&&this.textController.cursorPosition===0&&!this.isShowingHelp&&!this.isShowingPalette&&this.isTextfieldAndAutocompleteFocused){if(this.setState(()=>{this.isShowingShortcutsHelp=!this.isShowingShortcutsHelp}),!this.shortcutsHintUsed)this.shortcutsHintUsed=!0,this.sessionState={...this.sessionState,shortcutsHintUsed:!0},rz(this.sessionState);return!0}}if(this.isShowingShortcutsHelp){if(this.setState(()=>{this.isShowingShortcutsHelp=!1}),X.key==="Escape")return!0;return!1}return!1}),this.updateTerminalTitle();let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q)this.connectToSelectedIde(Q,"auto-startup").catch((X)=>{let V=X instanceof Error?X.message:String(X);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${V}`)})});else if(this.tuiContext.showIdePickerHint)this.toastController.show("Use /ide to connect to an IDE","success",5000);else if(this.tuiContext.showJetBrainsInstaller)this.openJetBrainsInstaller();let Y=this.widget.dependencies.threadState.mainThread;if(!Y){this.initNewsFeed();return}if(Y.autoSubmitDraft&&Y.messages.length===0)setTimeout(()=>{this.autoSubmitInitialDraft(Y.id)},100);this.initNewsFeed()}async autoSubmitInitialDraft(J){let Z=await this.getDraft(J);if(!Z)return;let Q=Z.text.trim();if(!Q&&Z.images.length===0)return;j.info("Auto-submitting initial handoff draft",{name:"handoff",threadID:J,hasDraftText:Boolean(Q),draftImageCount:Z.images.length}),this.textController.clear(),await this.proceedWithUserMessage(Q,[...Z.images])}handleSubmitFlowError(J){j.error("Failed to submit prompt message",J);let Z=J instanceof Error?J.message:String(J);this.showErrorMessage(Z)}checkForPendingNavigation(J){let Z=J??this.widget.dependencies.threadState.mainThread;if(!Z?.pendingNavigation)return;let Q=Z.pendingNavigation;if(this.pendingNavigationInFlightThreadID===Q)return;this.pendingNavigationInFlightThreadID=Q,this.widget.dependencies.activeThreadHandle.clearPendingNavigation().catch(()=>{return}),j.info("Pending navigation detected, navigating to new thread",{name:"handoff",fromThreadID:Z.id,targetThreadID:Q}),this.handleHandoffNavigation(Q).finally(()=>{if(this.pendingNavigationInFlightThreadID===Q)this.pendingNavigationInFlightThreadID=null})}handleHandoffNavigation=async(J)=>{try{await this.switchToExistingThread(J);let Z=this.widget.dependencies.threadState.mainThread;if(!Z){j.error("Failed to get new thread after handoff navigation");return}if(Z.autoSubmitDraft&&Z.messages.length===0){let Q=await this.getDraft(J);if(!Q)return;let Y=Q.text.trim();if(!Y&&Q.images.length===0)return;j.info("Auto-submitting handoff draft",{name:"handoff",threadID:J,hasDraftText:Boolean(Y),draftImageCount:Q.images.length}),this.textController.clear(),await this.proceedWithUserMessage(Y,[...Q.images])}}catch(Z){j.error("Failed to handle handoff navigation",{name:"handoff",newThreadID:J,error:Z})}};dispose(){if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeController)this.agentModeController.removeListener(this.agentModeListener),this.agentModeController.dispose();if(this.deepModeEffortHintController.dispose(),this.messageViewControllerUnsubscribe)this.messageViewControllerUnsubscribe(),this.messageViewControllerUnsubscribe=null;if(this.handoffController)this.handoffController.removeListener(this.handoffListener),this.handoffController.dispose();if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;if(this.adSubscription)this.adSubscription.unsubscribe();if(this.freeTierStatusSubscription)this.freeTierStatusSubscription.unsubscribe();if(this.allConnectedThreadActivityStatusesSubscription)this.allConnectedThreadActivityStatusesSubscription.unsubscribe();if(this.threadInitializationStatusSubscription)this.threadInitializationStatusSubscription.unsubscribe();if(this.threadTitlesSubscription)this.threadTitlesSubscription.unsubscribe();if(this.pendingNavigationSubscription)this.pendingNavigationSubscription.unsubscribe();if(this.mcpTrustSubscription)this.mcpTrustSubscription.unsubscribe();if(this.authStatusSubscription)this.authStatusSubscription.unsubscribe(),this.authStatusSubscription=null;if(Ax0(null),this.authModalKeyInterceptorUnsubscribe?.(),this.authModalKeyInterceptorUnsubscribe=null,this.pendingAuthLogin)this.pendingAuthLogin.abortController.abort(Error("TUI disposed")),this.pendingAuthLogin=null;if(this.mcpServersSubscription)this.mcpServersSubscription.unsubscribe();if(this.pendingSkillsSubscription)this.pendingSkillsSubscription.unsubscribe();if(this.pluginCommandsSubscription)this.pluginCommandsSubscription.unsubscribe();if(this.pluginInfosSubscription)this.pluginInfosSubscription.unsubscribe();if(this.skillListSubscription)this.skillListSubscription.unsubscribe();if(this.skillWarningsSubscription)this.skillWarningsSubscription.unsubscribe();if(this.skillErrorsSubscription)this.skillErrorsSubscription.unsubscribe();if(this.pendingApprovalsSubscription)this.pendingApprovalsSubscription.unsubscribe();if(this.unloadThreadsForPicker(),this.newsFeedSubscription)this.newsFeedSubscription.unsubscribe();if(this.deepReasoningEffortSubscription)this.deepReasoningEffortSubscription.unsubscribe(),this.deepReasoningEffortSubscription=null;if(this.anthropicSpeedSubscription)this.anthropicSpeedSubscription.unsubscribe(),this.anthropicSpeedSubscription=null;if(this.openAISpeedSubscription)this.openAISpeedSubscription.unsubscribe(),this.openAISpeedSubscription=null;if(this.submitOnEnterSubscription)this.submitOnEnterSubscription.unsubscribe(),this.submitOnEnterSubscription=null;if(this.showSkillsCountInPromptBarSubscription)this.showSkillsCountInPromptBarSubscription.unsubscribe(),this.showSkillsCountInPromptBarSubscription=null;if(this.stopElapsedTimeTimer(),this.winPasteHookImageUnsubscribe?.(),this.winPasteHookImageUnsubscribe=null,this.winPasteHookStateUnsubscribe?.(),this.winPasteHookStateUnsubscribe=null,this.mysteriousMessageSubscription)this.mysteriousMessageSubscription.unsubscribe();if(this.mysteryKeyInterceptorUnsubscribe?.(),this.mysterySequenceManager?.dispose(),this.threadPreviewController.removeListener(this.previewControllerListener),this.threadPreviewController.dispose(),this.toastController.dispose(),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;if(this.autocompleteFocusNodeListener)this.autocompleteFocusNode.removeListener(this.autocompleteFocusNodeListener),this.autocompleteFocusNodeListener=null;this.textController.removeListener(this.textChangeListener);for(let J of this.messageScrollControllers.values())J.dispose();this.messageScrollControllers.clear()}getCurrentConfirmation(){if(this.pendingApprovals.length>0){let J=this.pendingApprovals[0];return{type:"tool-use",tools:[{useBlock:{type:"tool_use",id:J.toolUseId,name:J.toolName,complete:!0,input:J.args},toAllow:J.toAllow??[]}],subthreadID:void 0,reason:J.reason??`Tool requires approval: ${J.toolName}`,isSubagent:J.context==="subagent",subagentToolName:J.subagentToolName}}return null}updateProgressBar(){}static AD_READINESS_TIMEOUT_MS=1000;scheduleAdSubscriptionWithIdeReadiness(){if(this.adsDisabledBySetting)return;if(!this.freeTierStatus.canUseAmpFree)return;if(this.isIdeReadyForAdContext()){this.subscribeToAds();return}this.adReadinessTimeout=setTimeout(()=>{if(this.adReadinessTimeout=null,!this.adSubscription)this.subscribeToAds()},RJ0.AD_READINESS_TIMEOUT_MS)}isIdeReadyForAdContext(){let J=this.ideStatus;if(!J||!J.enabled)return!1;return Boolean(J.openFile||J.visibleFiles&&J.visibleFiles.length>0)}unsubscribeFromAds(){if(this.adSubscription)this.adSubscription.unsubscribe(),this.adSubscription=null;if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;this.setState(()=>{this.randomAd=null})}subscribeToAds(){if(this.adSubscription)return;if(this.adsDisabledBySetting)return;if(!this.freeTierStatus.canUseAmpFree)return;this.adSubscription=Gg0(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>zg0(this.lastUserInteractionTime),this.widget.dependencies.codebaseContextService,()=>this.widget.dependencies.threadState.mainThread??void 0).subscribe({next:(J)=>{this.setState(()=>{this.randomAd=J}),H6.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})}})}onConfirmationResponse=async(J)=>{let Z=this.getCurrentConfirmation();if(!Z||Z.type!=="tool-use"){j.error("No current tool confirmation found");return}let Q=Z.tools[0]?.useBlock;if(!Q){j.error("No tool use block found in confirmation");return}if(J?.type==="deny-with-feedback"){let{feedback:V}=J;try{if(this.pendingApprovals.find((z)=>z.toolUseId===Q.id))await this.widget.dependencies.activeThreadHandle.resolveApproval(Q.id,!1,V.trim()||void 0);else await this.widget.dependencies.activeThreadHandle.resolveApproval(Q.id,!1,V.trim()||void 0)}catch(K){j.error("Failed to send deny with feedback:",K)}return}let Y=J?.type==="simple"?J.value:null;if(Y==="allow-all-session")u$("dangerouslyAllowAll",!0);if(Y==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0,"global")}catch(V){if(V&&V instanceof Error)this.setState(()=>{this.displayMessage=V});else j.error("Failed to write dangerouslyAllowAll setting:",V);return}if(Y==="always-guarded"){let V=Z.tools[0]?.toAllow??[],K=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],z=[...V,...K];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",z,"global")}if(Y==="connect-github"){let V=new URL("/settings#code-host-connections",this.tuiContext.ampURL).toString();await w8(this.context,V);return}if(Y==="disable-librarian"){let V=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!V.includes(T$))await this.widget.dependencies.settingsStorage.set("tools.disable",[...V,T$],"global")}let X=Y!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(Y);try{await this.widget.dependencies.activeThreadHandle.resolveApproval(Q.id,X)}catch(V){j.error("Failed to send tool confirmation:",V)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Z=J.viewState;if(Z.state!=="active"||!Z.ephemeralError)return null;return Z.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let{activeThreadHandle:Z}=this.widget.dependencies;switch(J){case"retry":await Z.retryTurn();break;case"dismiss":Z.dismissEphemeralError();break;case"new-thread":Z.dismissEphemeralError(),await this.startAndSwitchToNewThread();break;case"handoff":Z.dismissEphemeralError(),this.enterHandoffMode();break;case"add-credits":{let Q=new URL("/pay",this.tuiContext.ampURL);await w8(this.context,Q),this.showStatusMessage("Payment page opened. After paying, choose Retry.");break}}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};handleMCPTrustOpenSettings=async()=>{let{mcpTrustHandler:J,settingsStorage:Z}=this.widget.dependencies;await J.deny();try{await oY(Z.getSettingsFilePath())}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);await this.showErrorMessage(`Failed to open settings: ${Y}`)}};cancelStreamingMessage=async()=>{await this.widget.dependencies.activeThreadHandle.cancelStreaming()};switchToExistingThread=async(J,Z={})=>{let{recordInNavigationHistory:Q=!0}=Z,Y=Date.now(),X=this.widget.dependencies.threadState.mainThread?.id,V=Q&&X!==void 0&&X!==J;try{j.info(`[switchToExistingThread] Switching to thread: ${J}`);let K=Date.now();await this.widget.dependencies.threadPool.switchThread(J),j.info(`[switchToExistingThread] switchToThread resolved in ${Date.now()-K}ms`);let z=await this.widget.dependencies.threadService.get(J)??this.widget.dependencies.threadState.mainThread;if(!z||z.id!==J)throw Error("No active thread after switch");j.info(`[switchToExistingThread] Got thread ${J}, thread.agentMode: ${z.agentMode}`),j.info("[switchToExistingThread] Clearing agent mode"),this.agentModeController?.setMode(null);let G=Date.now();if(this.onThreadSwitch(),j.info(`[switchToExistingThread] onThreadSwitch completed in ${Date.now()-G}ms`),V&&X)this.recordNavigation(X);this.persistLastThreadId(J);let F=await this.getDraft(J);if(F&&W3(z)===0){if(this.textController.clear(),F.text)this.textController.insertText(F.text);if(F.images.length>0)this.setState(()=>{this.imageAttachments=[...F.images]})}j.info(`[switchToExistingThread] Completed in ${Date.now()-Y}ms`)}catch(K){j.error("Failed to switch to thread",{threadId:J,error:K});let z=K instanceof Error?K.message:String(K);if(z.includes("can't be opened in legacy mode")){await this.showErrorMessage(z);return}throw Error(`Failed to switch to thread: ${J}. ${z}`,{cause:K})}};async getDraft(J){return(await E1(this.widget.dependencies.threadPool.drafts$).catch(()=>null))?.get(J)??null}sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J,Z)=>{if(this.cancelBashInvocations(),this.shouldRequireAuthForPromptSubmit()){this.queuePromptUntilAuthenticated(J,Z??[...this.imageAttachments],{clearInput:Z===void 0});return}this.handoffController?.clearPendingPrompt(),this.widget.dependencies.history.add(J,process.cwd());let Q=this.widget.dependencies.threadState.mainThread;if(!Q)return;let Y=W3(Q)===0,X=this.getEffectiveAgentMode();if(Q.agentMode&&!Y&&X!==Q.agentMode){await this.showErrorMessage(`This thread uses ${Q.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let V=Z??this.imageAttachments,K=[{type:"text",text:J}];if(V.length>0)K.push(...V);if(await this.widget.dependencies.activeThreadHandle.sendMessage({content:K,agentMode:X}),this.persistLastThreadId(Q.id),Y)this.persistAgentMode(X);if(this.scrollMessageViewToBottom(),!Z)this.setState(()=>{this.imageAttachments=[]});H6.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}exitApplication=async()=>{this.setState(()=>{this.isExiting=!0});let J=this.widget.dependencies.threadState.mainThread;if(J&&J.messages.length===0){if(J.relationships?.find((Q)=>Q.type==="handoff"&&Q.role==="child"))await this.widget.dependencies.threadPool.deleteThread?.(J.id).catch(()=>{})}l4.instance.stop()};async persistAgentMode(J){let Q={...await oz(),agentMode:J};this.sessionState=Q,await rz(Q)}async persistLastThreadId(J){let Q={...await oz(),lastThreadId:J};this.sessionState=Q,await rz(Q)}onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;this.exitApplication()}else{if(this.setState(()=>{this.isConfirmingExit=!0}),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout);this.exitConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingExit=!1}),this.exitConfirmTimeout=null},1000)}};toHomeRelative(J){let Z=js5();if(J===Z)return"~";if(J.startsWith(Z+wG.sep))return"~"+J.slice(Z.length);return J}shorten(J){let Z=J.split(wG.sep).filter(Boolean);if(Z.length<=5)return J;return[Z.slice(0,2).join(wG.sep),"…",Z.slice(-2).join(wG.sep)].join(wG.sep)}buildDisplayText(J,Z,Q,Y){let X=Z?` (${Z})`:"",V=J+X;if(p5(V,Y)<=Q)return V;let K=J.split(wG.sep);if(K.length>2){let G=[K[0],"…",K[K.length-1]].join(wG.sep)+X;if(p5(G,Y)<=Q)return G}return sE(V,Q,Y)}build(J){this.lastRootContext=J;let Z=this.widget.dependencies.pluginPlatform;if(Z&&!Z.showToast){let z1=this.toastController;Z.showToast=(L4)=>z1.show(L4,"success")}if(Z&&!Z.showOpenedURLToast){let z1=this.toastController;Z.showOpenedURLToast=(L4)=>z1.show(`Opened URL: ${L4}`,"success",8000)}if(Z&&!Z.appendToThreadHandler){let z1=this.widget.dependencies;Z.appendToThreadHandler=async(L4)=>{for(let T4 of L4)await z1.activeThreadHandle.queueMessage([{type:"text",text:T4.content}])}}if(Z&&!Z.showInputDialog)Z.showInputDialog=(z1)=>{return new Promise((L4)=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.pendingInputDialog={options:z1,resolve:L4}})})};if(Z&&!Z.showConfirmDialog)Z.showConfirmDialog=(z1)=>{return new Promise((L4)=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.pendingConfirmDialog={options:z1,resolve:L4}})})};let Q=t1.of(J),Y=f0.of(J),X=Y.base;this.themeColors=X;let{colors:V,app:K}=Y;this.themeApp=K;let z=this.widget.dependencies.threadState.mainThread,G=z?.agentMode&&h3(z.agentMode),F=this.freeTierStatus.isDailyGrantEnabled,U=!this.adsDisabledBySetting&&(G||F)&&this.randomAd!==null,q=Boolean(U),{threadState:D}=this.widget.dependencies;this.updateTerminalTitle(),this.updateProgressBar();let W=this.getCurrentConfirmation(),H=D.items,B=D.mainThread||void 0,w=D.subagentToolsByParentID,N=D.toolProgressByToolUseID,O=D.todosList,E=B?.id,L=B,M=this.isTranscriptEmpty(),A=M&&this.isStartupThreadLoading(),I=this.threadInitializationMessage?.startsWith("Importing thread")??!1,P=this.widget.dependencies.threadPool.isDTWMode?.()===!0,_=(z1)=>new qd({key:new $3(`preview-message-view-${z1.id}`),items:TU(z1).items,toolProgressByToolUseID:new Map,controller:this.threadPreviewController.scrollController,autofocus:!1,thread:z1,denseView:z1.agentMode==="deep",focusNode:new r4({debugLabel:"PreviewFocus"}),onShowImagePreview:()=>{},stateController:this.previewMessageViewController,submitOnEnter:this.submitOnEnter,isDTWMode:P}),S=this.previewThread,y=S?S.messages.length>2000?new u0({mainAxisSize:"max",children:[new T1({child:new R0}),new i0({padding:C0.all(2),child:new l1({child:new $0({text:new C("Thread too long for preview",new h({color:V.mutedForeground,dim:!0}))})})})]}):_(S):M?new P$0({agentMode:this.getEffectiveAgentMode(),mysteriousMessage:this.mysteriousMessage,mysterySequenceProgress:this.mysterySequenceProgress,onShowMysteryModal:this.handleShowMysteryModal,onOrbExplode:this.handleSplashOrbExplode}):new ed0({threadID:E,items:H,subagentToolsByParentID:w,toolProgressByToolUseID:N,controller:E?this.getMessageScrollController(E):new Y5,autofocus:!1,onCopy:this.handleMainMessageViewCopy,thread:L,onMessageEditSubmit:this.handleMessageEditSubmit,onMessageRestoreSubmit:this.handleMessageRestoreSubmit,onShowForkDeprecation:this.showForkDeprecationMessage,getAffectedFiles:this.getAffectedFiles,denseView:L?.agentMode==="deep",focusNode:this.messageViewFocusNode,onDismissFocus:this.handleMainMessageViewDismissFocus,isInSelectionMode:this.isMessageViewInSelectionMode,isInHandoffMode:this.handoffState.isInHandoffMode,completionBuilder:this.getCompletionBuilder(),onShowImagePreview:this.handleShowEditingImagePreview,onSelectionChanged:this._handleSelectionChanged,onDoubleAtTrigger:this.handleDoubleAtTrigger,stateController:this.messageViewController,submitOnEnter:this.submitOnEnter,threadViewState:D.viewState,isDTWMode:P}),m=Math.max(Math.floor(Q.size.height*0.4),12),b=this.getCurrentEphemeralError(),k=Q.size.width<40,f=dM4(D),p=this.widget.dependencies.threadPool.getCompactionStatus?.(),l=M20(J),x=this.buildBottomWidget(b,W,V,Y,D,O,m,q,f,Q,l),r=new L$0({threadViewState:D.viewState,threadTokenUsage:f,compactionState:p?.compactionState??"idle",threadID:E??null,thread:D.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,mcpServers:this.mcpServers,plugins:this.pluginInfos,isNarrow:k,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!W,showingEphemeralError:Boolean(D.viewState.state==="active"&&D.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandNoun:this.executingCommand?.noun??null,executingCommandVerb:this.executingCommand?.verb??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),c=new O$0({bashInvocations:this.bashInvocations}),s=[],w0=_K4(this.tuiContext.buildTimestamp);if(w0){let z1=sL0(w0.ageMs,{verbose:!0});s.push(new c0({decoration:new v4(V.destructive),child:new i0({padding:C0.horizontal(1),child:new $0({text:new C("",new h({color:V.foreground,bold:!0}),[new C(`Your Amp version is ${z1} old — run `),new C("amp update",new h({color:V.warning})),new C(" or see ampcode.com/manual")]),textAlign:"center"})})}))}s.push(new T1({child:y}),c);let a=new i6({children:[new u0({mainAxisSize:"min",children:[U?new lg0({ad:this.randomAd,onImpression:(z1)=>{if(!z1.advertiserId){j.warn("[ad-telemetry] Skipping impression due to missing advertiserId",{adId:z1.id});return}let L4=z1.impressionId??mM4(16).toString("hex");this.lastAdImpressionId=L4;let T4=this.widget.dependencies.threadState.mainThread;if(!T4)return;let i4=T4.messages[T4.messages.length-1],E8=Date.now();CN("viewed",{adId:z1.id,advertiserId:z1.advertiserId,threadId:T4.id,messageId:i4?.messageId,impressionId:L4,placement:"tui",matchType:z1.metadata?.matchType,matchedPatterns:z1.metadata?.matchedPatterns,candidateAdPoolCount:z1.metadata?.candidateAdPoolCount,clientRegion:z1.metadata?.clientRegion,tokenProvided:!!z1.impressionToken,campaignId:z1.metadata?.campaignId,providerId:z1.metadata?.providerId,providerType:z1.metadata?.providerType,relevance:z1.metadata?.relevance}),CN("impressionStarted",{adId:z1.id,advertiserId:z1.advertiserId,impressionId:L4,placement:"tui",providerId:z1.metadata?.providerId,providerType:z1.metadata?.providerType}),this.widget.dependencies.internalAPIClient.recordAdImpression({adId:z1.id,impressionToken:z1.impressionToken,impressionId:L4,externalImpressionUrl:z1.externalImpressionUrl},{config:this.widget.dependencies.configService}).then((L7)=>{if(!L7.ok)throw Error(`recordAdImpression failed: ${L7.error.code??"unknown"}`);let zX=Math.round(Date.now()-E8);CN("impressionRecorded",{adId:z1.id,advertiserId:z1.advertiserId,impressionId:L4,placement:"tui",durationMs:zX,providerId:z1.metadata?.providerId,providerType:z1.metadata?.providerType})}).catch((L7)=>{let zX=Math.round(Date.now()-E8);CN("impressionFailed",{adId:z1.id,advertiserId:z1.advertiserId,impressionId:L4,errorMessage:L7 instanceof Error?L7.message:String(L7),errorType:"error",placement:"tui",durationMs:zX,providerId:z1.metadata?.providerId,providerType:z1.metadata?.providerType})})},onButtonClick:async()=>{let z1=this.randomAd;if(this.lastAdImpressionId&&z1.advertiserId){let i4=this.widget.dependencies.threadState.mainThread;if(!i4)return;let E8=i4.messages[i4.messages.length-1];CN("clicked",{adId:z1.id,advertiserId:z1.advertiserId,threadId:i4.id,messageId:E8?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to",matchType:z1.metadata?.matchType,matchedPatterns:z1.metadata?.matchedPatterns,candidateAdPoolCount:z1.metadata?.candidateAdPoolCount,clientRegion:z1.metadata?.clientRegion,providerId:z1.metadata?.providerId,providerType:z1.metadata?.providerType})}let T4=l4.instance.tuiInstance.clipboard.isOsc52Supported();if(d80())this.setState(()=>{this.adActionModal={showCopyOption:!1,url:z1.shortDestinationUrl,title:z1.buttonLabel},this.bringAdModalToFront("adAction")});else if(!await w8(this.context,z1.shortDestinationUrl))this.setState(()=>{this.adActionModal={showCopyOption:T4,url:z1.shortDestinationUrl},this.bringAdModalToFront("adAction")})},onAdInfoClick:()=>{this.setState(()=>{this.adInfoModal={provider:this.randomAd?.metadata?.provider},this.bringAdModalToFront("adInfo")})}}):new R0({height:0}),new c0({constraints:new M1(0,Q.size.width,0,m),child:x})]}),q?new x6({top:0,left:0,right:0,child:new iM4({userHeight:this.bottomGridUserHeight,maxHeight:m,onInitializeHeight:(z1)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(z1,m)})},onDrag:(z1)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(z1.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let L4=Math.floor(z1.localPosition.y)-this.bottomGridDragStartY,T4=Math.max(4,this.bottomGridDragStartHeight-L4),i4=Math.min(T4,m),E8=Math.floor(i4);if(this.bottomGridUserHeight!==E8)this.setState(()=>{this.bottomGridUserHeight=E8})},onRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null}})}):new R0({height:0})]}),F0=this.getParentThreadInfo();if(F0){let z1=F0.type==="handoff"?K.handoffMode:V.primary,L4=40,T4=l6(F0.title),i4=T4.length>40?T4.slice(0,39).join("")+"…":F0.title;s.push(new bp({link:this.parentThreadLinkAnchor,child:new Sp0({type:F0.type,title:i4,threadID:F0.threadID,labelColor:z1,mutedColor:V.mutedForeground,foregroundColor:V.foreground,onNavigate:(E8)=>this.switchToExistingThread(E8)})}))}s.push(a,new R0({height:1,child:new i0({padding:C0.horizontal(1),child:r})}));let z0=new u0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:s}),q0=new c0({constraints:M1.tight(Q.size.width,Q.size.height),decoration:new v4(V.background),child:z0}),Q0=new s4(()=>{if(this.isShowingPalette)return this.dismissPalette(),"handled";if(this.isShowingMCPStatusModal)return this.setState(()=>{this.isShowingMCPStatusModal=!1}),"handled";if(this.pendingAuthLogin)return this.cancelAuthLoginSession(),"handled";if(this.pendingOAuthRequest){let L4=this.pendingOAuthRequest;return this.setState(()=>{this.pendingOAuthRequest=null}),L4.reject(Error("OAuth authorization cancelled")),"handled"}if(this.isShowingPromptHistoryPicker)return this.setState(()=>{this.isShowingPromptHistoryPicker=!1}),"handled";if(this.pendingMCPServers.length>0)return this.widget.dependencies.mcpTrustHandler.deny(),"handled";if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingContextAnalyzeModal)return this.setState(()=>{this.isShowingContextAnalyzeModal=!1,this.contextAnalyzeDeps=null,this.contextAnalyzeFromDTW=null}),"handled";if(this.isShowingSkillListModal)return this.setState(()=>{this.isShowingSkillListModal=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingContextDetailOverlay)return this.setState(()=>{this.isShowingContextDetailOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.dismissTopAdModal())return"handled";if(this.handoffState.countdownSeconds!==null)return this.handoffController?.stopCountdown(),"handled";if(this.handoffState.isInHandoffMode){if(this.handoffState.isGeneratingHandoff)this.handoffController?.cancelGeneration();else this.exitHandoffMode();return"handled"}if(this.isInQueueMode)return this.exitQueueMode(),"handled";if(this.textController.hasSelection)return this.textController.clearSelection(),"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.textController.resetScrollOffset(),this.widget.dependencies.activeThreadHandle.clearPendingSkills(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.handoffState.isConfirmingAbortHandoff&&this.handoffController){let L4=this.handoffController.getPendingPrompt(),T4=this.imageAttachments;return this.textController.clear(),this.textController.resetScrollOffset(),this.widget.dependencies.activeThreadHandle.clearPendingSkills(),this.setState(()=>{this.imageAttachments=[]}),this.handoffController.confirmAbort().then((i4)=>{if(i4&&L4)this.textController.text=L4,this.handoffController?.clearPendingPrompt();if(i4&&T4.length>0)this.setState(()=>{this.imageAttachments=T4})}),"handled"}if(this.isConfirmingCancelProcessing){if(this.bashInvocations.length>0)this.cancelBashInvocations();if(this.cancelStreamingMessage().catch((L4)=>{j.error("Failed to cancel streaming message:",L4)}),this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout),this.cancelProcessingConfirmTimeout=null;return"handled"}if(this.executingCommand)return j.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.bashInvocations.length>0||this.isProcessing()){if(this.setState(()=>{this.isConfirmingCancelProcessing=!0}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout);return this.cancelProcessingConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout=null},1000),"handled"}if(this.handoffController?.getEmptyHandoffParentThreadID(this.widget.dependencies.threadState.mainThread))return this.handoffController.startAbortConfirmation(),"handled";if(this.textController.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return"ignored"}),H0=new s4(()=>{return this.onExitPressed(),"handled"}),i=new s4(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),n=new s4(()=>{return this.setState(()=>{this.isShowingMCPStatusModal=!this.isShowingMCPStatusModal}),"handled"}),e=new s4(()=>{if(r9.instance.toggleAll(),D.mainThread?.agentMode==="deep"||D.mainThread?.agentMode==="internal")UJ.instance.toggleAll();return"handled"}),J0=new s4(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return this.setState(()=>{this.isShowingPromptHistoryPicker=!0}),"handled"}),Z0=new s4(()=>{return l4.instance.toggleFrameStatsOverlay(),"handled"}),K0=new s4(()=>{return l4.instance.tuiInstance.getScreen().markForRefresh(),H6.instance.requestFrame(),"handled"}),t=new s4(()=>{return this.toggleAgentMode(),"handled"}),V0=new s4(()=>{return this.toggleDeepReasoningEffort(),"handled"}),N0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4){let T4=Math.max(Math.floor(Q.size.height*0.4),10),i4=Q.size.height-T4;L4.animatePageUp(i4,100)}return"handled"}),D0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4){let T4=Math.max(Math.floor(Q.size.height*0.4),10),i4=Q.size.height-T4;L4.animatePageDown(i4,100)}return"handled"}),O0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4){let T4=Math.max(Math.floor(Q.size.height*0.4),10),i4=Q.size.height-T4;L4.animatePageUp(Math.floor(i4/2),100)}return"handled"}),_0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4){let T4=Math.max(Math.floor(Q.size.height*0.4),10),i4=Q.size.height-T4;L4.animatePageDown(Math.floor(i4/2),100)}return"handled"}),e0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4)L4.animateTo(0,100);return"handled"}),a0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4)L4.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),F1=new s4(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";if(this.handoffState.isInHandoffMode)return"ignored";if(this.isInQueueMode)return"ignored";let{threadState:z1}=this.widget.dependencies;if(!z1.mainThread?.messages.some((T4)=>T4.role==="user"||VF(T4)))return"ignored";return this.setState(()=>{this.isMessageViewInSelectionMode=!0}),"handled"}),a1=new s4((z1)=>{if(z1.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),o1=new s4(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return H$0().then(async(z1)=>{if(z1)await this.handleInsertImage(z1)}),"handled"}),m0=new Map([[Y4.ctrl("c"),new Ep],[Y4.ctrl("l"),new Ip],[Y4.ctrl("o"),new q$0],[Y4.ctrl("v"),new Np],[Y4.alt("s"),new HT],[Y4.ctrl("s"),new HT],[Y4.alt("p"),new Ap],[Y4.ctrl("r"),new Cp],[Y4.alt("t"),new Mp],[Y4.ctrl("t"),new Rp],[Y4.key("PageUp"),new V$0],[Y4.key("PageDown"),new K$0],[Y4.alt("k"),new z$0],[Y4.alt("j"),new G$0],[Y4.key("Home"),new F$0],[Y4.key("End"),new U$0],[Y4.key("Escape"),new Op],[Y4.ctrl("p"),new BT("previous")],[Y4.ctrl("n"),new BT("next")],[Y4.key("Tab"),new fp]]);if(m0.set(Y4.alt("d"),new jp),!a9())m0.set(Y4.key("ArrowUp"),new fp);if(!1)m0.set(Y4.alt("c"),new Lp);let t0=new s4(()=>{if(this.isShowingStandalonePalette())return"handled";return this.showCommandPalette(),"handled"}),A1=new s4(()=>{return this.toggleThreadPickerWorkspaceFilter(),"handled"}),$4=new s4(()=>{if(this.mysteriousMessage)this.handleShowMysteryModal();return"handled"}),D6=new Map([[Op,Q0],[Ip,K0],[HT,t],[jp,V0],[q$0,t0],[Np,o1],[Lp,i],[N20,n],[Mp,e],[Ap,Z0],[Rp,A1],[Cp,J0],[Ep,H0],[V$0,N0],[K$0,D0],[z$0,O0],[G$0,_0],[F$0,e0],[U$0,a0],[fp,F1],[BT,a1],[Pp,$4]]),m1=[q0];if(this.splashOrbExplosion){let z1=rg(this.getEffectiveAgentMode());m1.push(new id0({key:new $3(`splash-orb-explosion-${this.splashOrbExplosion.seq}`),originX:this.splashOrbExplosion.originX,originY:this.splashOrbExplosion.originY,sparkleColors:[z1,V.warning],onComplete:this.handleSplashOrbExplosionComplete}))}if(A||I)m1.push(new l1({child:new iV({message:this.threadInitializationMessage??"Loading thread..."})}));if(this.isShowingConsoleOverlay)m1.push(new jp0);if(this.isShowingHelp&&this.paletteConfig)m1.push(new vp0({commands:this.getPaletteCommands().getAllCommands(),submitOnEnter:this.submitOnEnter}));if(this.isShowingContextAnalyzeModal){let{configService:z1}=this.widget.dependencies,L4=this.widget.dependencies.threadState.mainThread,T4=this.contextAnalyzeDeps,i4=this.contextAnalyzeFromDTW;if(L4&&(T4||i4)){let E8=T4?{configService:z1,agentModeOverride:this.getEffectiveAgentMode(),buildSystemPromptDeps:T4}:null;m1.push(new Rp0({deps:E8,thread:L4,dtwAnalyze:i4??void 0,onDismiss:()=>{this.setState(()=>{this.isShowingContextAnalyzeModal=!1,this.contextAnalyzeDeps=null,this.contextAnalyzeFromDTW=null})}}))}else this.setState(()=>{this.isShowingContextAnalyzeModal=!1,this.contextAnalyzeDeps=null,this.contextAnalyzeFromDTW=null})}if(this.isShowingSkillListModal&&!this.isShowingPalette)Promise.all([this.widget.dependencies.skillService.getSkills(),this.widget.dependencies.skillService.getSkillErrors(),this.widget.dependencies.skillService.getSkillWarnings()]).then(([z1,L4,T4])=>{if(this.isShowingSkillListModal&&this.mounted)this.skillListData={skills:z1,errors:L4,warnings:T4},this.setState()}),m1.push(new rd0({skills:this.skillListData?.skills??[],errors:this.skillListData?.errors??[],warnings:this.skillListData?.warnings??[],cwd:process.cwd(),onDismiss:()=>{this.setState(()=>{this.isShowingSkillListModal=!1,this.skillListData=null})},onAddSkill:()=>{this.showCommandPalette({type:"standalone",commandId:"skill-add",onSubmit:()=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.isShowingSkillListModal=!1,this.skillListData=null})},onCancel:()=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null})}})},onDocs:()=>{fX("https://ampcode.com/manual#agent-skills")},onInsertPrompt:(z1)=>{this.setState(()=>{this.isShowingSkillListModal=!1,this.skillListData=null,this.textController.text=z1})},onInvokeSkill:(z1)=>{this.widget.dependencies.activeThreadHandle.addPendingSkill({name:z1})}}));if(this.isShowingMCPStatusModal)m1.push(new sp0({servers:this.mcpServers,onDismiss:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!1})}}));if(this.isShowingPromptHistoryPicker)m1.push(new nd0({entries:this.widget.dependencies.history.getAll(),currentCwd:process.cwd(),onAccept:(z1)=>{this.setState(()=>{this.isShowingPromptHistoryPicker=!1,this.textController.text=z1,this.textController.cursorPosition=z1.length})},onDismiss:()=>{this.setState(()=>{this.isShowingPromptHistoryPicker=!1})}}));if(this.isShowingMysteriousMessageModal&&this.mysteriousMessage)m1.push(new cd0({message:this.mysteriousMessage,onDestruct:this.handleDestructMysteriousMessage}));if(this.isShowingForkDeprecationModal)m1.push(new Tp0({onDismiss:this.dismissForkDeprecationModal}));for(let z1=0;z1<this.adModalStack.length;z1++){let L4=this.adModalStack[z1],T4=z1===this.adModalStack.length-1;if(L4==="adAction"&&this.adActionModal)m1.push(new ig0({key:new $3(`ad-action-modal-${T4?"top":"back"}`),title:this.adActionModal.title??"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(i4)=>{let E8=this.adActionModal.url;if(i4==="copy")try{await l4.instance.tuiInstance.clipboard.writeText(E8),this.setState(()=>{this.displayMessage=new W$("Link copied to clipboard")})}catch(L7){j.error("Failed to copy to clipboard",{error:L7}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null,this.removeAdModalFromStack("adAction")})}}));if(L4==="adInfo"&&this.adInfoModal)m1.push(new ng0({key:new $3(`ad-info-modal-${T4?"top":"back"}`),provider:this.adInfoModal.provider,onClose:()=>{this.setState(()=>{this.adInfoModal=null,this.removeAdModalFromStack("adInfo")})}}))}if(this.pendingMCPServers.length>0){let{mcpTrustHandler:z1}=this.widget.dependencies;m1.push(new tp0({servers:this.pendingMCPServers,onAlwaysTrust:z1.trustAlways.bind(z1),onTrustOnce:z1.trustOnce.bind(z1),onOpenSettings:this.handleMCPTrustOpenSettings,onDismiss:z1.deny.bind(z1)}))}if(this.pendingAuthLogin)m1.push(new ag0({manualURL:this.pendingAuthLogin.manualURL,isAuthenticating:this.pendingAuthLogin.isAuthenticating||this.pendingAuthLogin.isOpeningBrowser,errorMessage:this.pendingAuthLogin.errorMessage}));if(this.pendingOAuthRequest)m1.push(new ld0({request:this.pendingOAuthRequest,onDismiss:()=>{this.setState(()=>{this.pendingOAuthRequest=null})}}));if(this.pendingInputDialog){let z1=this.pendingInputDialog;m1.push(new xp0({options:z1.options,onSubmit:(L4)=>{this.setState(()=>{this.pendingInputDialog=null}),z1.resolve(L4)},onCancel:()=>{this.setState(()=>{this.pendingInputDialog=null}),z1.resolve(void 0)}}))}if(this.pendingConfirmDialog){let z1=this.pendingConfirmDialog;m1.push(new Mp0({options:z1.options,onConfirm:()=>{this.setState(()=>{this.pendingConfirmDialog=null}),z1.resolve(!0)},onCancel:()=>{this.setState(()=>{this.pendingConfirmDialog=null}),z1.resolve(!1)}}))}if(this.isShowingFileChangesOverlay)m1.push(new mg0({threadData:D}));if(this.isShowingContextDetailOverlay){let z1=this.threadCostInfo?.costBreakdownURL;m1.push(new Pp0({tokenUsage:f??void 0,costInfo:this.threadCostInfo,onDismiss:()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!1})},onOpenCostBreakdown:z1?()=>{w8(J,z1)}:void 0}))}if(this.isShowingConfirmationOverlay)m1.push(new Ap0({details:this.confirmationOverlayContent}));if(this.imagePreview!==null)m1.push(new l1({child:new up0({image:this.imagePreview.image,imageIndex:this.imagePreview.index,onDismiss:this.handleImagePreviewDismiss,onRemove:this.handleImagePreviewRemove})}));if(this.fileImagePreviewPath!==null)m1.push(new l1({child:new Up({filePath:this.fileImagePreviewPath,onDismiss:this.handleFileImagePreviewDismiss})}));if(this.painterImagePreview!==null)m1.push(new l1({child:new Up({filePath:this.painterImagePreview.filePath,onDismiss:this.handlePainterImagePreviewDismiss})}));if(this.painterSaveDialog!==null)m1.push(new l1({child:new Up({filePath:this.painterSaveDialog.filePath,imageBlock:this.painterSaveDialog.image,onDismiss:this.handlePainterSaveDialogDismiss})}));if(this.skillPreview!==null){let z1=this.pendingSkills[this.skillPreview.skillIndex];if(z1)m1.push(new l1({child:new sd0({pendingSkill:z1,skill:this.cachedSkillForPreview,onDismiss:this.handleSkillPreviewDismiss,onRemove:this.skillPreview.onRemove})}))}let y4=this.getCommandPaletteContext(J);if(y4&&this.isShowingPalette&&this.paletteConfig)m1.push(new l1({child:new Ep0({commandContext:y4,mainThread:D.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette,showOptions:this.paletteShowOptions??void 0})}));if(this.isShowingIdePicker)m1.push(new yp0({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection}));let b4=new i6({children:m1});if(this.isShowingJetBrainsInstaller)return new uL({child:new S9({actions:D6,child:new C2({shortcuts:m0,debugLabel:"jetbrains-installer-shortcuts",child:new op0({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});let H4=this.widget.dependencies.threadState.mainThread?.id,S5=1+(this.bottomGridUserHeight??5)+1,X6=!this.isShowingPalette&&!this.isShowingIdePicker;return new tT({switchToThread:(z1)=>this.switchToExistingThread(z1),child:new HG({threadViewStates:this.getThreadViewStatesSnapshot(),threadTitles:this.threadTitles,threadSummaries:this.threadsForPicker,child:new _p0({getThreadCluster:this.getCurrentThreadClusterForMinimap,parentThreadID:F0?.threadID,anchorLink:F0?this.parentThreadLinkAnchor:void 0,bottomOffset:S5,enabled:X6,child:new xT({onShowImagePreview:this.handleShowFileImagePreview,child:new fT({onShowImagePreview:this.handleShowPainterImagePreview,onShowSaveDialog:this.handleShowPainterSaveDialog,child:new rY({controller:this.toastController,child:new uL({child:new Ad0({getThreadCluster:this.getThreadClusterForMinimap,currentThreadID:H4,enabled:X6,child:new rH({enabled:X6,child:new f70({controller:this.toastController,child:new S9({actions:D6,child:new C2({shortcuts:m0,debugLabel:"main-app-shortcuts",child:b4})})})})})})})})})})})})}buildScrollableTodoList(J,Z,Q){return new cM4({todos:J,enabled:Z,controller:this.todoScrollController,appTheme:Q})}buildBottomWidget(J,Z,Q,Y,X,V,K,z,G,F,U){if(J)return new Cp0({error:J,options:{freeTierEnabled:this.freeTierStatus.canUseAmpFree},onResponse:this.handleEphemeralErrorResponse});if(Z){if(this.displayMessage)this.handleDisplayMessageDismiss();return new Ip0({confirmationRequest:Z,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new ep0({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let q=this.handoffState.isInHandoffMode||!this.widget.dependencies.activeThreadHandle.invokeBashTool?[]:N$0(Y),D=this.agentModeController?.isInRestrictedFreeMode()??!1,W=this.isTextfieldAndAutocompleteFocused&&!D&&!this.isShowingStandalonePalette()&&!this.handoffState.isGeneratingHandoff;if(W&&!this.hasReplayedEarlyInput){this.hasReplayedEarlyInput=!0;let t=l4.instance.tuiInstance.getEarlyInputText();if(t)this.textController.insertText(t)}let H=this.submitOnEnter?{character:"Enter"}:{character:"Enter",modifiers:{meta:!0}},B=new Ud({key:this.textFieldKey,controller:this.textController,triggers:[new YB],completionBuilder:this.getCompletionBuilder(),onSubmitted:(t)=>{this.onTextSubmitted(t).catch((V0)=>{this.handleSubmitFlowError(V0)})},submitKey:H,theme:Q,placeholder:D?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,enabled:W,shellPromptRules:q,focusNode:this.autocompleteFocusNode,autofocus:!this.isMessageViewInSelectionMode&&!this.isShowingStandalonePalette()&&!this.isShowingIdePicker&&!this.isShowingSkillListModal,clipboard:l4.instance.tuiInstance.clipboard,onCopy:this._handleTextCopy.bind(this),onInsertImage:this.handleInsertImage,imageAttachments:this.imageAttachments,popImage:this.handlePopImage,onImageClick:this.handleImageClick,previousThreadId:this.previousThreadIdForHint&&(X.mainThread?.messages.length??0)===0?this.previousThreadIdForHint:void 0,onPreviousThreadHintAccepted:()=>{let t=this.previousThreadIdForHint;if(t)this.setState(()=>{this.previousThreadIdForHint=null}),this.textController.text=`following: @${t} `},onDoubleAtTrigger:(t)=>{this.handleDoubleAtTrigger(t)},pendingSkills:this.pendingSkills,onClearPendingSkill:(t)=>{this.widget.dependencies.activeThreadHandle.removePendingSkill(t)},popSkill:()=>{let t=this.pendingSkills[this.pendingSkills.length-1];if(t)this.widget.dependencies.activeThreadHandle.removePendingSkill(t.name)},onSkillClick:this.handleSkillClick,topWidget:this.isShowingShortcutsHelp?new od0({submitOnEnter:this.submitOnEnter}):void 0}),w=X.mainThread?.queuedMessages??[],N=Array.isArray(V)&&V.length>0,O=Array.isArray(w)&&w.length>0,E=this.widget.dependencies.threadPool,L=E.isDTWMode?.()===!0,M=O?new ad0({queuedMessages:w,onInterruptQueuedMessage:L?(t)=>this.widget.dependencies.activeThreadHandle.interruptQueuedMessage?.(t):void 0}):void 0,A=N?this.buildScrollableTodoList(V,this.isTextfieldAndAutocompleteFocused&&!D,Y):void 0,I=[],P=null,_=0,S=F.capabilities.emojiWidth,y=L?E.getTransportConnectionState?.():void 0;if(L&&y!==void 0)I.push({child:new $0({text:new C(`(dtw: ${y})`,new h({color:Q.mutedForeground,dim:!0}))}),position:"top-left"});let m=this.currentShellModeStatus;if(m)I.push({child:new $0({text:new C(m==="hidden"?"shell mode (incognito)":"shell mode",new h({color:m==="hidden"?Y.app.shellModeHidden:Y.app.shellMode}))}),position:"top-left"});if(this.handoffState.isInHandoffMode){let t=new h({color:Y.app.handoffMode}),V0=this.handoffState.isGeneratingHandoff&&this.handoffState.spinner?new C("",void 0,[new C("handoff ",t),new C(this.handoffState.spinner.toBraille(),t)]):new C("handoff (submit a goal for the new thread)",t);if(I.push({child:new $0({text:V0}),position:"top-left"}),this.handoffState.isGeneratingHandoff){let N0=new h({color:Q.foreground,dim:!0});I.push({child:new $0({text:new C("",void 0,[new C("Esc",new h({color:Y.app.keybind})),new C(" to cancel",N0)])}),position:"bottom-left"}),_=p5("Esc to cancel",S)}}if(this.handoffState.countdownSeconds!==null){let t=new h({color:Q.foreground,dim:!0}),V0=`Auto-submitting in ${this.handoffState.countdownSeconds}s`,N0=this.handoffState.countdownSeconds<10?1:0;I.push({child:new i0({padding:C0.only({right:N0}),child:new $0({text:new C(V0,new h({color:Y.app.handoffMode}))})}),position:"bottom-left"}),I.push({child:new $0({text:new C("",void 0,[new C("type",new h({color:Y.app.keybind})),new C(" to edit",t)])}),position:"bottom-left"}),_=p5("Auto-submitting in 10s",S)+2+p5("type to edit",S)}if(this.isInQueueMode){let t=new h({color:Y.app.queueMode});I.push({child:new $0({text:new C("queue",t)}),position:"top-left"})}let b=this.handoffController?.getEmptyHandoffParentThreadID(this.widget.dependencies.threadState.mainThread)??null,k=F.capabilities.animationSupport,f=k==="disabled"?0:k==="slow"?30:60,p=this.getEffectiveAgentMode(),l=rg(p),x=null,r=null,c=!1,s=this.agentModeController?.getVisibleModes()??[];if(!m&&!this.isInQueueMode&&s.length>1){let t=this.previewThread,V0=this.agentModeController?.getMode(),N0=t?t.agentMode??this.getEffectiveAgentMode():this.handoffState.isGeneratingHandoff&&V0?V0:this.getEffectiveAgentMode(),D0=this.formatAgentModeLabel(N0),O0=N0==="smart"&&this.anthropicSpeed==="fast",_0=rb(this.openAISpeed,y6(this.authStatus)?this.authStatus.features:this.tuiContext.features),e0=uK(N0)&&_0==="fast",a0=O0?"+fast(6x$)":e0?"+fast(2x$)":void 0,F1=a0?`${D0}${a0}`:D0,a1=rg(N0),o1=t??this.widget.dependencies.threadState.mainThread,m0=o1?W3(o1)>0:!1,V1="top-right";if(t){x=p5(F1,S);let t0=a0?new C("",void 0,[new C(D0,new h({color:a1})),new C(a0,new h({color:Q.warning}))]):new C(D0,new h({color:a1}));I.push({child:new $0({text:t0}),position:"top-right"})}else{let t0=!m0&&!this.handoffState.isGeneratingHandoff,A1=this.handoffState.isGeneratingHandoff,$4=new h({color:a1,dim:A1}),D6=new $0({text:a0?new C("",void 0,[new C(D0,$4),new C(a0,new h({color:Q.warning,dim:A1}))]):new C(D0,$4)}),m1=p5(F1,S),y4=t0?new n1({child:D6,onClick:()=>this.toggleAgentMode(),cursor:"pointer"}):D6,b4=[];if(x=m1,N0==="deep"&&!m0&&!this.handoffState.isGeneratingHandoff&&this.deepModeEffortHintController.isVisibleOrFalling()){let X4=this.deepModeEffortHintController.getHintWidth(S),S5=3;c=this.deepModeEffortHintController.isVisible()&&this.deepModeEffortHintController.isShimmering();let X6=this.deepModeEffortHintController.isVisible()&&!c?new $0({text:this.deepModeEffortHintController.buildVisibleTextSpan(Q.foreground)}):new R0({width:X4});b4.push(X6,new R0({width:3})),x+=X4+3,r=Q.foreground}if(b4.push(y4),this.showSkillsCountInPromptBar){let X4=this.availableSkillCountReady?this.availableSkillCount:this.widget.dependencies.skillService.listInstalled().length,S5=this.skillWarningCount>0||this.skillErrorCount>0,z1=`${S5?"⚠ ":""}${X4} ${m4(X4,"skill")}`,L4=2,T4=p5(z1,S);x+=2+T4;let i4=new h({color:S5?Q.warning:Q.foreground,dim:!S5});b4.push(new R0({width:2}),new n1({child:new $0({text:new C(z1,i4)}),onClick:()=>{this.setState(()=>{this.isShowingSkillListModal=!0})},cursor:"pointer"}))}I.push({child:new U1({mainAxisSize:"min",children:b4}),position:"top-right"})}}let a=f>0&&this.agentModePulseSeq>0&&!m&&!this.isInQueueMode&&!b&&s.length>1,F0=[];if(a){let V0=p2(p)?.uiHints?.fasterAnimation?3:1,N0=(x??0)+1,D0=N0>0?2+N0:1,O0=new x6({top:0,left:1,right:D0,height:1,child:new rp0({color:l,backgroundColor:Q.background,trigger:this.agentModePulseSeq,fps:f,speed:V0,trail:5,leftOffset:0,direction:"right-to-left"})});F0.push(O0)}if(c&&r&&x!==null){let t=this.deepModeEffortHintController.buildShimmerOverlay(x,r);if(t)F0.push(t)}if(this.deepModeEffortHintController.isFalling()&&r&&x!==null){let t=this.deepModeEffortHintController.buildFallingOverlay(x,r);if(t)F0.push(t)}if(F0.length>0)P=new x6({top:0,left:0,right:0,bottom:0,child:new i6({children:F0})});if(b&&this.handoffState.countdownSeconds===null){let t=this.handoffState.isConfirmingAbortHandoff?" again to abort ":" to abort ";I.push({child:new $0({text:new C("",void 0,[new C("Esc",new h({color:Y.app.keybind})),new C(t,new h({color:Q.foreground,dim:!0})),new C("handoff",new h({color:Y.app.handoffMode}))])}),position:"bottom-left"}),_=p5(`Esc${t}handoff`,S)}if(!b&&this.previousThreadIdForHint&&(X.mainThread?.messages.length??0)===0&&this.textController.text.trim()==="")I.push({child:new $0({text:new C("",void 0,[new C("press ",new h({color:Q.foreground,dim:!0})),new C("enter",new h({color:Y.app.keybind})),new C(" to reference the previous thread",new h({color:Q.foreground,dim:!0}))])}),position:"bottom-left"}),_=p5("press enter to reference the previous thread",S);let q0=X.mainThread?.env?.initial.trees?.[0]?.uri,Q0;if(q0)Q0=K1.parse(q0).fsPath;else Q0=process.cwd();let H0=this.toHomeRelative(Q0),i=this.shorten(H0),n=_>0?F.size.width-_-6:F.size.width-4,e=this.buildDisplayText(i,this.currentGitBranch||void 0,n,S);I.push({child:new $0({text:new C(e,new h({color:Q.foreground,dim:!0}))}),position:"bottom-right"});let J0=this.previewThread,Z0=this.widget.dependencies.threadState.mainThread;if((Z0?W3(Z0)>0:!1)&&!m&&!this.handoffState.isInHandoffMode&&!J0){let t=[],V0=new h({color:Q.foreground,dim:!0}),N0=new C(" · ",V0);if(G){let a0=G.totalInputTokens/G.maxInputTokens,F1=Math.round(a0*100),a1=Math.max(0,Math.min(F1,100)),o1=E$0(a0,G.maxInputTokens),m0=V0;if(o1==="danger")m0=new h({color:Q.destructive});else if(o1==="warning")m0=new h({color:Q.warning});else if(o1==="recommendation")m0=new h({color:Y.app.recommendation});if(t.length>0)t.push(N0);if(G.maxInputTokens>=1000){let V1=Math.round(G.maxInputTokens/1000);t.push(new C(`${a1}% of ${V1}k`,m0))}else t.push(new C(`${a1}%`,m0))}if(U&&this.threadCostInfo){let a0=nC(this.threadCostInfo,{colors:{foreground:Q.foreground},dim:!0});if(a0.length>0){if(t.length>0)t.push(N0);t.push(...a0)}}let D0=X.viewState,O0=D0.state==="active"?D0.turnStartTime:void 0,_0=D0.state==="active"?D0.turnElapsedMs:void 0,e0=null;if(X.mainThread?.agentMode==="deep"){let a0=O0?Date.now()-O0:_0;if(a0!==void 0){let F1=ru1(a0);e0=new $0({text:new C(F1,V0)})}}if(t.length>0||e0){let a0=[];if(t.length>0){let F1=new $0({text:new C("",void 0,t)});a0.push(U?new n1({child:F1,onClick:this.showContextDetailOverlay,cursor:"pointer"}):F1)}if(e0){if(t.length>0)a0.push(new $0({text:new C(" · ",V0)}));a0.push(e0)}I.push({child:new U1({mainAxisSize:"min",children:a0}),position:"top-left"})}}return new og0({leftChild:new T1({child:B}),rightChild1:M,rightChild2:A,maxHeight:K,overlayTexts:I,overlayLayer:P,backgroundColor:Q.background,borderColor:D||!this.isTextfieldAndAutocompleteFocused||this.handoffState.isGeneratingHandoff?Q.border:void 0,hasBanner:z,userHeight:this.bottomGridUserHeight,onInitializeHeight:(t)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(t,K)})},onDrag:(t)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(t.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let V0=Math.floor(t.localPosition.y)-this.bottomGridDragStartY,N0=Math.max(4,this.bottomGridDragStartHeight-V0),D0=Math.min(N0,K),O0=Math.floor(D0);if(this.bottomGridUserHeight!==O0)this.setState(()=>{this.bottomGridUserHeight=O0})},onDragRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null},enableResize:!z})}}function dM4(J){return J.resolvedTokenUsage}class cM4 extends d0{props;constructor(J){super();this.props=J}createState(){return new lM4}}class lM4 extends p0{viewportHeight=1;scrollListenerAttached=!1;initState(){if(!this.scrollListenerAttached)this.widget.props.controller.addListener(()=>{this.updateViewportHeight()}),this.scrollListenerAttached=!0}build(J){let{todos:Z,controller:Q,appTheme:Y}=this.widget.props;return new U1({crossAxisAlignment:"stretch",children:[new T1({child:new j6({controller:Q,autofocus:!1,child:new Zc0({todos:Z})})}),new u8({controller:Q,thumbColor:Y.app.scrollbarThumb,trackColor:Y.app.scrollbarTrack,getScrollInfo:()=>{let{maxScrollExtent:X,offset:V}=Q,K=this.viewportHeight,z=X+K;return{totalContentHeight:Math.max(z,0),viewportHeight:Math.max(K,1),scrollOffset:Math.max(V,0)}}})]})}updateViewportHeight(){let J=this.getViewportHeight();if(J!==this.viewportHeight)this.viewportHeight=J}getViewportHeight(){let J=this.context.findRenderObject();if(!J)return this.viewportHeight;let Z=(Y,X=0)=>{if(Y&&"size"in Y&&"children"in Y){let V=Y.children||[];for(let K of V){if(K&&"size"in K){let G=K.size;if(typeof G?.height==="number"&&G.height>0)return G.height}let z=Z(K,X+1);if(z>0)return z}}return 0},Q=Z(J);if(Q>0)return Q;if("size"in J){let Y=J.size;if(typeof Y?.height==="number"&&Y.height>0)return Y.height}return this.viewportHeight}}class iM4 extends d1{props;constructor(J){super();this.props=J}build(J){return new n1({child:new R0({height:1}),cursor:E5.NS_RESIZE,onDrag:(Z)=>{if(this.props.userHeight===void 0){let Y=J.findRenderObject()?.size.height??0;if(Y>0){this.props.onInitializeHeight(Y);return}}this.props.onDrag(Z)},onRelease:this.props.onRelease})}}function aM4(J){let Z=J.split(`
7500
+ `).length,B=Math.max(Math.min(H,q),3);this._viewportHeight=B;let w=new a3({markdown:Q.content}),N=new c0({constraints:new M1({maxHeight:B}),child:new U1({crossAxisAlignment:"stretch",children:[new T1({child:new j6({controller:this._scrollController,autofocus:!1,child:w})}),new u8({controller:this._scrollController,thumbColor:X.app.scrollbarThumb,trackColor:X.app.scrollbarTrack,getScrollInfo:()=>{let O=this._scrollController.maxScrollExtent,E=this._scrollController.offset,L=this._viewportHeight,M=O+L;return{totalContentHeight:Math.max(M,0),viewportHeight:Math.max(L,1),scrollOffset:Math.max(E,0)}}})]})});D.push(N),D.push(new R0({height:1}))}}else D.push(new $0({text:new C("(Loading skill details...)",new h({color:Y.foreground,dim:!0,italic:!0}))})),D.push(new R0({height:1}));if(Z.arguments)D.push(new $0({text:new C("",void 0,[new C("Arguments: ",new h({color:Y.foreground,dim:!0})),new C(Z.arguments,new h({color:Y.foreground}))])})),D.push(new R0({height:1}));let W=new u0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new $0({text:new C("",void 0,[new C(Z.name,new h({bold:!0,color:Y.success,underline:!0}))])}),new R0({height:1}),...D,new c7({options:this.getOptions(),onSelect:this.handleSelect,autofocus:!0,showDismissalMessage:!1,enableMouseInteraction:!0})]});return new k4({onKey:(H)=>{if(H.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"},child:new l1({child:new LH(new c0({constraints:new M1(G,G,0,F),decoration:{color:Y.background,border:u1.all(new v1(Y.success,1,"rounded"))},padding:C0.symmetric(2,1),child:W}))})})}}function Ns5(J,Z){if(J===Z)return!0;let Q=Object.keys(J),Y=Object.keys(Z);if(Q.length!==Y.length)return!1;for(let X of Q){if(!(X in Z))return!1;if(!Object.is(J[X],Z[X]))return!1}return!0}class td0 extends d0{stableProps;arePropsEqual;constructor({key:J,stableProps:Z,arePropsEqual:Q}){super(J?{key:J}:{});this.stableProps=Z,this.arePropsEqual=Q??Ns5}createState(){return new jJ0}}class jJ0 extends p0{cachedChild=null;build(J){let{stableProps:Z,arePropsEqual:Q}=this.widget,Y=this.cachedChild;if(Y&&Q(Y.props,Z))return Y.widget;let X=this.widget.buildStableChild(Z);return this.cachedChild={props:Z,widget:X},X}dispose(){this.cachedChild=null}}class ed0 extends td0{constructor(J){super({stableProps:J})}createState(){return new xM4}buildStableChild(J){let{threadID:Z,...Q}=J;return new qd({...Q,key:Z?new $3(`message-view-${Z}`):void 0})}}class xM4 extends jJ0{build(J){return super.build(J)}}H1();function Os5(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/3600000),X=Math.floor(Y/24),V=Math.floor(X/7),K=Math.floor(X/30);if(Y<1)return"Just now";if(Y<24)return`${Y}h ago`;if(X<7)return`${X}d ago`;if(V<=4)return`${V}w ago`;return`${K}mo ago`}class $c0{threadHistoryService;constructor(J){this.threadHistoryService=J}async fetchThreadSummaries(J="",Z){try{let Q=await new Promise((Y)=>{let X=this.threadHistoryService.observeThreadList(Z).subscribe((V)=>{X.unsubscribe(),Y(V)})});return{ok:!0,threads:this.formatThreadSummaries(Q,J,Z)}}catch(Q){return{ok:!1,errorMsg:Q instanceof Error?Q.message:"An unexpected error occurred"}}}observeThreadSummaries(J="",Z={}){return this.threadHistoryService.observeHistory().pipe(D1((Q)=>this.formatThreadSummaries(Q,J,Z)))}formatThreadSummaries(J,Z,Q={}){return J.filter((X)=>{if(X.mainThreadID)return!1;if(!Q.includeArchived&&X.archived)return!1;if(!Z.trim())return!0;let V=X.title?.toLowerCase()||"untitled",K=X.id.toLowerCase(),z=Z.toLowerCase();return V.includes(z)||K.includes(z)}).map((X)=>{let V=new Date(X.userLastInteractedAt),K=Os5(V),z=X.id.slice(-8),G=X.env?.initial.trees?.[0]?.uri;return{id:X.id,title:X.title||"Untitled",updatedAt:new Date(X.userLastInteractedAt).toISOString(),description:{timeAgo:K,title:X.title||"Untitled",shortThreadID:z},diffStats:X.summaryStats?.diffStats,workspaceURI:G,relationships:X.relationships,agentMode:X.agentMode,details:{messageCount:X.summaryStats?.messageCount},archived:X.archived}})}}h0();_4();_4();function fM4(J){let Z=fI1(J),Q=Array.from(Z.entries()).map(([V,K])=>({path:V,diffStats:K})),X=K2(J)?.totalInputTokens??0;return{filesAffected:Q,totalTokens:X}}class Jc0{currentId=null;current=null;statsCache=new Map;subscribeTimer=null;subscription=null;listeners=[];threadService=null;scrollController=new Y5;constructor(){}setThreadService(J){this.threadService=J}async select(J){if(!this.threadService){j.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId===J)return;this.cancelTimerAndSubscription(),this.currentId=J;let Z=await this.threadService.get(J);if(Z){if(this.currentId===J)this.current=Z,this.notifyListeners()}this.subscribeTimer=setTimeout(()=>{this.subscribeLive(J)},1000)}clear(){this.cancelTimerAndSubscription(),this.currentId=null,this.current=null,this.notifyListeners()}addListener(J){this.listeners.push(J)}removeListener(J){let Z=this.listeners.indexOf(J);if(Z!==-1)this.listeners.splice(Z,1)}getCurrentThread(){return this.current}getCurrentStats(){if(!this.current)return null;let J=this.statsCache.get(this.current.id);if(J&&J.version===this.current.v)return J.stats;let Z=fM4(this.current);return this.statsCache.set(this.current.id,{stats:Z,version:this.current.v}),Z}clearStatsCache(){this.statsCache.clear()}dispose(){this.cancelTimerAndSubscription(),this.clearStatsCache(),this.scrollController.dispose(),this.listeners=[]}subscribeLive(J){if(!this.threadService){j.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId!==J)return;this.subscription=this.threadService.observePatches(J).pipe(Qr()).subscribe((Z)=>{if(this.currentId===J)this.current=Z,this.notifyListeners()})}cancelTimerAndSubscription(){if(this.subscribeTimer)clearTimeout(this.subscribeTimer),this.subscribeTimer=null;if(this.subscription)this.subscription.unsubscribe(),this.subscription=null}notifyListeners(){for(let J of this.listeners)J(this.current)}}class Zc0 extends d0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new bM4}}class bM4 extends p0{build(J){let Q=f0.of(J).colors,{todos:Y,title:X="TODOs"}=this.widget.props;if(!Array.isArray(Y)||Y.length===0)return new R0({width:0,height:0});let V=Y.map((K)=>this.buildTodoItem(K,Q));return new c0({child:new i0({padding:C0.symmetric(1,0),child:new u0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new $0({text:new C(X,new h({bold:!0,color:Q.foreground}))}),...V]})})})}buildTodoItem(J,Z){let Q=this.getStatusIcon(J.status),Y=J.status==="completed",X=new h({bold:J.status==="in-progress",color:Z.foreground,dim:Y}),V=new h({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Z.foreground,dim:Y});return new U1({crossAxisAlignment:"start",children:[new $0({text:new C(Q,X)}),new R0({width:1}),new T1({child:new $0({text:new C(J.content,V)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}function hM4(J,Z){switch(J){case"update-available":return[new C("A newer Amp is available. Run ",new h({color:Z.foreground,dim:!0})),new C("amp update",new h({color:Z.warning}))];case"update-available-unrecognized-path":return[new C("A newer Amp is available.",new h({color:Z.foreground,dim:!0}))];case"update-available-brew":return[new C("A newer Amp is available. Run ",new h({color:Z.foreground,dim:!0})),new C("brew upgrade ampcode",new h({color:Z.warning}))];case"updated":return null;case"updated-with-warning":return[new C("Update complete, run ",new h({color:Z.foreground,dim:!0})),new C("amp update",new h({color:Z.warning})),new C(" to see warnings",new h({color:Z.foreground,dim:!0}))];case"update-error":return[new C("Update failed, run ",new h({color:Z.foreground,dim:!0})),new C("amp update",new h({color:Z.warning})),new C(" to see warnings",new h({color:Z.foreground,dim:!0}))];case"hidden":return null}}async function Ps5(J){return new Promise((Z)=>{Es5("git",["branch","--show-current"],{cwd:J},(Q,Y)=>{if(Q){Z(null);return}let X=Y.trim();Z(X||null)})})}function pM4(J){return"interrupt"in J&&J.interrupt===!0}class Qc0 extends d0{dependencies;constructor(J){super();this.dependencies=J}createState(){return new RJ0}}class RJ0 extends p0{get tuiContext(){return DZ.require(this.context)}debugThreadViewState=process.env.AMP_DEBUG_THREAD_VIEW==="1";lastThreadStatusDebugSignature=null;themeColors=null;themeApp=null;ideStatus=null;randomAd=null;adSubscription=null;adsDisabledBySetting=!1;adReadinessTimeout=null;threadLoadSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();hasShownWinPasteHookRecoveryWarning=!1;winPasteHookImageUnsubscribe=null;winPasteHookStateUnsubscribe=null;isConfirmingExit=!1;isExiting=!1;isConfirmingClearInput=!1;isConfirmingCancelProcessing=!1;statusMessage=null;statusMessageTimer=null;isShowingHelp=!1;isShowingShortcutsHelp=!1;isShowingContextAnalyzeModal=!1;isShowingSkillListModal=!1;skillListData=null;shortcutsHintUsed=!1;deepReasoningEffort="high";anthropicSpeed=void 0;openAISpeed=void 0;deepReasoningEffortSubscription=null;anthropicSpeedSubscription=null;openAISpeedSubscription=null;sessionState=bC;isShowingConsoleOverlay=!1;isShowingMCPStatusModal=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingContextDetailOverlay=!1;threadCostInfo=void 0;threadCostInfoThreadID=void 0;lastInferenceState=void 0;elapsedTimeTimer=null;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;cancelProcessingConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];pendingSkills=[];pendingSkillsSubscription=null;skillListSubscription=null;skillWarningsSubscription=null;skillErrorsSubscription=null;availableSkillCount=0;availableSkillCountReady=!1;showSkillsCountInPromptBar=!0;showSkillsCountInPromptBarSubscription=null;skillWarningCount=0;skillErrorCount=0;pendingApprovals=[];pendingApprovalsSubscription=null;submitOnEnter=!0;submitOnEnterSubscription=null;displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;isShowingPalette=!1;isShowingPromptHistoryPicker=!1;paletteShowOptions=null;paletteOnThreadMentionSelected=null;threadsForPicker=[];parentThreadTitles=new Map;parentThreadTitleLoadsInFlight=new Set;clustersForPicker=[];isLoadingThreads=!1;threadPreviewController=new Jc0;previewThread=null;todoScrollController=(()=>{let J=new Y5;return J.followMode=!1,J})();contextAnalyzeDeps=null;contextAnalyzeFromDTW=null;openContextAnalyzeModal=()=>{if(this.widget.dependencies.threadPool.isDTWMode?.()){let J=this.widget.dependencies.threadState.mainThread;if(!J)return;this.contextAnalyzeDeps=null,this.contextAnalyzeFromDTW=(Z)=>g30({ampURL:this.tuiContext.ampURL,configService:this.widget.dependencies.configService,threadID:J.id,workerURL:process.env.AMP_WORKER_URL,signal:Z}),this.setState(()=>{this.isShowingContextAnalyzeModal=!0});return}this.contextAnalyzeFromDTW=null,this.widget.dependencies.createSystemPromptDeps().then((J)=>{this.contextAnalyzeDeps=J,this.setState(()=>{this.isShowingContextAnalyzeModal=!0})})};filterThreadPickerByWorkspace=!0;currentGitBranch=null;messageViewFocusNode=new r4({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new r4({debugLabel:"AutocompleteFocus"});autocompleteFocusNodeListener=null;isTextfieldAndAutocompleteFocused=!1;hasReplayedEarlyInput=!1;submitDisabledHint=null;submitDisabledHintTimer=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;imagePreview=null;fileImagePreviewPath=null;painterImagePreview=null;painterSaveDialog=null;messageViewController=new AJ0;previewMessageViewController=new AJ0;handleMainMessageViewCopy=(J,Z)=>{this._handleTextCopy(J,Z)};handleMainMessageViewDismissFocus=()=>{if(this.setState(()=>{this.isMessageViewInSelectionMode=!1,this.imagePreview=null}),!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()};messageViewControllerUnsubscribe=null;lastEditingMessageOrdinal=null;skillPreview=null;cachedSkillForPreview=null;adActionModal=null;adInfoModal=null;adModalStack=[];newsFeedReader=null;newsFeedEntries=[];newsFeedSubscription=null;bottomGridUserHeight=void 0;bottomGridDragStartY=null;bottomGridDragStartHeight=null;parentThreadLinkAnchor=new hp;previousThreadIdForHint=null;handoffController=null;handoffState={isInHandoffMode:!1,isGeneratingHandoff:!1,isConfirmingAbortHandoff:!1,pendingHandoffPrompt:null,spinner:null,countdownSeconds:null};isInQueueMode=!1;pendingMCPServers=[];mcpTrustSubscription=null;pendingOAuthRequest=null;pendingAuthLogin=null;authStatus="pending";authStatusSubscription=null;authModalKeyInterceptorUnsubscribe=null;isCreatingAuthLoginSession=!1;queuedPromptAfterAuth=null;pendingInputDialog=null;pendingConfirmDialog=null;mcpServers=[];mcpServersSubscription=null;pluginInfos=[];pluginInfosSubscription=null;agentModeController=null;freeTierStatus={canUseAmpFree:!1,isDailyGrantEnabled:!1};agentModePulseSeq=0;lastEffectiveAgentMode="smart";deepModeEffortHintController=new vg0({getDeepReasoningEffort:()=>this.deepReasoningEffort,getEffectiveAgentMode:()=>this.getEffectiveAgentMode(),canShowHintInCurrentThread:()=>{let J=this.widget.dependencies.threadState.mainThread;return!!J&&W3(J)===0},requestRender:()=>{if(!this.mounted)return;this.setState(()=>{})},isMounted:()=>this.mounted});updateState="hidden";updateServiceSubscription=null;toastController=new x70;isMessageViewInSelectionMode=!1;threadBackStack=[];threadForwardStack=[];isShowingForkDeprecationModal=!1;mysteriousMessage=null;isShowingMysteriousMessageModal=!1;mysteriousMessageSubscription=null;mysterySequenceManager=null;mysterySequenceProgress=null;mysteryKeyInterceptorUnsubscribe=null;static MYSTERY_SEQUENCE=["ctrl+x","y","z"];splashOrbExplosion=null;splashOrbExplosionSeq=0;freeTierStatusSubscription=null;allConnectedThreadActivityStatusesSubscription=null;threadInitializationStatusSubscription=null;allConnectedThreadActivityStatuses={};threadInitializationMessage=null;threadTitlesSubscription=null;threadTitles={};pendingNavigationSubscription=null;pendingNavigationInFlightThreadID=null;pluginCommands=[];pluginCommandsSubscription=null;async initNewsFeed(){let J=async(Q)=>{return p3(Q,void 0,this.widget.dependencies.configService)},Z=Bm1();this.newsFeedReader=new Tg0(Z,J,"/news.rss"),this.newsFeedSubscription=this.newsFeedReader.stream().subscribe({next:(Q)=>{if(Q.length>0)this.setState(()=>{this.newsFeedEntries=[...Q,...this.newsFeedEntries]})},error:(Q)=>{j.error("News feed error:",Q)}})}bringAdModalToFront(J){this.adModalStack=this.adModalStack.filter((Z)=>Z!==J),this.adModalStack.push(J)}removeAdModalFromStack(J){this.adModalStack=this.adModalStack.filter((Z)=>Z!==J)}getTopAdModal(){for(let J=this.adModalStack.length-1;J>=0;J--){let Z=this.adModalStack[J];if(Z==="adAction"&&this.adActionModal)return Z;if(Z==="adInfo"&&this.adInfoModal)return Z}return null}dismissTopAdModal(){let J=this.getTopAdModal();if(!J)return!1;return this.setState(()=>{if(J==="adAction")this.adActionModal=null;if(J==="adInfo")this.adInfoModal=null;this.removeAdModalFromStack(J)}),!0}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}navigateBack=async()=>{if(this.threadBackStack.length===0)return;let J=this.widget.dependencies.threadState.mainThread?.id;if(!J)return;let Z=this.threadBackStack.pop();this.threadForwardStack.push(J),await this.switchToExistingThread(Z,{recordInNavigationHistory:!1})};navigateForward=async()=>{if(this.threadForwardStack.length===0)return;let J=this.widget.dependencies.threadState.mainThread?.id;if(!J)return;let Z=this.threadForwardStack.pop();this.threadBackStack.push(J),await this.switchToExistingThread(Z,{recordInNavigationHistory:!1})};onThreadSwitch(){this.handoffController?.resetUIState(),this.exitQueueMode(),this.isMessageViewInSelectionMode=!1,this.imagePreview=null}canInterruptQueuedInference(){let{activeThreadHandle:J,threadPool:Z,threadState:Q}=this.widget.dependencies,Y=Q.mainThread?.queuedMessages?.some((X)=>!pM4(X))??!1;return Z.queueOnSubmitByDefault&&Boolean(J.interruptQueuedMessage)&&Y&&gO(Q.viewState)}interruptNextQueuedMessage=async()=>{let{activeThreadHandle:J,threadState:Z}=this.widget.dependencies,Q=Z.mainThread?.queuedMessages?.find((Y)=>!pM4(Y))?.id;if(!Q||!J.interruptQueuedMessage)return;await J.interruptQueuedMessage(Q)};startAndSwitchToNewThread=async()=>{let J=this.widget.dependencies.threadState.mainThread?.id;if(J)this.recordNavigation(J);await this.widget.dependencies.threadPool.createThread(),this.setState(()=>{this.onThreadSwitch(),this.previousThreadIdForHint=J??null})};canChangeAgentModeInPromptEditor(){return(this.messageViewController.editingMessageOrdinal===0||this.handoffState.isInHandoffMode)&&!this.handoffState.isGeneratingHandoff}getEffectiveAgentMode(){if(!this.agentModeController)return"smart";return(this.canChangeAgentModeInPromptEditor()?this.agentModeController.getMode():null)??this.agentModeController.getEffectiveMode()}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(J.viewState.interactionState==="handoff")return!0;if(Boolean(J.viewState.inferenceState==="running"))return!0;return J.items.filter((Y)=>Y.type==="toolResult").filter((Y)=>Y.toolResult.run.status==="in-progress"||Y.toolResult.run.status==="queued").length>0}showSubmitDisabledHint(J){if(this.submitDisabledHintTimer)clearTimeout(this.submitDisabledHintTimer);this.setState(()=>{this.submitDisabledHint=J}),this.submitDisabledHintTimer=setTimeout(()=>{this.setState(()=>{this.submitDisabledHint=null}),this.submitDisabledHintTimer=null},3000)}getUIHint(){let J=this.themeColors?.colorScheme;if(!J)return null;let Z=this.themeApp;if(!Z)return null;if(this.submitDisabledHint)return new C(this.submitDisabledHint,new h({color:J.foreground,dim:!0}));if(this.isExiting)return new C("Exiting...",new h({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new C("",void 0,[new C("Ctrl+C",new h({color:Z.keybind})),new C(" again to exit",new h({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new C("",void 0,[new C("Esc",new h({color:Z.keybind})),new C(" again to clear input",new h({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new C("",void 0,[new C("Escape",new h({color:Z.keybind})),new C(" to close help",new h({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let U=this.getEffectiveAgentMode(),q=rg(U);return new C("",void 0,[new C("Images aren't supported in ",new h({color:J.warning,dim:!1})),new C(U,new h({color:q})),new C(" mode.",new h({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0){if(this.isConfirmingCancelProcessing)return new C("",void 0,[new C("Esc",new h({color:Z.keybind})),new C(" again to cancel",new h({color:J.foreground,dim:!0}))]);if(this.canInterruptQueuedInference())return new C("",void 0,[new C("Enter",new h({color:Z.keybind})),new C(" to interject",new h({color:J.foreground,dim:!0}))]);return new C("",void 0,[new C("Esc",new h({color:Z.keybind})),new C(" to cancel",new h({color:J.foreground,dim:!0}))])}let{threadState:Q}=this.widget.dependencies;if(this.statusMessage){if(this.debugThreadViewState)j.info("[tui-ui] footer status override",{source:"statusMessage",statusMessage:this.statusMessage,inferenceState:Q.viewState.state==="active"?Q.viewState.inferenceState:void 0});return new C(this.statusMessage,new h({color:J.foreground,dim:!0}))}let Y=hM4(this.updateState,J);if(Y){if(this.debugThreadViewState)j.info("[tui-ui] footer status override",{source:"updateState",inferenceState:Q.viewState.state==="active"?Q.viewState.inferenceState:void 0});return new C("",void 0,Y)}let X=this.getCurrentConfirmation(),V=dM4(Q),K=this.widget.dependencies.threadPool.getCompactionStatus?.(),z=new pp({threadViewState:Q.viewState,tokenUsage:V,thread:Q.mainThread??void 0,compactionState:K?.compactionState??"idle",waitingForConfirmation:!!X,showingEphemeralError:Boolean(Q.viewState.state==="active"&&Q.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandNoun:this.executingCommand?.noun??null,executingCommandVerb:this.executingCommand?.verb??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),G=gp(z);if(this.debugThreadViewState){let U=JSON.stringify({inferenceState:Q.viewState.state==="active"?Q.viewState.inferenceState:void 0,interactionState:Q.viewState.interactionState,statusType:G.type});if(U!==this.lastThreadStatusDebugSignature)this.lastThreadStatusDebugSignature=U,j.info("[tui-ui] footer thread status",JSON.parse(U))}let F=!this.shortcutsHintUsed||this.sessionState.launchCount<10;if(G.type==="none"&&!this.isShowingShortcutsHelp&&this.textController.text===""&&F)return new C("",void 0,[new C("?",new h({color:Z.keybind})),new C(" for shortcuts",new h({color:J.foreground,dim:!0}))]);return null}getParentThreadInfo(){let J=this.previewThread??this.widget.dependencies.threadState.mainThread;if(!J)return null;let Z=ck(J).filter((K)=>K.type==="fork"||K.type==="handoff");if(Z.length===0)return null;let Q=Z[0],Y=Q.threadID,X=this.threadsForPicker.find((K)=>K.id===Y);if(!X?.title)this.ensureParentThreadTitleLoaded(Y);let V=X?.title??this.parentThreadTitles.get(Y)??Y.slice(-8);return{type:Q.type==="handoff"?"handoff":"fork",title:V,threadID:Y}}ensureParentThreadTitleLoaded(J){if(this.parentThreadTitles.has(J)||this.parentThreadTitleLoadsInFlight.has(J))return;this.parentThreadTitleLoadsInFlight.add(J),this.widget.dependencies.threadService.getPrimitiveProperty(J,"title").then((Z)=>{if(!this.mounted||!Z)return;this.setState(()=>{this.parentThreadTitles.set(J,Z)})}).catch((Z)=>{j.debug("Failed to load parent thread title",{threadID:J,error:Z})}).finally(()=>{this.parentThreadTitleLoadsInFlight.delete(J)})}getThreadClusterForMinimap=(J)=>{let Z=this.clustersForPicker.find((Q)=>Q.threads.some((Y)=>Y.id===J));if(!Z||Z.threads.length<2)return null;return Z.threads.map((Q)=>({id:Q.id,title:Q.title,parentID:Q.parentID,updatedAt:Q.updatedAt,isActive:this.isThreadActivelyWorking(Q.id)}))};getCurrentThreadClusterForMinimap=()=>{let J=this.previewThread??this.widget.dependencies.threadState.mainThread;if(!J)return null;return this.getThreadClusterForMinimap(J.id)};enrichClustersWithActiveState=(J)=>{return J.map((Z)=>({...Z,threads:Z.threads.map((Q)=>({...Q,isActive:this.isThreadActivelyWorking(Q.id)}))}))};areRecordValuesEqual(J,Z){if(J===Z)return!0;let Q=Object.entries(J),Y=Object.entries(Z);if(Q.length!==Y.length)return!1;for(let[X,V]of Q){if(!Object.hasOwn(Z,X))return!1;if(!Object.is(V,Z[X]))return!1}return!0}getThreadViewStatesSnapshot(){let J={...this.allConnectedThreadActivityStatuses},Z=this.widget.dependencies.threadState.mainThread;if(Z)J[Z.id]=this.widget.dependencies.threadState.viewState;return J}isThreadActivelyWorking(J){return gO(this.allConnectedThreadActivityStatuses[J])}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}isStartupThreadLoading(){if(!this.tuiContext.startupThreadID)return!1;let{threadPool:J}=this.widget.dependencies;return J.hasPendingInitialization?.()===!0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Z,activeThreadHandle:Q}=this.widget.dependencies;if(!Z.mainThread?.id)return;let X=Z.mainThread?.messages.findIndex((V)=>V===J);if(X===void 0||X===-1)return;try{this.cancelBashInvocations(),await Q.cancelTurn(),await Q.restoreTo(X),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(V){j.error("Failed to edit message:",V)}};showForkDeprecationMessage=()=>{this.setState(()=>{this.isShowingForkDeprecationModal=!0})};dismissForkDeprecationModal=()=>{this.setState(()=>{this.isShowingForkDeprecationModal=!1})};handleMessageEditSubmit=async(J,Z,Q)=>{let{threadState:Y,activeThreadHandle:X}=this.widget.dependencies,V=Y.mainThread;if(!V)return;let K=V.messages.findIndex((F)=>F.messageId!==void 0&&F.messageId===J.messageId);if(K===-1)return;let z=K===0,G=z?this.agentModeController?.getMode()??V.agentMode??this.getEffectiveAgentMode():V.agentMode;if(this.shouldRequireAuthForPromptSubmit()){this.showSubmitDisabledHint("Sign in required before editing and resubmitting messages"),this.ensureAuthLoginSession();return}try{this.cancelBashInvocations(),await X.cancelTurn(),this.widget.dependencies.history.add(Z,process.cwd());let F=aH(Z);if(F&&X.invokeBashTool)await X.restoreTo(K),this.invokeBashCommand(F.cmd,{visibility:F.visibility});else{let U=[{type:"text",text:Z}];if(Q.length>0)U.push(...Q);let q=G;if(V.agentMode&&!z&&q!==V.agentMode){j.error(`Cannot edit message: This thread uses ${V.agentMode} mode. To change mode, create a new thread.`);return}await X.sendMessage({content:U,agentMode:q,editIndex:K})}this.scrollMessageViewToBottom()}catch(F){j.error("Failed to edit message:",F)}};getAffectedFiles=async(J)=>{let{activeThreadHandle:Z,threadState:Q}=this.widget.dependencies;try{let Y=Q.mainThread;if(!Y)return[];let X=Y.messages.findIndex((K)=>K===J);if(X===-1)return[];return(await Z.getFilesAffectedByTruncation(X)).map(b9)}catch(Y){return j.error("Failed to get affected files:",Y),[]}};textController=new i7;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new Y5);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Z=J.mainThread?.id;if(!Z)return;this.getMessageScrollController(Z).scrollToBottom()}_handleSelectionChanged=(J)=>{this.setState(()=>{})};updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Z=J.mainThread?.title;if(Z!==this.currentTitle){this.currentTitle=Z;let Q=process.cwd().replace(process.env.HOME||"","~"),Y=Z?`amp - ${Z} - ${Q}`:"";process.stdout.write(B90(Y))}}_handleTextCopy(J,Z){if(J&&J.length>0){let Q=Z?"Selection copied to clipboard":"Failed to copy selection to clipboard",Y=Z?"success":"error";this.toastController.show(Q,Y,2000)}}textFieldKey=new $3("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;paletteCommands;paletteConfig;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text;if(J==="")this.textController.resetScrollOffset();if(J!=="")this.deepModeEffortHintController.dismissForInteraction();if(this.handoffState.countdownSeconds!==null)this.handoffController?.stopCountdown();if(J==="/"&&!this.handoffState.isGeneratingHandoff){this.showCommandPalette(),this.textController.clear(),this.toastController.show("Use [[Ctrl-O]] to open the command palette","warning");return}let Z=aH(J),Q=J===""&&this.bottomGridUserHeight!==void 0,Y=this.handoffState.isInHandoffMode||!this.widget.dependencies.activeThreadHandle.invokeBashTool?void 0:Z?.visibility;this.setState(()=>{if(this.currentShellModeStatus=Y,Q)this.bottomGridUserHeight=void 0})};navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!1}),H6.instance.addPostFrameCallback(()=>{this.autocompleteFocusNode.requestFocus()})};handleIdeSelection=async(J,Z)=>{let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q&&this.isSameIdeConfig(Q,J)){this.dismissIdePicker();return}try{await this.connectToSelectedIde(J,Z)}catch(Y){let X=Y instanceof Error?Y.message:String(Y);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.dismissIdePicker()};isSameIdeConfig(J,Z){if(J.connection!==Z.connection||J.ideName!==Z.ideName||J.pid!==Z.pid||J.port!==Z.port||J.authToken!==Z.authToken||J.workspaceId!==Z.workspaceId)return!1;if(J.workspaceFolders.length!==Z.workspaceFolders.length)return!1;return J.workspaceFolders.every((Q)=>Z.workspaceFolders.includes(Q))}async connectToSelectedIde(J,Z){await this.widget.dependencies.ideClient.start(J,!0,Z)}previewControllerListener=(J)=>{this.setState(()=>{this.previewThread=J})};showStandaloneThreadPicker=()=>{this.showCommandPalette({type:"standalone",commandId:"continue",onSubmit:()=>{this.threadPreviewController.clear(),this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null}),H6.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette)this.autocompleteFocusNode.requestFocus()})},onCancel:()=>{this.exitApplication()}})};toggleThreadPickerWorkspaceFilter=()=>{this.setState(()=>{this.filterThreadPickerByWorkspace=!this.filterThreadPickerByWorkspace})};handleDoubleAtTrigger=(J)=>{let{text:Z,cursorPosition:Q}=J,X=Z.slice(0,Q).lastIndexOf("@@"),V=J!==this.textController;if(j.info("[handleDoubleAtTrigger] called",{isEditingPreviousMessage:V,text:Z,cursor:Q,atAtIndex:X}),V)this.setState(()=>{this.paletteOnThreadMentionSelected=(K)=>{let z=this.messageViewController.editingController;if(!z){j.warn("[paletteOnThreadMentionSelected] no editing controller found");return}this.insertThreadMention(z,K)}});else this.setState(()=>{this.paletteOnThreadMentionSelected=null});this.showCommandPalette({type:"standalone",commandId:"mention-thread",onBeforeExecute:V?void 0:()=>{if(X!==-1){let K=J.text,z=K.slice(0,X)+K.slice(X+2);J.text=z,J.cursorPosition=X}},onSubmit:()=>{this.setState(()=>{this.paletteOnThreadMentionSelected=null}),this.dismissPalette()},onCancel:()=>{this.setState(()=>{this.paletteOnThreadMentionSelected=null}),this.dismissPalette()}})};insertThreadMention(J,Z){let{text:Q,cursorPosition:Y}=J,V=Q.slice(0,Y).lastIndexOf("@@");if(V!==-1){let K=Q.slice(Y),z=K.length===0,G=`@${Z}${z?" ":""}`,F=Q.slice(0,V)+G+K,U=V+G.length;J.text=F,J.cursorPosition=U}else J.insertText(`@${Z} `)}showCommandPalette(J){if(this.handoffState.isGeneratingHandoff)return;let Z=!this.isShowingPalette;if(this.setState(()=>{if(this.isShowingPalette=Z,this.paletteShowOptions=Z?J??null:null,!Z)this.threadsForPicker=[],this.clustersForPicker=[],this.isLoadingThreads=!1}),Z)this.loadThreadsForPicker();else this.unloadThreadsForPicker()}isShowingStandalonePalette(){return this.isShowingPalette&&this.paletteShowOptions?.type==="standalone"}getPaletteCommands(){if(!this.paletteCommands){if(!this.paletteConfig)throw Error("Config not yet available");this.paletteCommands=new Np0(this.widget.dependencies.configService,(J)=>{this.setState(()=>{this.executingCommand=J})},()=>{this.setState(()=>{this.executingCommand=null})},this.paletteConfig)}return this.paletteCommands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new Lp0(this.widget.dependencies.fuzzyServer);return this.completionBuilder}unloadThreadsForPicker(){if(this.threadLoadSubscription)this.threadLoadSubscription.unsubscribe(),this.threadLoadSubscription=null;this.threadPreviewController.clearStatsCache(),this.widget.dependencies.threadHistoryService.resetCache()}dismissPalette=()=>{if(this.isExiting)return;this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.threadsForPicker=[],this.clustersForPicker=[],this.isLoadingThreads=!1}),this.unloadThreadsForPicker()};lastRootContext;getCommandPaletteContext=(J)=>{let{threadState:Z,recentThreadIDs:Q}=this.widget.dependencies;if(!Z.mainThread)return null;let Y=J??this.lastRootContext;if(!Y)return null;let X=K1.file(process.cwd()),V=g1(X);return{recentThreadIDs:Q,currentThreadID:Z.mainThread.id,contextFallback:Y,context:J,threadPool:this.widget.dependencies.threadPool,createSystemPromptDeps:this.widget.dependencies.createSystemPromptDeps,activeThreadHandle:this.widget.dependencies.activeThreadHandle,editorState:this.textController,isProcessing:this.isProcessing(),thread:Z.mainThread,ampURL:this.tuiContext.ampURL,threadService:this.widget.dependencies.threadService,configService:this.widget.dependencies.configService,skillService:this.widget.dependencies.skillService,openInEditor:this.openInEditor,takeImageAttachments:()=>{let K=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),K},setImageAttachments:(K)=>{this.setState(()=>{this.imageAttachments=K})},editorDispatch:(K)=>{switch(K.type){case"set-input":this.textController.clear(),this.textController.insertText(K.input);break;case"set-input-with-cursor":this.textController.clear(),this.textController.insertText(K.input),this.textController.cursorPosition=K.cursorPosition;break;case"insert-text":this.textController.insertText(K.text);break;case"clear":this.textController.clear();break}},submitMessage:(K)=>{this.onTextSubmitted(K).catch((z)=>{this.handleSubmitFlowError(z)})},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},openContextAnalyze:()=>{this.openContextAnalyzeModal()},openSkillList:()=>{this.setState(()=>{this.isShowingSkillListModal=!0})},settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.tuiContext.clientId,mcpService:this.widget.dependencies.mcpService,toolboxService:this.widget.dependencies.toolboxService,createThread:async()=>{await this.startAndSwitchToNewThread()},navigateBack:this.navigateBack,navigateForward:this.navigateForward,canNavigateBack:this.threadBackStack.length>0,canNavigateForward:this.threadForwardStack.length>0,canUseAmpFree:this.freeTierStatus.canUseAmpFree,isDailyGrantEnabled:this.freeTierStatus.isDailyGrantEnabled,switchToThread:async(K)=>{await this.switchToExistingThread(K),this.setState(()=>{this.isMessageViewInSelectionMode=!1,this.imagePreview=null});return},handleHandoff:async(K,z)=>{let{goal:G,images:F}=z;if(!G)return{ok:!1,error:Error("Goal is required")};try{let U=this.widget.dependencies.threadState.mainThread;if(!U)return{ok:!1,error:Error("No active thread")};let q=setTimeout(()=>K.abort(new uT("Handoff took too long and was aborted (timeout: 60s)")),60000);try{let D=await this.widget.dependencies.threadPool.createHandoff(U.id,{goal:G,images:F,agentMode:U.agentMode,queuedMessages:U.queuedMessages?[...U.queuedMessages]:void 0,signal:K.signal});return clearTimeout(q),await this.switchToExistingThread(D),{ok:!0}}catch(D){if(clearTimeout(q),D instanceof Error&&(D.name==="AbortError"||D.message.includes("aborted")))throw K.signal.reason;throw D}}catch(U){return j.error("Failed to create handoff thread",{error:U}),{ok:!1,error:U instanceof Error?U:Error(String(U))}}},getGuidanceFiles:(K)=>{return this.widget.dependencies.activeThreadHandle.getGuidanceFiles(K)},openIdePicker:()=>{this.openIdePicker()},openPromptHistoryPicker:()=>{this.setState(()=>{this.isShowingPromptHistoryPicker=!0})},getAgentMode:()=>{return this.agentModeController?.getMode()??null},setAgentMode:(K)=>{this.agentModeController?.setMode(K)},toggleAgentMode:this.toggleAgentMode,toggleDeepReasoningEffort:this.toggleDeepReasoningEffort,getEffectiveAgentMode:()=>this.getEffectiveAgentMode(),getEditorText:()=>this.textController.text,userEmail:y6(this.authStatus)?this.authStatus.user.email:void 0,workspace:this.tuiContext.workspace??null,completionBuilder:this.getCompletionBuilder(),threads:this.threadsForPicker,clusters:this.enrichClustersWithActiveState(this.clustersForPicker),previewController:this.threadPreviewController,isLoadingThreads:this.isLoadingThreads,filterByWorkspace:this.filterThreadPickerByWorkspace,currentWorkspace:V,threadViewStates:this.getThreadViewStatesSnapshot(),newsFeedEntries:this.newsFeedEntries,showMCPStatusModal:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!0})},internalAPIClient:this.widget.dependencies.internalAPIClient,features:y6(this.authStatus)?this.authStatus.features:this.tuiContext.features,showStatusMessage:(K,z=2000)=>{this.showStatusMessage(K,z)},showToast:(K,z="success",G)=>{this.toastController.show(K,z,G)},getThemeName:()=>LB4(Y).themeName,isMessageViewInteractionActive:this.isMessageViewInSelectionMode||this.messageViewController.editingMessageOrdinal!==null,enterHandoffMode:this.enterHandoffMode,isInHandoffMode:this.handoffState.isInHandoffMode,enterQueueMode:this.enterQueueMode,submitQueue:this.submitQueue,isInQueueMode:this.isInQueueMode,addPendingSkill:(K)=>{this.widget.dependencies.activeThreadHandle.addPendingSkill(K)},onThreadMentionSelected:this.paletteOnThreadMentionSelected??void 0,canChangeAgentModeInPromptEditor:()=>this.canChangeAgentModeInPromptEditor(),pluginCommands:this.pluginCommands,executePluginCommand:this.widget.dependencies.pluginService?(K,z,G)=>this.widget.dependencies.pluginService.commands.execute(K,z,{threadID:G}):void 0,reloadPlugins:this.widget.dependencies.pluginService?()=>this.widget.dependencies.pluginService.reload():void 0,pluginService:this.widget.dependencies.pluginService}};loadThreadsForPicker(){if(this.threadLoadSubscription)return;this.setState(()=>{this.isLoadingThreads=!0});let J=new $c0(this.widget.dependencies.threadHistoryService);this.threadLoadSubscription=J.observeThreadSummaries("",{includeArchived:!0}).subscribe({next:(Z)=>{this.setState(()=>{this.threadsForPicker=Z,this.clustersForPicker=_O4(Z),this.isLoadingThreads=!1})},error:()=>{this.setState(()=>{this.isLoadingThreads=!1})}})}updateGitBranch=async()=>{let J=await Ps5(process.cwd());this.setState(()=>{this.currentGitBranch=J})};removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Z)=>Z.id!==J)})};invokeBashCommand=(J,{visibility:Z})=>{if(!this.widget.dependencies.activeThreadHandle.invokeBashTool)return;let Q=Date.now(),Y=`bash-${Q}-${Math.random().toString(36).substring(7)}`,X={cmd:J},V=new AbortController;this.widget.dependencies.activeThreadHandle.invokeBashTool(X,{hidden:Z===nH,abortController:V}).subscribe({next:(K)=>{this.setState(()=>{if(this.bashInvocations.find((G)=>G.id===Y))this.bashInvocations=this.bashInvocations.map((G)=>G.id===Y?{...G,toolRun:K}:G);else{let G={id:Y,args:X,toolRun:K,startTime:Q,abortController:V,hidden:Z===nH};this.bashInvocations=[...this.bashInvocations,G]}})},error:()=>this.removeBashInvocation(Y),complete:()=>this.removeBashInvocation(Y)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Z)=>Z.toolRun.status==="in-progress");if(J)J.abortController.abort()};showContextDetailOverlay=()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!0}),this.fetchThreadCostInfo()};fetchThreadCostInfo=uB4(()=>{let J=this.widget.dependencies.threadState.mainThread?.id;if(!J)return;this.widget.dependencies.internalAPIClient.threadDisplayCostInfo({threadID:J},{config:this.widget.dependencies.configService}).then((Z)=>{if(Z.ok)this.setState(()=>{this.threadCostInfo=Z.result,this.threadCostInfoThreadID=J})}).catch(()=>{this.setState(()=>{this.threadCostInfo=void 0,this.threadCostInfoThreadID=J})})},150);maybeRefetchThreadCostInfo=(J)=>{let Z=this.lastInferenceState==="running",Q=J==="running",Y=J==="idle"&&Z,X=Q&&!Z;if(Y)this.fetchThreadCostInfo();if(X)this.startElapsedTimeTimer();else if(Z&&!Q)this.stopElapsedTimeTimer();this.lastInferenceState=J};startElapsedTimeTimer=()=>{if(this.elapsedTimeTimer)return;this.elapsedTimeTimer=setInterval(()=>{let J=this.widget.dependencies.threadState.viewState;if(!(J.state==="active"&&J.inferenceState==="running")){this.stopElapsedTimeTimer();return}this.setState(()=>{})},1000)};stopElapsedTimeTimer=()=>{if(this.elapsedTimeTimer)clearInterval(this.elapsedTimeTimer),this.elapsedTimeTimer=null};toggleAgentMode=()=>{if(!this.agentModeController)return;if(this.handoffState.isGeneratingHandoff)return;let J=this.canChangeAgentModeInPromptEditor();if(this.agentModeController.toggle(J))this.setState(()=>{this.showImageUnsupportedHint=!1,this.agentModePulseSeq++})};handleMessageViewControllerUpdate=()=>{let J=this.messageViewController.editingMessageOrdinal;if(J===this.lastEditingMessageOrdinal)return;if(this.lastEditingMessageOrdinal===0&&J!==0){let Y=this.agentModeController;if(!Y){this.lastEditingMessageOrdinal=J,this.setState(()=>{});return}if(Y.getMode()!==null)Y.setMode(null)}this.lastEditingMessageOrdinal=J,this.setState(()=>{})};showStatusMessage(J,Z=2000){if(this.statusMessageTimer)clearTimeout(this.statusMessageTimer);this.setState(()=>{this.statusMessage=J}),this.statusMessageTimer=setTimeout(()=>{this.setState(()=>{this.statusMessage=null}),this.statusMessageTimer=null},Z)}applyDeepReasoningEffort(J){this.deepReasoningEffort=J,u$("agent.deepReasoningEffort",J)}commitDeepReasoningEffort(J){let Z=this.deepReasoningEffort;if(this.applyDeepReasoningEffort(J),J===Z)return Promise.resolve(!0);return this.widget.dependencies.configService.updateSettings("agent.deepReasoningEffort",J,"global").then(()=>!0).catch((Q)=>{return this.applyDeepReasoningEffort(Z),j.error("Failed to persist deep reasoning setting",{error:Q}),this.showStatusMessage("Failed to save deep reasoning effort"),!1})}getNextDeepReasoningEffort(J){return J==="medium"?"high":J==="high"?"xhigh":"medium"}toggleDeepReasoningEffort=async()=>{if(this.deepModeEffortHintController.dismissForInteraction(),this.getEffectiveAgentMode()!=="deep"){this.showStatusMessage("Deep reasoning effort is only available in deep mode");return}let Z=this.widget.dependencies.threadState.mainThread;if(!Z)return;if(W3(Z)>0){this.showStatusMessage("Deep reasoning effort can only be toggled before the first message");return}let Q=this.getNextDeepReasoningEffort(this.deepReasoningEffort);if(!await this.commitDeepReasoningEffort(Q))return;this.showStatusMessage(`Deep reasoning effort: ${Q}`),this.setState(()=>{this.agentModePulseSeq++})};formatAgentModeLabel(J){if(J!=="deep")return J;if(this.deepReasoningEffort==="high")return"deep²";if(this.deepReasoningEffort==="xhigh")return"deep³";return"deep"}handleInsertImage=async(J)=>{let Z=this.getEffectiveAgentMode();if(!vk(Z)){if(this.imageUnsupportedHintTimer)clearTimeout(this.imageUnsupportedHintTimer);return this.setState(()=>{this.showImageUnsupportedHint=!0}),this.imageUnsupportedHintTimer=setTimeout(()=>{this.setState(()=>{this.showImageUnsupportedHint=!1}),this.imageUnsupportedHintTimer=null},5000),!1}if(this.imageAttachments.length>=BI)return!1;let Q=await vT(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q]}),!1;return this.setState(()=>{this.displayMessage=Error(`Failed to attach image: ${Q}`)}),!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};handleImageClick=(J)=>{let Z=this.imageAttachments[J];if(Z)this.setState(()=>{this.imagePreview={image:Z,index:J,onRemove:()=>{let Q=this.imageAttachments.indexOf(Z);if(Q!==-1)this.setState(()=>{this.imageAttachments=this.imageAttachments.filter((Y,X)=>X!==Q),this.imagePreview=null})}}})};handleImagePreviewDismiss=()=>{this.setState(()=>{this.imagePreview=null})};handleShowFileImagePreview=(J)=>{this.setState(()=>{this.fileImagePreviewPath=J})};handleFileImagePreviewDismiss=()=>{this.setState(()=>{this.fileImagePreviewPath=null})};handleShowPainterImagePreview=(J,Z)=>{this.setState(()=>{this.painterImagePreview={image:J,filePath:Z}})};handlePainterImagePreviewDismiss=()=>{this.setState(()=>{this.painterImagePreview=null})};handleShowPainterSaveDialog=(J,Z)=>{this.setState(()=>{this.painterSaveDialog={image:J,filePath:Z}})};handlePainterSaveDialogDismiss=()=>{this.setState(()=>{this.painterSaveDialog=null})};handleSkillClick=(J)=>{let Z=this.pendingSkills[J];if(Z)this.setState(()=>{this.cachedSkillForPreview=null,this.skillPreview={skillIndex:J,onRemove:()=>{this.widget.dependencies.activeThreadHandle.removePendingSkill(Z.name),this.setState(()=>{this.skillPreview=null,this.cachedSkillForPreview=null})}}}),this.widget.dependencies.skillService.getSkills().then((Q)=>{let Y=Q.find((X)=>X.name===Z.name)??null;if(this.skillPreview!==null)this.setState(()=>{this.cachedSkillForPreview=Y})})};handleSkillPreviewDismiss=()=>{this.setState(()=>{this.skillPreview=null,this.cachedSkillForPreview=null})};handleShowEditingImagePreview=(J,Z,Q)=>{this.setState(()=>{this.imagePreview={image:J,index:Z,onRemove:Q}})};handleImagePreviewRemove=()=>{if(this.imagePreview)this.imagePreview.onRemove(),this.setState(()=>{this.imagePreview=null})};handleShowMysteryModal=()=>{if(this.mysteriousMessage)this.setState(()=>{this.isShowingMysteriousMessageModal=!0})};handleSplashOrbExplode=(J)=>{this.splashOrbExplosionSeq+=1,this.setState(()=>{this.splashOrbExplosion={seq:this.splashOrbExplosionSeq,originX:J.x,originY:J.y}})};handleSplashOrbExplosionComplete=()=>{if(!this.splashOrbExplosion)return;this.setState(()=>{this.splashOrbExplosion=null})};handleDestructMysteriousMessage=()=>{if(!this.mysteriousMessage)return;let J=this.mysteriousMessage.id;this.widget.dependencies.internalAPIClient.markAsReadMysteriousMessage({messageId:J},{config:this.widget.dependencies.configService}).then((Z)=>{if(!Z.ok)j.error("Failed to destruct mysterious message",Z.error);else this.setState(()=>{this.mysteriousMessage=null,this.isShowingMysteriousMessageModal=!1})}).catch((Z)=>{j.error("Failed to destruct mysterious message",Z)})};exitMessageViewInteraction=()=>{this.messageViewController.setSelectedUserMessageOrdinal(null),this.messageViewController.setIsShowingRestoreConfirmation(!1),this.messageViewController.setIsShowingEditConfirmation(!1),this.messageViewController.setPendingEditText(null),this.messageViewController.setPendingEditImageAttachments([]),this.messageViewController.setAffectedFiles([]),this.messageViewController.stopEditing(),this.setState(()=>{this.isMessageViewInSelectionMode=!1,this.imagePreview=null}),this.scrollMessageViewToBottom(),H6.instance.addPostFrameCallback(()=>{if(!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})};enterHandoffMode=()=>{this.dismissPalette(),this.exitMessageViewInteraction(),this.handoffController?.enter()};exitHandoffMode=()=>{this.handoffController?.exit()};submitHandoff=async(J)=>{let Z=this.imageAttachments;if(this.resetHistory(),!this.handoffController){this.showSubmitDisabledHint("Handoff controller not initialized");return}let Q=await this.handoffController.submit(J,Z,this.agentModeController?.getMode()??null);if(!Q.ok&&Q.error.message!=="Cancelled")this.displayMessage=Q.error,this.setState(()=>{});else if(Q.ok)this.setState(()=>{this.imageAttachments=[]}),setTimeout(()=>{this.handoffController?.startCountdown(()=>{this.autoSubmitHandoffDraft().catch((Y)=>{this.handleSubmitFlowError(Y)})})},0)};autoSubmitHandoffDraft=async()=>{let J=this.textController.text;if(J.trim())this.textController.clear(),await this.sendUserMessage(J)};enterQueueMode=()=>{this.dismissPalette(),this.exitMessageViewInteraction(),this.setState(()=>{this.isInQueueMode=!0})};exitQueueMode=()=>{this.setState(()=>{this.isInQueueMode=!1})};submitQueue=(J)=>{this.exitMessageViewInteraction();let{threadState:Z}=this.widget.dependencies;if((Z.mainThread?.queuedMessages?.length??0)>=l00){this.toastController.show(`Queue is full (max ${l00} messages)`,"error",3000);return}let Y=this.imageAttachments;this.resetHistory(),this.setState(()=>{this.imageAttachments=[]}),this.textController.clear();let X=[{type:"text",text:J}];if(Y.length>0)X.push(...Y);this.widget.dependencies.activeThreadHandle.queueMessage(X),this.exitQueueMode()};isAuthRequiredStatus(J){if(!RD(J))return!1;let Z=J.error.message.toLowerCase();return Z.includes("user not found")||Z.includes("auth-required")||Z.includes("unauthorized")||Z.includes("forbidden")||Z.includes("401")||Z.includes("403")||Z.includes("api key")||Z.includes("access token")}shouldRequireAuthForPromptSubmit(){if(!this.tuiContext.hasAPIKeyAtStartup&&!y6(this.authStatus))return!0;return this.isAuthRequiredStatus(this.authStatus)&&!y6(this.authStatus)}queuePromptUntilAuthenticated(J,Z=[...this.imageAttachments],Q){if(this.queuedPromptAfterAuth={text:J,images:Z},Q?.clearInput??!0)this.textController.clear(),this.textController.resetScrollOffset(),this.resetHistory(),this.setState(()=>{this.imageAttachments=[]});this.showStatusMessage("Sign in required. Prompt queued and will send after login.",2500),this.ensureAuthLoginSession()}ensureAuthLoginSession=async()=>{if(this.pendingAuthLogin||this.isCreatingAuthLoginSession||y6(this.authStatus))return;this.isCreatingAuthLoginSession=!0;try{let J=mM4(32).toString("hex"),Z=await yC(this.tuiContext.ampURL,J),Q=await yC(this.tuiContext.ampURL,J,!1),Y=new AbortController;this.setState(()=>{this.pendingAuthLogin={authToken:J,browserURL:Z,manualURL:Q,abortController:Y,isOpeningBrowser:!1,isAuthenticating:!0,errorMessage:null}}),uK4(this.tuiContext.ampURL,J,this.widget.dependencies.secretStorage,Y).then(()=>{this.showStatusMessage("Login successful",2000),this.checkAuthStatusAfterLogin()}).catch((X)=>{if(Y.signal.aborted)return;let V=X instanceof Error?X.message:"Login failed. Please try again.";this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage=V,this.pendingAuthLogin.isAuthenticating=!1})})}catch(J){let Z=J instanceof Error?J.message:"Unable to start login flow. Please try again.";this.setState(()=>{if(!this.pendingAuthLogin){this.displayMessage=Error(Z);return}this.pendingAuthLogin.errorMessage=Z,this.pendingAuthLogin.isAuthenticating=!1})}finally{this.isCreatingAuthLoginSession=!1}};openAuthLoginBrowser=async()=>{if(!this.pendingAuthLogin)return;let J=this.pendingAuthLogin.browserURL,Z=this.pendingAuthLogin.abortController;this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.isOpeningBrowser=!0,this.pendingAuthLogin.errorMessage=null});try{await fX(J,Z.signal)}catch(Q){let Y=Q instanceof Error?Q.message:"Unable to open browser. Copy the manual link.";this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage=Y})}finally{this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.isOpeningBrowser=!1})}};copyAuthLoginLink=async()=>{let J=this.pendingAuthLogin?.manualURL;if(!J)return;try{await l4.instance.tuiInstance.clipboard.writeText(J),this.showStatusMessage("Login link copied to clipboard",2000)}catch(Z){j.error("Failed to copy login link",{error:Z}),this.showStatusMessage("Failed to copy login link",2000)}};checkAuthStatusAfterLogin=async()=>{try{let J=await this.widget.dependencies.configService.getLatest(),Z=_k(J),Q=await this.widget.dependencies.internalAPIClient.getUserInfo({},{config:this.widget.dependencies.configService,signal:AbortSignal.timeout(Z)});if(!Q.ok){this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage="Still waiting for login confirmation. Finish login in your browser, then press I again."});return}this.setState(()=>{this.authStatus={user:Q.result,features:Q.result.features,workspace:Q.result.team,mysteriousMessage:Q.result.mysteriousMessage},this.pendingAuthLogin=null}),await this.maybeResumeQueuedPromptAfterAuth()}catch(J){j.error("Failed to verify login state",{error:J}),this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage="Unable to verify login yet. Press I again in a moment."})}};cancelAuthLoginSession=()=>{if(this.pendingAuthLogin)this.pendingAuthLogin.abortController.abort(Error("Authentication cancelled"));this.setState(()=>{this.pendingAuthLogin=null})};maybeResumeQueuedPromptAfterAuth=async()=>{if(!y6(this.authStatus))return;let J=this.queuedPromptAfterAuth;if(!J)return;this.queuedPromptAfterAuth=null,await this.proceedWithUserMessage(J.text,J.images)};handleAuthModalKey=(J)=>{if(!this.pendingAuthLogin||this.pendingInputDialog)return!1;let Z=J.key.length===1?J.key.toLowerCase():J.key;if(Z==="Enter"||Z==="o")return this.openAuthLoginBrowser(),!0;if(Z==="c")return this.copyAuthLoginLink(),!0;if(Z==="i")return this.checkAuthStatusAfterLogin(),!0;if(Z==="p")return this.promptForAuthLoginCode(),!0;return!1};promptForAuthLoginCode=async()=>{if(!this.pendingAuthLogin)return;let{authToken:J,abortController:Z}=this.pendingAuthLogin,Q=await new Promise((Y)=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.pendingInputDialog={options:{title:"Paste Login Code",helpText:"Paste the login code from the browser page. This is not your API key.",submitButtonText:"Verify"},resolve:Y}})});if(!Q||!this.pendingAuthLogin)return;try{let{accessToken:Y}=nx0(Q,J);await this.widget.dependencies.secretStorage.set("apiKey",Y,this.tuiContext.ampURL),Z.abort(Error("Authentication completed from pasted code")),this.showStatusMessage("Login code accepted",2000),await this.checkAuthStatusAfterLogin()}catch(Y){let X=Y instanceof Error?Y.message:"Invalid login code.";this.setState(()=>{if(!this.pendingAuthLogin)return;this.pendingAuthLogin.errorMessage=X,this.pendingAuthLogin.isAuthenticating=!1})}};openInEditor=async(J)=>{try{let Z=await Ls5(wG.join(Rs5(),"amp-edit-")),Q=wG.join(Z,"message.amp.md");await Is5(Q,J,"utf-8"),await oY(Q);try{let Y=await Ms5(Q,"utf-8");this.textController.text=Y}catch(Y){if(Y?.code!=="ENOENT")j.error("Failed to read temporary file",Y)}try{await gM4(Q),await As5(Z)}catch(Y){j.warn("Failed to clean up temporary file",Y)}}catch(Z){j.error("Error opening editor:",Z)}};onTextSubmitted=async(J)=>{if(!J.trim()&&this.imageAttachments.length===0){if(!this.canInterruptQueuedInference())return;try{await this.interruptNextQueuedMessage();return}catch(Y){j.error("Failed to interrupt queued message from empty submit",Y)}return}let Z=J.trim();if(Z===":q"){this.widget.dependencies.setExitNotice?.("Vim reflex detected. Exiting politely."),await this.exitApplication();return}if(Z==="exit"||Z==="quit"){await this.exitApplication();return}if(this.handoffState.isInHandoffMode){await this.submitHandoff(J);return}if(this.isInQueueMode){this.submitQueue(J);return}let Q=aH(J);if(Q&&this.widget.dependencies.activeThreadHandle.invokeBashTool)if(!Q.cmd){this.showSubmitDisabledHint("No command provided");return}else if(this.isProcessing()){this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}else{this.invokeBashCommand(Q.cmd,{visibility:Q.visibility}),this.widget.dependencies.history.add(J,process.cwd()),this.textController.clear(),this.textController.resetScrollOffset(),this.resetHistory();return}if(this.shouldRequireAuthForPromptSubmit()){this.queuePromptUntilAuthenticated(J);return}this.textController.clear(),this.textController.resetScrollOffset(),this.resetHistory(),await this.updateGitBranch(),await this.sendUserMessage(J)};agentModeListener=()=>{let J=this.agentModeController?.getMode(),Z=this.canChangeAgentModeInPromptEditor(),Q=this.widget.dependencies.threadState.mainThread;if(!Q)return;let Y=!Z&&J!==null&&W3(Q)>0&&Q.agentMode!==J;if(this.handoffState.countdownSeconds!==null)this.handoffController?.stopCountdown();if(!Z&&J&&J!==this.sessionState.agentMode)this.persistAgentMode(J);if(Y)this.agentModeController?.setMode(null);let X=this.lastEffectiveAgentMode,V=this.getEffectiveAgentMode();this.lastEffectiveAgentMode=V,this.deepModeEffortHintController.onAgentModeTransition(X,V),this.setState(()=>{})};handoffListener=(J)=>{this.setState(()=>{this.handoffState=J})};handleWinPasteHookImagePaste=async(J)=>{this.lastUserInteractionTime=Date.now();let Z=this.imageAttachments.length;try{await this.handleInsertImage(J.image.tempFile)}catch(Q){j.error("Failed to process win-paste-hook image paste event",{error:Q})}if(this.imageAttachments.length<=Z)await gM4(J.image.tempFile).catch(()=>{})};handleWinPasteHookStateChange=(J)=>{if(J.current!=="disabled_session"||this.hasShownWinPasteHookRecoveryWarning)return;this.hasShownWinPasteHookRecoveryWarning=!0,this.toastController.show('Windows clipboard hook unavailable. Open the command palette (Ctrl+O) and run "paste image from clipboard".',"warning",7000)};initState(){if(OQ.getInstance().interceptConsole(),this.threadPreviewController.setThreadService(this.widget.dependencies.threadService),this.threadPreviewController.addListener(this.previewControllerListener),this.handoffController=new yg0({getActiveThreadHandle:()=>this.widget.dependencies.activeThreadHandle,getThreadPool:()=>this.widget.dependencies.threadPool,switchToThread:(X)=>{return this.textController.clear(),this.switchToExistingThread(X)}}),this.handoffController.addListener(this.handoffListener),this.tuiContext.openThreadSwitcher)this.showStandaloneThreadPicker();l4.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),l4.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),l4.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()});let J=l4.instance.tuiInstance;if(this.winPasteHookImageUnsubscribe=J.onWinPasteHookImagePaste((X)=>{this.handleWinPasteHookImagePaste(X)}),this.winPasteHookStateUnsubscribe=J.onWinPasteHookStateChange((X)=>{this.handleWinPasteHookStateChange(X)}),this.authStatus=this.tuiContext.initialServerStatus,this.authStatusSubscription=nJ(this.widget.dependencies.configService).subscribe((X)=>{if(this.setState(()=>{if(this.authStatus=X,y6(X))this.pendingAuthLogin=null}),this.agentModeController?.updateVisibilityContext({userEmail:y6(X)?X.user.email:void 0}),y6(X)){this.maybeResumeQueuedPromptAfterAuth();return}if(this.isAuthRequiredStatus(X))this.ensureAuthLoginSession()}),this.authModalKeyInterceptorUnsubscribe=l4.instance.addKeyInterceptor((X)=>this.handleAuthModalKey(X)),!this.tuiContext.hasAPIKeyAtStartup)this.ensureAuthLoginSession();this.autocompleteFocusNodeListener=(X)=>{H6.instance.addPostFrameCallback(()=>{if(!this.mounted)return;this.setState(()=>{this.isTextfieldAndAutocompleteFocused=X.hasFocus})},"TuiUIState.autocompleteFocusNodeListener")},this.autocompleteFocusNode.addListener(this.autocompleteFocusNodeListener),this.sessionState=this.tuiContext.sessionState??bC,this.shortcutsHintUsed=this.sessionState.shortcutsHintUsed,this.messageViewControllerUnsubscribe??=this.messageViewController.subscribe(this.handleMessageViewControllerUpdate),Promise.all([this.tuiContext.freeTierStatusPromise??Promise.resolve(void 0),E1(this.widget.dependencies.configService.config)]).then(([X,V])=>{if(X)this.freeTierStatus=X;this.paletteConfig=V;let K=Jy(V.settings),z=V.settings["anthropic.speed"],G=V.settings["openai.speed"];this.showSkillsCountInPromptBar=V.settings["internal.cli.showSkillsCountInPromptBar"]!==!1,this.adsDisabledBySetting=V.settings.newAdsDisplay===!0,this.applyDeepReasoningEffort(K),this.anthropicSpeed=z,this.openAISpeed=G,this.deepReasoningEffortSubscription=this.widget.dependencies.configService.config.pipe(D1((F)=>Jy(F.settings)),M4()).subscribe((F)=>{if(F!==this.deepReasoningEffort)this.applyDeepReasoningEffort(F),this.setState(()=>{this.agentModePulseSeq++})}),this.anthropicSpeedSubscription=this.widget.dependencies.configService.config.pipe(D1((F)=>({settings:F.settings})),M4((F,U)=>F.settings["anthropic.speed"]===U.settings["anthropic.speed"])).subscribe(({settings:F})=>{let U=F["anthropic.speed"];if(U!==this.anthropicSpeed)this.anthropicSpeed=U,this.setState(()=>{this.agentModePulseSeq++})}),this.openAISpeedSubscription=this.widget.dependencies.configService.config.pipe(D1((F)=>({settings:F.settings})),M4((F,U)=>F.settings["openai.speed"]===U.settings["openai.speed"])).subscribe(({settings:F})=>{let U=F["openai.speed"];if(U!==this.openAISpeed)this.openAISpeed=U,this.setState(()=>{this.agentModePulseSeq++})}),this.showSkillsCountInPromptBarSubscription=this.widget.dependencies.configService.config.pipe(D1((F)=>({settings:F.settings})),M4((F,U)=>F.settings["internal.cli.showSkillsCountInPromptBar"]===U.settings["internal.cli.showSkillsCountInPromptBar"])).subscribe(({settings:F})=>{let U=F["internal.cli.showSkillsCountInPromptBar"]!==!1;if(U!==this.showSkillsCountInPromptBar)this.setState(()=>{this.showSkillsCountInPromptBar=U})}),this.submitOnEnter=V.settings.submitOnEnter??!0,this.submitOnEnterSubscription=this.widget.dependencies.configService.config.pipe(D1((F)=>({settings:F.settings})),M4((F,U)=>F.settings.submitOnEnter===U.settings.submitOnEnter)).subscribe(({settings:F})=>{let U=F.submitOnEnter??!0;if(U!==this.submitOnEnter)this.setState(()=>{this.submitOnEnter=U})}),this.agentModeController=new _g0({initialCliMode:this.tuiContext.initialAgentMode,sessionState:this.sessionState,freeTierStatus:this.freeTierStatus,workspace:this.tuiContext.workspace??null,userEmail:y6(this.authStatus)?this.authStatus.user.email:void 0,initialSettings:V.settings,config$:this.widget.dependencies.configService.config,getThread:()=>this.widget.dependencies.threadState.mainThread}),this.agentModeController.addListener(this.agentModeListener),this.lastEffectiveAgentMode=this.getEffectiveAgentMode(),this.deepModeEffortHintController.maybeShowForInitialDeepMode(),this.scheduleAdSubscriptionWithIdeReadiness(),this.setState(()=>{})}),this.updateGitBranch(),this.allConnectedThreadActivityStatusesSubscription=this.widget.dependencies.threadPool.allConnectedThreadActivityStatuses$.subscribe((X)=>{if(this.areRecordValuesEqual(this.allConnectedThreadActivityStatuses,X))return;this.setState(()=>{this.allConnectedThreadActivityStatuses=X})}),this.threadTitlesSubscription=this.widget.dependencies.threadPool.threadTitles$.subscribe((X)=>{if(this.areRecordValuesEqual(this.threadTitles,X))return;this.setState(()=>{this.threadTitles=X})}),this.threadInitializationStatusSubscription=this.widget.dependencies.threadPool.initializationStatus$?.subscribe((X)=>{let V=X.pending?X.message:null;if(V===this.threadInitializationMessage)return;this.setState(()=>{this.threadInitializationMessage=V})})??null,this.pendingNavigationSubscription=this.widget.dependencies.threadPool.threadHandles$.pipe(M4(),Q4((X)=>X?X.thread$:v0.of(null))).subscribe((X)=>{this.checkForPendingNavigation(X);let V=X?.id;if(this.threadCostInfoThreadID!==V){if(this.threadCostInfo=void 0,this.threadCostInfoThreadID=V,V&&W3(X)>0)this.fetchThreadCostInfo()}let K=X?this.widget.dependencies.threadState.viewState:void 0;this.maybeRefetchThreadCostInfo(K?.state==="active"?K.inferenceState:void 0)}),this.freeTierStatusSubscription=Ke1(async()=>{let X=await this.widget.dependencies.configService.getLatest(),V=_k(X),K=await this.widget.dependencies.internalAPIClient.getUserFreeTierStatus({},{config:this.widget.dependencies.configService,signal:AbortSignal.timeout(V)});if(!K.ok)throw K.error;return K.result}).subscribe({next:(X)=>{if(X){let V=this.freeTierStatus.canUseAmpFree;if(this.setState(()=>{this.freeTierStatus=X}),this.agentModeController?.updateVisibilityContext({freeTierStatus:X}),X.canUseAmpFree!==V)if(X.canUseAmpFree){if(!this.adSubscription&&!this.adsDisabledBySetting)this.scheduleAdSubscriptionWithIdeReadiness()}else this.unsubscribeFromAds()}},error:(X)=>{j.debug("Failed to fetch free tier status",X)}});let{mcpTrustHandler:Z}=this.widget.dependencies;if(this.mcpTrustSubscription=Z.pendingServers$.subscribe((X)=>{this.setState(()=>{this.pendingMCPServers=X})}),Ax0((X)=>{this.setState(()=>{this.pendingOAuthRequest=X})}),this.mcpServersSubscription=this.widget.dependencies.mcpService.servers.subscribe((X)=>{this.setState(()=>{this.mcpServers=X})}),this.pendingSkillsSubscription=this.widget.dependencies.activeThreadHandle.pendingSkills$.subscribe((X)=>{this.setState(()=>{this.pendingSkills=X})}),this.widget.dependencies.pluginService){let X=this.widget.dependencies.pluginService;this.pluginCommandsSubscription=_J(X.plugins,X.commands.changed).subscribe(()=>{let V=X.commands.list();this.setState(()=>{this.pluginCommands=V})}),this.pluginInfosSubscription=X.plugins.subscribe((V)=>{this.setState(()=>{this.pluginInfos=V})})}this.skillListSubscription=this.widget.dependencies.skillService.skills.subscribe((X)=>{let V=X.filter((K)=>!K.baseDir.startsWith("builtin://")).length;this.setState(()=>{this.availableSkillCount=V,this.availableSkillCountReady=!0})}),this.skillWarningsSubscription=this.widget.dependencies.skillService.skillWarnings.subscribe((X)=>{this.setState(()=>{this.skillWarningCount=X.length})}),this.skillErrorsSubscription=this.widget.dependencies.skillService.skillErrors.subscribe((X)=>{this.setState(()=>{this.skillErrorCount=X.length})}),this.pendingApprovalsSubscription=this.widget.dependencies.activeThreadHandle.pendingApprovals$.subscribe((X)=>{this.setState(()=>{this.pendingApprovals=X})}),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((X)=>{let V=this.isIdeReadyForAdContext();if(this.setState(()=>{this.ideStatus=X}),!V&&this.isIdeReadyForAdContext()){if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;if(!this.adSubscription&&!this.adsDisabledBySetting)this.subscribeToAds()}}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(X)=>{try{if(!this.widget.dependencies.threadState.mainThread){j.warn("No active thread found to handle IDE message");return}await new Promise((K)=>setTimeout(K,50)),await this.widget.dependencies.activeThreadHandle.sendMessage({content:[{type:"text",text:X}]}),j.debug("Message sent from IDE to agent",{message:X.slice(0,100)})}catch(V){this.handleSubmitFlowError(V)}}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((X)=>{this.textController.insertText(X),j.debug("Appended text to CLI prompt from IDE",{text:X.slice(0,100)})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((X)=>{this.setState(()=>{this.updateState=X})}),this.mysteriousMessageSubscription=nJ(this.widget.dependencies.configService).pipe(F5((X)=>X!=="pending"),D1((X)=>y6(X)?X.mysteriousMessage??null:null),M4((X,V)=>X?.id===V?.id)).subscribe((X)=>{this.setState(()=>{if(X?.id!==this.mysteriousMessage?.id)this.isShowingMysteriousMessageModal=!1;if(this.mysteriousMessage=X,X&&!this.mysterySequenceManager)this.mysterySequenceManager=new E20(new Map([[new O20(RJ0.MYSTERY_SEQUENCE),new Pp]])),this.mysteryKeyInterceptorUnsubscribe=l4.instance.addKeyInterceptor((V)=>{if(!this.mysterySequenceManager)return!1;if(this.isShowingMysteriousMessageModal)return!1;let K=this.mysterySequenceManager.handleKeyEvent(V);if(K.consumed){if(K.intent)this.handleShowMysteryModal();return this.setState(()=>{this.mysterySequenceProgress=K.progress}),!0}else if(this.mysterySequenceProgress)this.setState(()=>{this.mysterySequenceProgress=null});return!1});else if(!X)this.mysteryKeyInterceptorUnsubscribe?.(),this.mysteryKeyInterceptorUnsubscribe=null,this.mysterySequenceManager?.dispose(),this.mysterySequenceManager=null,this.mysterySequenceProgress=null})}),this.textController.addListener(this.textChangeListener),l4.instance.addKeyInterceptor((X)=>{if(X.key==="?"){if(this.textController.text===""&&this.textController.cursorPosition===0&&!this.isShowingHelp&&!this.isShowingPalette&&this.isTextfieldAndAutocompleteFocused){if(this.setState(()=>{this.isShowingShortcutsHelp=!this.isShowingShortcutsHelp}),!this.shortcutsHintUsed)this.shortcutsHintUsed=!0,this.sessionState={...this.sessionState,shortcutsHintUsed:!0},rz(this.sessionState);return!0}}if(this.isShowingShortcutsHelp){if(this.setState(()=>{this.isShowingShortcutsHelp=!1}),X.key==="Escape")return!0;return!1}return!1}),this.updateTerminalTitle();let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q)this.connectToSelectedIde(Q,"auto-startup").catch((X)=>{let V=X instanceof Error?X.message:String(X);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${V}`)})});else if(this.tuiContext.showIdePickerHint)this.toastController.show("Use /ide to connect to an IDE","success",5000);else if(this.tuiContext.showJetBrainsInstaller)this.openJetBrainsInstaller();let Y=this.widget.dependencies.threadState.mainThread;if(!Y){this.initNewsFeed();return}if(Y.autoSubmitDraft&&Y.messages.length===0)setTimeout(()=>{this.autoSubmitInitialDraft(Y.id)},100);this.initNewsFeed()}async autoSubmitInitialDraft(J){let Z=await this.getDraft(J);if(!Z)return;let Q=Z.text.trim();if(!Q&&Z.images.length===0)return;j.info("Auto-submitting initial handoff draft",{name:"handoff",threadID:J,hasDraftText:Boolean(Q),draftImageCount:Z.images.length}),this.textController.clear(),await this.proceedWithUserMessage(Q,[...Z.images])}handleSubmitFlowError(J){j.error("Failed to submit prompt message",J);let Z=J instanceof Error?J.message:String(J);this.showErrorMessage(Z)}checkForPendingNavigation(J){let Z=J??this.widget.dependencies.threadState.mainThread;if(!Z?.pendingNavigation)return;let Q=Z.pendingNavigation;if(this.pendingNavigationInFlightThreadID===Q)return;this.pendingNavigationInFlightThreadID=Q,this.widget.dependencies.activeThreadHandle.clearPendingNavigation().catch(()=>{return}),j.info("Pending navigation detected, navigating to new thread",{name:"handoff",fromThreadID:Z.id,targetThreadID:Q}),this.handleHandoffNavigation(Q).finally(()=>{if(this.pendingNavigationInFlightThreadID===Q)this.pendingNavigationInFlightThreadID=null})}handleHandoffNavigation=async(J)=>{try{await this.switchToExistingThread(J);let Z=this.widget.dependencies.threadState.mainThread;if(!Z){j.error("Failed to get new thread after handoff navigation");return}if(Z.autoSubmitDraft&&Z.messages.length===0){let Q=await this.getDraft(J);if(!Q)return;let Y=Q.text.trim();if(!Y&&Q.images.length===0)return;j.info("Auto-submitting handoff draft",{name:"handoff",threadID:J,hasDraftText:Boolean(Y),draftImageCount:Q.images.length}),this.textController.clear(),await this.proceedWithUserMessage(Y,[...Q.images])}}catch(Z){j.error("Failed to handle handoff navigation",{name:"handoff",newThreadID:J,error:Z})}};dispose(){if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeController)this.agentModeController.removeListener(this.agentModeListener),this.agentModeController.dispose();if(this.deepModeEffortHintController.dispose(),this.messageViewControllerUnsubscribe)this.messageViewControllerUnsubscribe(),this.messageViewControllerUnsubscribe=null;if(this.handoffController)this.handoffController.removeListener(this.handoffListener),this.handoffController.dispose();if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;if(this.adSubscription)this.adSubscription.unsubscribe();if(this.freeTierStatusSubscription)this.freeTierStatusSubscription.unsubscribe();if(this.allConnectedThreadActivityStatusesSubscription)this.allConnectedThreadActivityStatusesSubscription.unsubscribe();if(this.threadInitializationStatusSubscription)this.threadInitializationStatusSubscription.unsubscribe();if(this.threadTitlesSubscription)this.threadTitlesSubscription.unsubscribe();if(this.pendingNavigationSubscription)this.pendingNavigationSubscription.unsubscribe();if(this.mcpTrustSubscription)this.mcpTrustSubscription.unsubscribe();if(this.authStatusSubscription)this.authStatusSubscription.unsubscribe(),this.authStatusSubscription=null;if(Ax0(null),this.authModalKeyInterceptorUnsubscribe?.(),this.authModalKeyInterceptorUnsubscribe=null,this.pendingAuthLogin)this.pendingAuthLogin.abortController.abort(Error("TUI disposed")),this.pendingAuthLogin=null;if(this.mcpServersSubscription)this.mcpServersSubscription.unsubscribe();if(this.pendingSkillsSubscription)this.pendingSkillsSubscription.unsubscribe();if(this.pluginCommandsSubscription)this.pluginCommandsSubscription.unsubscribe();if(this.pluginInfosSubscription)this.pluginInfosSubscription.unsubscribe();if(this.skillListSubscription)this.skillListSubscription.unsubscribe();if(this.skillWarningsSubscription)this.skillWarningsSubscription.unsubscribe();if(this.skillErrorsSubscription)this.skillErrorsSubscription.unsubscribe();if(this.pendingApprovalsSubscription)this.pendingApprovalsSubscription.unsubscribe();if(this.unloadThreadsForPicker(),this.newsFeedSubscription)this.newsFeedSubscription.unsubscribe();if(this.deepReasoningEffortSubscription)this.deepReasoningEffortSubscription.unsubscribe(),this.deepReasoningEffortSubscription=null;if(this.anthropicSpeedSubscription)this.anthropicSpeedSubscription.unsubscribe(),this.anthropicSpeedSubscription=null;if(this.openAISpeedSubscription)this.openAISpeedSubscription.unsubscribe(),this.openAISpeedSubscription=null;if(this.submitOnEnterSubscription)this.submitOnEnterSubscription.unsubscribe(),this.submitOnEnterSubscription=null;if(this.showSkillsCountInPromptBarSubscription)this.showSkillsCountInPromptBarSubscription.unsubscribe(),this.showSkillsCountInPromptBarSubscription=null;if(this.stopElapsedTimeTimer(),this.winPasteHookImageUnsubscribe?.(),this.winPasteHookImageUnsubscribe=null,this.winPasteHookStateUnsubscribe?.(),this.winPasteHookStateUnsubscribe=null,this.mysteriousMessageSubscription)this.mysteriousMessageSubscription.unsubscribe();if(this.mysteryKeyInterceptorUnsubscribe?.(),this.mysterySequenceManager?.dispose(),this.threadPreviewController.removeListener(this.previewControllerListener),this.threadPreviewController.dispose(),this.toastController.dispose(),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;if(this.autocompleteFocusNodeListener)this.autocompleteFocusNode.removeListener(this.autocompleteFocusNodeListener),this.autocompleteFocusNodeListener=null;this.textController.removeListener(this.textChangeListener);for(let J of this.messageScrollControllers.values())J.dispose();this.messageScrollControllers.clear()}getCurrentConfirmation(){if(this.pendingApprovals.length>0){let J=this.pendingApprovals[0];return{type:"tool-use",tools:[{useBlock:{type:"tool_use",id:J.toolUseId,name:J.toolName,complete:!0,input:J.args},toAllow:J.toAllow??[]}],subthreadID:void 0,reason:J.reason??`Tool requires approval: ${J.toolName}`,isSubagent:J.context==="subagent",subagentToolName:J.subagentToolName}}return null}updateProgressBar(){}static AD_READINESS_TIMEOUT_MS=1000;scheduleAdSubscriptionWithIdeReadiness(){if(this.adsDisabledBySetting)return;if(!this.freeTierStatus.canUseAmpFree)return;if(this.isIdeReadyForAdContext()){this.subscribeToAds();return}this.adReadinessTimeout=setTimeout(()=>{if(this.adReadinessTimeout=null,!this.adSubscription)this.subscribeToAds()},RJ0.AD_READINESS_TIMEOUT_MS)}isIdeReadyForAdContext(){let J=this.ideStatus;if(!J||!J.enabled)return!1;return Boolean(J.openFile||J.visibleFiles&&J.visibleFiles.length>0)}unsubscribeFromAds(){if(this.adSubscription)this.adSubscription.unsubscribe(),this.adSubscription=null;if(this.adReadinessTimeout)clearTimeout(this.adReadinessTimeout),this.adReadinessTimeout=null;this.setState(()=>{this.randomAd=null})}subscribeToAds(){if(this.adSubscription)return;if(this.adsDisabledBySetting)return;if(!this.freeTierStatus.canUseAmpFree)return;this.adSubscription=Gg0(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>zg0(this.lastUserInteractionTime),this.widget.dependencies.codebaseContextService,()=>this.widget.dependencies.threadState.mainThread??void 0).subscribe({next:(J)=>{this.setState(()=>{this.randomAd=J}),H6.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})}})}onConfirmationResponse=async(J)=>{let Z=this.getCurrentConfirmation();if(!Z||Z.type!=="tool-use"){j.error("No current tool confirmation found");return}let Q=Z.tools[0]?.useBlock;if(!Q){j.error("No tool use block found in confirmation");return}if(J?.type==="deny-with-feedback"){let{feedback:V}=J;try{if(this.pendingApprovals.find((z)=>z.toolUseId===Q.id))await this.widget.dependencies.activeThreadHandle.resolveApproval(Q.id,!1,V.trim()||void 0);else await this.widget.dependencies.activeThreadHandle.resolveApproval(Q.id,!1,V.trim()||void 0)}catch(K){j.error("Failed to send deny with feedback:",K)}return}let Y=J?.type==="simple"?J.value:null;if(Y==="allow-all-session")u$("dangerouslyAllowAll",!0);if(Y==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0,"global")}catch(V){if(V&&V instanceof Error)this.setState(()=>{this.displayMessage=V});else j.error("Failed to write dangerouslyAllowAll setting:",V);return}if(Y==="always-guarded"){let V=Z.tools[0]?.toAllow??[],K=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],z=[...V,...K];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",z,"global")}if(Y==="connect-github"){let V=new URL("/settings#code-host-connections",this.tuiContext.ampURL).toString();await w8(this.context,V);return}if(Y==="disable-librarian"){let V=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!V.includes(T$))await this.widget.dependencies.settingsStorage.set("tools.disable",[...V,T$],"global")}let X=Y!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(Y);try{await this.widget.dependencies.activeThreadHandle.resolveApproval(Q.id,X)}catch(V){j.error("Failed to send tool confirmation:",V)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Z=J.viewState;if(Z.state!=="active"||!Z.ephemeralError)return null;return Z.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let{activeThreadHandle:Z}=this.widget.dependencies;switch(J){case"retry":await Z.retryTurn();break;case"dismiss":Z.dismissEphemeralError();break;case"new-thread":Z.dismissEphemeralError(),await this.startAndSwitchToNewThread();break;case"handoff":Z.dismissEphemeralError(),this.enterHandoffMode();break;case"add-credits":{let Q=new URL("/pay",this.tuiContext.ampURL);await w8(this.context,Q),this.showStatusMessage("Payment page opened. After paying, choose Retry.");break}}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};handleMCPTrustOpenSettings=async()=>{let{mcpTrustHandler:J,settingsStorage:Z}=this.widget.dependencies;await J.deny();try{await oY(Z.getSettingsFilePath())}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);await this.showErrorMessage(`Failed to open settings: ${Y}`)}};cancelStreamingMessage=async()=>{await this.widget.dependencies.activeThreadHandle.cancelStreaming()};switchToExistingThread=async(J,Z={})=>{let{recordInNavigationHistory:Q=!0}=Z,Y=Date.now(),X=this.widget.dependencies.threadState.mainThread?.id,V=Q&&X!==void 0&&X!==J;try{j.info(`[switchToExistingThread] Switching to thread: ${J}`);let K=Date.now();await this.widget.dependencies.threadPool.switchThread(J),j.info(`[switchToExistingThread] switchToThread resolved in ${Date.now()-K}ms`);let z=await this.widget.dependencies.threadService.get(J)??this.widget.dependencies.threadState.mainThread;if(!z||z.id!==J)throw Error("No active thread after switch");j.info(`[switchToExistingThread] Got thread ${J}, thread.agentMode: ${z.agentMode}`),j.info("[switchToExistingThread] Clearing agent mode"),this.agentModeController?.setMode(null);let G=Date.now();if(this.onThreadSwitch(),j.info(`[switchToExistingThread] onThreadSwitch completed in ${Date.now()-G}ms`),V&&X)this.recordNavigation(X);this.persistLastThreadId(J);let F=await this.getDraft(J);if(F&&W3(z)===0){if(this.textController.clear(),F.text)this.textController.insertText(F.text);if(F.images.length>0)this.setState(()=>{this.imageAttachments=[...F.images]})}j.info(`[switchToExistingThread] Completed in ${Date.now()-Y}ms`)}catch(K){j.error("Failed to switch to thread",{threadId:J,error:K});let z=K instanceof Error?K.message:String(K);if(z.includes("can't be opened in legacy mode")){await this.showErrorMessage(z);return}throw Error(`Failed to switch to thread: ${J}. ${z}`,{cause:K})}};async getDraft(J){return(await E1(this.widget.dependencies.threadPool.drafts$).catch(()=>null))?.get(J)??null}sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J,Z)=>{if(this.cancelBashInvocations(),this.shouldRequireAuthForPromptSubmit()){this.queuePromptUntilAuthenticated(J,Z??[...this.imageAttachments],{clearInput:Z===void 0});return}this.handoffController?.clearPendingPrompt(),this.widget.dependencies.history.add(J,process.cwd());let Q=this.widget.dependencies.threadState.mainThread;if(!Q)return;let Y=W3(Q)===0,X=this.getEffectiveAgentMode();if(Q.agentMode&&!Y&&X!==Q.agentMode){await this.showErrorMessage(`This thread uses ${Q.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let V=Z??this.imageAttachments,K=[{type:"text",text:J}];if(V.length>0)K.push(...V);if(await this.widget.dependencies.activeThreadHandle.sendMessage({content:K,agentMode:X}),this.persistLastThreadId(Q.id),Y)this.persistAgentMode(X);if(this.scrollMessageViewToBottom(),!Z)this.setState(()=>{this.imageAttachments=[]});H6.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}exitApplication=async()=>{this.setState(()=>{this.isExiting=!0});let J=this.widget.dependencies.threadState.mainThread;if(J&&J.messages.length===0){if(J.relationships?.find((Q)=>Q.type==="handoff"&&Q.role==="child"))await this.widget.dependencies.threadPool.deleteThread?.(J.id).catch(()=>{})}l4.instance.stop()};async persistAgentMode(J){let Q={...await oz(),agentMode:J};this.sessionState=Q,await rz(Q)}async persistLastThreadId(J){let Q={...await oz(),lastThreadId:J};this.sessionState=Q,await rz(Q)}onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;this.exitApplication()}else{if(this.setState(()=>{this.isConfirmingExit=!0}),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout);this.exitConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingExit=!1}),this.exitConfirmTimeout=null},1000)}};toHomeRelative(J){let Z=js5();if(J===Z)return"~";if(J.startsWith(Z+wG.sep))return"~"+J.slice(Z.length);return J}shorten(J){let Z=J.split(wG.sep).filter(Boolean);if(Z.length<=5)return J;return[Z.slice(0,2).join(wG.sep),"…",Z.slice(-2).join(wG.sep)].join(wG.sep)}buildDisplayText(J,Z,Q,Y){let X=Z?` (${Z})`:"",V=J+X;if(p5(V,Y)<=Q)return V;let K=J.split(wG.sep);if(K.length>2){let G=[K[0],"…",K[K.length-1]].join(wG.sep)+X;if(p5(G,Y)<=Q)return G}return sE(V,Q,Y)}build(J){this.lastRootContext=J;let Z=this.widget.dependencies.pluginPlatform;if(Z&&!Z.showToast){let z1=this.toastController;Z.showToast=(L4)=>z1.show(L4,"success")}if(Z&&!Z.showOpenedURLToast){let z1=this.toastController;Z.showOpenedURLToast=(L4)=>z1.show(`Opened URL: ${L4}`,"success",8000)}if(Z&&!Z.appendToThreadHandler){let z1=this.widget.dependencies;Z.appendToThreadHandler=async(L4)=>{for(let T4 of L4)await z1.activeThreadHandle.queueMessage([{type:"text",text:T4.content}])}}if(Z&&!Z.showInputDialog)Z.showInputDialog=(z1)=>{return new Promise((L4)=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.pendingInputDialog={options:z1,resolve:L4}})})};if(Z&&!Z.showConfirmDialog)Z.showConfirmDialog=(z1)=>{return new Promise((L4)=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.pendingConfirmDialog={options:z1,resolve:L4}})})};let Q=t1.of(J),Y=f0.of(J),X=Y.base;this.themeColors=X;let{colors:V,app:K}=Y;this.themeApp=K;let z=this.widget.dependencies.threadState.mainThread,G=z?.agentMode&&h3(z.agentMode),F=this.freeTierStatus.isDailyGrantEnabled,U=!this.adsDisabledBySetting&&(G||F)&&this.randomAd!==null,q=Boolean(U),{threadState:D}=this.widget.dependencies;this.updateTerminalTitle(),this.updateProgressBar();let W=this.getCurrentConfirmation(),H=D.items,B=D.mainThread||void 0,w=D.subagentToolsByParentID,N=D.toolProgressByToolUseID,O=D.todosList,E=B?.id,L=B,M=this.isTranscriptEmpty(),A=M&&this.isStartupThreadLoading(),I=this.threadInitializationMessage?.startsWith("Importing thread")??!1,P=this.widget.dependencies.threadPool.isDTWMode?.()===!0,_=(z1)=>new qd({key:new $3(`preview-message-view-${z1.id}`),items:TU(z1).items,toolProgressByToolUseID:new Map,controller:this.threadPreviewController.scrollController,autofocus:!1,thread:z1,denseView:z1.agentMode==="deep",focusNode:new r4({debugLabel:"PreviewFocus"}),onShowImagePreview:()=>{},stateController:this.previewMessageViewController,submitOnEnter:this.submitOnEnter,isDTWMode:P}),S=this.previewThread,y=S?S.messages.length>2000?new u0({mainAxisSize:"max",children:[new T1({child:new R0}),new i0({padding:C0.all(2),child:new l1({child:new $0({text:new C("Thread too long for preview",new h({color:V.mutedForeground,dim:!0}))})})})]}):_(S):M?new P$0({agentMode:this.getEffectiveAgentMode(),mysteriousMessage:this.mysteriousMessage,mysterySequenceProgress:this.mysterySequenceProgress,onShowMysteryModal:this.handleShowMysteryModal,onOrbExplode:this.handleSplashOrbExplode}):new ed0({threadID:E,items:H,subagentToolsByParentID:w,toolProgressByToolUseID:N,controller:E?this.getMessageScrollController(E):new Y5,autofocus:!1,onCopy:this.handleMainMessageViewCopy,thread:L,onMessageEditSubmit:this.handleMessageEditSubmit,...P?{}:{onMessageRestoreSubmit:this.handleMessageRestoreSubmit},onShowForkDeprecation:this.showForkDeprecationMessage,getAffectedFiles:this.getAffectedFiles,denseView:L?.agentMode==="deep",focusNode:this.messageViewFocusNode,onDismissFocus:this.handleMainMessageViewDismissFocus,isInSelectionMode:this.isMessageViewInSelectionMode,isInHandoffMode:this.handoffState.isInHandoffMode,completionBuilder:this.getCompletionBuilder(),onShowImagePreview:this.handleShowEditingImagePreview,onSelectionChanged:this._handleSelectionChanged,onDoubleAtTrigger:this.handleDoubleAtTrigger,stateController:this.messageViewController,submitOnEnter:this.submitOnEnter,threadViewState:D.viewState,isDTWMode:P}),m=Math.max(Math.floor(Q.size.height*0.4),12),b=this.getCurrentEphemeralError(),k=Q.size.width<40,f=dM4(D),p=this.widget.dependencies.threadPool.getCompactionStatus?.(),l=M20(J),x=this.buildBottomWidget(b,W,V,Y,D,O,m,q,f,Q,l),r=new L$0({threadViewState:D.viewState,threadTokenUsage:f,compactionState:p?.compactionState??"idle",threadID:E??null,thread:D.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,mcpServers:this.mcpServers,plugins:this.pluginInfos,isNarrow:k,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!W,showingEphemeralError:Boolean(D.viewState.state==="active"&&D.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandNoun:this.executingCommand?.noun??null,executingCommandVerb:this.executingCommand?.verb??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),c=new O$0({bashInvocations:this.bashInvocations}),s=[],w0=_K4(this.tuiContext.buildTimestamp);if(w0){let z1=sL0(w0.ageMs,{verbose:!0});s.push(new c0({decoration:new v4(V.destructive),child:new i0({padding:C0.horizontal(1),child:new $0({text:new C("",new h({color:V.foreground,bold:!0}),[new C(`Your Amp version is ${z1} old — run `),new C("amp update",new h({color:V.warning})),new C(" or see ampcode.com/manual")]),textAlign:"center"})})}))}s.push(new T1({child:y}),c);let a=new i6({children:[new u0({mainAxisSize:"min",children:[U?new lg0({ad:this.randomAd,onImpression:(z1)=>{if(!z1.advertiserId){j.warn("[ad-telemetry] Skipping impression due to missing advertiserId",{adId:z1.id});return}let L4=z1.impressionId??mM4(16).toString("hex");this.lastAdImpressionId=L4;let T4=this.widget.dependencies.threadState.mainThread;if(!T4)return;let i4=T4.messages[T4.messages.length-1],E8=Date.now();CN("viewed",{adId:z1.id,advertiserId:z1.advertiserId,threadId:T4.id,messageId:i4?.messageId,impressionId:L4,placement:"tui",matchType:z1.metadata?.matchType,matchedPatterns:z1.metadata?.matchedPatterns,candidateAdPoolCount:z1.metadata?.candidateAdPoolCount,clientRegion:z1.metadata?.clientRegion,tokenProvided:!!z1.impressionToken,campaignId:z1.metadata?.campaignId,providerId:z1.metadata?.providerId,providerType:z1.metadata?.providerType,relevance:z1.metadata?.relevance}),CN("impressionStarted",{adId:z1.id,advertiserId:z1.advertiserId,impressionId:L4,placement:"tui",providerId:z1.metadata?.providerId,providerType:z1.metadata?.providerType}),this.widget.dependencies.internalAPIClient.recordAdImpression({adId:z1.id,impressionToken:z1.impressionToken,impressionId:L4,externalImpressionUrl:z1.externalImpressionUrl},{config:this.widget.dependencies.configService}).then((L7)=>{if(!L7.ok)throw Error(`recordAdImpression failed: ${L7.error.code??"unknown"}`);let zX=Math.round(Date.now()-E8);CN("impressionRecorded",{adId:z1.id,advertiserId:z1.advertiserId,impressionId:L4,placement:"tui",durationMs:zX,providerId:z1.metadata?.providerId,providerType:z1.metadata?.providerType})}).catch((L7)=>{let zX=Math.round(Date.now()-E8);CN("impressionFailed",{adId:z1.id,advertiserId:z1.advertiserId,impressionId:L4,errorMessage:L7 instanceof Error?L7.message:String(L7),errorType:"error",placement:"tui",durationMs:zX,providerId:z1.metadata?.providerId,providerType:z1.metadata?.providerType})})},onButtonClick:async()=>{let z1=this.randomAd;if(this.lastAdImpressionId&&z1.advertiserId){let i4=this.widget.dependencies.threadState.mainThread;if(!i4)return;let E8=i4.messages[i4.messages.length-1];CN("clicked",{adId:z1.id,advertiserId:z1.advertiserId,threadId:i4.id,messageId:E8?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to",matchType:z1.metadata?.matchType,matchedPatterns:z1.metadata?.matchedPatterns,candidateAdPoolCount:z1.metadata?.candidateAdPoolCount,clientRegion:z1.metadata?.clientRegion,providerId:z1.metadata?.providerId,providerType:z1.metadata?.providerType})}let T4=l4.instance.tuiInstance.clipboard.isOsc52Supported();if(d80())this.setState(()=>{this.adActionModal={showCopyOption:!1,url:z1.shortDestinationUrl,title:z1.buttonLabel},this.bringAdModalToFront("adAction")});else if(!await w8(this.context,z1.shortDestinationUrl))this.setState(()=>{this.adActionModal={showCopyOption:T4,url:z1.shortDestinationUrl},this.bringAdModalToFront("adAction")})},onAdInfoClick:()=>{this.setState(()=>{this.adInfoModal={provider:this.randomAd?.metadata?.provider},this.bringAdModalToFront("adInfo")})}}):new R0({height:0}),new c0({constraints:new M1(0,Q.size.width,0,m),child:x})]}),q?new x6({top:0,left:0,right:0,child:new iM4({userHeight:this.bottomGridUserHeight,maxHeight:m,onInitializeHeight:(z1)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(z1,m)})},onDrag:(z1)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(z1.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let L4=Math.floor(z1.localPosition.y)-this.bottomGridDragStartY,T4=Math.max(4,this.bottomGridDragStartHeight-L4),i4=Math.min(T4,m),E8=Math.floor(i4);if(this.bottomGridUserHeight!==E8)this.setState(()=>{this.bottomGridUserHeight=E8})},onRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null}})}):new R0({height:0})]}),F0=this.getParentThreadInfo();if(F0){let z1=F0.type==="handoff"?K.handoffMode:V.primary,L4=40,T4=l6(F0.title),i4=T4.length>40?T4.slice(0,39).join("")+"…":F0.title;s.push(new bp({link:this.parentThreadLinkAnchor,child:new Sp0({type:F0.type,title:i4,threadID:F0.threadID,labelColor:z1,mutedColor:V.mutedForeground,foregroundColor:V.foreground,onNavigate:(E8)=>this.switchToExistingThread(E8)})}))}s.push(a,new R0({height:1,child:new i0({padding:C0.horizontal(1),child:r})}));let z0=new u0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:s}),q0=new c0({constraints:M1.tight(Q.size.width,Q.size.height),decoration:new v4(V.background),child:z0}),Q0=new s4(()=>{if(this.isShowingPalette)return this.dismissPalette(),"handled";if(this.isShowingMCPStatusModal)return this.setState(()=>{this.isShowingMCPStatusModal=!1}),"handled";if(this.pendingAuthLogin)return this.cancelAuthLoginSession(),"handled";if(this.pendingOAuthRequest){let L4=this.pendingOAuthRequest;return this.setState(()=>{this.pendingOAuthRequest=null}),L4.reject(Error("OAuth authorization cancelled")),"handled"}if(this.isShowingPromptHistoryPicker)return this.setState(()=>{this.isShowingPromptHistoryPicker=!1}),"handled";if(this.pendingMCPServers.length>0)return this.widget.dependencies.mcpTrustHandler.deny(),"handled";if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingContextAnalyzeModal)return this.setState(()=>{this.isShowingContextAnalyzeModal=!1,this.contextAnalyzeDeps=null,this.contextAnalyzeFromDTW=null}),"handled";if(this.isShowingSkillListModal)return this.setState(()=>{this.isShowingSkillListModal=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingContextDetailOverlay)return this.setState(()=>{this.isShowingContextDetailOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.dismissTopAdModal())return"handled";if(this.handoffState.countdownSeconds!==null)return this.handoffController?.stopCountdown(),"handled";if(this.handoffState.isInHandoffMode){if(this.handoffState.isGeneratingHandoff)this.handoffController?.cancelGeneration();else this.exitHandoffMode();return"handled"}if(this.isInQueueMode)return this.exitQueueMode(),"handled";if(this.textController.hasSelection)return this.textController.clearSelection(),"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.textController.resetScrollOffset(),this.widget.dependencies.activeThreadHandle.clearPendingSkills(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.handoffState.isConfirmingAbortHandoff&&this.handoffController){let L4=this.handoffController.getPendingPrompt(),T4=this.imageAttachments;return this.textController.clear(),this.textController.resetScrollOffset(),this.widget.dependencies.activeThreadHandle.clearPendingSkills(),this.setState(()=>{this.imageAttachments=[]}),this.handoffController.confirmAbort().then((i4)=>{if(i4&&L4)this.textController.text=L4,this.handoffController?.clearPendingPrompt();if(i4&&T4.length>0)this.setState(()=>{this.imageAttachments=T4})}),"handled"}if(this.isConfirmingCancelProcessing){if(this.bashInvocations.length>0)this.cancelBashInvocations();if(this.cancelStreamingMessage().catch((L4)=>{j.error("Failed to cancel streaming message:",L4)}),this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout),this.cancelProcessingConfirmTimeout=null;return"handled"}if(this.executingCommand)return j.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.bashInvocations.length>0||this.isProcessing()){if(this.setState(()=>{this.isConfirmingCancelProcessing=!0}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout);return this.cancelProcessingConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout=null},1000),"handled"}if(this.handoffController?.getEmptyHandoffParentThreadID(this.widget.dependencies.threadState.mainThread))return this.handoffController.startAbortConfirmation(),"handled";if(this.textController.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return"ignored"}),H0=new s4(()=>{return this.onExitPressed(),"handled"}),i=new s4(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),n=new s4(()=>{return this.setState(()=>{this.isShowingMCPStatusModal=!this.isShowingMCPStatusModal}),"handled"}),e=new s4(()=>{if(r9.instance.toggleAll(),D.mainThread?.agentMode==="deep"||D.mainThread?.agentMode==="internal")UJ.instance.toggleAll();return"handled"}),J0=new s4(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return this.setState(()=>{this.isShowingPromptHistoryPicker=!0}),"handled"}),Z0=new s4(()=>{return l4.instance.toggleFrameStatsOverlay(),"handled"}),K0=new s4(()=>{return l4.instance.tuiInstance.getScreen().markForRefresh(),H6.instance.requestFrame(),"handled"}),t=new s4(()=>{return this.toggleAgentMode(),"handled"}),V0=new s4(()=>{return this.toggleDeepReasoningEffort(),"handled"}),N0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4){let T4=Math.max(Math.floor(Q.size.height*0.4),10),i4=Q.size.height-T4;L4.animatePageUp(i4,100)}return"handled"}),D0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4){let T4=Math.max(Math.floor(Q.size.height*0.4),10),i4=Q.size.height-T4;L4.animatePageDown(i4,100)}return"handled"}),O0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4){let T4=Math.max(Math.floor(Q.size.height*0.4),10),i4=Q.size.height-T4;L4.animatePageUp(Math.floor(i4/2),100)}return"handled"}),_0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4){let T4=Math.max(Math.floor(Q.size.height*0.4),10),i4=Q.size.height-T4;L4.animatePageDown(Math.floor(i4/2),100)}return"handled"}),e0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4)L4.animateTo(0,100);return"handled"}),a0=new s4(()=>{let L4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:T4}=this.widget.dependencies,i4=T4.mainThread?.id;return i4?this.getMessageScrollController(i4):null})();if(L4)L4.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),F1=new s4(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";if(this.handoffState.isInHandoffMode)return"ignored";if(this.isInQueueMode)return"ignored";let{threadState:z1}=this.widget.dependencies;if(!z1.mainThread?.messages.some((T4)=>T4.role==="user"||VF(T4)))return"ignored";return this.setState(()=>{this.isMessageViewInSelectionMode=!0}),"handled"}),a1=new s4((z1)=>{if(z1.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),o1=new s4(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return H$0().then(async(z1)=>{if(z1)await this.handleInsertImage(z1)}),"handled"}),m0=new Map([[Y4.ctrl("c"),new Ep],[Y4.ctrl("l"),new Ip],[Y4.ctrl("o"),new q$0],[Y4.ctrl("v"),new Np],[Y4.alt("s"),new HT],[Y4.ctrl("s"),new HT],[Y4.alt("p"),new Ap],[Y4.ctrl("r"),new Cp],[Y4.alt("t"),new Mp],[Y4.ctrl("t"),new Rp],[Y4.key("PageUp"),new V$0],[Y4.key("PageDown"),new K$0],[Y4.alt("k"),new z$0],[Y4.alt("j"),new G$0],[Y4.key("Home"),new F$0],[Y4.key("End"),new U$0],[Y4.key("Escape"),new Op],[Y4.ctrl("p"),new BT("previous")],[Y4.ctrl("n"),new BT("next")],[Y4.key("Tab"),new fp]]);if(m0.set(Y4.alt("d"),new jp),!a9())m0.set(Y4.key("ArrowUp"),new fp);if(!1)m0.set(Y4.alt("c"),new Lp);let t0=new s4(()=>{if(this.isShowingStandalonePalette())return"handled";return this.showCommandPalette(),"handled"}),A1=new s4(()=>{return this.toggleThreadPickerWorkspaceFilter(),"handled"}),$4=new s4(()=>{if(this.mysteriousMessage)this.handleShowMysteryModal();return"handled"}),D6=new Map([[Op,Q0],[Ip,K0],[HT,t],[jp,V0],[q$0,t0],[Np,o1],[Lp,i],[N20,n],[Mp,e],[Ap,Z0],[Rp,A1],[Cp,J0],[Ep,H0],[V$0,N0],[K$0,D0],[z$0,O0],[G$0,_0],[F$0,e0],[U$0,a0],[fp,F1],[BT,a1],[Pp,$4]]),m1=[q0];if(this.splashOrbExplosion){let z1=rg(this.getEffectiveAgentMode());m1.push(new id0({key:new $3(`splash-orb-explosion-${this.splashOrbExplosion.seq}`),originX:this.splashOrbExplosion.originX,originY:this.splashOrbExplosion.originY,sparkleColors:[z1,V.warning],onComplete:this.handleSplashOrbExplosionComplete}))}if(A||I)m1.push(new l1({child:new iV({message:this.threadInitializationMessage??"Loading thread..."})}));if(this.isShowingConsoleOverlay)m1.push(new jp0);if(this.isShowingHelp&&this.paletteConfig)m1.push(new vp0({commands:this.getPaletteCommands().getAllCommands(),submitOnEnter:this.submitOnEnter}));if(this.isShowingContextAnalyzeModal){let{configService:z1}=this.widget.dependencies,L4=this.widget.dependencies.threadState.mainThread,T4=this.contextAnalyzeDeps,i4=this.contextAnalyzeFromDTW;if(L4&&(T4||i4)){let E8=T4?{configService:z1,agentModeOverride:this.getEffectiveAgentMode(),buildSystemPromptDeps:T4}:null;m1.push(new Rp0({deps:E8,thread:L4,dtwAnalyze:i4??void 0,onDismiss:()=>{this.setState(()=>{this.isShowingContextAnalyzeModal=!1,this.contextAnalyzeDeps=null,this.contextAnalyzeFromDTW=null})}}))}else this.setState(()=>{this.isShowingContextAnalyzeModal=!1,this.contextAnalyzeDeps=null,this.contextAnalyzeFromDTW=null})}if(this.isShowingSkillListModal&&!this.isShowingPalette)Promise.all([this.widget.dependencies.skillService.getSkills(),this.widget.dependencies.skillService.getSkillErrors(),this.widget.dependencies.skillService.getSkillWarnings()]).then(([z1,L4,T4])=>{if(this.isShowingSkillListModal&&this.mounted)this.skillListData={skills:z1,errors:L4,warnings:T4},this.setState()}),m1.push(new rd0({skills:this.skillListData?.skills??[],errors:this.skillListData?.errors??[],warnings:this.skillListData?.warnings??[],cwd:process.cwd(),onDismiss:()=>{this.setState(()=>{this.isShowingSkillListModal=!1,this.skillListData=null})},onAddSkill:()=>{this.showCommandPalette({type:"standalone",commandId:"skill-add",onSubmit:()=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null,this.isShowingSkillListModal=!1,this.skillListData=null})},onCancel:()=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteShowOptions=null})}})},onDocs:()=>{fX("https://ampcode.com/manual#agent-skills")},onInsertPrompt:(z1)=>{this.setState(()=>{this.isShowingSkillListModal=!1,this.skillListData=null,this.textController.text=z1})},onInvokeSkill:(z1)=>{this.widget.dependencies.activeThreadHandle.addPendingSkill({name:z1})}}));if(this.isShowingMCPStatusModal)m1.push(new sp0({servers:this.mcpServers,onDismiss:()=>{this.setState(()=>{this.isShowingMCPStatusModal=!1})}}));if(this.isShowingPromptHistoryPicker)m1.push(new nd0({entries:this.widget.dependencies.history.getAll(),currentCwd:process.cwd(),onAccept:(z1)=>{this.setState(()=>{this.isShowingPromptHistoryPicker=!1,this.textController.text=z1,this.textController.cursorPosition=z1.length})},onDismiss:()=>{this.setState(()=>{this.isShowingPromptHistoryPicker=!1})}}));if(this.isShowingMysteriousMessageModal&&this.mysteriousMessage)m1.push(new cd0({message:this.mysteriousMessage,onDestruct:this.handleDestructMysteriousMessage}));if(this.isShowingForkDeprecationModal)m1.push(new Tp0({onDismiss:this.dismissForkDeprecationModal}));for(let z1=0;z1<this.adModalStack.length;z1++){let L4=this.adModalStack[z1],T4=z1===this.adModalStack.length-1;if(L4==="adAction"&&this.adActionModal)m1.push(new ig0({key:new $3(`ad-action-modal-${T4?"top":"back"}`),title:this.adActionModal.title??"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(i4)=>{let E8=this.adActionModal.url;if(i4==="copy")try{await l4.instance.tuiInstance.clipboard.writeText(E8),this.setState(()=>{this.displayMessage=new W$("Link copied to clipboard")})}catch(L7){j.error("Failed to copy to clipboard",{error:L7}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null,this.removeAdModalFromStack("adAction")})}}));if(L4==="adInfo"&&this.adInfoModal)m1.push(new ng0({key:new $3(`ad-info-modal-${T4?"top":"back"}`),provider:this.adInfoModal.provider,onClose:()=>{this.setState(()=>{this.adInfoModal=null,this.removeAdModalFromStack("adInfo")})}}))}if(this.pendingMCPServers.length>0){let{mcpTrustHandler:z1}=this.widget.dependencies;m1.push(new tp0({servers:this.pendingMCPServers,onAlwaysTrust:z1.trustAlways.bind(z1),onTrustOnce:z1.trustOnce.bind(z1),onOpenSettings:this.handleMCPTrustOpenSettings,onDismiss:z1.deny.bind(z1)}))}if(this.pendingAuthLogin)m1.push(new ag0({manualURL:this.pendingAuthLogin.manualURL,isAuthenticating:this.pendingAuthLogin.isAuthenticating||this.pendingAuthLogin.isOpeningBrowser,errorMessage:this.pendingAuthLogin.errorMessage}));if(this.pendingOAuthRequest)m1.push(new ld0({request:this.pendingOAuthRequest,onDismiss:()=>{this.setState(()=>{this.pendingOAuthRequest=null})}}));if(this.pendingInputDialog){let z1=this.pendingInputDialog;m1.push(new xp0({options:z1.options,onSubmit:(L4)=>{this.setState(()=>{this.pendingInputDialog=null}),z1.resolve(L4)},onCancel:()=>{this.setState(()=>{this.pendingInputDialog=null}),z1.resolve(void 0)}}))}if(this.pendingConfirmDialog){let z1=this.pendingConfirmDialog;m1.push(new Mp0({options:z1.options,onConfirm:()=>{this.setState(()=>{this.pendingConfirmDialog=null}),z1.resolve(!0)},onCancel:()=>{this.setState(()=>{this.pendingConfirmDialog=null}),z1.resolve(!1)}}))}if(this.isShowingFileChangesOverlay)m1.push(new mg0({threadData:D}));if(this.isShowingContextDetailOverlay){let z1=this.threadCostInfo?.costBreakdownURL;m1.push(new Pp0({tokenUsage:f??void 0,costInfo:this.threadCostInfo,onDismiss:()=>{this.setState(()=>{this.isShowingContextDetailOverlay=!1})},onOpenCostBreakdown:z1?()=>{w8(J,z1)}:void 0}))}if(this.isShowingConfirmationOverlay)m1.push(new Ap0({details:this.confirmationOverlayContent}));if(this.imagePreview!==null)m1.push(new l1({child:new up0({image:this.imagePreview.image,imageIndex:this.imagePreview.index,onDismiss:this.handleImagePreviewDismiss,onRemove:this.handleImagePreviewRemove})}));if(this.fileImagePreviewPath!==null)m1.push(new l1({child:new Up({filePath:this.fileImagePreviewPath,onDismiss:this.handleFileImagePreviewDismiss})}));if(this.painterImagePreview!==null)m1.push(new l1({child:new Up({filePath:this.painterImagePreview.filePath,onDismiss:this.handlePainterImagePreviewDismiss})}));if(this.painterSaveDialog!==null)m1.push(new l1({child:new Up({filePath:this.painterSaveDialog.filePath,imageBlock:this.painterSaveDialog.image,onDismiss:this.handlePainterSaveDialogDismiss})}));if(this.skillPreview!==null){let z1=this.pendingSkills[this.skillPreview.skillIndex];if(z1)m1.push(new l1({child:new sd0({pendingSkill:z1,skill:this.cachedSkillForPreview,onDismiss:this.handleSkillPreviewDismiss,onRemove:this.skillPreview.onRemove})}))}let y4=this.getCommandPaletteContext(J);if(y4&&this.isShowingPalette&&this.paletteConfig)m1.push(new l1({child:new Ep0({commandContext:y4,mainThread:D.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette,showOptions:this.paletteShowOptions??void 0})}));if(this.isShowingIdePicker)m1.push(new yp0({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection}));let b4=new i6({children:m1});if(this.isShowingJetBrainsInstaller)return new uL({child:new S9({actions:D6,child:new C2({shortcuts:m0,debugLabel:"jetbrains-installer-shortcuts",child:new op0({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});let H4=this.widget.dependencies.threadState.mainThread?.id,S5=1+(this.bottomGridUserHeight??5)+1,X6=!this.isShowingPalette&&!this.isShowingIdePicker;return new tT({switchToThread:(z1)=>this.switchToExistingThread(z1),child:new HG({threadViewStates:this.getThreadViewStatesSnapshot(),threadTitles:this.threadTitles,threadSummaries:this.threadsForPicker,child:new _p0({getThreadCluster:this.getCurrentThreadClusterForMinimap,parentThreadID:F0?.threadID,anchorLink:F0?this.parentThreadLinkAnchor:void 0,bottomOffset:S5,enabled:X6,child:new xT({onShowImagePreview:this.handleShowFileImagePreview,child:new fT({onShowImagePreview:this.handleShowPainterImagePreview,onShowSaveDialog:this.handleShowPainterSaveDialog,child:new rY({controller:this.toastController,child:new uL({child:new Ad0({getThreadCluster:this.getThreadClusterForMinimap,currentThreadID:H4,enabled:X6,child:new rH({enabled:X6,child:new f70({controller:this.toastController,child:new S9({actions:D6,child:new C2({shortcuts:m0,debugLabel:"main-app-shortcuts",child:b4})})})})})})})})})})})})}buildScrollableTodoList(J,Z,Q){return new cM4({todos:J,enabled:Z,controller:this.todoScrollController,appTheme:Q})}buildBottomWidget(J,Z,Q,Y,X,V,K,z,G,F,U){if(J)return new Cp0({error:J,options:{freeTierEnabled:this.freeTierStatus.canUseAmpFree},onResponse:this.handleEphemeralErrorResponse});if(Z){if(this.displayMessage)this.handleDisplayMessageDismiss();return new Ip0({confirmationRequest:Z,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new ep0({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let q=this.handoffState.isInHandoffMode||!this.widget.dependencies.activeThreadHandle.invokeBashTool?[]:N$0(Y),D=this.agentModeController?.isInRestrictedFreeMode()??!1,W=this.isTextfieldAndAutocompleteFocused&&!D&&!this.isShowingStandalonePalette()&&!this.handoffState.isGeneratingHandoff;if(W&&!this.hasReplayedEarlyInput){this.hasReplayedEarlyInput=!0;let t=l4.instance.tuiInstance.getEarlyInputText();if(t)this.textController.insertText(t)}let H=this.submitOnEnter?{character:"Enter"}:{character:"Enter",modifiers:{meta:!0}},B=new Ud({key:this.textFieldKey,controller:this.textController,triggers:[new YB],completionBuilder:this.getCompletionBuilder(),onSubmitted:(t)=>{this.onTextSubmitted(t).catch((V0)=>{this.handleSubmitFlowError(V0)})},submitKey:H,theme:Q,placeholder:D?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,enabled:W,shellPromptRules:q,focusNode:this.autocompleteFocusNode,autofocus:!this.isMessageViewInSelectionMode&&!this.isShowingStandalonePalette()&&!this.isShowingIdePicker&&!this.isShowingSkillListModal,clipboard:l4.instance.tuiInstance.clipboard,onCopy:this._handleTextCopy.bind(this),onInsertImage:this.handleInsertImage,imageAttachments:this.imageAttachments,popImage:this.handlePopImage,onImageClick:this.handleImageClick,previousThreadId:this.previousThreadIdForHint&&(X.mainThread?.messages.length??0)===0?this.previousThreadIdForHint:void 0,onPreviousThreadHintAccepted:()=>{let t=this.previousThreadIdForHint;if(t)this.setState(()=>{this.previousThreadIdForHint=null}),this.textController.text=`following: @${t} `},onDoubleAtTrigger:(t)=>{this.handleDoubleAtTrigger(t)},pendingSkills:this.pendingSkills,onClearPendingSkill:(t)=>{this.widget.dependencies.activeThreadHandle.removePendingSkill(t)},popSkill:()=>{let t=this.pendingSkills[this.pendingSkills.length-1];if(t)this.widget.dependencies.activeThreadHandle.removePendingSkill(t.name)},onSkillClick:this.handleSkillClick,topWidget:this.isShowingShortcutsHelp?new od0({submitOnEnter:this.submitOnEnter}):void 0}),w=X.mainThread?.queuedMessages??[],N=Array.isArray(V)&&V.length>0,O=Array.isArray(w)&&w.length>0,E=this.widget.dependencies.threadPool,L=E.isDTWMode?.()===!0,M=O?new ad0({queuedMessages:w,onInterruptQueuedMessage:L?(t)=>this.widget.dependencies.activeThreadHandle.interruptQueuedMessage?.(t):void 0}):void 0,A=N?this.buildScrollableTodoList(V,this.isTextfieldAndAutocompleteFocused&&!D,Y):void 0,I=[],P=null,_=0,S=F.capabilities.emojiWidth,y=L?E.getTransportConnectionState?.():void 0;if(L&&y!==void 0)I.push({child:new $0({text:new C(`(dtw: ${y})`,new h({color:Q.mutedForeground,dim:!0}))}),position:"top-left"});let m=this.currentShellModeStatus;if(m)I.push({child:new $0({text:new C(m==="hidden"?"shell mode (incognito)":"shell mode",new h({color:m==="hidden"?Y.app.shellModeHidden:Y.app.shellMode}))}),position:"top-left"});if(this.handoffState.isInHandoffMode){let t=new h({color:Y.app.handoffMode}),V0=this.handoffState.isGeneratingHandoff&&this.handoffState.spinner?new C("",void 0,[new C("handoff ",t),new C(this.handoffState.spinner.toBraille(),t)]):new C("handoff (submit a goal for the new thread)",t);if(I.push({child:new $0({text:V0}),position:"top-left"}),this.handoffState.isGeneratingHandoff){let N0=new h({color:Q.foreground,dim:!0});I.push({child:new $0({text:new C("",void 0,[new C("Esc",new h({color:Y.app.keybind})),new C(" to cancel",N0)])}),position:"bottom-left"}),_=p5("Esc to cancel",S)}}if(this.handoffState.countdownSeconds!==null){let t=new h({color:Q.foreground,dim:!0}),V0=`Auto-submitting in ${this.handoffState.countdownSeconds}s`,N0=this.handoffState.countdownSeconds<10?1:0;I.push({child:new i0({padding:C0.only({right:N0}),child:new $0({text:new C(V0,new h({color:Y.app.handoffMode}))})}),position:"bottom-left"}),I.push({child:new $0({text:new C("",void 0,[new C("type",new h({color:Y.app.keybind})),new C(" to edit",t)])}),position:"bottom-left"}),_=p5("Auto-submitting in 10s",S)+2+p5("type to edit",S)}if(this.isInQueueMode){let t=new h({color:Y.app.queueMode});I.push({child:new $0({text:new C("queue",t)}),position:"top-left"})}let b=this.handoffController?.getEmptyHandoffParentThreadID(this.widget.dependencies.threadState.mainThread)??null,k=F.capabilities.animationSupport,f=k==="disabled"?0:k==="slow"?30:60,p=this.getEffectiveAgentMode(),l=rg(p),x=null,r=null,c=!1,s=this.agentModeController?.getVisibleModes()??[];if(!m&&!this.isInQueueMode&&s.length>1){let t=this.previewThread,V0=this.agentModeController?.getMode(),N0=t?t.agentMode??this.getEffectiveAgentMode():this.handoffState.isGeneratingHandoff&&V0?V0:this.getEffectiveAgentMode(),D0=this.formatAgentModeLabel(N0),O0=N0==="smart"&&this.anthropicSpeed==="fast",_0=rb(this.openAISpeed,y6(this.authStatus)?this.authStatus.features:this.tuiContext.features),e0=uK(N0)&&_0==="fast",a0=O0?"+fast(6x$)":e0?"+fast(2x$)":void 0,F1=a0?`${D0}${a0}`:D0,a1=rg(N0),o1=t??this.widget.dependencies.threadState.mainThread,m0=o1?W3(o1)>0:!1,V1="top-right";if(t){x=p5(F1,S);let t0=a0?new C("",void 0,[new C(D0,new h({color:a1})),new C(a0,new h({color:Q.warning}))]):new C(D0,new h({color:a1}));I.push({child:new $0({text:t0}),position:"top-right"})}else{let t0=!m0&&!this.handoffState.isGeneratingHandoff,A1=this.handoffState.isGeneratingHandoff,$4=new h({color:a1,dim:A1}),D6=new $0({text:a0?new C("",void 0,[new C(D0,$4),new C(a0,new h({color:Q.warning,dim:A1}))]):new C(D0,$4)}),m1=p5(F1,S),y4=t0?new n1({child:D6,onClick:()=>this.toggleAgentMode(),cursor:"pointer"}):D6,b4=[];if(x=m1,N0==="deep"&&!m0&&!this.handoffState.isGeneratingHandoff&&this.deepModeEffortHintController.isVisibleOrFalling()){let X4=this.deepModeEffortHintController.getHintWidth(S),S5=3;c=this.deepModeEffortHintController.isVisible()&&this.deepModeEffortHintController.isShimmering();let X6=this.deepModeEffortHintController.isVisible()&&!c?new $0({text:this.deepModeEffortHintController.buildVisibleTextSpan(Q.foreground)}):new R0({width:X4});b4.push(X6,new R0({width:3})),x+=X4+3,r=Q.foreground}if(b4.push(y4),this.showSkillsCountInPromptBar){let X4=this.availableSkillCountReady?this.availableSkillCount:this.widget.dependencies.skillService.listInstalled().length,S5=this.skillWarningCount>0||this.skillErrorCount>0,z1=`${S5?"⚠ ":""}${X4} ${m4(X4,"skill")}`,L4=2,T4=p5(z1,S);x+=2+T4;let i4=new h({color:S5?Q.warning:Q.foreground,dim:!S5});b4.push(new R0({width:2}),new n1({child:new $0({text:new C(z1,i4)}),onClick:()=>{this.setState(()=>{this.isShowingSkillListModal=!0})},cursor:"pointer"}))}I.push({child:new U1({mainAxisSize:"min",children:b4}),position:"top-right"})}}let a=f>0&&this.agentModePulseSeq>0&&!m&&!this.isInQueueMode&&!b&&s.length>1,F0=[];if(a){let V0=p2(p)?.uiHints?.fasterAnimation?3:1,N0=(x??0)+1,D0=N0>0?2+N0:1,O0=new x6({top:0,left:1,right:D0,height:1,child:new rp0({color:l,backgroundColor:Q.background,trigger:this.agentModePulseSeq,fps:f,speed:V0,trail:5,leftOffset:0,direction:"right-to-left"})});F0.push(O0)}if(c&&r&&x!==null){let t=this.deepModeEffortHintController.buildShimmerOverlay(x,r);if(t)F0.push(t)}if(this.deepModeEffortHintController.isFalling()&&r&&x!==null){let t=this.deepModeEffortHintController.buildFallingOverlay(x,r);if(t)F0.push(t)}if(F0.length>0)P=new x6({top:0,left:0,right:0,bottom:0,child:new i6({children:F0})});if(b&&this.handoffState.countdownSeconds===null){let t=this.handoffState.isConfirmingAbortHandoff?" again to abort ":" to abort ";I.push({child:new $0({text:new C("",void 0,[new C("Esc",new h({color:Y.app.keybind})),new C(t,new h({color:Q.foreground,dim:!0})),new C("handoff",new h({color:Y.app.handoffMode}))])}),position:"bottom-left"}),_=p5(`Esc${t}handoff`,S)}if(!b&&this.previousThreadIdForHint&&(X.mainThread?.messages.length??0)===0&&this.textController.text.trim()==="")I.push({child:new $0({text:new C("",void 0,[new C("press ",new h({color:Q.foreground,dim:!0})),new C("enter",new h({color:Y.app.keybind})),new C(" to reference the previous thread",new h({color:Q.foreground,dim:!0}))])}),position:"bottom-left"}),_=p5("press enter to reference the previous thread",S);let q0=X.mainThread?.env?.initial.trees?.[0]?.uri,Q0;if(q0)Q0=K1.parse(q0).fsPath;else Q0=process.cwd();let H0=this.toHomeRelative(Q0),i=this.shorten(H0),n=_>0?F.size.width-_-6:F.size.width-4,e=this.buildDisplayText(i,this.currentGitBranch||void 0,n,S);I.push({child:new $0({text:new C(e,new h({color:Q.foreground,dim:!0}))}),position:"bottom-right"});let J0=this.previewThread,Z0=this.widget.dependencies.threadState.mainThread;if((Z0?W3(Z0)>0:!1)&&!m&&!this.handoffState.isInHandoffMode&&!J0){let t=[],V0=new h({color:Q.foreground,dim:!0}),N0=new C(" · ",V0);if(G){let a0=G.totalInputTokens/G.maxInputTokens,F1=Math.round(a0*100),a1=Math.max(0,Math.min(F1,100)),o1=E$0(a0,G.maxInputTokens),m0=V0;if(o1==="danger")m0=new h({color:Q.destructive});else if(o1==="warning")m0=new h({color:Q.warning});else if(o1==="recommendation")m0=new h({color:Y.app.recommendation});if(t.length>0)t.push(N0);if(G.maxInputTokens>=1000){let V1=Math.round(G.maxInputTokens/1000);t.push(new C(`${a1}% of ${V1}k`,m0))}else t.push(new C(`${a1}%`,m0))}if(U&&this.threadCostInfo){let a0=nC(this.threadCostInfo,{colors:{foreground:Q.foreground},dim:!0});if(a0.length>0){if(t.length>0)t.push(N0);t.push(...a0)}}let D0=X.viewState,O0=D0.state==="active"?D0.turnStartTime:void 0,_0=D0.state==="active"?D0.turnElapsedMs:void 0,e0=null;if(X.mainThread?.agentMode==="deep"){let a0=O0?Date.now()-O0:_0;if(a0!==void 0){let F1=ru1(a0);e0=new $0({text:new C(F1,V0)})}}if(t.length>0||e0){let a0=[];if(t.length>0){let F1=new $0({text:new C("",void 0,t)});a0.push(U?new n1({child:F1,onClick:this.showContextDetailOverlay,cursor:"pointer"}):F1)}if(e0){if(t.length>0)a0.push(new $0({text:new C(" · ",V0)}));a0.push(e0)}I.push({child:new U1({mainAxisSize:"min",children:a0}),position:"top-left"})}}return new og0({leftChild:new T1({child:B}),rightChild1:M,rightChild2:A,maxHeight:K,overlayTexts:I,overlayLayer:P,backgroundColor:Q.background,borderColor:D||!this.isTextfieldAndAutocompleteFocused||this.handoffState.isGeneratingHandoff?Q.border:void 0,hasBanner:z,userHeight:this.bottomGridUserHeight,onInitializeHeight:(t)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(t,K)})},onDrag:(t)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(t.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let V0=Math.floor(t.localPosition.y)-this.bottomGridDragStartY,N0=Math.max(4,this.bottomGridDragStartHeight-V0),D0=Math.min(N0,K),O0=Math.floor(D0);if(this.bottomGridUserHeight!==O0)this.setState(()=>{this.bottomGridUserHeight=O0})},onDragRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null},enableResize:!z})}}function dM4(J){return J.resolvedTokenUsage}class cM4 extends d0{props;constructor(J){super();this.props=J}createState(){return new lM4}}class lM4 extends p0{viewportHeight=1;scrollListenerAttached=!1;initState(){if(!this.scrollListenerAttached)this.widget.props.controller.addListener(()=>{this.updateViewportHeight()}),this.scrollListenerAttached=!0}build(J){let{todos:Z,controller:Q,appTheme:Y}=this.widget.props;return new U1({crossAxisAlignment:"stretch",children:[new T1({child:new j6({controller:Q,autofocus:!1,child:new Zc0({todos:Z})})}),new u8({controller:Q,thumbColor:Y.app.scrollbarThumb,trackColor:Y.app.scrollbarTrack,getScrollInfo:()=>{let{maxScrollExtent:X,offset:V}=Q,K=this.viewportHeight,z=X+K;return{totalContentHeight:Math.max(z,0),viewportHeight:Math.max(K,1),scrollOffset:Math.max(V,0)}}})]})}updateViewportHeight(){let J=this.getViewportHeight();if(J!==this.viewportHeight)this.viewportHeight=J}getViewportHeight(){let J=this.context.findRenderObject();if(!J)return this.viewportHeight;let Z=(Y,X=0)=>{if(Y&&"size"in Y&&"children"in Y){let V=Y.children||[];for(let K of V){if(K&&"size"in K){let G=K.size;if(typeof G?.height==="number"&&G.height>0)return G.height}let z=Z(K,X+1);if(z>0)return z}}return 0},Q=Z(J);if(Q>0)return Q;if("size"in J){let Y=J.size;if(typeof Y?.height==="number"&&Y.height>0)return Y.height}return this.viewportHeight}}class iM4 extends d1{props;constructor(J){super();this.props=J}build(J){return new n1({child:new R0({height:1}),cursor:E5.NS_RESIZE,onDrag:(Z)=>{if(this.props.userHeight===void 0){let Y=J.findRenderObject()?.size.height??0;if(Y>0){this.props.onInitializeHeight(Y);return}}this.props.onDrag(Z)},onRelease:this.props.onRelease})}}function aM4(J){let Z=J.split(`
7501
7501
  `);try{return Z.map((Q)=>{let Y=Q.indexOf(":");if(Y===-1)return{label:"",content:nM4(Q)};let X=Q.slice(0,Y+1),V=Q.slice(Y+1);return{label:X,content:nM4(V)}})}catch(Q){return Z.map((Y)=>({label:"",content:[{type:"text",text:Y}]}))}}function nM4(J){let Z=[],Q=/(\+?\$[\d,.]+(?:\/\$[\d,.]+)?(?:\/hour)?)|(\busage paid\b|\bpaid\b)|(\s-\s(?=https?:\/\/))|((https?:\/\/)[^\s]+)|([^$\s][^\s]*)/gi,Y,X=0;while((Y=Q.exec(J))!==null){if(Y.index>X){let U=J.slice(X,Y.index);if(U)Z.push({type:"text",text:U})}let[V,K,z,G,F]=Y;if(K)Z.push({type:"amount",text:K});else if(z)Z.push({type:"paid",text:z});else if(G);else if(F)Z.push({type:"url",text:F});else{let U=V.replace(/\s+\)/g,")");Z.push({type:"text",text:U})}X=Q.lastIndex}if(X<J.length){let V=J.slice(X);if(V)Z.push({type:"text",text:V})}return Z}h$();async function Cs5(J){return aM4(J).map((Z)=>{let Q=Z.content.map((Y)=>{switch(Y.type){case"amount":case"paid":return Z1.bold.green(Y.text);case"url":return Z1.dim(" - ")+Z1.blue.underline(Y.text);default:return Z1.dim(Y.text)}}).join("");if(Z.label)return Z1.bold(Z.label)+Q;return Q}).join(`
7502
7502
  `)}function oM4(J,Z){J.command("usage").description("Show your current Amp usage and credit balance").action(async(Q,Y)=>{let X=Y.optsWithGlobals(),V=await Z(X),K=await V.settings.get("proxy"),z=qj1({settings:{url:V.ampURL,proxy:K},secrets:{getToken:(F,U)=>V.secrets.get(F,U)}}),G=await A6.userDisplayBalanceInfo({},{config:z});if(!G.ok){if(G.error.code==="auth-required")process.stderr.write(Z1.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(Z1.red("Error: ")+G.error.message+`
7503
7503
  `),process.exit(1)}process.stdout.write(await Cs5(G.result.displayText)+`
7504
7504
  `),process.exit(0)})}var a13=wB.join(y$,"logs","headless.log"),Sl0=wB.join(vC,"device-id.json");async function o13(){for(let J of GN)try{if((await J.listConfigs()).length>0)return J}catch(Z){j.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => D4(N_(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){E7.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
7505
- `)}function r13(J){process.emitWarning=(Z,Q,Y,X)=>{let V=typeof Z==="string"?Z:Z.message||String(Z),K=Q||"Warning",z=!1;J.warn(V,{name:K,code:Y})}}function O7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")u$("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")u$("experimental.agentMode",Z.mode)}function PR4(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 s13(J){try{return await jR4(J,"utf-8")}catch{return J}}async function vl0(J,Z,Q){let Y=PR4(J,Z);if(!Y)return;let X=y6(Q)?Q.features:[],V=y6(Q)?Q.user.email:void 0;if(!TR4(X,z2.HARNESS_SYSTEM_PROMPT)&&!CR4(V))throw new c1("You are not allowed to do this.",1);u$("systemPrompt",await s13(Y))}function CR4(J){return!!(J&&Ao(J))}function TR4(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function kl0(J){return(J.userEmail?vZ(J.userEmail):!1)||TR4(J.features,z2.DTW_TUI)}function wR4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new c1("This TUI mode is not enabled for your user;",1)}function yl0(J,Z){if(typeof J==="boolean")return J;if(!y6(Z))return!1;return kl0({userEmail:Z.user.email,features:Z.features})}function ul0(J){if(!y6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function t13(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 xl0(J){let Y=t13(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new c1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}var NR4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??cY,description:`Custom settings file path (overrides the default location ${cY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${hE})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:a9(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:xK.SMART.key,description:`Set the agent mode (${vX().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:vX().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],OR4=(J)=>("deprecated"in J)&&J.deprecated===!0,e13=(J)=>("hidden"in J)&&J.hidden===!0,$43=(J)=>("default"in J),J43=(J)=>("default"in J)?J.default:void 0,_R4=[{name:"toggle-skills-count",entryPoint:rx0}];function Z43(J,Z){let Q=Z.args[0],Y=Z.commands.map((V)=>V.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let V=Y.filter((z)=>Q.includes(z)||z.includes(Q)),K="Run amp --help for a list of available commands.";if(V.length>0)K=`Did you mean: ${V.join(", ")}? Or run amp --help for all commands.`;throw new c1(B8.unknownCommand(Q),1,K)}}async function bl0(J){return{...J,getThreadEnvironment:$J,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new JV(J.fileSystem),generateThreadTitle:r00,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>nJ(J.configService),pluginService:J.pluginService}}function SR4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:$J,filesystem:J.fileSystem,threadService:J.threadService}}var WZ0=K1.file(RR4.homedir()),fl0=process.env.XDG_CONFIG_HOME?K1.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(WZ0,".config");function Q43(J){return y24({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){k24(Z);let Q=L90(),Y=wf0();if((!Q||Y||Ez4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(jU("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(jU("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(L90()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function Y43(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>v0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function k9(J,Z,Q){let Y=Q?.deferAuth??!1;Xj1("0.0.1773425987-gff03c8");let X=Dr({storage:J.settings,secretStorage:J.secrets,workspaceRoots:v0.of([K1.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:WZ0,userConfigDir:fl0});Hz4(X);let V=await X.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(V.settings)});let{toolService:K,dispose:z}=C24({configService:X}),G=new Map,F=()=>G.clear(),U=new rL0(X,J.settings.getWorkspaceRootPath()),q=Xm1({configService:X,filesystem:r6}),D=iu1({configService:X,trustStore:U,skillMCPServers:q.skillMCPServers,createOAuthProvider:async(w0,a,F0)=>{let z0=`${w0}:${a}`,q0=G.get(z0);if(q0)return j.debug("Reusing existing OAuth provider for server",{serverName:w0,serverUrl:a}),q0;j.debug("Creating OAuth provider for server",{serverName:w0,serverUrl:a});let Q0=(async()=>{let H0=new _N(J.secrets),i=await H0.getClientInfo(w0,a),n=F0?.scopes??i?.scopes,e=wV4();j.info("OAuth headless mode check",{useHeadless:e,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:p6.isTTY});let J0;if(e)J0=J.executeMode?BV4():HV4(w0);let Z0=new WL0({storage:H0,serverName:w0,serverUrl:a,clientId:F0?.clientId??i?.clientId,clientSecret:F0?.clientSecret??i?.clientSecret,authUrl:F0?.authUrl??i?.authUrl,tokenUrl:F0?.tokenUrl??i?.tokenUrl,scopes:n,headlessAuthHandler:J0});return j.debug("OAuth provider created",{serverName:w0,serverUrl:a,hasManualClientId:!!(F0?.clientId??i?.clientId),willUseDCR:!(F0?.clientId??i?.clientId),scopes:n,headlessMode:e,executeMode:J.executeMode}),Z0})();return G.set(z0,Q0),Q0}}),W=tv0({configService:X,filesystem:r6,spawn:e50}),H;if(J.executeMode){let w0=await f84({toolService:K,providers:[D,W],initialTimeout:15000});H=w0.registrations;for(let[a,F0]of w0.initErrors)j.warn(`${a} provider initialization slow or failed:`,F0)}else H=ev0({toolService:K,providers:[D,W]});if(Z.jetbrains)XN("JetBrains");else if(Z.ide&&eV4())XN("VS Code");else if(Z.ide&&$K4())XN("Neovim");else if(Z.ide){let w0=await o13();if(w0){let a=Mr(w0.ideName);if(a)XN(a)}}if(J.executeMode)Vj1(!0);let B,w=m8.status.pipe(D1((w0)=>Boolean(w0.connected&&w0.authenticated&&w0.ideName&&bj1(w0.ideName))),M4()).subscribe((w0)=>{if(w0){if(!B)B=K.registerTool(x84)}else B?.dispose(),B=void 0}),N;if(!J.executeMode){let w0=await J.settings.get("fuzzy.alwaysIncludePaths")??[];N=new k80(process.cwd(),{alwaysIncludePaths:w0},!0)}else N=new class extends k80{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let O=!1;{let w0=await J.secrets.get("apiKey",J.ampURL);if(O=Boolean(w0),j.info("API key lookup before login",{found:Boolean(w0),ampURL:J.ampURL,deferAuth:Y}),!w0)if(Y)j.info("No API key found, continuing startup with deferred auth");else{p6.write(`No API key found. Starting login flow...
7505
+ `)}function r13(J){process.emitWarning=(Z,Q,Y,X)=>{let V=typeof Z==="string"?Z:Z.message||String(Z),K=Q||"Warning",z=!1;J.warn(V,{name:K,code:Y})}}function O7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")u$("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")u$("experimental.agentMode",Z.mode)}function PR4(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 s13(J){try{return await jR4(J,"utf-8")}catch{return J}}async function vl0(J,Z,Q){let Y=PR4(J,Z);if(!Y)return;let X=y6(Q)?Q.features:[],V=y6(Q)?Q.user.email:void 0;if(!TR4(X,z2.HARNESS_SYSTEM_PROMPT)&&!CR4(V))throw new c1("You are not allowed to do this.",1);u$("systemPrompt",await s13(Y))}function CR4(J){return!!(J&&Ao(J))}function TR4(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function kl0(J){return(J.userEmail?vZ(J.userEmail):!1)||TR4(J.features,z2.DTW_TUI)}function wR4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new c1("This TUI mode is not enabled for your user;",1)}function yl0(J,Z){if(typeof J==="boolean")return J;if(!y6(Z))return!1;return kl0({userEmail:Z.user.email,features:Z.features})}function ul0(J){if(!y6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function t13(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 xl0(J){let Y=t13(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new c1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}var NR4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??cY,description:`Custom settings file path (overrides the default location ${cY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${hE})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:a9(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:xK.SMART.key,description:`Set the agent mode (${vX().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:vX().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],OR4=(J)=>("deprecated"in J)&&J.deprecated===!0,e13=(J)=>("hidden"in J)&&J.hidden===!0,$43=(J)=>("default"in J),J43=(J)=>("default"in J)?J.default:void 0,_R4=[{name:"toggle-skills-count",entryPoint:rx0}];function Z43(J,Z){let Q=Z.args[0],Y=Z.commands.map((V)=>V.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let V=Y.filter((z)=>Q.includes(z)||z.includes(Q)),K="Run amp --help for a list of available commands.";if(V.length>0)K=`Did you mean: ${V.join(", ")}? Or run amp --help for all commands.`;throw new c1(B8.unknownCommand(Q),1,K)}}async function bl0(J){return{...J,getThreadEnvironment:$J,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new JV(J.fileSystem),generateThreadTitle:r00,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>nJ(J.configService),pluginService:J.pluginService}}function SR4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:$J,filesystem:J.fileSystem,threadService:J.threadService}}var WZ0=K1.file(RR4.homedir()),fl0=process.env.XDG_CONFIG_HOME?K1.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(WZ0,".config");function Q43(J){return y24({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){k24(Z);let Q=L90(),Y=wf0();if((!Q||Y||Ez4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(jU("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(jU("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(L90()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function Y43(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>v0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function k9(J,Z,Q){let Y=Q?.deferAuth??!1;Xj1("0.0.1773432280-gcd86a7");let X=Dr({storage:J.settings,secretStorage:J.secrets,workspaceRoots:v0.of([K1.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:WZ0,userConfigDir:fl0});Hz4(X);let V=await X.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(V.settings)});let{toolService:K,dispose:z}=C24({configService:X}),G=new Map,F=()=>G.clear(),U=new rL0(X,J.settings.getWorkspaceRootPath()),q=Xm1({configService:X,filesystem:r6}),D=iu1({configService:X,trustStore:U,skillMCPServers:q.skillMCPServers,createOAuthProvider:async(w0,a,F0)=>{let z0=`${w0}:${a}`,q0=G.get(z0);if(q0)return j.debug("Reusing existing OAuth provider for server",{serverName:w0,serverUrl:a}),q0;j.debug("Creating OAuth provider for server",{serverName:w0,serverUrl:a});let Q0=(async()=>{let H0=new _N(J.secrets),i=await H0.getClientInfo(w0,a),n=F0?.scopes??i?.scopes,e=wV4();j.info("OAuth headless mode check",{useHeadless:e,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:p6.isTTY});let J0;if(e)J0=J.executeMode?BV4():HV4(w0);let Z0=new WL0({storage:H0,serverName:w0,serverUrl:a,clientId:F0?.clientId??i?.clientId,clientSecret:F0?.clientSecret??i?.clientSecret,authUrl:F0?.authUrl??i?.authUrl,tokenUrl:F0?.tokenUrl??i?.tokenUrl,scopes:n,headlessAuthHandler:J0});return j.debug("OAuth provider created",{serverName:w0,serverUrl:a,hasManualClientId:!!(F0?.clientId??i?.clientId),willUseDCR:!(F0?.clientId??i?.clientId),scopes:n,headlessMode:e,executeMode:J.executeMode}),Z0})();return G.set(z0,Q0),Q0}}),W=tv0({configService:X,filesystem:r6,spawn:e50}),H;if(J.executeMode){let w0=await f84({toolService:K,providers:[D,W],initialTimeout:15000});H=w0.registrations;for(let[a,F0]of w0.initErrors)j.warn(`${a} provider initialization slow or failed:`,F0)}else H=ev0({toolService:K,providers:[D,W]});if(Z.jetbrains)XN("JetBrains");else if(Z.ide&&eV4())XN("VS Code");else if(Z.ide&&$K4())XN("Neovim");else if(Z.ide){let w0=await o13();if(w0){let a=Mr(w0.ideName);if(a)XN(a)}}if(J.executeMode)Vj1(!0);let B,w=m8.status.pipe(D1((w0)=>Boolean(w0.connected&&w0.authenticated&&w0.ideName&&bj1(w0.ideName))),M4()).subscribe((w0)=>{if(w0){if(!B)B=K.registerTool(x84)}else B?.dispose(),B=void 0}),N;if(!J.executeMode){let w0=await J.settings.get("fuzzy.alwaysIncludePaths")??[];N=new k80(process.cwd(),{alwaysIncludePaths:w0},!0)}else N=new class extends k80{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let O=!1;{let w0=await J.secrets.get("apiKey",J.ampURL);if(O=Boolean(w0),j.info("API key lookup before login",{found:Boolean(w0),ampURL:J.ampURL,deferAuth:Y}),!w0)if(Y)j.info("No API key found, continuing startup with deferred auth");else{p6.write(`No API key found. Starting login flow...
7506
7506
  `);let a=await X43(J),F0=await J.secrets.get("apiKey",J.ampURL);if(j.info("Login flow completed",{success:a,storedKeyPresent:Boolean(F0),ampURL:J.ampURL}),!a)await EU(),process.exit(1);O=!0}}{let w0=await X.getLatest(),a=w0.settings.url,F0=w0.secrets.isSet?.[a];j.info("Config secrets state after login",{configURL:a,apiKeySet:F0?.apiKey??!1})}let E=E1(nJ(X).pipe(F5((w0)=>w0!=="pending"))),L=await Um1({isDevelopment:!1}),M=Y?"pending":await E;if(!Y)j.info("Server status resolved",{status:"ready",isAuthenticated:y6(M),isError:RD(M),errorMessage:RD(M)?M.error.message:void 0});let A=new sI0(L,X),I=new cA0(L,{lazy:!0,maxThreads:200});j.info("Starting Amp background services");let P=Z.takeMeBack?!1:void 0,_=yl0(P,M),S=Boolean(_||Z.headless);if(S)j.info("DTW mode enabled: thread sync service disabled");let y=S?Y43():ug1({threadService:A,threadHistoryService:I,configService:X,isExtensionDevelopment:!1}),m;m8.status.subscribe((w0)=>{m=w0});let b=new Uw0({workspaceRoots:[K1.file(process.cwd())],fileSystem:Z.jetbrains||Z.ide?xt:r6,getCurrentFile:()=>{if(!m?.openFile)return;try{return K1.parse(m.openFile)}catch(w0){j.warn("Failed to parse current file URI",{uri:m.openFile,error:w0});return}},getOpenFiles:()=>{if(!m?.visibleFiles?.length)return[];let w0=m.openFile;return m.visibleFiles.filter((a)=>a!==w0).map((a)=>{try{return K1.parse(a)}catch(F0){return j.warn("Failed to parse visible file URI",{uri:a,error:F0}),null}}).filter((a)=>a!==null)}}),k=new Ef0,f=process.env.PLUGINS??"off",p=Z.headless?Jz4():void 0,l=p??new Q90({configService:X}),x=l instanceof Q90?l:void 0;if(x)x.pluginExecutorKind=_?"local":"unknown";let r=HM0({configService:X,fileSystem:Z.jetbrains||Z.ide?xt:r6,platform:l,internalPlugins:_R4,pluginFilter:f}),c=ax1({pluginService:r,toolService:K}),s={codebaseContextService:b,configService:X,toolService:K,mcpService:D,skillService:q,toolboxService:W,trustStore:U,threadService:A,threadHistoryService:I,threadSyncService:y,threadStorage:L,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:N,fileSystem:Z.jetbrains||Z.ide?xt:r6,terminal:k,pluginService:r,pluginPlatform:x,headlessPluginPlatform:p,serverStatus:M,serverStatusPromise:E,hasAPIKeyAtStartup:O};return{...s,async asyncDispose(){if(s.mcpService.hasAuthenticatingClients())j.info("Waiting for OAuth authentication to complete before exit..."),await s.mcpService.waitForAuthentication();for(let w0 of H.values())w0.dispose();await s.mcpService.dispose(),F(),await s.threadService.asyncDispose(),s.configService.unsubscribe(),z(),s.fuzzyServer.dispose(),s.threadSyncService.dispose(),s.settingsStorage[Symbol.dispose](),w.unsubscribe(),B?.dispose(),c.dispose(),await s.pluginService.dispose()}}}async function X43(J){if(!J.executeMode){if(!await ax0("Would you like to log in to Amp? [(y)es, (n)o]: "))return p6.write(`Login cancelled. Run the command again to retry.
7507
7507
  `),!1}return await vR4(J)}async function vR4(J){let Z=c13(32).toString("hex"),Q=await yC(J.ampURL,Z),Y=new AbortController;try{await fX(Q,Y.signal)}catch(V){j.error("Error opening browser",{error:V})}let X=await yC(J.ampURL,Z,!1);p6.write(`If your browser does not open automatically, visit:
7508
7508
 
@@ -7510,7 +7510,7 @@ ${Z1.blue.bold(X)}
7510
7510
 
7511
7511
  `);try{return await yK4(J.ampURL,Z,J.secrets,Y),p6.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(V){return j.error("Login failed",{error:V}),E7.write(`
7512
7512
  Login failed: ${V instanceof Error?V.message:String(V)}
7513
- `),!1}}function ER4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function V43(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new c1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!D8(Y.threadId))throw new c1("Create response did not include a valid thread ID",1);return Y.threadId}function K43(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 z43(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new c1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function G43(){let J=new sW().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)gE(),process.exit(0);let B=H.originalError??H;MX4(B)}),J.option("-V, --version","Print the version number and exit",()=>{let B;try{B=`, ${PD(new Date("2026-03-13T18:25:24.718Z"))} ago`}catch{}p6.write(`0.0.1773425987-gff03c8 (released 2026-03-13T18:25:24.718Z${B??""})
7513
+ `),!1}}function ER4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function V43(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new c1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!D8(Y.threadId))throw new c1("Create response did not include a valid thread ID",1);return Y.threadId}function K43(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 z43(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new c1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function G43(){let J=new sW().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)gE(),process.exit(0);let B=H.originalError??H;MX4(B)}),J.option("-V, --version","Print the version number and exit",()=>{let B;try{B=`, ${PD(new Date("2026-03-13T20:10:28.325Z"))} ago`}catch{}p6.write(`0.0.1773432280-gcd86a7 (released 2026-03-13T20:10:28.325Z${B??""})
7514
7514
  `),process.exit(0)}),J.addHelpText("after",rV4()),J.configureHelp({formatHelp:sV4}),J.command("logout").description("Log out by removing stored API key").action(async(H,B)=>{let w=B.optsWithGlobals(),N=await E3(w);await B43(N)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(H,B)=>{let w=B.optsWithGlobals(),N=await E3(w);await H43(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 E3(N);await aX4(H??"get",O.ampURL,O.secrets),process.exit(process.exitCode??0)}),J.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(H,B)=>{let w=B.optsWithGlobals(),N=await E3(w);await oX4(N.ampURL,N.secrets),process.exit(process.exitCode??0)}),J.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
7515
7515
  Actions:
7516
7516
  create Create a new DTW thread and print its ID
@@ -7573,8 +7573,8 @@ ${L}
7573
7573
 
7574
7574
  This thread belongs to a different user and cannot be continued for security reasons. Set AMP_RESUME_OTHER_USER_THREADS_INSECURE=1 to bypass this check.`)}}async function F43(J){j.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new Lg({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized]).then(()=>{return}),toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:$J,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new JV(J.fileSystem),ampURL:J.ampURL});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw j.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function U43(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await mC()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await mC()).trimEnd(),stdinInput:null}}function q43(J,Z,Q){if(J.remote&&!Z)throw new c1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new c1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new c1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new c1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new c1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new c1("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(J.streamJsonInput&&typeof J.execute==="string"&&J.execute.trim()!=="")throw new c1("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"}]}}' | amp --execute --stream-json --stream-json-input`);if(Z&&Q===""&&!J.streamJsonInput&&!J.headless)throw new c1("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
7575
7575
  Or pipe via stdin: echo "your message" | amp --execute`)}async function HZ0(J,Z,Q){let Y=process.hrtime.bigint(),X=(z0,q0)=>{let Q0=Number(process.hrtime.bigint()-q0)/1e6,H0=A$4();j.info("Startup phase",{phase:z0,phaseMs:Math.round(Q0),sinceMainMs:H0===null?void 0:Math.round(H0)})},{userInput:V,stdinInput:K}=await U43(Z),z=!!Z.streamJson||!!Z.streamJsonThinking;q43({...Z,streamJson:z},J.executeMode,V),O7(Q,Z);let G=process.hrtime.bigint(),F=Boolean(await J.secrets.get("apiKey",J.ampURL)),U=!J.executeMode&&!Z.headless&&F;j.info("Interactive auth startup mode",{deferInteractiveAuth:U,hasAPIKeyAtStartup:F,executeMode:J.executeMode,headless:Boolean(Z.headless)});let q=await k9(J,Z,{deferAuth:U});X("runMainThread:createThreadDependencies",G),G=process.hrtime.bigint();let D=await bl0(q);X("runMainThread:createWorkerDeps",G);let{serverStatus:W}=q;if(!U&&RD(W)){let z0=ym(Error(W.error.message));if(z0.message===B8.networkOffline||z0.message===B8.networkTimeout)throw xl0(J.ampURL);throw new c1(B8.invalidAPIKey,1)}let H=y6(W)?W:null,B=H?.user.email,w=CR4(B),N=kl0({userEmail:B,features:H?.features}),O=Z.takeMeBack?!1:void 0,E=H!==null&&yl0(O,H);if(!U)await vl0(Q,Z,W);let L=ul0(W),M=L?.features??[],A=L?.team??null,I=J90(Z,L);if(I instanceof Error)G3(I.message);if((J.executeMode||z)&&h3(Z.mode)&&!w)throw new c1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(H&&!iq(Z.mode,B))throw new c1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await Yz4(V,K,q.configService),await q.asyncDispose(),process.exit(0);if(Z.headless){if(!B||!vZ(B))throw new c1("Headless DTW mode is only available for Amp employees",1);let z0=await q.secretStorage.get("apiKey",J.ampURL);if(!z0)throw new c1("API key required for headless mode. Please run `amp login` first.",1);let q0=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if(q0&&!D8(q0))throw new c1(`Invalid thread ID: ${q0}`,1);let Q0=q0??await I43({dependencies:q,visibility:I??void 0}),H0=await LV4(Q0);if(H0.status==="already-running")await q.asyncDispose(),await EU(),process.exit(0);try{await WV4({ampURL:J.ampURL,apiKey:z0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:Q0,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 H0.release(),await q.asyncDispose()}await EU(),process.exit(0)}let P={threadService:q.threadService,workerDeps:D,createThread:async()=>{let z0=U?await q.serverStatusPromise:W,q0=await N80(J.settings,process.cwd(),ul0(z0),I);if(q0 instanceof Error)G3(q0.message);return um0(D,{threadMeta:q0?yV(q0):void 0,agentMode:Z.mode,onFirstAssistantMessage:LR4})},validateThreadOwnership:async(z0,q0)=>{if(q0?.nonBlockingOwnershipCheck){MR4(z0,q.configService).catch((Q0)=>{if(Q0 instanceof c1){if(q0.onOwnershipError){q0.onOwnershipError(Q0,z0);return}RC(Q0,z0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})});return}try{await MR4(z0,q.configService)}catch(Q0){if(Q0 instanceof c1)throw Q0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})}},switchThreadVisibility:I,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:LR4},_=async(z0)=>{try{if(z0==="dtw")return F43({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 IH4(P,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(q0){if(q0 instanceof c1)throw q0;throw await RC(q0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")E7.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
7576
- `),await EU(),process.exit(1);let S=(async()=>{if(U){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await q.configService.getLatest(),q0=_k(z0),Q0=await A6.getUserFreeTierStatus({},{config:q.configService,signal:AbortSignal.timeout(q0)});if(Q0.ok)return j.info("User free tier status:",Q0),Q0.result;return}catch(z0){j.error("Failed to fetch free tier status:",z0);return}})(),m=!J.executeMode?new _f0:null,b,k=null;if(m)b=m,k=(async()=>{let z0=U?await q.serverStatusPromise:q.serverStatus;await vl0(Q,Z,z0);let q0=process.hrtime.bigint(),Q0=yl0(O,z0),H0=y6(z0)?kl0({userEmail:z0.user.email,features:z0.features}):!1;wR4({dtwEnabled:Q0,hasV2TUIAccess:H0});let i=await _(Q0?"dtw":"worker");if(X("runMainThread:createThreadPool",q0),m.attach(i),V){let n=await E1(i.threadHandles$);if(!n)throw new c1("No active thread is available yet.",1);await n.sendMessage({content:[{type:"text",text:V}]})}})(),k.catch(async(z0)=>{let q0=z0 instanceof Error?z0:Error(String(z0));m.setInitError(q0),await RC(z0,Z.threadId)});else G=process.hrtime.bigint(),wR4({dtwEnabled:E,hasV2TUIAccess:N}),b=await _(E?"dtw":"worker"),X("runMainThread:createThreadPool",G);let f=Z.notifications!==void 0?Z.notifications:!J.executeMode;G=process.hrtime.bigint();let p=await q.configService.getLatest();if(X("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),Q43({configService:q.configService,threadService:q.threadService,config:p,useNotificationsForService:f,threadViewStates$:()=>b.threadHandles$.pipe(Q4((z0)=>{if(!z0)return v0.of({});return X5(z0.thread$,z0.threadViewState$).pipe(D1(([q0,Q0])=>({[q0.id]:Q0})))}))}),X("runMainThread:createCliNotificationService",G),J.executeMode){iK4(q.mcpService,J.settings);let z0={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},q0=await kX4({threadPool:b,...z0});if(Z.archive)await A6.archiveThread({thread:q0,archived:!0},{config:q.configService});await q.asyncDispose(),process.exit(0)}let l=!1,x=!1;if(Z.jetbrains||Z.ide){await cj1();let z0=await UN({jetbrainsOnly:Z.jetbrains});if(z0.length===0){if(Z.jetbrains)l=!await q.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let q0=z0[0];if(q0)m8.selectConfig(q0)}else x=!0}G=process.hrtime.bigint();let r=ix0("0.0.1773425987-gff03c8",q.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let c=new dA0(q.threadStorage);X("runMainThread:createThreadFuzzyIndexer",G),G=process.hrtime.bigint();let s=new ox0(q.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",G),V&&J.executeMode){let z0=await E1(b.threadHandles$);if(!z0)throw new c1("No active thread is available yet.",1);await z0.sendMessage({content:[{type:"text",text:V}]})}G=process.hrtime.bigint();let w0=await oz();X("runMainThread:loadSessionState",G),j.info("Loaded session state:",w0);let a={...w0,launchCount:w0.launchCount+1};rz(a);let F0=Z.threadId&&D8(Z.threadId)?Z.threadId:void 0;try{if(G=process.hrtime.bigint(),await vB4({codebaseContextService:q.codebaseContextService,history:new Fx0,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadHistoryService:q.threadHistoryService,threadFuzzyIndexer:c,skillService:q.skillService,configService:q.configService,secretStorage:q.secretStorage,internalAPIClient:A6,threadPool:b,createSystemPromptDeps:async()=>SR4(q),ideClient:m8,mcpService:q.mcpService,toolboxService:q.toolboxService,mcpTrustHandler:s,updateService:r,pluginPlatform:q.pluginPlatform,pluginService:q.pluginService},{initialServerStatus:q.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:q.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:F0,showJetBrainsInstaller:l,showIdePickerHint:x,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:a,freeTierStatusPromise:S,workspace:A??null,features:M,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-13T18:25:24.718Z"},(z0)=>new Kg0({...z0,threadPool:z0.threadPool},(q0)=>new Qc0({...q0,threadState:q0.threadState}))),X("runMainThread:mountApp-returned",G),k)await k}finally{}await q.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function E3(J){if(j.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)E7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7577
- `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await tu1({get:async(z)=>{if(z!==Au)return;try{let G=await jR4(Sl0,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==Au)return;await IR4(wB.dirname(Sl0),{recursive:!0}),await l13(Sl0,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:gK()});Kj1(Y);let X=await yV4({...J,workspaceTrust:{current:!0,changes:Wk},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 cK4(J.mcpConfig);X=lK4(X,z)}let V=wB.dirname(X.getSettingsFilePath());v24(vC,V);let K=await X.get("url","global");if(!K)K=J7;if(j.info("Resolved Amp URL",{ampURL:K,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!QD(K))j.info("Targeting custom Amp server",{ampURL:K});return X=sI1(X),{executeMode:Z,isTTY:Q,ampURL:K,settings:X,secrets:Gz4(await Px0(J,X))}}function D43(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let V=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),K=J[Q+1];if(K&&!K.startsWith("--"))Z[V]=K,Q++}}return Z}async function W43(){M$4();let J=D43(process.argv),Z=process.argv.includes("--headless")||process.argv.some((V)=>V.startsWith("--headless="));uY4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?a13:void 0)});let Q=process.argv.includes("--no-color"),Y=process.argv.includes("--color"),X=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!Y&&!X)Z1.level=0;if(r13(j),j.info("Starting Amp CLI.",{version:"0.0.1773425987-gff03c8",buildTimestamp:"2026-03-13T18:25:24.718Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new c1(B8.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await G43().parseAsync(process.argv)}_24().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await W43().catch(RC)});async function H43(J,Z){let Q=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Q)await J.settings.set("url",process.env.AMP_URL,"global"),p6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7576
+ `),await EU(),process.exit(1);let S=(async()=>{if(U){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await q.configService.getLatest(),q0=_k(z0),Q0=await A6.getUserFreeTierStatus({},{config:q.configService,signal:AbortSignal.timeout(q0)});if(Q0.ok)return j.info("User free tier status:",Q0),Q0.result;return}catch(z0){j.error("Failed to fetch free tier status:",z0);return}})(),m=!J.executeMode?new _f0:null,b,k=null;if(m)b=m,k=(async()=>{let z0=U?await q.serverStatusPromise:q.serverStatus;await vl0(Q,Z,z0);let q0=process.hrtime.bigint(),Q0=yl0(O,z0),H0=y6(z0)?kl0({userEmail:z0.user.email,features:z0.features}):!1;wR4({dtwEnabled:Q0,hasV2TUIAccess:H0});let i=await _(Q0?"dtw":"worker");if(X("runMainThread:createThreadPool",q0),m.attach(i),V){let n=await E1(i.threadHandles$);if(!n)throw new c1("No active thread is available yet.",1);await n.sendMessage({content:[{type:"text",text:V}]})}})(),k.catch(async(z0)=>{let q0=z0 instanceof Error?z0:Error(String(z0));m.setInitError(q0),await RC(z0,Z.threadId)});else G=process.hrtime.bigint(),wR4({dtwEnabled:E,hasV2TUIAccess:N}),b=await _(E?"dtw":"worker"),X("runMainThread:createThreadPool",G);let f=Z.notifications!==void 0?Z.notifications:!J.executeMode;G=process.hrtime.bigint();let p=await q.configService.getLatest();if(X("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),Q43({configService:q.configService,threadService:q.threadService,config:p,useNotificationsForService:f,threadViewStates$:()=>b.threadHandles$.pipe(Q4((z0)=>{if(!z0)return v0.of({});return X5(z0.thread$,z0.threadViewState$).pipe(D1(([q0,Q0])=>({[q0.id]:Q0})))}))}),X("runMainThread:createCliNotificationService",G),J.executeMode){iK4(q.mcpService,J.settings);let z0={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},q0=await kX4({threadPool:b,...z0});if(Z.archive)await A6.archiveThread({thread:q0,archived:!0},{config:q.configService});await q.asyncDispose(),process.exit(0)}let l=!1,x=!1;if(Z.jetbrains||Z.ide){await cj1();let z0=await UN({jetbrainsOnly:Z.jetbrains});if(z0.length===0){if(Z.jetbrains)l=!await q.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let q0=z0[0];if(q0)m8.selectConfig(q0)}else x=!0}G=process.hrtime.bigint();let r=ix0("0.0.1773432280-gcd86a7",q.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let c=new dA0(q.threadStorage);X("runMainThread:createThreadFuzzyIndexer",G),G=process.hrtime.bigint();let s=new ox0(q.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",G),V&&J.executeMode){let z0=await E1(b.threadHandles$);if(!z0)throw new c1("No active thread is available yet.",1);await z0.sendMessage({content:[{type:"text",text:V}]})}G=process.hrtime.bigint();let w0=await oz();X("runMainThread:loadSessionState",G),j.info("Loaded session state:",w0);let a={...w0,launchCount:w0.launchCount+1};rz(a);let F0=Z.threadId&&D8(Z.threadId)?Z.threadId:void 0;try{if(G=process.hrtime.bigint(),await vB4({codebaseContextService:q.codebaseContextService,history:new Fx0,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadHistoryService:q.threadHistoryService,threadFuzzyIndexer:c,skillService:q.skillService,configService:q.configService,secretStorage:q.secretStorage,internalAPIClient:A6,threadPool:b,createSystemPromptDeps:async()=>SR4(q),ideClient:m8,mcpService:q.mcpService,toolboxService:q.toolboxService,mcpTrustHandler:s,updateService:r,pluginPlatform:q.pluginPlatform,pluginService:q.pluginService},{initialServerStatus:q.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:q.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:F0,showJetBrainsInstaller:l,showIdePickerHint:x,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:a,freeTierStatusPromise:S,workspace:A??null,features:M,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-13T20:10:28.325Z"},(z0)=>new Kg0({...z0,threadPool:z0.threadPool},(q0)=>new Qc0({...q0,threadState:q0.threadState}))),X("runMainThread:mountApp-returned",G),k)await k}finally{}await q.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function E3(J){if(j.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)E7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7577
+ `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await tu1({get:async(z)=>{if(z!==Au)return;try{let G=await jR4(Sl0,"utf-8");return JSON.parse(G).installationID}catch{return}},set:async(z,G)=>{if(z!==Au)return;await IR4(wB.dirname(Sl0),{recursive:!0}),await l13(Sl0,JSON.stringify({installationID:G},null,2),{mode:384})}},{clientType:"cli",platform:gK()});Kj1(Y);let X=await yV4({...J,workspaceTrust:{current:!0,changes:Wk},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 cK4(J.mcpConfig);X=lK4(X,z)}let V=wB.dirname(X.getSettingsFilePath());v24(vC,V);let K=await X.get("url","global");if(!K)K=J7;if(j.info("Resolved Amp URL",{ampURL:K,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!QD(K))j.info("Targeting custom Amp server",{ampURL:K});return X=sI1(X),{executeMode:Z,isTTY:Q,ampURL:K,settings:X,secrets:Gz4(await Px0(J,X))}}function D43(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let V=Y.slice(2).replace(/-([a-z])/g,(z,G)=>G.toUpperCase()),K=J[Q+1];if(K&&!K.startsWith("--"))Z[V]=K,Q++}}return Z}async function W43(){M$4();let J=D43(process.argv),Z=process.argv.includes("--headless")||process.argv.some((V)=>V.startsWith("--headless="));uY4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?a13:void 0)});let Q=process.argv.includes("--no-color"),Y=process.argv.includes("--color"),X=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!Y&&!X)Z1.level=0;if(r13(j),j.info("Starting Amp CLI.",{version:"0.0.1773432280-gcd86a7",buildTimestamp:"2026-03-13T20:10:28.325Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new c1(B8.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await G43().parseAsync(process.argv)}_24().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await W43().catch(RC)});async function H43(J,Z){let Q=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Q)await J.settings.set("url",process.env.AMP_URL,"global"),p6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7578
7578
  `);else if(!QD(J.ampURL))p6.write(`Logging in to ${new URL(J.ampURL).hostname}
7579
7579
  `);let Y=process.env.AMP_API_KEY;if(Y)p6.write(`API key found in environment variable, storing...
7580
7580
  `),await Z.set("apiKey",Y,J.ampURL),p6.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1773425987-gff03c8",
3
+ "version": "0.0.1773432280-gcd86a7",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {