@sourcegraph/amp 0.0.1769716999-gdf283f → 0.0.1769719558-g98dc3a

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 +12 -12
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -7770,11 +7770,11 @@ ${U}`))}},error:(F)=>{if(!z)z=!0,K(Error(`Failed to spawn brew: ${F.message}`))}
7770
7770
  ${U}`;if(X==="pnpm"&&U.includes("Unable to find the global bin directory"))D+=`
7771
7771
 
7772
7772
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
7773
- npm install -g @sourcegraph/amp`;K(Error(D))}},error:(F)=>{if(!H)H=!0,K(Error(`Failed to spawn ${X}: ${F.message}`))},complete:()=>{if(!H)H=!0,V()}})})}b1();b1();Vj();async function p91(J,Q){let Y=Q||"https://registry.npmjs.org",X=new AbortController,G=setTimeout(()=>X.abort(),5000);try{let V=await fetch(`${Y}/@sourcegraph/amp`,{signal:X.signal});if(!V.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await V.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=qX6(J,q),H=W<0,z,F;if(K.time){let U=K.time[J],D=K.time[q],B=Date.now();if(U)z=Math.floor((B-new Date(U).getTime())/3600000);if(D)F=Math.floor((B-new Date(D).getTime())/3600000)}return E.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:F}),{hasUpdate:H,latestVersion:q,currentVersion:J,currentVersionAge:z,latestVersionAge:F,source:"npm"}}catch(V){return E.debug("Error checking npm version",{error:V}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(G)}}var kL8="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function d91(J){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),5000);try{let Y=await fetch(`${kL8}?t=${Date.now()}`,{signal:Q.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 G=qX6(J,X),V=G<0;return E.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:G,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return E.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Z)}}var yL8=604800000;function KX6(J){if(!J)return null;let Q=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Q))return null;let Z=Date.now()-Q;if(Z>yL8)return{ageMs:Z};return null}function qX6(J,Q){let Z=(V)=>{let[K,q]=V.split("-");return{parts:K?.split(".").map(Number)||[],label:q}},Y=Z(J),X=Z(Q),G=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<G;V++){let K=Y.parts[V]||0,q=X.parts[V]||0;if(K<q)return-1;if(K>q)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 nx1(J){try{let Q=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Q)return null;let Z=parseInt(Q[1],10)*1000,Y=Q[2],X=Z!==0?Rz(Z):void 0;return{sha:Y,age:X}}catch{return null}}K0();function c91(J,Q){let Z=new F6,Y=Z.pipe(q4({shouldCountRefs:!1}));return setImmediate(async()=>{let X=new hG().scoped("update"),G=Y.subscribe({next:(V)=>{X.debug("emit new state",V)}});try{let V=process.env.AMP_TEST_UPDATE_STATUS;if(V){X.debug("using fake update status for testing",{status:V}),await KL(500),Z.next(V);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){X.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let K=await Q.get("updates.mode");if(K==="disabled"){X.debug("checking disabled");return}let q=await u91(),W=q==="binary"||q==="brew";X.debug("checking",{currentVersion:J,mode:K,packageManager:q,isBinaryDistribution:W});let H=W?await d91(J):await p91(J,Dw());if(!(H.latestVersion&&H.hasUpdate)){X.debug("no update available");return}let z=()=>{if(H.currentVersionAge!==void 0&&H.latestVersionAge!==void 0){let F=H.currentVersionAge-H.latestVersionAge,U=0.5;if(Math.abs(F)<0.5)return X.debug("versions too close together, suppressing update warning",{currentVersionAge:H.currentVersionAge,latestVersionAge:H.latestVersionAge,ageDifferenceHours:F}),!0}return!1};if(!K)K=q==="pnpm"?"warn":"auto",X.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:K});if(q==="brew"){if(!z())Z.next("update-available-brew");return}if(q==="binary"&&process.execPath!==ux1()){if(X.debug("non-standard binary path, showing warning"),!z())Z.next("update-available-unrecognized-path");return}if(K==="warn"){if(!z())Z.next("update-available");return}if(!q){if(X.debug("auto-update not supported, falling back to warn mode"),!z())Z.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(X.debug("binary auto-update not supported on Windows, falling back to warn mode"),!z())Z.next("update-available");return}try{await Tg(H.latestVersion,q);let F=await vU(H.latestVersion),U={from:H.currentVersion,to:H.latestVersion,...F};if(F.status==="same")X.info("success",U),Z.next("updated");else X.warn("success with warning",U),Z.next("updated-with-warning")}catch(F){Z.next("update-error")}}catch(V){X.debug("check failed",{error:V})}finally{await KL(5000),Z.next("hidden"),G.unsubscribe(),Z.complete()}}),{state:Y}}Vj();import{stderr as BK}from"node:process";function WX6(J){let Q=new nV().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 fx1(Y.force||!1,Y.verbose||!1,"0.0.1769716999-gdf283f"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new nV("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 xL8(Y.targetVersion)});J.addCommand(Z)}async function xL8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")BK.write(p1.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
7773
+ npm install -g @sourcegraph/amp`;K(Error(D))}},error:(F)=>{if(!H)H=!0,K(Error(`Failed to spawn ${X}: ${F.message}`))},complete:()=>{if(!H)H=!0,V()}})})}b1();b1();Vj();async function p91(J,Q){let Y=Q||"https://registry.npmjs.org",X=new AbortController,G=setTimeout(()=>X.abort(),5000);try{let V=await fetch(`${Y}/@sourcegraph/amp`,{signal:X.signal});if(!V.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await V.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=qX6(J,q),H=W<0,z,F;if(K.time){let U=K.time[J],D=K.time[q],B=Date.now();if(U)z=Math.floor((B-new Date(U).getTime())/3600000);if(D)F=Math.floor((B-new Date(D).getTime())/3600000)}return E.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:F}),{hasUpdate:H,latestVersion:q,currentVersion:J,currentVersionAge:z,latestVersionAge:F,source:"npm"}}catch(V){return E.debug("Error checking npm version",{error:V}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(G)}}var kL8="https://storage.googleapis.com/amp-public-assets-prod-0/cli/cli-version.txt";async function d91(J){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),5000);try{let Y=await fetch(`${kL8}?t=${Date.now()}`,{signal:Q.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 G=qX6(J,X),V=G<0;return E.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:G,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return E.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Z)}}var yL8=604800000;function KX6(J){if(!J)return null;let Q=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Q))return null;let Z=Date.now()-Q;if(Z>yL8)return{ageMs:Z};return null}function qX6(J,Q){let Z=(V)=>{let[K,q]=V.split("-");return{parts:K?.split(".").map(Number)||[],label:q}},Y=Z(J),X=Z(Q),G=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<G;V++){let K=Y.parts[V]||0,q=X.parts[V]||0;if(K<q)return-1;if(K>q)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 nx1(J){try{let Q=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Q)return null;let Z=parseInt(Q[1],10)*1000,Y=Q[2],X=Z!==0?Rz(Z):void 0;return{sha:Y,age:X}}catch{return null}}K0();function c91(J,Q){let Z=new F6,Y=Z.pipe(q4({shouldCountRefs:!1}));return setImmediate(async()=>{let X=new hG().scoped("update"),G=Y.subscribe({next:(V)=>{X.debug("emit new state",V)}});try{let V=process.env.AMP_TEST_UPDATE_STATUS;if(V){X.debug("using fake update status for testing",{status:V}),await KL(500),Z.next(V);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){X.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let K=await Q.get("updates.mode");if(K==="disabled"){X.debug("checking disabled");return}let q=await u91(),W=q==="binary"||q==="brew";X.debug("checking",{currentVersion:J,mode:K,packageManager:q,isBinaryDistribution:W});let H=W?await d91(J):await p91(J,Dw());if(!(H.latestVersion&&H.hasUpdate)){X.debug("no update available");return}let z=()=>{if(H.currentVersionAge!==void 0&&H.latestVersionAge!==void 0){let F=H.currentVersionAge-H.latestVersionAge,U=0.5;if(Math.abs(F)<0.5)return X.debug("versions too close together, suppressing update warning",{currentVersionAge:H.currentVersionAge,latestVersionAge:H.latestVersionAge,ageDifferenceHours:F}),!0}return!1};if(!K)K=q==="pnpm"?"warn":"auto",X.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:K});if(q==="brew"){if(!z())Z.next("update-available-brew");return}if(q==="binary"&&process.execPath!==ux1()){if(X.debug("non-standard binary path, showing warning"),!z())Z.next("update-available-unrecognized-path");return}if(K==="warn"){if(!z())Z.next("update-available");return}if(!q){if(X.debug("auto-update not supported, falling back to warn mode"),!z())Z.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(X.debug("binary auto-update not supported on Windows, falling back to warn mode"),!z())Z.next("update-available");return}try{await Tg(H.latestVersion,q);let F=await vU(H.latestVersion),U={from:H.currentVersion,to:H.latestVersion,...F};if(F.status==="same")X.info("success",U),Z.next("updated");else X.warn("success with warning",U),Z.next("updated-with-warning")}catch(F){Z.next("update-error")}}catch(V){X.debug("check failed",{error:V})}finally{await KL(5000),Z.next("hidden"),G.unsubscribe(),Z.complete()}}),{state:Y}}Vj();import{stderr as BK}from"node:process";function WX6(J){let Q=new nV().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 fx1(Y.force||!1,Y.verbose||!1,"0.0.1769719558-g98dc3a"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new nV("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 xL8(Y.targetVersion)});J.addCommand(Z)}async function xL8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")BK.write(p1.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
7774
7774
 
7775
7775
  `));try{if(!J){BK.write(p1.blue(`Checking for updates...
7776
- `));let{hasUpdate:Y,latestVersion:X}=hx1()?await d91("0.0.1769716999-gdf283f"):await p91("0.0.1769716999-gdf283f",Dw());if(!Y){let G=nx1("0.0.1769716999-gdf283f"),V=G?.age?`released ${G.age} ago`:`built ${Rz(new Date("2026-01-29T20:08:22.760Z"))} ago`;BK.write(p1.green(`✓ Amp is already up to date on version ${"0.0.1769716999-gdf283f"} (${V})
7777
- `));let K=await vU("0.0.1769716999-gdf283f");if(K.warning)BK.write(`
7776
+ `));let{hasUpdate:Y,latestVersion:X}=hx1()?await d91("0.0.1769719558-g98dc3a"):await p91("0.0.1769719558-g98dc3a",Dw());if(!Y){let G=nx1("0.0.1769719558-g98dc3a"),V=G?.age?`released ${G.age} ago`:`built ${Rz(new Date("2026-01-29T20:51:01.893Z"))} ago`;BK.write(p1.green(`✓ Amp is already up to date on version ${"0.0.1769719558-g98dc3a"} (${V})
7777
+ `));let K=await vU("0.0.1769719558-g98dc3a");if(K.warning)BK.write(`
7778
7778
  `+p1.yellow(K.warning)+`
7779
7779
  `);process.exit(0)}if(!X)BK.write(p1.yellow("[WARN] could not find latest version")),process.exit(0);J=X}BK.write(p1.blue(`Updating to version ${J}...
7780
7780
  `)),await Tg(J,void 0,(Y)=>{BK.write(p1.dim(`Running: ${Y}
@@ -8537,7 +8537,7 @@ exit code: ${G}`,new g({color:Y.foreground,dim:!0,italic:!0})));if(V)K.push(new
8537
8537
 
8538
8538
  (Command and output not shown to agent)`,new g({color:Y.foreground,dim:!0,italic:!0})));if(K.length===0)return null;return new J1({text:new y("",void 0,K),selectable:!0})}function MH6(J,Q){let Z=v1.of(Q),Y=UU(J);if(Y?.visibility===FU)return Z.app.shellModeHidden;if(Y?.visibility===B81)return Z.app.shellMode;return Z.app.userMessage}function LH6(J,Q,Z,Y){if(Q.length===0)return null;let G=v1.maybeOf(J)?.colors??B0.of(J).colorScheme,V=[new J1({text:new y("Images: ",new g({color:G.foreground,dim:!0}))})];for(let K=0;K<Q.length;K++){let q=K;if(V.push(new B6({onClick:()=>Y(q),cursor:"pointer",child:new J1({text:new y(`[image ${K+1}]`,new g({color:Z.color,italic:Z.italic,underline:!0}))})})),K<Q.length-1)V.push(new J1({text:new y(" ")}))}return new s1({padding:I1.only({}),child:new Z0({mainAxisSize:"min",children:V})})}function gC8(J,Q){if(Q.length===0)return null;let Z=[];for(let Y of Q)Z.push(new J1({text:new y(`Loaded ${eQ(Y.uri)} (${Y.lineCount} lines)`,new g({color:v1.of(J).app.toolSuccess,dim:!0})),selectable:!0}));if(Z.length===1)return Z[0];return new S1({mainAxisSize:"min",crossAxisAlignment:"start",children:Z})}function wH6(J){let Q=[];for(let Z of J.content)if(Z.type==="text")Q.push(Z.text);return Q.join(`
8539
8539
  `).trim()}function Ff1(J,Q,Z,Y){let X=[];if(X.push(new y(J,Q)),Z)X.push(new y(" (interrupted)",new g({color:Y,italic:!0})));return new J1({text:new y("",void 0,X),selectable:!0})}class RT extends _0{props;constructor(J){super();this.props=J}build(J){let Q=this.props.message,Z=v1.of(J),{colors:Y}=Z,X="",G,V,K=null;if(Q.role==="info"){let z=Ja(Q);if(!z)return new m1;X=`${p36(z.hidden??!1)} ${z.args.cmd}`;let U=MH6(X,J);G=U,V=U,K=Df1(J,z)}else{X=wH6(Q);let z=Q.interrupted?Y.warning:Y.success;V=z,G=z}let q=new g({color:V,italic:!0}),W=[];if(Q.role==="user"){let z=Q.content.filter((D)=>D.type==="image"),U=LH6(J,z,q,(D)=>{let B=z[D];if(B)this.props.onShowImagePreview(B,D)});if(U)W.push(U)}if(X){if(W.length>0)W.push(new j1({height:1}));W.push(Ff1(X,q,Q.role==="user"?Q.interrupted:void 0,Y.warning))}if(K){if(W.length>0)W.push(new j1({height:1}));W.push(K)}if(Q.role==="user"&&Q.discoveredGuidanceFiles){let z=gC8(J,Q.discoveredGuidanceFiles);if(z){if(W.length>0)W.push(new j1({height:1}));W.push(z)}}let H;if(W.length===0)H=new m1;else if(W.length===1)H=W[0];else H=new S1({mainAxisSize:"min",crossAxisAlignment:"start",children:W});return new m1({decoration:{color:Y.background,border:new y0(void 0,void 0,void 0,new I0(G,2,"solid"))},padding:I1.only({left:1}),child:H})}}class _71 extends _0{props;constructor(J){super();this.props=J}build(J){let Q=v1.of(J),Z=Q.colors,Y=this.props.message,X="",G=Q.app.selectedMessage,V=Q.app.selectedMessage,K=null,q=Ja(Y);if(q){X=`${q.hidden?"$$":"$"} ${q.args.cmd}`;let M=MH6(X,J);G=M,V=M,K=Df1(J,q)}else if(Y.role==="user")X=wH6(Y),V=Y.interrupted?Z.warning:Z.success;let W=new g({color:V,italic:!0}),H=[];if(Y.role==="user"){let M=Y.content.filter((O)=>O.type==="image"),w=LH6(J,M,W,(O)=>{let A=M[O];if(A)this.props.onShowImagePreview(A,O)});if(w)H.push(w)}if(X){if(H.length>0)H.push(new j1({height:1}));H.push(Ff1(X,W,Y.role==="user"?Y.interrupted:void 0,Z.warning))}if(K){if(H.length>0)H.push(new j1({height:1}));H.push(K)}let z;if(H.length===0)z=new m1;else if(H.length===1)z=H[0];else z=new S1({mainAxisSize:"min",crossAxisAlignment:"start",children:H});let F=new m1({decoration:{border:y0.all(new I0(G,2,"solid"))},padding:I1.only({left:1,right:1}),width:1/0,child:z});if(this.props.isShowingRestoreConfirmation){let N=new AH6({affectedFiles:this.props.affectedFiles,onConfirm:this.props.onRestoreConfirm,onCancel:this.props.onRestoreCancel});return new S1({children:[new Uf1,new j1({height:1}),N,new j1({height:1}),new CZ({forceDim:!0,child:new m1({decoration:{border:new y0(void 0,void 0,void 0,new I0(G,2,"solid"))},padding:I1.only({left:1,right:1}),width:1/0,child:z})})]})}if(this.props.isShowingEditConfirmation){let N=new RH6({affectedFiles:this.props.affectedFiles,onConfirm:this.props.onEditConfirm,onCancel:this.props.onEditCancel}),M=this.props.pendingEditText??X,L=Ff1(M,W,void 0,Z.warning),w=new S1({mainAxisSize:"min",crossAxisAlignment:"start",children:[L,new j1({height:1}),N]});return new m1({decoration:{border:y0.all(new I0(G,2,"solid"))},padding:I1.only({left:1,right:1}),width:1/0,child:w})}let U=Q.app,D=[new y("e",new g({color:U.keybind})),new y(" to edit",new g({color:Z.foreground,dim:!0}))],B=new U81({child:new u4({children:[F,new p4({left:2,right:0,bottom:0,child:new J1({text:new y("",void 0,D)})})]})});if(!this.props.isFirstMessage)return new s1({padding:I1.only({}),child:B});return new s1({padding:I1.only({}),child:new S1({mainAxisSize:"min",crossAxisAlignment:"start",children:[new Uf1,new j1({height:1}),B]})})}}class Uf1 extends _0{build(J){let Q=v1.of(J),Z=Q.colors,Y=Q.app,X=[new y(" r",new g({color:Y.keybind})),new y(" to restore ",new g({color:Z.foreground,dim:!0}))];return new u4({children:[new m1({decoration:{border:new y0(new I0(Z.selection,2,"solid"),void 0,void 0,void 0)},width:1/0,height:1}),new p4({left:0,right:0,top:0,child:new b0({child:new J1({text:new y("",void 0,X)})})})]})}}function OH6(J,Q){if(Q.length===0)return null;let Y=v1.of(J).colors,X=QD(J),G=[];for(let V=0;V<Q.length;V++){let K=Q[V];if(V>0)G.push(new y(`
8540
- `));let q=K.startsWith("file://")?Q0.parse(K):Q0.file(K),W=V7(q,X??void 0);G.push(new y(` • ${W}`,new g({color:Y.foreground,dim:!0})))}return new J1({text:new y("",void 0,G)})}class AH6 extends _0{props;constructor(J){super();this.props=J}build(J){let Q=this.props.affectedFiles,Z=Q.length>0,Y=Z?"This will delete this message and any subsequent messages in the thread, and will restore the following files:":"This will delete this message and any subsequent messages in the thread.",X=v1.of(J),G=[new J1({text:new y(Y,new g({color:X.app.command,bold:!0}))}),new j1({height:1})],V=OH6(J,Q);if(V)G.push(V),G.push(new j1({height:1}));let K=[{value:"confirm",label:Z?"Delete and restore":"Delete"},{value:"cancel",label:"Cancel"}];return G.push(new w7({options:K,onSelect:(q)=>{if(q==="confirm")this.props.onConfirm();else this.props.onCancel()},padding:I1.all(0),showDismissalMessage:!1,enableMouseInteraction:!1,showBorder:!1})),new S1({mainAxisSize:"min",crossAxisAlignment:"start",children:G})}}class RH6 extends _0{props;constructor(J){super();this.props=J}build(J){let Q=this.props.affectedFiles,Z=v1.of(J),Y=[],X=OH6(J,Q);if(X)Y.push(new J1({text:new y("This will restore the following files:",new g({color:Z.app.command,bold:!0}))})),Y.push(new j1({height:1})),Y.push(X),Y.push(new j1({height:1}));let G=[{value:"confirm",label:"Confirm edit"},{value:"cancel",label:"Cancel"}];return Y.push(new w7({options:G,onSelect:(V)=>{if(V==="confirm")this.props.onConfirm();else this.props.onCancel()},padding:I1.all(0),showDismissalMessage:!1,enableMouseInteraction:!1,showBorder:!1})),new S1({mainAxisSize:"min",crossAxisAlignment:"start",children:Y})}}class S71 extends d1{controller;onSubmitted;message;completionBuilder;autocompleteHandle;onShowImagePreview;onDoubleAtTrigger;constructor(J){super();this.controller=J.controller,this.onSubmitted=J.onSubmitted,this.message=J.message,this.completionBuilder=J.completionBuilder,this.autocompleteHandle=J.autocompleteHandle,this.onShowImagePreview=J.onShowImagePreview,this.onDoubleAtTrigger=J.onDoubleAtTrigger}createState(){return new jH6}}class jH6 extends u1{currentShellModeStatus;imageAttachments=[];get controller(){return this.widget.controller}initState(){this.controller.addListener(this.textChangeListener);let J=UU(this.controller.text);if(this.currentShellModeStatus=J?.visibility,this.widget.message){let Q=this.widget.message.content.filter((Z)=>Z.type==="image");this.imageAttachments=Q}}dispose(){this.controller.removeListener(this.textChangeListener),super.dispose()}textChangeListener=()=>{let J=this.controller.text,Z=UU(J)?.visibility;if(Z!==this.currentShellModeStatus)this.currentShellModeStatus=Z,this.setState(()=>{})};handleSubmit=(J)=>{this.widget.onSubmitted(J,this.imageAttachments)};handleInsertImage=(J)=>{let Q=XU(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q]}),!1;return!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};handleImageClick=(J)=>{let Q=this.imageAttachments[J];if(Q)this.widget.onShowImagePreview(Q,J,()=>{this.setState(()=>{this.imageAttachments=this.imageAttachments.filter((Z,Y)=>Y!==J)})})};build(J){let Q=v1.of(J),Z=Q.colors,Y=Q.app,X=this.currentShellModeStatus?u36(Q,this.currentShellModeStatus):Y.selectedMessage,G=null,V=this.widget.message&&Ja(this.widget.message);if(V)G=Df1(J,V);let K=new aL({controller:this.controller,triggers:[new XK],completionBuilder:this.widget.completionBuilder,ampURL:"",onSubmitted:this.handleSubmit,theme:Z,placeholder:"",enabled:!0,autofocus:!0,shellPromptRules:NP(Q),imageAttachments:this.imageAttachments,onInsertImage:this.handleInsertImage,popImage:this.handlePopImage,onImageClick:this.handleImageClick,minLines:1,textColor:X,autocompleteHandle:this.widget.autocompleteHandle,autoOverlayPosition:!0,onDoubleAtTrigger:this.widget.onDoubleAtTrigger}),q=[];if(q.push(K),G)q.push(new j1({height:1})),q.push(G);let W;if(q.length===1)W=q[0];else W=new S1({mainAxisSize:"min",crossAxisAlignment:"start",children:q});let H=[];if(this.currentShellModeStatus===FU)H.push(new y("shell mode (incognito)",new g({color:Q.app.shellModeHidden})));else if(this.currentShellModeStatus===B81)H.push(new y("shell mode",new g({color:Q.app.shellMode})));else H.push(new y("esc",new g({color:Y.keybind})),new y(" to cancel",new g({color:Z.foreground,dim:!0})));return new U81({child:new KY({decoration:{border:y0.all(new I0(X,2,"solid"))},padding:I1.only({left:1,right:1}),overlays:[{child:new J1({text:new y("",void 0,H)}),position:"bottom",alignment:"left"}],child:W})})}}class k71 extends _8{}class y71 extends _8{}class Bf1 extends _8{}class Nf1 extends _8{}class Mf1 extends _8{}class Lf1 extends _8{}class wf1 extends _8{}class Of1 extends _8{}function uC8(J,Q,Z){let X=v1.maybeOf(J)?.colors??B0.of(J).colorScheme,V=Q.trimStart().startsWith("You're absolutely right"),K=new L9(`${Z}-text`),q=[];if(V)q.push(new db1({key:K,markdown:Q,defaultColor:X.foreground}));else q.push(new n8({key:K,markdown:Q}));if(q.length===1)return q[0];return new S1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:q})}function pC8(J,Q){let Y=B0.of(J).colorScheme,X=v1.of(J);if(Q.summary.type!=="message")return new m1;return new S1({crossAxisAlignment:"start",children:[new J1({text:new y("Summary:",new g({color:Y.foreground,dim:!0,bold:!0,italic:!0})),selectable:!0}),new j1({height:1}),new n8({markdown:Q.summary.summary,styleScheme:{text:new g({color:Y.foreground,dim:!0,italic:!0}),inlineCode:new g({color:Y.foreground,dim:!0,italic:!0}),codeBlock:new g({color:Y.foreground,dim:!0,italic:!0}),tableBorder:X.app.tableBorder,link:new g({color:Y.foreground,dim:!0,italic:!0}),syntaxHighlight:{keyword:Y.foreground,string:Y.foreground,number:Y.foreground,comment:Y.foreground,function:Y.foreground,variable:Y.foreground,type:Y.foreground,operator:Y.foreground}}})]})}class x71 extends d1{items;subagentToolsByParentID;controller;autofocus;onNewMessage;showScrollbar;onCopy;onMessageEditSubmit;onShellCommandSubmit;onMessageRestoreSubmit;onShowForkDeprecation;getAffectedFiles;thread;focusNode;onDismissFocus;isInSelectionMode=!1;isInHandoffMode=!1;completionBuilder;onShowImagePreview;onSelectionChanged;onDoubleAtTrigger;stateController;get userMessageIndices(){let J=[];for(let Q=0;Q<this.items.length;Q++){let Z=this.items[Q];if(Z?.type==="message"){if(Z.message.role==="user"||bk(Z.message))J.push(Q)}}return J}constructor({key:J,items:Q,subagentToolsByParentID:Z={},controller:Y,autofocus:X=!1,onNewMessage:G,showScrollbar:V=!0,onCopy:K,onMessageEditSubmit:q,onMessageRestoreSubmit:W,onShowForkDeprecation:H,getAffectedFiles:z,thread:F,focusNode:U,onDismissFocus:D,isInSelectionMode:B=!1,isInHandoffMode:N=!1,completionBuilder:M,onShowImagePreview:L,onSelectionChanged:w,onDoubleAtTrigger:O,stateController:A}){super(J?{key:J}:{});this.items=Q,this.subagentToolsByParentID=Z,this.controller=Y,this.autofocus=X,this.onNewMessage=G,this.showScrollbar=V,this.onCopy=K,this.onMessageEditSubmit=q,this.onMessageRestoreSubmit=W,this.onShowForkDeprecation=H,this.getAffectedFiles=z,this.thread=F,this.focusNode=U,this.onDismissFocus=D,this.isInSelectionMode=B,this.isInHandoffMode=N,this.completionBuilder=M,this.onShowImagePreview=L,this.onSelectionChanged=w,this.onDoubleAtTrigger=O,this.stateController=A}createState(){return new EH6}}class EH6 extends u1{_controller=null;_isDisposed=!1;_globalToggleListener;_streamingIndexes=new Set;_viewportHeight=25;_widgetCache=new Map;_lastCostDisplayState=null;_autocompleteHandle={dismiss:()=>{}};_scrollListener=null;_controllerUnsubscribe=null;get controller(){return this._controller}get _stateController(){return this.widget.stateController}dismiss(){Y4.instance.addPostFrameCallback(()=>{this.widget.focusNode?.unfocus()}),this.widget.onDismissFocus?.()}_navigateUp(J,Q){if(Q<=0)return null;if(J===null)return Q-1;if(J<=0)return 0;return J-1}_navigateDown(J,Q){if(Q<=0)return null;if(J===null)return null;if(J>=Q-1)return null;return J+1}_ordinalToIndex(J,Q){if(Q===null)return null;if(Q<0||Q>=J.length)return null;return J[Q]??null}_getUserCount(){return this.widget.userMessageIndices.length}_clearSelectedUserMessage(){let J=this._stateController.selectedUserMessageOrdinal,Q=J!==null?this.getUserMessageIndexFromOrdinal(J):null;this.setState(()=>{if(Q!=null)this._widgetCache.delete(Q);this._stateController.setSelectedUserMessageOrdinal(null)})}_selectUserMessageByOrdinal(J){let Q=this._stateController.selectedUserMessageOrdinal,Z=J,Y=Q!==null?this.getUserMessageIndexFromOrdinal(Q):null,X=this.getUserMessageIndexFromOrdinal(Z);if(Y!==null)this._widgetCache.delete(Y);if(X!==null)this._widgetCache.delete(X);if(this.setState(()=>{this._stateController.setSelectedUserMessageOrdinal(Z)}),X!==null)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(X,{animated:!0,edge:"top",duration:200})})}_selectEditingUserMessageByOrdinal(J){let Q=this._stateController.editingMessageOrdinal,Z=Q!==null?this.getUserMessageIndexFromOrdinal(Q):null,Y=J!==null?this.getUserMessageIndexFromOrdinal(J):null;if(Z!==null)this._widgetCache.delete(Z);if(Y!==null)this._widgetCache.delete(Y);if(J===null)this.setState(()=>{this._stateController.stopEditing()});else{let X=this.getUserMessageIndexFromOrdinal(J),G=X!==null?this.widget.items[X]:null,V=G?.type==="message"?k7(G.message.content):"";this.setState(()=>{this._stateController.startEditing(J,V)})}}getUserMessageIndexFromOrdinal(J){return this.widget.userMessageIndices[J]??null}getOrdinalFromUserMessageIndex(J){let Z=this.widget.userMessageIndices.indexOf(J);return Z>=0?Z:null}getLatestUserMessageOrdinal(){let J=this.widget.userMessageIndices;return J.length>0?J.length-1:null}navigateToUserMessage(J){let Q=this._getUserCount(),Z=this._stateController.selectedUserMessageOrdinal,Y=J==="up"?this._navigateUp(Z,Q):this._navigateDown(Z,Q);if(Y===null&&J==="down"){this._controller?.animateToBottom(100),this._clearSelectedUserMessage(),this.dismiss();return}if(Y!==null)this._selectUserMessageByOrdinal(Y)}handleNavigateUserMessageUp=()=>{if(this._stateController.editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("up"),"handled"};handleNavigateUserMessageDown=()=>{if(this._stateController.editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("down"),"handled"};handleEscape=()=>{if(this._stateController.editingMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._stateController.editingMessageOrdinal);if(J!=null)this._widgetCache.delete(J);return this.setState(()=>{this._stateController.stopEditing()}),Y4.instance.addPostFrameCallback(()=>{this.widget.focusNode?.requestFocus()}),"handled"}else if(this._stateController.selectedUserMessageOrdinal!==null)return this._clearSelectedUserMessage(),this.setState(()=>{this._stateController.stopEditing()}),this.dismiss(),this._controller?.animateToBottom(100),"handled";return"ignored"};handleScrollDown=()=>{if(this._stateController.selectedUserMessageOrdinal!==null)return this._controller?.scrollDown(1),"handled";return"ignored"};handleScrollUp=()=>{if(this._stateController.selectedUserMessageOrdinal!==null)return this._controller?.scrollUp(1),"handled";return"ignored"};handleEditMessage=()=>{let J=this._stateController.selectedUserMessageOrdinal;if(J!==null)return this._selectEditingUserMessageByOrdinal(J),"handled";return"ignored"};handleRestoreMessage=()=>{let J=this._stateController.selectedUserMessageOrdinal;if(J!==null){let Q=this._ordinalToIndex(this.widget.userMessageIndices,J);if(Q!=null){if(Q===0)return"ignored";let Z=this.widget.items[Q];if(Z?.type==="message"&&(Z.message.role==="user"||bk(Z.message)))this.showRestoreConfirmation(Z.message,Q)}return"handled"}return"ignored"};async showRestoreConfirmation(J,Q){let Z=[];if(this.widget.getAffectedFiles)try{Z=await this.widget.getAffectedFiles(J)}catch{Z=[]}if(this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingRestoreConfirmation(!0),this._stateController.setAffectedFiles(Z)}),this.controller.atBottom)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(Q)})}handleRestoreConfirm=()=>{let J=this._stateController.selectedUserMessageOrdinal;if(J!==null){let Q=this._ordinalToIndex(this.widget.userMessageIndices,J);if(Q!=null){if(Q===0)return"ignored";let Z=this.widget.items[Q];if(Z?.type==="message"&&(Z.message.role==="user"||Z.message.role==="info"))this.widget.onMessageRestoreSubmit?.(Z.message),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingRestoreConfirmation(!1),this._stateController.setAffectedFiles([])}),this.dismiss()}return"handled"}return"ignored"};handleRestoreCancel=()=>{let J=this._stateController.selectedUserMessageOrdinal;if(J!==null){let Q=this._ordinalToIndex(this.widget.userMessageIndices,J);if(Q!=null){if(this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingRestoreConfirmation(!1),this._stateController.setAffectedFiles([])}),this.controller.atBottom)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(Q)})}}return"handled"};handleForkMessage=()=>{if(this._stateController.selectedUserMessageOrdinal!==null&&this.widget.onShowForkDeprecation)return this.widget.onShowForkDeprecation(),this._clearSelectedUserMessage(),this.setState(()=>{}),this.dismiss(),"handled";return"ignored"};handleEditConfirmationRequest=async(J,Q)=>{if(J.trim()===""&&Q.length===0)return;let Z=this._stateController.editingMessageOrdinal;if(Z!==null){let Y=this._ordinalToIndex(this.widget.userMessageIndices,Z);if(Y!=null){let X=this.widget.items[Y],G=[];if(this.widget.getAffectedFiles&&X?.type==="message")try{G=await this.widget.getAffectedFiles(X.message)}catch{G=[]}if(G.length===0&&X?.type==="message"&&(X.message.role==="user"||X.message.role==="info")){this.widget.onMessageEditSubmit?.(X.message,J,Q),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._stateController.stopEditing()}),this.dismiss(),this.controller.animateToBottom(100);return}if(this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingEditConfirmation(!0),this._stateController.setPendingEditText(J),this._stateController.setPendingEditImageAttachments(Q),this._stateController.setAffectedFiles(G),this._stateController.stopEditing()}),this.controller.atBottom)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(Y)})}}};handleEditConfirm=()=>{let J=this._stateController.selectedUserMessageOrdinal,Q=this._stateController.pendingEditText;if(J!==null&&Q!==null){let Z=this._ordinalToIndex(this.widget.userMessageIndices,J);if(Z!=null){let Y=this.widget.items[Z];if(Y?.type==="message"&&(Y.message.role==="user"||Y.message.role==="info"))this.widget.onMessageEditSubmit?.(Y.message,Q,[...this._stateController.pendingEditImageAttachments]),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingEditConfirmation(!1),this._stateController.setPendingEditText(null),this._stateController.setPendingEditImageAttachments([]),this._stateController.setAffectedFiles([])}),this.dismiss(),this.controller.animateToBottom(100)}}};handleEditCancel=()=>{let J=this._stateController.selectedUserMessageOrdinal;if(J!==null){let Q=this._ordinalToIndex(this.widget.userMessageIndices,J);if(Q!=null){if(this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingEditConfirmation(!1),this._stateController.setPendingEditText(null),this._stateController.setPendingEditImageAttachments([]),this._stateController.setAffectedFiles([])}),this.controller.atBottom)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(Q)})}}};_signatureFor(J){if(J.type==="message"){let Q=J.message;if(Q.role==="user"){let Z=k7(Q.content),Y=Q.content.filter((X)=>X.type==="image").length;return`${J.id}|user|${Q.interrupted?1:0}|${Y}|${Z}`}else if(Q.role==="assistant"){let Z=k7(Q.content),Y=Q.state?.type??"none",X=Q.content.filter((W)=>W.type==="thinking"),G=Q.content.filter((W)=>W.type==="tool_use"),V=X.map((W)=>UT(W.thinking)).join("|"),K=Q.usage,q=K?`${K.inputTokens}|${K.outputTokens}|${K.cacheCreationInputTokens??""}|${K.cacheReadInputTokens??""}|${K.model??""}`:"no-usage";return`${J.id}|assistant|${Y}|${X.length}|${G.length}|${Z}|${V}|${q}|${Q.turnElapsedMs??""}`}else{let Y=Q.content.map((X)=>X.type).join(",");return`${J.id}|info|${Y}`}}else{let Z=J.toolResult.run.status,Y=J.toolResult.userInput,X=Y?`accepted:${Y.accepted?1:0}|ask:${Y.askAnswers?Object.keys(Y.askAnswers).length:0}`:"none";return`${J.id}|tool|${Z}|${J.toolUse.id}|${X}`}}getThinkingBlockExpanded(J,Q){let Z=`${J}-${Q}`;return this._stateController.thinkingBlockStates.get(Z)??A7.instance.allExpanded}toggleThinkingBlock=(J,Q)=>{return(Z)=>{let Y=`${J}-${Q}`;this.setState(()=>{this._stateController.setThinkingBlockState(Y,Z),this._widgetCache.delete(J)})}};buildThinkingBlock(J,Q,Z,Y,X){let G=Z===X,V=Y.state?.type==="streaming"&&G,K=Y.state?.type==="cancelled"&&G;return new Pw({key:new L9(`thinking-${Q}-${Z}`),thinkingBlock:J,expanded:this.getThinkingBlockExpanded(Q,Z),onToggle:this.toggleThinkingBlock(Q,Z),isStreaming:V,isCancelled:K})}buildAssistantMessageWidget(J,Q,Z,Y){let X=Q.content.map((U,D)=>({block:U,index:D})).filter((U)=>U.block.type==="thinking"&&UT(U.block.thinking).length>0),G=X.length>0,V=X.length>0?X.at(-1).index:-1,K=Q.content.filter((U)=>U.type==="text"&&!U.hidden),q=[];if(X.forEach(({block:U,index:D},B)=>{if(B>0)q.push(new j1({height:1}));q.push(this.buildThinkingBlock(U,Z,D,Q,V))}),G&&K.length>0)q.push(new j1({height:1}));let W=k7(K);if(W.trim())q.push(uC8(J,W,Y));let H=pb1(J),z=Q.usage!=null&&(Q.usage.inputTokens>0||Q.usage.outputTokens>0);if(H&&z){let D=v1.maybeOf(J)?.colors??B0.of(J).colorScheme,B=h26(Q.usage);q.push(new s1({padding:I1.only({top:1}),child:new J1({text:new y(B,new g({color:D.foreground,dim:!0}))})}))}let F;if(q.length===0)F=new m1;else if(q.length===1)F=q[0];else F=new S1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:q});return F}buildThreadItemWidget(J,Q,Z){let Y=new L9(`thread-item-${Q.id}`);if(Q.type==="message"){let X=Q.message;if(X.role==="user"){let G,V=(K,q)=>{this.widget.onShowImagePreview(K,q,()=>{})};if(!this.widget.isInSelectionMode)G=new RT({message:X,isFirstMessage:Z>0,onShowImagePreview:V});else{let K=this.getOrdinalFromUserMessageIndex(Z);if(K===null)G=new RT({message:X,isFirstMessage:Z>0,onShowImagePreview:V});else if(this._stateController.editingMessageOrdinal===K&&this._stateController.editingController)G=new S71({controller:this._stateController.editingController,message:X,onSubmitted:(q,W)=>{this.handleEditConfirmationRequest(q,W)},completionBuilder:this.widget.completionBuilder,autocompleteHandle:this._autocompleteHandle,onShowImagePreview:this.widget.onShowImagePreview,onDoubleAtTrigger:this.widget.onDoubleAtTrigger});else if(this._stateController.selectedUserMessageOrdinal===K)G=new _71({message:X,isFirstMessage:Z>0,isShowingRestoreConfirmation:this._stateController.isShowingRestoreConfirmation,isShowingEditConfirmation:this._stateController.isShowingEditConfirmation,affectedFiles:[...this._stateController.affectedFiles],pendingEditText:this._stateController.pendingEditText??void 0,onRestoreConfirm:()=>{this.handleRestoreConfirm()},onRestoreCancel:()=>{this.handleRestoreCancel()},onEditConfirm:()=>{this.handleEditConfirm()},onEditCancel:()=>{this.handleEditCancel()},onShowImagePreview:V});else G=new RT({message:X,isFirstMessage:Z>0,onShowImagePreview:V})}return G}else if(X.role==="assistant"){let G=this.buildAssistantMessageWidget(J,X,Z,Q.id);return new m1({key:Y,child:G})}else{let G=X,V=[],K=this.getOrdinalFromUserMessageIndex(Z),q=this.widget.isInSelectionMode&&K!==null&&this._stateController.selectedUserMessageOrdinal===K,W=(H,z)=>{this.widget.onShowImagePreview(H,z,()=>{})};for(let H of G.content)if(H.type==="manual_bash_invocation")if(this._stateController.editingMessageOrdinal===K&&this._stateController.editingController)V.push(new S71({controller:this._stateController.editingController,message:G,onSubmitted:(z,F)=>{this.handleEditConfirmationRequest(z,F)},completionBuilder:this.widget.completionBuilder,autocompleteHandle:this._autocompleteHandle,onShowImagePreview:this.widget.onShowImagePreview,onDoubleAtTrigger:this.widget.onDoubleAtTrigger}));else if(!this.widget.isInSelectionMode||!q)V.push(new RT({message:G,isFirstMessage:Z>0,onShowImagePreview:W}));else V.push(new _71({message:G,isFirstMessage:Z>0,isShowingRestoreConfirmation:this._stateController.isShowingRestoreConfirmation,isShowingEditConfirmation:this._stateController.isShowingEditConfirmation,affectedFiles:[...this._stateController.affectedFiles],pendingEditText:this._stateController.pendingEditText??void 0,onRestoreConfirm:()=>{this.handleRestoreConfirm()},onRestoreCancel:()=>{this.handleRestoreCancel()},onEditConfirm:()=>{this.handleEditConfirm()},onEditCancel:()=>{this.handleEditCancel()},onShowImagePreview:W}));else if(H.type==="summary"&&H.summary.type==="message")V.push(pC8(J,H));if(V.length===0)return new m1;if(V.length===1)return V[0];return new S1({crossAxisAlignment:"stretch",children:V})}}else{let X=new oW({toolUse:Q.toolUse,toolRun:Q.toolResult.run,userInput:Q.toolResult.userInput,subagentTools:this.widget.subagentToolsByParentID[Q.toolUse.id],thread:this.widget.thread});return new m1({key:Y,child:X})}}initState(){if(super.initState(),this._controller=this.widget.controller||new k4,this._scrollListener=()=>{this._autocompleteHandle.dismiss()},this._controller.addListener(this._scrollListener),this._globalToggleListener=()=>{this.setState(()=>{this._stateController.clearThinkingBlockStates(),this._widgetCache.clear()})},A7.instance.addListener(this._globalToggleListener),this._controllerUnsubscribe=this._stateController.subscribe(()=>{this.setState(()=>{})}),this.widget.items.length>0)Y4.instance.requestFrame()}didUpdateWidget(J){if(super.didUpdateWidget(J),!J.isInSelectionMode&&this.widget.isInSelectionMode){this.widget.focusNode?.requestFocus();let Z=this.getLatestUserMessageOrdinal();if(Z!==null)this._selectUserMessageByOrdinal(Z)}if(J.items===this.widget.items)return;let Q=Math.min(J.items.length,this.widget.items.length);for(let Z=0;Z<Q;Z++){let Y=J.items[Z],X=this.widget.items[Z];if(Y&&X){if(Y.type!==X.type){this._widgetCache.delete(Z);continue}if(Y.type==="toolResult"&&X.type==="toolResult"){let G=Y.toolResult.run,V=X.toolResult.run;if(G.status!==V.status||"result"in G!=="result"in V||"error"in G!=="error"in V)this._widgetCache.delete(Z);if(Y.toolResult.userInput!==X.toolResult.userInput)this._widgetCache.delete(Z)}if(Y.type==="message"&&X.type==="message"){let G=Y.message,V=X.message;if(G.content!==V.content)this._widgetCache.delete(Z)}}}if(this.widget.items.length<J.items.length)this._cleanupOrphanedCacheEntries();this._updateStreamingIndexes();for(let Z of this._streamingIndexes)if(Z>=this.widget.items.length)this._streamingIndexes.delete(Z)}_cleanupOrphanedCacheEntries(){for(let J of this._widgetCache.keys())if(J>=this.widget.items.length)this._widgetCache.delete(J)}_isMessageStreaming(J){if(J.type!=="message")return!1;let Q=J.message;if(Q.role!=="assistant")return!1;if(Q.state.type==="streaming")return!0;return Q.content.at(-1)?.type==="thinking"}_updateStreamingIndexes(){for(let J of this._streamingIndexes)if(J>=this.widget.items.length)this._streamingIndexes.delete(J);for(let J=0;J<this.widget.items.length;J++){let Q=this.widget.items[J];if(!Q)continue;let Z=this._isMessageStreaming(Q);if(Z&&!this._streamingIndexes.has(J))this._streamingIndexes.add(J);else if(!Z&&this._streamingIndexes.has(J))this._streamingIndexes.delete(J)}}_getViewportHeight(){let J=this.context.findRenderObject();if(J&&"size"in J){let Q=J.size;if(typeof Q.height==="number"&&Q.height>0)return this._viewportHeight=Q.height,Q.height}return this._viewportHeight}dispose(){if(this._isDisposed=!0,this._widgetCache.clear(),this._scrollListener&&this._controller)this._controller.removeListener(this._scrollListener),this._scrollListener=null;if(this._globalToggleListener)A7.instance.removeListener(this._globalToggleListener);if(this._controllerUnsubscribe)this._controllerUnsubscribe(),this._controllerUnsubscribe=null;if(!this.widget.controller)this._controller?.dispose();this.widget.focusNode?.dispose(),super.dispose()}build(J){let Q=v1.of(J),Z=pb1(J);if(this._lastCostDisplayState!==null&&this._lastCostDisplayState!==Z)this._widgetCache.clear();this._lastCostDisplayState=Z;let Y=this._getTotalItemCount(J),X=[];for(let F=0;F<Y;F++)if(X.push(this._buildItemAtIndex(J,F)),F<Y-1)X.push(new j1({height:1}));let G=new e6({controller:this._controller,autofocus:this.widget.autofocus,position:"bottom",child:new S1({key:new L9("message-list-column"),crossAxisAlignment:"start",children:X})}),K=[new s1({padding:I1.only({left:2,right:this.widget.showScrollbar?3:2,bottom:1}),child:G})];if(this.widget.showScrollbar&&this._controller){let F=new A9({controller:this._controller,getScrollInfo:()=>this._getScrollbarInfo(),thickness:1,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack});K.push(new p4({right:1,top:0,bottom:0,child:new j1({width:1,child:F})}))}let q=new u4({children:K}),W=new oX({child:q,onCopy:this.widget.onCopy,onSelectionChanged:this.widget.onSelectionChanged}),H=new Map([[k71,new M6(this.handleNavigateUserMessageUp)],[y71,new M6(this.handleNavigateUserMessageDown)],[Bf1,new M6(this.handleEscape)],[Nf1,new M6(this.handleScrollDown)],[Mf1,new M6(this.handleScrollUp)],[Lf1,new M6(this.handleEditMessage)],[wf1,new M6(this.handleRestoreMessage)],[Of1,new M6(this.handleForkMessage)]]),z=new Map([[v0.key("Tab"),new k71],[v0.shift("Tab"),new y71],[v0.key("Escape"),new Bf1],[v0.key("j"),new Nf1],[v0.key("k"),new Mf1],[v0.key("e"),new Lf1],[v0.key("r"),new wf1],[v0.key("f"),new Of1]]);if(!L7())z.set(v0.key("ArrowUp"),new k71),z.set(v0.key("ArrowDown"),new y71);if(this.widget.focusNode)return new A6({focusNode:this.widget.focusNode,child:new N5({actions:H,child:new d7({shortcuts:z,focusNode:this.widget.focusNode,child:W})})});return W}_getTotalItemCount(J){return this.widget.items.length}_shouldDimItem(J){if(this.widget.isInHandoffMode)return!0;if(this._stateController.isShowingRestoreConfirmation||this._stateController.isShowingEditConfirmation){let Z=this._stateController.selectedUserMessageOrdinal;if(Z===null)return!1;let Y=this.getUserMessageIndexFromOrdinal(Z);if(Y===null)return!1;return J>Y}let Q=this._stateController.editingMessageOrdinal;if(Q!==null){let Z=this.getUserMessageIndexFromOrdinal(Q);if(Z===null)return!1;return J>Z}return!1}_buildItemAtIndex(J,Q){let Z=this.widget.items[Q];if(!Z)return new m1;let Y=Z.type==="message"&&this._isMessageStreaming(Z),X=Z.type==="toolResult"&&(Z.toolResult.run.status==="queued"||Z.toolResult.run.status==="in-progress")&&!("result"in Z.toolResult.run)&&!("error"in Z.toolResult.run),G=this._shouldDimItem(Q);if(!Y&&!X){let q=`${this._signatureFor(Z)}|dim:${G?1:0}`,W=this._widgetCache.get(Q);if(W&&W.sig===q)return W.widget;let H=this.buildThreadItemWidget(J,Z,Q),z=G?new CZ({forceDim:!0,child:H}):H;return this._widgetCache.set(Q,{sig:q,widget:z}),z}let K=this.buildThreadItemWidget(J,Z,Q);return G?new CZ({forceDim:!0,child:K}):K}onNewMessage(){if(this._isDisposed)return;this.widget.onNewMessage?.()}scrollToTop(){if(this._isDisposed||!this._controller)return;this._controller.scrollToTop()}scrollToMessage(J,{animated:Q=!1,offsetPercent:Z=0.25,edge:Y="top",duration:X}={}){if(this._isDisposed||!this._controller)return!1;let G=this._getMessageRelativeOffset(J,Y);if(G===null)return!1;let V=this._getViewportHeight(),K=Math.floor(V*Z),q=G-K;if(Q)this._controller.animateTo(q,X);else this._controller.jumpTo(q);return!0}_getColumnElement(){let J=this.context.element;if(!J)return null;let Q=new L9("message-list-column"),Z=(Y)=>{if(Y.widget.key?.equals(Q))return Y;for(let X of Y.children){let G=Z(X);if(G)return G}return null};return Z(J)}_getMessageRelativeOffset(J,Q){let Z=this._getColumnElement();if(!Z)return null;let Y=J*2,X=Z.children[Y];if(!X?.renderObject)return null;let G=X.renderObject,V=Z.renderObject;if(!V)return null;let K=G.localToGlobal({x:0,y:0}),q=V.localToGlobal({x:0,y:0}),W=0;if(Q==="bottom")W=G.size.height;return K.y+W-q.y}_getScrollbarInfo(){let J=this._controller?.maxScrollExtent??0,Q=this._getViewportHeight(),Z=this._controller?.offset??0,Y=J+Q;return{totalContentHeight:Math.max(Y,0),viewportHeight:Math.max(Q,1),scrollOffset:Math.max(Z,0)}}}class IH6 extends TZ{color;constructor({color:J,key:Q}){super({key:Q});this.color=J}createRenderObject(){return new PH6(this.color)}updateRenderObject(J){J.color=this.color}}class PH6 extends U6{color;constructor(J){super();this.color=J}performLayout(){let J=this._lastConstraints;if(J)this.setSize(J.maxWidth,1)}paint(J,Q,Z){let Y=Math.floor(this.size.width);for(let X=0;X<Y;X++)J.setChar(Q+X,Z,"─",{fg:this.color},1)}}var dC8=24,cC8=[{left:{keys:"Ctrl+O",description:"command palette"},right:{keys:"Ctrl+R",description:"prompt history"}},{left:{keys:"$ or $$",description:"shell commands"},right:{keys:"Ctrl+V",description:"paste images"}},{left:{keys:"Shift+Enter",description:"newline"},right:{keys:"Ctrl+S",description:"switch modes"}},{left:{keys:"Alt+D",description:"toggle deep reasoning"},right:{keys:"Ctrl+G",description:"edit in $EDITOR"}},{left:{keys:"@ / @@",description:"mention files/threads"},right:{keys:"Tab/Shift+Tab",description:"navigate messages"}},{left:{keys:"Ctrl+C Ctrl+C",description:"exit"},right:{keys:"?",description:"toggle this help"}}];class Af1 extends _0{constructor(J={}){super(J.key?{key:J.key}:{})}build(J){let Z=B0.of(J).colorScheme,X=v1.of(J).app,G=new g({color:X.keybind}),V=new g({color:Z.foreground,dim:!0}),K=$P()&&!GS1,q=cC8.map((H)=>{let z=H.left.keys==="Shift+Enter"&&K?"Alt+Enter":H.left.keys,F=H.left.description,U=z.length+1+F.length,D=" ".repeat(Math.max(0,dC8-U)),B=H.right.keys,N=H.right.description;return new J1({text:new y("",void 0,[new y(z,G),new y(" ",V),new y(F,V),new y(D+" ",V),new y(B,G),new y(" ",V),new y(N,V)])})});if(K){let z=Y81("https://ampcode.com/manual/appendix#amp-cli-tmux");q.push(new j1({height:1})),q.push(new J1({text:new y("",void 0,[new y("Enable ",V),new y("extended-keys",new g({color:X.command})),new y(" in tmux to use ",V),new y("Shift+Enter",G),new y(". See ",V),new y("https://ampcode.com/manual/appendix#amp-cli-tmux",new g({color:X.link,underline:!0}),void 0,z)])}))}let W=new Z0({children:[new L0({child:new IH6({color:Z.border})})]});return new S1({crossAxisAlignment:"start",mainAxisSize:"min",children:[...q,W]})}}class v71 extends TZ{text;baseColor;backgroundColor;glow;time;agentMode;orbWidth;orbHeight;glowIntensity;shockwaves;constructor({key:J,text:Q,baseColor:Z,backgroundColor:Y,glow:X,time:G,agentMode:V,orbWidth:K=40,orbHeight:q=40,glowIntensity:W=0.4,shockwaves:H=[]}){super(J?{key:J}:{});this.text=Q,this.baseColor=Z,this.backgroundColor=Y,this.glow=X,this.time=G,this.agentMode=V,this.orbWidth=K,this.orbHeight=q,this.glowIntensity=W,this.shockwaves=H}createElement(){return new ZK(this)}createRenderObject(){return new TH6(this.text,this.baseColor,this.backgroundColor,this.glow,this.time,this.agentMode,this.orbWidth,this.orbHeight,this.glowIntensity,this.shockwaves)}updateRenderObject(J){J.update(this.text,this.baseColor,this.backgroundColor,this.glow,this.time,this.agentMode,this.orbWidth,this.orbHeight,this.glowIntensity,this.shockwaves)}}var lC8=0.5;class TH6 extends U6{_text;_baseColor;_backgroundColor;_glow;_time;_agentMode;_orbWidth;_orbHeight;_glowIntensity;_shockwaves;constructor(J,Q,Z,Y,X,G,V,K,q,W){super();this._text=J;this._baseColor=Q;this._backgroundColor=Z;this._glow=Y;this._time=X;this._agentMode=G;this._orbWidth=V;this._orbHeight=K;this._glowIntensity=q;this._shockwaves=W}update(J,Q,Z,Y,X,G,V,K,q,W){let H=J!==this._text;if(this._text=J,this._baseColor=Q,this._backgroundColor=Z,this._glow=Y,this._time=X,this._agentMode=G,this._orbWidth=V,this._orbHeight=K,this._glowIntensity=q,this._shockwaves=W,H)this.markNeedsLayout();this.markNeedsPaint()}getMinIntrinsicWidth(J){return w9(this._text,!1)}getMaxIntrinsicWidth(J){return w9(this._text,!1)}getMinIntrinsicHeight(J){return 1}getMaxIntrinsicHeight(J){return 1}performLayout(){let J=this._lastConstraints;L6(!!J,"performLayout called without constraints");let Q=w9(this._text,!1),Z=J.constrain(Q,1);this.setSize(Z.width,Z.height),super.performLayout()}paint(J,Q=0,Z=0){let Y=Q+this.offset.x,X=Z+this.offset.y,G=s4(this._text),V=this._agentMode==="rush"?2.5:1,{primary:K,secondary:q}=Pb1(this._agentMode),W=Y;for(let H=0;H<G.length;H++){let z=G[H],F=v9(z,!1),D=(1-H/Math.max(G.length-1,1)*0.7)**1.2,B=this._glow.sample(this._orbWidth-2+H*0.5,this._orbHeight/2,this._time,V),N=0;for(let O of this._shockwaves){let A=this._time-O.startTime;if(A<0||A>eU)continue;let R=this._orbWidth*0.7+H,j=this._orbHeight/2,T=R-O.x,C=(j-O.y)/lC8,S=Math.sqrt(T*T+C*C),b=A*Cb1,u=Math.abs(S-b);if(u<Ku){let m=1-A/eU,k=(1-u/Ku)*m;N=Math.max(N,k*0.6)}}let M=B**0.7,L=Math.min(1,M*D+N),w=this.blendWithGlow(this._baseColor,L,K,q);J.setCell(W,X,{char:z,width:F,style:{fg:w,bg:this._backgroundColor}}),W+=F}}blendWithGlow(J,Q,Z,Y){let X=J71(Z,Y,Q),G=Q*this._glowIntensity;if(J.type==="rgb"){let V=J.value,K=Math.round(V.r*(1-G)+X.r*G),q=Math.round(V.g*(1-G)+X.g*G),W=Math.round(V.b*(1-G)+X.b*G);return{type:"rgb",value:{r:K,g:q,b:W}}}if(G>0.15)return{type:"rgb",value:{r:X.r,g:X.g,b:X.b}};return J}}var CH6=["ctrl+x","y","z"],_H6=1.5,b71="!@#$%^&*()_+-=[]{}|;:,.<>?/~`0123456789";function iC8(J,Q,Z){let Y=Math.max(J.length,Q.length),X=[];for(let G=0;G<Y;G++){let V=J[G]??" ",K=Q[G]??" ",q=V===" "||V===`
8540
+ `));let q=K.startsWith("file://")?Q0.parse(K):Q0.file(K),W=V7(q,X??void 0);G.push(new y(` • ${W}`,new g({color:Y.foreground,dim:!0})))}return new J1({text:new y("",void 0,G)})}class AH6 extends _0{props;constructor(J){super();this.props=J}build(J){let Q=this.props.affectedFiles,Z=Q.length>0,Y=Z?"This will delete this message and any subsequent messages in the thread, and will restore the following files:":"This will delete this message and any subsequent messages in the thread.",X=v1.of(J),G=[new J1({text:new y(Y,new g({color:X.app.command,bold:!0}))}),new j1({height:1})],V=OH6(J,Q);if(V)G.push(V),G.push(new j1({height:1}));let K=[{value:"confirm",label:Z?"Delete and restore":"Delete"},{value:"cancel",label:"Cancel"}];return G.push(new w7({options:K,onSelect:(q)=>{if(q==="confirm")this.props.onConfirm();else this.props.onCancel()},padding:I1.all(0),showDismissalMessage:!1,enableMouseInteraction:!1,showBorder:!1})),new S1({mainAxisSize:"min",crossAxisAlignment:"start",children:G})}}class RH6 extends _0{props;constructor(J){super();this.props=J}build(J){let Q=this.props.affectedFiles,Z=v1.of(J),Y=[],X=OH6(J,Q);if(X)Y.push(new J1({text:new y("This will restore the following files:",new g({color:Z.app.command,bold:!0}))})),Y.push(new j1({height:1})),Y.push(X),Y.push(new j1({height:1}));let G=[{value:"confirm",label:"Confirm edit"},{value:"cancel",label:"Cancel"}];return Y.push(new w7({options:G,onSelect:(V)=>{if(V==="confirm")this.props.onConfirm();else this.props.onCancel()},padding:I1.all(0),showDismissalMessage:!1,enableMouseInteraction:!1,showBorder:!1})),new S1({mainAxisSize:"min",crossAxisAlignment:"start",children:Y})}}class S71 extends d1{controller;onSubmitted;message;completionBuilder;autocompleteHandle;onShowImagePreview;onDoubleAtTrigger;constructor(J){super();this.controller=J.controller,this.onSubmitted=J.onSubmitted,this.message=J.message,this.completionBuilder=J.completionBuilder,this.autocompleteHandle=J.autocompleteHandle,this.onShowImagePreview=J.onShowImagePreview,this.onDoubleAtTrigger=J.onDoubleAtTrigger}createState(){return new jH6}}class jH6 extends u1{currentShellModeStatus;imageAttachments=[];get controller(){return this.widget.controller}initState(){this.controller.addListener(this.textChangeListener);let J=UU(this.controller.text);if(this.currentShellModeStatus=J?.visibility,this.widget.message){let Q=this.widget.message.content.filter((Z)=>Z.type==="image");this.imageAttachments=Q}}dispose(){this.controller.removeListener(this.textChangeListener),super.dispose()}textChangeListener=()=>{let J=this.controller.text,Z=UU(J)?.visibility;if(Z!==this.currentShellModeStatus)this.currentShellModeStatus=Z,this.setState(()=>{})};handleSubmit=(J)=>{this.widget.onSubmitted(J,this.imageAttachments)};handleInsertImage=(J)=>{let Q=XU(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q]}),!1;return!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};handleImageClick=(J)=>{let Q=this.imageAttachments[J];if(Q)this.widget.onShowImagePreview(Q,J,()=>{this.setState(()=>{this.imageAttachments=this.imageAttachments.filter((Z,Y)=>Y!==J)})})};build(J){let Q=v1.of(J),Z=Q.colors,Y=Q.app,X=this.currentShellModeStatus?u36(Q,this.currentShellModeStatus):Y.selectedMessage,G=null,V=this.widget.message&&Ja(this.widget.message);if(V)G=Df1(J,V);let K=new aL({controller:this.controller,triggers:[new XK],completionBuilder:this.widget.completionBuilder,ampURL:"",onSubmitted:this.handleSubmit,theme:Z,placeholder:"",enabled:!0,autofocus:!0,shellPromptRules:NP(Q),imageAttachments:this.imageAttachments,onInsertImage:this.handleInsertImage,popImage:this.handlePopImage,onImageClick:this.handleImageClick,minLines:1,textColor:X,autocompleteHandle:this.widget.autocompleteHandle,autoOverlayPosition:!0,onDoubleAtTrigger:this.widget.onDoubleAtTrigger}),q=[];if(q.push(K),G)q.push(new j1({height:1})),q.push(G);let W;if(q.length===1)W=q[0];else W=new S1({mainAxisSize:"min",crossAxisAlignment:"start",children:q});let H=[];if(this.currentShellModeStatus===FU)H.push(new y("shell mode (incognito)",new g({color:Q.app.shellModeHidden})));else if(this.currentShellModeStatus===B81)H.push(new y("shell mode",new g({color:Q.app.shellMode})));else H.push(new y("esc",new g({color:Y.keybind})),new y(" to cancel",new g({color:Z.foreground,dim:!0})));return new U81({child:new KY({decoration:{border:y0.all(new I0(X,2,"solid"))},padding:I1.only({left:1,right:1}),overlays:[{child:new J1({text:new y("",void 0,H)}),position:"bottom",alignment:"left"}],child:W})})}}class k71 extends _8{}class y71 extends _8{}class Bf1 extends _8{}class Nf1 extends _8{}class Mf1 extends _8{}class Lf1 extends _8{}class wf1 extends _8{}class Of1 extends _8{}function uC8(J,Q,Z){let X=v1.maybeOf(J)?.colors??B0.of(J).colorScheme,V=Q.trimStart().startsWith("You're absolutely right"),K=new L9(`${Z}-text`),q=[];if(V)q.push(new db1({key:K,markdown:Q,defaultColor:X.foreground}));else q.push(new n8({key:K,markdown:Q}));if(q.length===1)return q[0];return new S1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:q})}function pC8(J,Q){let Y=B0.of(J).colorScheme,X=v1.of(J);if(Q.summary.type!=="message")return new m1;return new S1({crossAxisAlignment:"start",children:[new J1({text:new y("Summary:",new g({color:Y.foreground,dim:!0,bold:!0,italic:!0})),selectable:!0}),new j1({height:1}),new n8({markdown:Q.summary.summary,styleScheme:{text:new g({color:Y.foreground,dim:!0,italic:!0}),inlineCode:new g({color:Y.foreground,dim:!0,italic:!0}),codeBlock:new g({color:Y.foreground,dim:!0,italic:!0}),tableBorder:X.app.tableBorder,link:new g({color:Y.foreground,dim:!0,italic:!0}),syntaxHighlight:{keyword:Y.foreground,string:Y.foreground,number:Y.foreground,comment:Y.foreground,function:Y.foreground,variable:Y.foreground,type:Y.foreground,operator:Y.foreground}}})]})}class x71 extends d1{items;subagentToolsByParentID;controller;autofocus;onNewMessage;showScrollbar;onCopy;onMessageEditSubmit;onShellCommandSubmit;onMessageRestoreSubmit;onShowForkDeprecation;getAffectedFiles;thread;focusNode;onDismissFocus;isInSelectionMode=!1;isInHandoffMode=!1;completionBuilder;onShowImagePreview;onSelectionChanged;onDoubleAtTrigger;stateController;get userMessageIndices(){let J=[];for(let Q=0;Q<this.items.length;Q++){let Z=this.items[Q];if(Z?.type==="message"){if(Z.message.role==="user"||bk(Z.message))J.push(Q)}}return J}constructor({key:J,items:Q,subagentToolsByParentID:Z={},controller:Y,autofocus:X=!1,onNewMessage:G,showScrollbar:V=!0,onCopy:K,onMessageEditSubmit:q,onMessageRestoreSubmit:W,onShowForkDeprecation:H,getAffectedFiles:z,thread:F,focusNode:U,onDismissFocus:D,isInSelectionMode:B=!1,isInHandoffMode:N=!1,completionBuilder:M,onShowImagePreview:L,onSelectionChanged:w,onDoubleAtTrigger:O,stateController:A}){super(J?{key:J}:{});this.items=Q,this.subagentToolsByParentID=Z,this.controller=Y,this.autofocus=X,this.onNewMessage=G,this.showScrollbar=V,this.onCopy=K,this.onMessageEditSubmit=q,this.onMessageRestoreSubmit=W,this.onShowForkDeprecation=H,this.getAffectedFiles=z,this.thread=F,this.focusNode=U,this.onDismissFocus=D,this.isInSelectionMode=B,this.isInHandoffMode=N,this.completionBuilder=M,this.onShowImagePreview=L,this.onSelectionChanged=w,this.onDoubleAtTrigger=O,this.stateController=A}createState(){return new EH6}}class EH6 extends u1{_controller=null;_isDisposed=!1;_globalToggleListener;_streamingIndexes=new Set;_viewportHeight=25;_widgetCache=new Map;_lastCostDisplayState=null;_autocompleteHandle={dismiss:()=>{}};_scrollListener=null;_controllerUnsubscribe=null;get controller(){return this._controller}get _stateController(){return this.widget.stateController}dismiss(){Y4.instance.addPostFrameCallback(()=>{this.widget.focusNode?.unfocus()}),this.widget.onDismissFocus?.()}_navigateUp(J,Q){if(Q<=0)return null;if(J===null)return Q-1;if(J<=0)return 0;return J-1}_navigateDown(J,Q){if(Q<=0)return null;if(J===null)return null;if(J>=Q-1)return null;return J+1}_ordinalToIndex(J,Q){if(Q===null)return null;if(Q<0||Q>=J.length)return null;return J[Q]??null}_getUserCount(){return this.widget.userMessageIndices.length}_clearSelectedUserMessage(){let J=this._stateController.selectedUserMessageOrdinal,Q=J!==null?this.getUserMessageIndexFromOrdinal(J):null;this.setState(()=>{if(Q!=null)this._widgetCache.delete(Q);this._stateController.setSelectedUserMessageOrdinal(null)})}_selectUserMessageByOrdinal(J){let Q=this._stateController.selectedUserMessageOrdinal,Z=J,Y=Q!==null?this.getUserMessageIndexFromOrdinal(Q):null,X=this.getUserMessageIndexFromOrdinal(Z);if(Y!==null)this._widgetCache.delete(Y);if(X!==null)this._widgetCache.delete(X);if(this.setState(()=>{this._stateController.setSelectedUserMessageOrdinal(Z)}),X!==null)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(X,{animated:!0,edge:"top",duration:200})})}_selectEditingUserMessageByOrdinal(J){let Q=this._stateController.editingMessageOrdinal,Z=Q!==null?this.getUserMessageIndexFromOrdinal(Q):null,Y=J!==null?this.getUserMessageIndexFromOrdinal(J):null;if(Z!==null)this._widgetCache.delete(Z);if(Y!==null)this._widgetCache.delete(Y);if(J===null)this.setState(()=>{this._stateController.stopEditing()});else{let X=this.getUserMessageIndexFromOrdinal(J),G=X!==null?this.widget.items[X]:null,V=G?.type==="message"?k7(G.message.content):"";this.setState(()=>{this._stateController.startEditing(J,V)})}}getUserMessageIndexFromOrdinal(J){return this.widget.userMessageIndices[J]??null}getOrdinalFromUserMessageIndex(J){let Z=this.widget.userMessageIndices.indexOf(J);return Z>=0?Z:null}getLatestUserMessageOrdinal(){let J=this.widget.userMessageIndices;return J.length>0?J.length-1:null}navigateToUserMessage(J){let Q=this._getUserCount(),Z=this._stateController.selectedUserMessageOrdinal,Y=J==="up"?this._navigateUp(Z,Q):this._navigateDown(Z,Q);if(Y===null&&J==="down"){this._controller?.animateToBottom(100),this._clearSelectedUserMessage(),this.dismiss();return}if(Y!==null)this._selectUserMessageByOrdinal(Y)}handleNavigateUserMessageUp=()=>{if(this._stateController.editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("up"),"handled"};handleNavigateUserMessageDown=()=>{if(this._stateController.editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("down"),"handled"};handleEscape=()=>{if(this._stateController.editingMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._stateController.editingMessageOrdinal);if(J!=null)this._widgetCache.delete(J);return this.setState(()=>{this._stateController.stopEditing()}),Y4.instance.addPostFrameCallback(()=>{this.widget.focusNode?.requestFocus()}),"handled"}else if(this._stateController.selectedUserMessageOrdinal!==null)return this._clearSelectedUserMessage(),this.setState(()=>{this._stateController.stopEditing()}),this.dismiss(),this._controller?.animateToBottom(100),"handled";return"ignored"};handleScrollDown=()=>{if(this._stateController.selectedUserMessageOrdinal!==null)return this._controller?.scrollDown(1),"handled";return"ignored"};handleScrollUp=()=>{if(this._stateController.selectedUserMessageOrdinal!==null)return this._controller?.scrollUp(1),"handled";return"ignored"};handleEditMessage=()=>{let J=this._stateController.selectedUserMessageOrdinal;if(J!==null)return this._selectEditingUserMessageByOrdinal(J),"handled";return"ignored"};handleRestoreMessage=()=>{let J=this._stateController.selectedUserMessageOrdinal;if(J!==null){let Q=this._ordinalToIndex(this.widget.userMessageIndices,J);if(Q!=null){if(Q===0)return"ignored";let Z=this.widget.items[Q];if(Z?.type==="message"&&(Z.message.role==="user"||bk(Z.message)))this.showRestoreConfirmation(Z.message,Q)}return"handled"}return"ignored"};async showRestoreConfirmation(J,Q){let Z=[];if(this.widget.getAffectedFiles)try{Z=await this.widget.getAffectedFiles(J)}catch{Z=[]}if(this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingRestoreConfirmation(!0),this._stateController.setAffectedFiles(Z)}),this.controller.atBottom)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(Q)})}handleRestoreConfirm=()=>{let J=this._stateController.selectedUserMessageOrdinal;if(J!==null){let Q=this._ordinalToIndex(this.widget.userMessageIndices,J);if(Q!=null){if(Q===0)return"ignored";let Z=this.widget.items[Q];if(Z?.type==="message"&&(Z.message.role==="user"||Z.message.role==="info"))this.widget.onMessageRestoreSubmit?.(Z.message),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingRestoreConfirmation(!1),this._stateController.setAffectedFiles([])}),this.dismiss()}return"handled"}return"ignored"};handleRestoreCancel=()=>{let J=this._stateController.selectedUserMessageOrdinal;if(J!==null){let Q=this._ordinalToIndex(this.widget.userMessageIndices,J);if(Q!=null){if(this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingRestoreConfirmation(!1),this._stateController.setAffectedFiles([])}),this.controller.atBottom)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(Q)})}}return"handled"};handleForkMessage=()=>{if(this._stateController.selectedUserMessageOrdinal!==null&&this.widget.onShowForkDeprecation)return this.widget.onShowForkDeprecation(),this._clearSelectedUserMessage(),this.setState(()=>{}),this.dismiss(),"handled";return"ignored"};handleEditConfirmationRequest=async(J,Q)=>{if(J.trim()===""&&Q.length===0)return;let Z=this._stateController.editingMessageOrdinal;if(Z!==null){let Y=this._ordinalToIndex(this.widget.userMessageIndices,Z);if(Y!=null){let X=this.widget.items[Y],G=[];if(this.widget.getAffectedFiles&&X?.type==="message")try{G=await this.widget.getAffectedFiles(X.message)}catch{G=[]}if(G.length===0&&X?.type==="message"&&(X.message.role==="user"||X.message.role==="info")){this.widget.onMessageEditSubmit?.(X.message,J,Q),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._stateController.stopEditing()}),this.dismiss(),this.controller.animateToBottom(100);return}if(this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingEditConfirmation(!0),this._stateController.setPendingEditText(J),this._stateController.setPendingEditImageAttachments(Q),this._stateController.setAffectedFiles(G),this._stateController.stopEditing()}),this.controller.atBottom)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(Y)})}}};handleEditConfirm=()=>{let J=this._stateController.selectedUserMessageOrdinal,Q=this._stateController.pendingEditText;if(J!==null&&Q!==null){let Z=this._ordinalToIndex(this.widget.userMessageIndices,J);if(Z!=null){let Y=this.widget.items[Z];if(Y?.type==="message"&&(Y.message.role==="user"||Y.message.role==="info"))this.widget.onMessageEditSubmit?.(Y.message,Q,[...this._stateController.pendingEditImageAttachments]),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingEditConfirmation(!1),this._stateController.setPendingEditText(null),this._stateController.setPendingEditImageAttachments([]),this._stateController.setAffectedFiles([])}),this.dismiss(),this.controller.animateToBottom(100)}}};handleEditCancel=()=>{let J=this._stateController.selectedUserMessageOrdinal;if(J!==null){let Q=this._ordinalToIndex(this.widget.userMessageIndices,J);if(Q!=null){if(this.setState(()=>{this._widgetCache.clear(),this._stateController.setIsShowingEditConfirmation(!1),this._stateController.setPendingEditText(null),this._stateController.setPendingEditImageAttachments([]),this._stateController.setAffectedFiles([])}),this.controller.atBottom)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(Q)})}}};_signatureFor(J){if(J.type==="message"){let Q=J.message;if(Q.role==="user"){let Z=k7(Q.content),Y=Q.content.filter((X)=>X.type==="image").length;return`${J.id}|user|${Q.interrupted?1:0}|${Y}|${Z}`}else if(Q.role==="assistant"){let Z=k7(Q.content),Y=Q.state?.type??"none",X=Q.content.filter((W)=>W.type==="thinking"),G=Q.content.filter((W)=>W.type==="tool_use"),V=X.map((W)=>UT(W.thinking)).join("|"),K=Q.usage,q=K?`${K.inputTokens}|${K.outputTokens}|${K.cacheCreationInputTokens??""}|${K.cacheReadInputTokens??""}|${K.model??""}`:"no-usage";return`${J.id}|assistant|${Y}|${X.length}|${G.length}|${Z}|${V}|${q}|${Q.turnElapsedMs??""}`}else{let Y=Q.content.map((X)=>X.type).join(",");return`${J.id}|info|${Y}`}}else{let Z=J.toolResult.run.status,Y=J.toolResult.userInput,X=Y?`accepted:${Y.accepted?1:0}|ask:${Y.askAnswers?Object.keys(Y.askAnswers).length:0}`:"none";return`${J.id}|tool|${Z}|${J.toolUse.id}|${X}`}}getThinkingBlockExpanded(J,Q){let Z=`${J}-${Q}`;return this._stateController.thinkingBlockStates.get(Z)??A7.instance.allExpanded}toggleThinkingBlock=(J,Q)=>{return(Z)=>{let Y=`${J}-${Q}`;this.setState(()=>{this._stateController.setThinkingBlockState(Y,Z),this._widgetCache.delete(J)})}};buildThinkingBlock(J,Q,Z,Y,X){let G=Z===X,V=Y.state?.type==="streaming"&&G,K=Y.state?.type==="cancelled"&&G;return new Pw({key:new L9(`thinking-${Q}-${Z}`),thinkingBlock:J,expanded:this.getThinkingBlockExpanded(Q,Z),onToggle:this.toggleThinkingBlock(Q,Z),isStreaming:V,isCancelled:K})}buildAssistantMessageWidget(J,Q,Z,Y){let X=Q.content.map((U,D)=>({block:U,index:D})).filter((U)=>U.block.type==="thinking"&&UT(U.block.thinking).length>0),G=X.length>0,V=X.length>0?X.at(-1).index:-1,K=Q.content.filter((U)=>U.type==="text"&&!U.hidden),q=[];X.forEach(({block:U,index:D},B)=>{if(B>0)q.push(new j1({height:1}));q.push(this.buildThinkingBlock(U,Z,D,Q,V))});let W=k7(K);if(G&&W.trim().length>0)q.push(new j1({height:1}));if(W.trim())q.push(uC8(J,W,Y));let H=pb1(J),z=Q.usage!=null&&(Q.usage.inputTokens>0||Q.usage.outputTokens>0);if(H&&z){let D=v1.maybeOf(J)?.colors??B0.of(J).colorScheme,B=h26(Q.usage);q.push(new s1({padding:I1.only({top:1}),child:new J1({text:new y(B,new g({color:D.foreground,dim:!0}))})}))}let F;if(q.length===0)F=new m1;else if(q.length===1)F=q[0];else F=new S1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:q});return F}buildThreadItemWidget(J,Q,Z){let Y=new L9(`thread-item-${Q.id}`);if(Q.type==="message"){let X=Q.message;if(X.role==="user"){let G,V=(K,q)=>{this.widget.onShowImagePreview(K,q,()=>{})};if(!this.widget.isInSelectionMode)G=new RT({message:X,isFirstMessage:Z>0,onShowImagePreview:V});else{let K=this.getOrdinalFromUserMessageIndex(Z);if(K===null)G=new RT({message:X,isFirstMessage:Z>0,onShowImagePreview:V});else if(this._stateController.editingMessageOrdinal===K&&this._stateController.editingController)G=new S71({controller:this._stateController.editingController,message:X,onSubmitted:(q,W)=>{this.handleEditConfirmationRequest(q,W)},completionBuilder:this.widget.completionBuilder,autocompleteHandle:this._autocompleteHandle,onShowImagePreview:this.widget.onShowImagePreview,onDoubleAtTrigger:this.widget.onDoubleAtTrigger});else if(this._stateController.selectedUserMessageOrdinal===K)G=new _71({message:X,isFirstMessage:Z>0,isShowingRestoreConfirmation:this._stateController.isShowingRestoreConfirmation,isShowingEditConfirmation:this._stateController.isShowingEditConfirmation,affectedFiles:[...this._stateController.affectedFiles],pendingEditText:this._stateController.pendingEditText??void 0,onRestoreConfirm:()=>{this.handleRestoreConfirm()},onRestoreCancel:()=>{this.handleRestoreCancel()},onEditConfirm:()=>{this.handleEditConfirm()},onEditCancel:()=>{this.handleEditCancel()},onShowImagePreview:V});else G=new RT({message:X,isFirstMessage:Z>0,onShowImagePreview:V})}return G}else if(X.role==="assistant"){let G=this.buildAssistantMessageWidget(J,X,Z,Q.id);return new m1({key:Y,child:G})}else{let G=X,V=[],K=this.getOrdinalFromUserMessageIndex(Z),q=this.widget.isInSelectionMode&&K!==null&&this._stateController.selectedUserMessageOrdinal===K,W=(H,z)=>{this.widget.onShowImagePreview(H,z,()=>{})};for(let H of G.content)if(H.type==="manual_bash_invocation")if(this._stateController.editingMessageOrdinal===K&&this._stateController.editingController)V.push(new S71({controller:this._stateController.editingController,message:G,onSubmitted:(z,F)=>{this.handleEditConfirmationRequest(z,F)},completionBuilder:this.widget.completionBuilder,autocompleteHandle:this._autocompleteHandle,onShowImagePreview:this.widget.onShowImagePreview,onDoubleAtTrigger:this.widget.onDoubleAtTrigger}));else if(!this.widget.isInSelectionMode||!q)V.push(new RT({message:G,isFirstMessage:Z>0,onShowImagePreview:W}));else V.push(new _71({message:G,isFirstMessage:Z>0,isShowingRestoreConfirmation:this._stateController.isShowingRestoreConfirmation,isShowingEditConfirmation:this._stateController.isShowingEditConfirmation,affectedFiles:[...this._stateController.affectedFiles],pendingEditText:this._stateController.pendingEditText??void 0,onRestoreConfirm:()=>{this.handleRestoreConfirm()},onRestoreCancel:()=>{this.handleRestoreCancel()},onEditConfirm:()=>{this.handleEditConfirm()},onEditCancel:()=>{this.handleEditCancel()},onShowImagePreview:W}));else if(H.type==="summary"&&H.summary.type==="message")V.push(pC8(J,H));if(V.length===0)return new m1;if(V.length===1)return V[0];return new S1({crossAxisAlignment:"stretch",children:V})}}else{let X=new oW({toolUse:Q.toolUse,toolRun:Q.toolResult.run,userInput:Q.toolResult.userInput,subagentTools:this.widget.subagentToolsByParentID[Q.toolUse.id],thread:this.widget.thread});return new m1({key:Y,child:X})}}initState(){if(super.initState(),this._controller=this.widget.controller||new k4,this._scrollListener=()=>{this._autocompleteHandle.dismiss()},this._controller.addListener(this._scrollListener),this._globalToggleListener=()=>{this.setState(()=>{this._stateController.clearThinkingBlockStates(),this._widgetCache.clear()})},A7.instance.addListener(this._globalToggleListener),this._controllerUnsubscribe=this._stateController.subscribe(()=>{this.setState(()=>{})}),this.widget.items.length>0)Y4.instance.requestFrame()}didUpdateWidget(J){if(super.didUpdateWidget(J),!J.isInSelectionMode&&this.widget.isInSelectionMode){this.widget.focusNode?.requestFocus();let Z=this.getLatestUserMessageOrdinal();if(Z!==null)this._selectUserMessageByOrdinal(Z)}if(J.items===this.widget.items)return;let Q=Math.min(J.items.length,this.widget.items.length);for(let Z=0;Z<Q;Z++){let Y=J.items[Z],X=this.widget.items[Z];if(Y&&X){if(Y.type!==X.type){this._widgetCache.delete(Z);continue}if(Y.type==="toolResult"&&X.type==="toolResult"){let G=Y.toolResult.run,V=X.toolResult.run;if(G.status!==V.status||"result"in G!=="result"in V||"error"in G!=="error"in V)this._widgetCache.delete(Z);if(Y.toolResult.userInput!==X.toolResult.userInput)this._widgetCache.delete(Z)}if(Y.type==="message"&&X.type==="message"){let G=Y.message,V=X.message;if(G.content!==V.content)this._widgetCache.delete(Z)}}}if(this.widget.items.length<J.items.length)this._cleanupOrphanedCacheEntries();this._updateStreamingIndexes();for(let Z of this._streamingIndexes)if(Z>=this.widget.items.length)this._streamingIndexes.delete(Z)}_cleanupOrphanedCacheEntries(){for(let J of this._widgetCache.keys())if(J>=this.widget.items.length)this._widgetCache.delete(J)}_isMessageStreaming(J){if(J.type!=="message")return!1;let Q=J.message;if(Q.role!=="assistant")return!1;if(Q.state.type==="streaming")return!0;return Q.content.at(-1)?.type==="thinking"}_updateStreamingIndexes(){for(let J of this._streamingIndexes)if(J>=this.widget.items.length)this._streamingIndexes.delete(J);for(let J=0;J<this.widget.items.length;J++){let Q=this.widget.items[J];if(!Q)continue;let Z=this._isMessageStreaming(Q);if(Z&&!this._streamingIndexes.has(J))this._streamingIndexes.add(J);else if(!Z&&this._streamingIndexes.has(J))this._streamingIndexes.delete(J)}}_getViewportHeight(){let J=this.context.findRenderObject();if(J&&"size"in J){let Q=J.size;if(typeof Q.height==="number"&&Q.height>0)return this._viewportHeight=Q.height,Q.height}return this._viewportHeight}dispose(){if(this._isDisposed=!0,this._widgetCache.clear(),this._scrollListener&&this._controller)this._controller.removeListener(this._scrollListener),this._scrollListener=null;if(this._globalToggleListener)A7.instance.removeListener(this._globalToggleListener);if(this._controllerUnsubscribe)this._controllerUnsubscribe(),this._controllerUnsubscribe=null;if(!this.widget.controller)this._controller?.dispose();this.widget.focusNode?.dispose(),super.dispose()}build(J){let Q=v1.of(J),Z=pb1(J);if(this._lastCostDisplayState!==null&&this._lastCostDisplayState!==Z)this._widgetCache.clear();this._lastCostDisplayState=Z;let Y=this._getTotalItemCount(J),X=[];for(let F=0;F<Y;F++)if(X.push(this._buildItemAtIndex(J,F)),F<Y-1)X.push(new j1({height:1}));let G=new e6({controller:this._controller,autofocus:this.widget.autofocus,position:"bottom",child:new S1({key:new L9("message-list-column"),crossAxisAlignment:"start",children:X})}),K=[new s1({padding:I1.only({left:2,right:this.widget.showScrollbar?3:2,bottom:1}),child:G})];if(this.widget.showScrollbar&&this._controller){let F=new A9({controller:this._controller,getScrollInfo:()=>this._getScrollbarInfo(),thickness:1,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack});K.push(new p4({right:1,top:0,bottom:0,child:new j1({width:1,child:F})}))}let q=new u4({children:K}),W=new oX({child:q,onCopy:this.widget.onCopy,onSelectionChanged:this.widget.onSelectionChanged}),H=new Map([[k71,new M6(this.handleNavigateUserMessageUp)],[y71,new M6(this.handleNavigateUserMessageDown)],[Bf1,new M6(this.handleEscape)],[Nf1,new M6(this.handleScrollDown)],[Mf1,new M6(this.handleScrollUp)],[Lf1,new M6(this.handleEditMessage)],[wf1,new M6(this.handleRestoreMessage)],[Of1,new M6(this.handleForkMessage)]]),z=new Map([[v0.key("Tab"),new k71],[v0.shift("Tab"),new y71],[v0.key("Escape"),new Bf1],[v0.key("j"),new Nf1],[v0.key("k"),new Mf1],[v0.key("e"),new Lf1],[v0.key("r"),new wf1],[v0.key("f"),new Of1]]);if(!L7())z.set(v0.key("ArrowUp"),new k71),z.set(v0.key("ArrowDown"),new y71);if(this.widget.focusNode)return new A6({focusNode:this.widget.focusNode,child:new N5({actions:H,child:new d7({shortcuts:z,focusNode:this.widget.focusNode,child:W})})});return W}_getTotalItemCount(J){return this.widget.items.length}_shouldDimItem(J){if(this.widget.isInHandoffMode)return!0;if(this._stateController.isShowingRestoreConfirmation||this._stateController.isShowingEditConfirmation){let Z=this._stateController.selectedUserMessageOrdinal;if(Z===null)return!1;let Y=this.getUserMessageIndexFromOrdinal(Z);if(Y===null)return!1;return J>Y}let Q=this._stateController.editingMessageOrdinal;if(Q!==null){let Z=this.getUserMessageIndexFromOrdinal(Q);if(Z===null)return!1;return J>Z}return!1}_buildItemAtIndex(J,Q){let Z=this.widget.items[Q];if(!Z)return new m1;let Y=Z.type==="message"&&this._isMessageStreaming(Z),X=Z.type==="toolResult"&&(Z.toolResult.run.status==="queued"||Z.toolResult.run.status==="in-progress")&&!("result"in Z.toolResult.run)&&!("error"in Z.toolResult.run),G=this._shouldDimItem(Q);if(!Y&&!X){let q=`${this._signatureFor(Z)}|dim:${G?1:0}`,W=this._widgetCache.get(Q);if(W&&W.sig===q)return W.widget;let H=this.buildThreadItemWidget(J,Z,Q),z=G?new CZ({forceDim:!0,child:H}):H;return this._widgetCache.set(Q,{sig:q,widget:z}),z}let K=this.buildThreadItemWidget(J,Z,Q);return G?new CZ({forceDim:!0,child:K}):K}onNewMessage(){if(this._isDisposed)return;this.widget.onNewMessage?.()}scrollToTop(){if(this._isDisposed||!this._controller)return;this._controller.scrollToTop()}scrollToMessage(J,{animated:Q=!1,offsetPercent:Z=0.25,edge:Y="top",duration:X}={}){if(this._isDisposed||!this._controller)return!1;let G=this._getMessageRelativeOffset(J,Y);if(G===null)return!1;let V=this._getViewportHeight(),K=Math.floor(V*Z),q=G-K;if(Q)this._controller.animateTo(q,X);else this._controller.jumpTo(q);return!0}_getColumnElement(){let J=this.context.element;if(!J)return null;let Q=new L9("message-list-column"),Z=(Y)=>{if(Y.widget.key?.equals(Q))return Y;for(let X of Y.children){let G=Z(X);if(G)return G}return null};return Z(J)}_getMessageRelativeOffset(J,Q){let Z=this._getColumnElement();if(!Z)return null;let Y=J*2,X=Z.children[Y];if(!X?.renderObject)return null;let G=X.renderObject,V=Z.renderObject;if(!V)return null;let K=G.localToGlobal({x:0,y:0}),q=V.localToGlobal({x:0,y:0}),W=0;if(Q==="bottom")W=G.size.height;return K.y+W-q.y}_getScrollbarInfo(){let J=this._controller?.maxScrollExtent??0,Q=this._getViewportHeight(),Z=this._controller?.offset??0,Y=J+Q;return{totalContentHeight:Math.max(Y,0),viewportHeight:Math.max(Q,1),scrollOffset:Math.max(Z,0)}}}class IH6 extends TZ{color;constructor({color:J,key:Q}){super({key:Q});this.color=J}createRenderObject(){return new PH6(this.color)}updateRenderObject(J){J.color=this.color}}class PH6 extends U6{color;constructor(J){super();this.color=J}performLayout(){let J=this._lastConstraints;if(J)this.setSize(J.maxWidth,1)}paint(J,Q,Z){let Y=Math.floor(this.size.width);for(let X=0;X<Y;X++)J.setChar(Q+X,Z,"─",{fg:this.color},1)}}var dC8=24,cC8=[{left:{keys:"Ctrl+O",description:"command palette"},right:{keys:"Ctrl+R",description:"prompt history"}},{left:{keys:"$ or $$",description:"shell commands"},right:{keys:"Ctrl+V",description:"paste images"}},{left:{keys:"Shift+Enter",description:"newline"},right:{keys:"Ctrl+S",description:"switch modes"}},{left:{keys:"Alt+D",description:"toggle deep reasoning"},right:{keys:"Ctrl+G",description:"edit in $EDITOR"}},{left:{keys:"@ / @@",description:"mention files/threads"},right:{keys:"Tab/Shift+Tab",description:"navigate messages"}},{left:{keys:"Ctrl+C Ctrl+C",description:"exit"},right:{keys:"?",description:"toggle this help"}}];class Af1 extends _0{constructor(J={}){super(J.key?{key:J.key}:{})}build(J){let Z=B0.of(J).colorScheme,X=v1.of(J).app,G=new g({color:X.keybind}),V=new g({color:Z.foreground,dim:!0}),K=$P()&&!GS1,q=cC8.map((H)=>{let z=H.left.keys==="Shift+Enter"&&K?"Alt+Enter":H.left.keys,F=H.left.description,U=z.length+1+F.length,D=" ".repeat(Math.max(0,dC8-U)),B=H.right.keys,N=H.right.description;return new J1({text:new y("",void 0,[new y(z,G),new y(" ",V),new y(F,V),new y(D+" ",V),new y(B,G),new y(" ",V),new y(N,V)])})});if(K){let z=Y81("https://ampcode.com/manual/appendix#amp-cli-tmux");q.push(new j1({height:1})),q.push(new J1({text:new y("",void 0,[new y("Enable ",V),new y("extended-keys",new g({color:X.command})),new y(" in tmux to use ",V),new y("Shift+Enter",G),new y(". See ",V),new y("https://ampcode.com/manual/appendix#amp-cli-tmux",new g({color:X.link,underline:!0}),void 0,z)])}))}let W=new Z0({children:[new L0({child:new IH6({color:Z.border})})]});return new S1({crossAxisAlignment:"start",mainAxisSize:"min",children:[...q,W]})}}class v71 extends TZ{text;baseColor;backgroundColor;glow;time;agentMode;orbWidth;orbHeight;glowIntensity;shockwaves;constructor({key:J,text:Q,baseColor:Z,backgroundColor:Y,glow:X,time:G,agentMode:V,orbWidth:K=40,orbHeight:q=40,glowIntensity:W=0.4,shockwaves:H=[]}){super(J?{key:J}:{});this.text=Q,this.baseColor=Z,this.backgroundColor=Y,this.glow=X,this.time=G,this.agentMode=V,this.orbWidth=K,this.orbHeight=q,this.glowIntensity=W,this.shockwaves=H}createElement(){return new ZK(this)}createRenderObject(){return new TH6(this.text,this.baseColor,this.backgroundColor,this.glow,this.time,this.agentMode,this.orbWidth,this.orbHeight,this.glowIntensity,this.shockwaves)}updateRenderObject(J){J.update(this.text,this.baseColor,this.backgroundColor,this.glow,this.time,this.agentMode,this.orbWidth,this.orbHeight,this.glowIntensity,this.shockwaves)}}var lC8=0.5;class TH6 extends U6{_text;_baseColor;_backgroundColor;_glow;_time;_agentMode;_orbWidth;_orbHeight;_glowIntensity;_shockwaves;constructor(J,Q,Z,Y,X,G,V,K,q,W){super();this._text=J;this._baseColor=Q;this._backgroundColor=Z;this._glow=Y;this._time=X;this._agentMode=G;this._orbWidth=V;this._orbHeight=K;this._glowIntensity=q;this._shockwaves=W}update(J,Q,Z,Y,X,G,V,K,q,W){let H=J!==this._text;if(this._text=J,this._baseColor=Q,this._backgroundColor=Z,this._glow=Y,this._time=X,this._agentMode=G,this._orbWidth=V,this._orbHeight=K,this._glowIntensity=q,this._shockwaves=W,H)this.markNeedsLayout();this.markNeedsPaint()}getMinIntrinsicWidth(J){return w9(this._text,!1)}getMaxIntrinsicWidth(J){return w9(this._text,!1)}getMinIntrinsicHeight(J){return 1}getMaxIntrinsicHeight(J){return 1}performLayout(){let J=this._lastConstraints;L6(!!J,"performLayout called without constraints");let Q=w9(this._text,!1),Z=J.constrain(Q,1);this.setSize(Z.width,Z.height),super.performLayout()}paint(J,Q=0,Z=0){let Y=Q+this.offset.x,X=Z+this.offset.y,G=s4(this._text),V=this._agentMode==="rush"?2.5:1,{primary:K,secondary:q}=Pb1(this._agentMode),W=Y;for(let H=0;H<G.length;H++){let z=G[H],F=v9(z,!1),D=(1-H/Math.max(G.length-1,1)*0.7)**1.2,B=this._glow.sample(this._orbWidth-2+H*0.5,this._orbHeight/2,this._time,V),N=0;for(let O of this._shockwaves){let A=this._time-O.startTime;if(A<0||A>eU)continue;let R=this._orbWidth*0.7+H,j=this._orbHeight/2,T=R-O.x,C=(j-O.y)/lC8,S=Math.sqrt(T*T+C*C),b=A*Cb1,u=Math.abs(S-b);if(u<Ku){let m=1-A/eU,k=(1-u/Ku)*m;N=Math.max(N,k*0.6)}}let M=B**0.7,L=Math.min(1,M*D+N),w=this.blendWithGlow(this._baseColor,L,K,q);J.setCell(W,X,{char:z,width:F,style:{fg:w,bg:this._backgroundColor}}),W+=F}}blendWithGlow(J,Q,Z,Y){let X=J71(Z,Y,Q),G=Q*this._glowIntensity;if(J.type==="rgb"){let V=J.value,K=Math.round(V.r*(1-G)+X.r*G),q=Math.round(V.g*(1-G)+X.g*G),W=Math.round(V.b*(1-G)+X.b*G);return{type:"rgb",value:{r:K,g:q,b:W}}}if(G>0.15)return{type:"rgb",value:{r:X.r,g:X.g,b:X.b}};return J}}var CH6=["ctrl+x","y","z"],_H6=1.5,b71="!@#$%^&*()_+-=[]{}|;:,.<>?/~`0123456789";function iC8(J,Q,Z){let Y=Math.max(J.length,Q.length),X=[];for(let G=0;G<Y;G++){let V=J[G]??" ",K=Q[G]??" ",q=V===" "||V===`
8541
8541
  `||V==="\t",W=K===" "||K===`
8542
8542
  `||K==="\t";if(q&&W){X.push(Z<0.5?V:K);continue}let H=G/Y*0.4,z=Math.max(0,Math.min(1,(Z-H)/(1-H)));if(z===0)X.push(V);else if(z>=1)X.push(K);else if(q)X.push(z<0.7?" ":K);else if(W)X.push(z<0.3?V:" ");else if(z<0.5){let F=z*2;if(Math.random()<F)X.push(b71[Math.floor(Math.random()*b71.length)]);else X.push(V)}else{let F=(z-0.5)*2;if(Math.random()<F)X.push(K);else X.push(b71[Math.floor(Math.random()*b71.length)])}}return X.join("").trimEnd()}var SH6=[{type:"command",text:'amp -x "What package manager do we use here?"'},{type:"command",text:'amp -x "Run the linter and fix the errors"'},{type:"hint",text:"Use Ctrl+O to open the command palette"},{type:"hint",text:"Use Ctrl+G to edit the prompt in your $EDITOR"},{type:"hint",text:"Use the `prompt: queue` command to enqueue messages without interrupting the agent"},{type:"hint",text:"Use the `thread: browser` command to open your thread in the browser"},{type:"hint",text:"Use the `thread: new` command to start a fresh thread"},{type:"hint",text:"Use the `thread: handoff` command to draft a new thread with relevant context"},{type:"hint",text:"Use the `thread: visibility` command to change thread visibility settings"},{type:"hint",text:"Use the `settings: open in editor` command to configure Amp"},{type:"hint",text:"Use the `agents-md: generate` command to create an AGENTS.md"},{type:"hint",text:"Use Tab/Shift+Tab to navigate to previous messages to edit or restore to a previous state"},{type:"prompt",text:'"Use the oracle to review the code we just wrote."'},{type:"prompt",text:'"Use subagents to update these components to use the new attribute we added."'},{type:"prompt",text:'"Do not write any code yet. Plan first."'},{type:"prompt",text:'"Think hard before you start implementing."'},{type:"prompt",text:`"Use 'psql' to change all blog_posts to have comments"`},{type:"prompt",text:'"Run <build command> and fix all the errors"'},{type:"quote",text:`"We are at the 'introduction of photography' period of programming. Painting by hand just doesn't have the same appeal anymore" - Orta Therox`},{type:"quote",text:'"Programming in the normal way feels like walking. You type out each expression, stepping incrementally toward your goal. When programming with AI, each move is bigger than a step. You lift off the ground." - Mary Rose Cook'},{type:"quote",text:'"Tomorrow all this may change, but right now after daily experience writing code with LLMs I strongly believe the maximum quality of work is reached using the human+LLM equation." - antirez'},{type:"quote",text:`"The magic that's coming now is the most powerful yet. And that means that we're beginning a profound period of exploration and creativity, trying to understand how to make that magic work and to derive new advantages from its power." - Tim O'Reilly`},{type:"quote",text:`"They're applying years of hard-won engineering wisdom to shape and constrain the AI's output. The AI is accelerating their implementation, but their expertise is what keeps the code maintainable." - Addy Osmani`},{type:"quote",text:'"I love computers just for the—sheer machine of it. This is the most exciting new thing that computers have been doing, probably in my lifetime." - DHH'},{type:"quote",text:`"We wouldn't even need to bother looking at the AI-generated code any more, just like we don't bother looking at the machine code generated by a compiler." - Martin Kleppmann`},{type:"quote",text:'"Real progress is messy, iterative, and deeply intertwined with the tools we build. Large language models are the latest, most dramatic example of that truth." - Daniel Lemire'},{type:"quote",text:`"'Human in the loop' is evolving from 'human who fixes AI mistakes' to 'human who directs AI work.'" - Ethan Mollick`},{type:"quote",text:`"I'm trying to code like a surgeon. A surgeon isn't a manager, they do the actual work! But their skills and time are highly leveraged." - Geoffrey Litt`},{type:"quote",text:`"It's important to do things fast. You learn more per unit time because you make contact with reality more frequently." - Nat Friedman`},{type:"quote",text:'"Once coding speed jumps, everything around it becomes the constraint. Your throughput gets capped by whatever is slowest." - Paul Dix'},{type:"quote",text:'"Bubble or no bubble, no one knows anything." - Benedict Evans'},{type:"quote",text:`"I actually don't think documentation is too important: LLMs can read the code a lot faster than you to figure out how to use it." - Simon Willison`},{type:"quote",text:`"The vast majority of AI tokens in the future will be used on things we don't even do today as workers." - Aaron Levie`},{type:"quote",text:`"Once you're airborne, you're suddenly immune to the length of the runway. You have days, not months. Time to break some things." - Kent Beck`},{type:"quote",text:'"Absolutely every fundamental assumption about how I work has to be questioned. There are days when it feels like I would be better off if I did not know anything about programming and started from scratch." - David Crawshaw'},{type:"quote",text:'"Code was the easiest part." - Andrej Karpathy'},{type:"quote",text:`"It's amazing for learning a codebase you're not familiar with, so it's great for discovery. Getting us out of writing boilerplate, getting us out of memorizing APIs, getting us out of looking up that thing from Stack Overflow." - Jeremy Howard`},{type:"quote",text:`"Don't anthropomorphize them!" - Steven Sinofsky`}],Rf1=40,jf1=40;class f71 extends d1{agentMode;mysteriousMessage;mysterySequenceProgress;onShowMysteryModal;deprecatedCommandPaths;constructor(J={}){super(J.key?{key:J.key}:{});this.agentMode=J.agentMode,this.mysteriousMessage=J.mysteriousMessage,this.mysterySequenceProgress=J.mysterySequenceProgress,this.onShowMysteryModal=J.onShowMysteryModal,this.deprecatedCommandPaths=J.deprecatedCommandPaths}createState(){return new kH6}}class kH6 extends u1{_glow;_t=0;_timer=null;_fps=0;_shockwaves=[];_suggestion;_morphStartTime=null;_previousHasMystery=!1;initState(){super.initState(),this._glow=new tU,this._suggestion=SH6[Math.floor(Math.random()*SH6.length)],this._previousHasMystery=!!this.widget.mysteriousMessage}getMorphProgress(J){if(this._morphStartTime===null)return null;let Q=J-this._morphStartTime;if(Q>=_H6)return null;return Q/_H6}dispose(){if(this._timer)clearInterval(this._timer),this._timer=null;super.dispose()}startAnimation(J){if(this._timer)clearInterval(this._timer),this._timer=null;if(this._fps=J,J>0)this._timer=setInterval(()=>{this._t+=1/J,this._shockwaves=this._shockwaves.filter((Q)=>this._t-Q.startTime<eU),this.setState(()=>{})},1000/J)}build(J){let Z=B0.of(J).colorScheme,X=v1.of(J).app,V=d0.of(J).capabilities.animationSupport,K=V==="fast"?60:V==="slow"?15:0;if(K!==this._fps)this.startAnimation(K);let q=!!this.widget.mysteriousMessage,W=this._suggestion,H=V==="disabled"?3:this._t;if(q&&!this._previousHasMystery&&V!=="disabled")this._morphStartTime=H;this._previousHasMystery=q;let z=this.getMorphProgress(H),F=z!==null,U=W.type==="quote"||W.type==="news"?new g({color:Z.foreground,dim:!0}):W.type==="hint"?new g({color:Z.secondary}):new g({color:W.type==="prompt"||W.type==="note"?Z.primary:Z.warning}),D=new g({color:X.keybind}),B=new g({color:X.command}),N=new g({color:Z.foreground,dim:!0}),M=[];if(W.type==="hint"){let S=W.text.split(/(`[^`]+`)/g);for(let b of S)if(b.startsWith("`")&&b.endsWith("`")){let u=b.slice(1,-1);M.push(new y(u,B))}else M.push(new y(b,U))}else M.push(new y(W.text,U));let L=V==="fast",w=(S)=>{this._shockwaves.push(S),this.setState(()=>{})},O=L?new v71({text:"Welcome to Amp",baseColor:Z.foreground,backgroundColor:Z.background,glow:this._glow,time:H,agentMode:this.widget.agentMode,orbWidth:Rf1,orbHeight:jf1,glowIntensity:1,shockwaves:this._shockwaves}):new J1({text:new y("Welcome to Amp",new g({color:Z.foreground}))}),A=null;if(q){let b=0.3+(Math.sin(H*0.5)*0.5+0.5)*0.4,u=new g({color:Z.primary,italic:!0,dim:b<0.5}),k=this.widget.mysterySequenceProgress?.matched.length??0,v=k>0?"Keep going...":"A message awaits...",f=[];for(let c=0;c<CH6.length;c++){let h=CH6[c],i=h==="ctrl+x"?"Ctrl-X":h.toUpperCase(),o=c<k?new g({color:Z.primary,bold:!0}):D;if(c>0)f.push(new y(", ",N));f.push(new y(i,o))}A=new S1({crossAxisAlignment:"start",mainAxisSize:"min",children:[L?new v71({text:v,baseColor:Z.primary,glow:this._glow,time:H,agentMode:this.widget.agentMode,orbWidth:Rf1,orbHeight:jf1,glowIntensity:0.6,shockwaves:this._shockwaves}):new J1({text:new y(v,u)}),new J1({text:new y("",void 0,[...f,new y(" to unlock",N)])})]})}let R,j=`A message awaits...
8543
8543
  Ctrl-X, Y, Z to unlock`;if(F){let b=W.text.replace(/`([^`]+)`/g,"$1")+`
@@ -8547,7 +8547,7 @@ Ctrl-X, Y, Z to unlock`;if(F){let b=W.text.replace(/`([^`]+)`/g,"$1")+`
8547
8547
  `),new y("Ctrl+O",D),new y(" for ",N),new y("help",B),new y(`
8548
8548
 
8549
8549
 
8550
- `,N)])}),R];if(!q&&!F&&W.url){let S=W.url.replace(/^https?:\/\//,"");T.push(new z8({uri:W.url,text:S,style:new g({color:Z.secondary,underline:!0})}))}if(A&&!F)T.push(A);if(this.widget.deprecatedCommandPaths&&this.widget.deprecatedCommandPaths.length>0&&!q&&!F){let S=new g({color:Z.destructive});T.push(new j1({height:1}),new J1({text:new y("Custom commands have been removed. See how to migrate them to skills:",S)}),new z8({uri:"https://ampcode.com/news/slashing-custom-commands",text:"ampcode.com/news/slashing-custom-commands",style:new g({color:Z.secondary,underline:!0})}))}let C=new j1({width:50,child:new S1({crossAxisAlignment:"start",mainAxisSize:"min",children:T})});return b0.child(new Z0({mainAxisAlignment:"center",crossAxisAlignment:"center",mainAxisSize:"min",children:[new _b1({width:Rf1,height:jf1,agentMode:this.widget.agentMode,glow:this._glow,backgroundColor:Z.background,t:H,fps:0,shockwaves:this._shockwaves,onShockwave:w,...V==="disabled"&&{seed:42}}),new j1({width:2}),C]}))}}T6();O6();T6();K0();class Ef1{threadService;workers=new Map;threadsMap=new Map;mainThreadSubs=new Map;workerStatusSubs=new Map;mainThreadObservable;workerStatusObservable;emitMainThread=null;emitWorkerStatus=null;constructor(J){this.threadService=J;this.mainThreadObservable=new T1((Q)=>{return this.emitMainThread=(Z)=>Q.next(Z),()=>{this.emitMainThread=null}}),this.workerStatusObservable=new T1((Q)=>{return this.emitWorkerStatus=(Z)=>Q.next(Z),()=>{this.emitWorkerStatus=null}})}registerWorker(J){let Q=J.thread.id;if(this.workers.has(Q))this.unregisterWorker(Q);this.threadsMap.set(Q,J.thread),this.workers.set(Q,{state:"initial"});let Z=this.threadService.observePatches(Q).pipe(eA()).subscribe((X)=>{this.threadsMap.set(Q,X);let G=this.workers.get(Q)||{state:"initial"};if(this.emitMainThread)this.emitMainThread({threadID:Q,mainThread:X,workerStatus:G})});this.mainThreadSubs.set(Q,Z);let Y=J.status.subscribe((X)=>{if(this.workers.set(Q,X),this.emitWorkerStatus)this.emitWorkerStatus({threadID:Q,status:X})});this.workerStatusSubs.set(Q,Y)}unregisterWorker(J){let Q=this.mainThreadSubs.get(J);if(Q)Q.unsubscribe(),this.mainThreadSubs.delete(J);let Z=this.workerStatusSubs.get(J);if(Z)Z.unsubscribe(),this.workerStatusSubs.delete(J);this.workers.delete(J),this.threadsMap.delete(J)}observeThread(J){return{mainThread:new T1((Q)=>{return this.mainThreadObservable.subscribe((Z)=>{if(Z.threadID===J)Q.next(Z)})}),workerStatus:new T1((Q)=>{return this.workerStatusObservable.subscribe((Z)=>{if(Z.threadID===J)Q.next(Z)})})}}get threadViewStates(){let J={};for(let[Q,Z]of this.threadsMap){let Y=this.workers.get(Q);if(Y)J[Q]=LW(Z,Y)}return J}get threadTitles(){let J={};for(let[Q,Z]of this.threadsMap)J[Q]=Z.title;return J}dispose(){for(let J of this.mainThreadSubs.values())J.unsubscribe();for(let J of this.workerStatusSubs.values())J.unsubscribe();this.mainThreadSubs.clear(),this.workerStatusSubs.clear(),this.workers.clear(),this.threadsMap.clear()}}function nC8(J,Q){switch(Q.type){case"main-thread-patch":{let{thread:Z,workerStatus:Y}=Q,{items:X}=h71(Z),G=LW(Z,Y),V=sH({messages:Z.messages}),K=Array.isArray(V)?V:[];return{...J,items:X,viewState:G,todosList:K,mainThread:Z}}case"worker-status-change":{if(!J.mainThread)return J;let Z=LW(J.mainThread,Q.workerStatus);if(Z===J.viewState)return J;return{...J,viewState:Z}}default:return J}}function h71(J){let Q=[],Z=new Map,Y=new Set;for(let[X,G]of J.messages.entries()){let V=`${G.role}-${X}`;switch(G.role){case"assistant":{let K=G.state.type==="streaming";for(let W of G.content)if(W.type==="tool_use"){if(Z.set(W.id,W),K)Y.add(W.id)}if(G.content.some((W)=>W.type==="text"&&W.text.trim()||W.type==="thinking"))Q.push({type:"message",id:V,message:G});for(let W of G.content)if(W.type==="tool_use"){let H=!1;for(let z=X+1;z<J.messages.length;z++){let F=J.messages[z];if(F){for(let U of F.content)if(U.type==="tool_result"&&U.toolUseID===W.id){H=!0;break}}if(H)break}if(!H)Q.push({type:"toolResult",id:W.id,toolUse:W,toolResult:{type:"tool_result",toolUseID:W.id,run:{status:K?"in-progress":"queued"}}})}break}case"info":{if(G.content.some((q)=>q.type==="manual_bash_invocation"||q.type==="summary"&&q.summary.type==="message"))Q.push({type:"message",id:V,message:G});break}case"user":{let K=G.content.some((q)=>q.type==="text"&&q.text.trim()||q.type==="image");for(let q of G.content)if(q.type==="tool_result"){let W=Z.get(q.toolUseID)??i2(J,q.toolUseID);if(!W)throw Error(`(bug) tool use ${q.toolUseID} not found`);Q.push({type:"toolResult",id:q.toolUseID,toolUse:W,toolResult:q})}if(K)Q.push({type:"message",id:V,message:G});break}}}return{items:Q}}class If1 extends d1{props;constructor(J){super();this.props=J}createState(){return new yH6}}class yH6 extends u1{state={items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null};workerController;subscriptions=[];recentThreadIDs=[];currentWorker;constructor(){super();this.workerController=null,this.currentWorker=null}addToRecentThreads(J){this.setState(()=>{let Q=this.recentThreadIDs.indexOf(J);if(Q!==-1)this.recentThreadIDs.splice(Q,1);if(this.recentThreadIDs.unshift(J),this.recentThreadIDs.length>50)this.recentThreadIDs.pop()})}initState(){let{threadService:J,worker:Q}=this.widget.props;this.workerController=new Ef1(J),this.currentWorker=Q,this.setupSubscriptions(Q),this.addToRecentThreads(Q.thread.id)}dispose(){this.cleanup()}didUpdateWidget(J){if(J.props.threadService!==this.widget.props.threadService||J.props.worker!==this.widget.props.worker)this.cleanup(),this.setupSubscriptions(this.widget.props.worker)}setupSubscriptions(J){this.workerController.registerWorker(J);let Q=this.workerController.observeThread(J.thread.id),Z=Q.mainThread.subscribe((X)=>{this.dispatch({type:"main-thread-patch",thread:X.mainThread,workerStatus:X.workerStatus})});this.subscriptions.push(Z);let Y=Q.workerStatus.subscribe((X)=>{this.dispatch({type:"worker-status-change",workerStatus:X.status})});this.subscriptions.push(Y)}cleanup(){this.subscriptions.forEach((J)=>J.unsubscribe()),this.subscriptions=[]}switchWorker(J){this.cleanup(),this.setState(()=>{this.currentWorker=J}),this.setState(()=>{this.state={items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null}}),this.setupSubscriptions(J),this.addToRecentThreads(J.thread.id)}dispatch(J){this.setState(()=>{this.state=nC8(this.state,J)})}getThreadData(){let J=(X)=>X===t8||X===R4||X===eY||X===f2,Q=new Map;for(let X of this.state.items)if(X.type==="toolResult"&&J(X.toolUse.name))Q.set(X.toolUse.id,{toolUseId:X.toolUse.id,toolName:X.toolUse.name,toolRun:X.toolResult.run});let Z=Array.from(Q.values()),Y={};for(let{toolUseId:X,toolRun:G}of Z){let V=[],K;if(G.status==="in-progress"||G.status==="done"||G.status==="error"||G.status==="cancelled")K=G.progress;if(Array.isArray(K)){let q=0;for(let W of K)if(W.tool_uses)for(let H of W.tool_uses){let z=`${X}:progress:${q++}`,F=H.status==="done"&&H.result!==void 0?{status:"done",result:H.result}:{status:H.status},U=H.normalized_name??H.tool_name;V.push({toolUse:tA(U,H.input,z),toolRun:F})}}Y[X]=V}return{...this.state,subagentToolsByParentID:Y}}build(J){let Q=this.getThreadData();return this.widget.props.builder(J,Q,this.workerController,(Z)=>this.switchWorker(Z),()=>this.currentWorker,this.recentThreadIDs)}}class Pf1 extends d1{props;constructor(J){super({key:J.key});this.props=J}createState(){return new xH6}}class xH6 extends u1{build(J){let Z=v1.of(J).colors,{todos:Y,title:X="TODOs"}=this.widget.props;if(!Array.isArray(Y)||Y.length===0)return new j1({width:0,height:0});let G=Y.map((V)=>this.buildTodoItem(V,Z));return new m1({child:new s1({padding:I1.symmetric(1,0),child:new S1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new J1({text:new y(X,new g({bold:!0,color:Z.foreground}))}),...G]})})})}buildTodoItem(J,Q){let Z=this.getStatusIcon(J.status),Y=J.status==="completed",X=new g({bold:J.status==="in-progress",color:Q.foreground,dim:Y}),G=new g({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Q.foreground,dim:Y});return new Z0({crossAxisAlignment:"start",children:[new J1({text:new y(Z,X)}),new j1({width:1}),new L0({child:new J1({text:new y(J.content,G)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class Tf1 extends d1{ad;onDismiss;onButtonClick;onImpression;onAdInfoClick;constructor({key:J,ad:Q,onDismiss:Z,onButtonClick:Y,onImpression:X,onAdInfoClick:G}){super({key:J});this.ad=Q,this.onDismiss=Z,this.onButtonClick=Y,this.onImpression=X,this.onAdInfoClick=G}createState(){return new vH6}}class vH6 extends u1{lastTrackedAdId=null;initState(){super.initState(),this.fireImpressionIfNeeded()}didUpdateWidget(J){super.didUpdateWidget(J),this.fireImpressionIfNeeded()}fireImpressionIfNeeded(){let J=this.widget.ad;if(J.id!==this.lastTrackedAdId)this.lastTrackedAdId=J.id,this.widget.onImpression?.(J)}build(J){let Q=v1.of(J),Z=Q.colors.primary,Y=Q.colors.foreground,X=Q.colors.background,G=this.widget.ad;return new m1({decoration:new K6(X,new y0(new I0(Z,1,"rounded"),new I0(Z,1,"rounded"),void 0,new I0(Z,1,"rounded"))),child:new s1({padding:I1.horizontal(1),child:new S1({children:[new Z0({crossAxisAlignment:"start",children:[new L0({child:new J1({text:new y(G.content,new g({color:Y}))})}),new j1({width:4}),new B6({onClick:()=>this.widget.onAdInfoClick?.(),cursor:"pointer",child:new J1({text:new y("Ad",new g({color:Y,dim:!0}))})})]}),new Z0({crossAxisAlignment:"start",children:[new fm({text:G.buttonLabel,onPressed:()=>this.widget.onButtonClick?.(),padding:I1.horizontal(1),color:Z,reverse:!0}),new j1({width:2}),new J1({text:new y(G.destinationUrlHostname,new g({color:Y,dim:!0}))})]})]})})})}}class Cf1 extends d1{props;constructor(J){super({key:J.key});this.props=J}createState(){return new bH6(this.props.autofocus??!0)}}class bH6 extends u1{autofocus;constructor(J){super();this.autofocus=J}build(J){let Z=B0.of(J).colorScheme,Y=(W)=>{if(W.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(W.ctrlKey&&W.key==="c"||W.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},X=d0.sizeOf(J),G=Math.min(60,X.width-4),V=X.height-4,K=[];if(this.widget.props.title)K.push(new J1({text:new y(this.widget.props.title,new g({bold:!0,color:Z.primary}))}),new j1({height:1}));if(this.widget.props.message)K.push(new J1({text:new y(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)K.push(new j1({height:1}));let q=[];if(this.widget.props.showCopyOption)q.push(new J1({text:new y("Enter to copy",new g({dim:!0}))}));return q.push(new J1({text:new y("Escape to close",new g({dim:!0}))})),K.push(new Z0({children:q.flatMap((W,H)=>H<q.length-1?[W,new j1({width:1}),new J1({text:new y("•",new g({dim:!0}))}),new j1({width:1})]:[W]),mainAxisSize:"min"})),new b0({child:new m1({constraints:new D0(G,G,0,V),decoration:new K6(Z.background,new y0(new I0(Z.primary,1,"rounded"),new I0(Z.primary,1,"rounded"),new I0(Z.primary,1,"rounded"),new I0(Z.primary,1,"rounded"))),padding:new I1(2,2,2,2),child:new A6({autofocus:this.autofocus,onKey:Y,child:new S1({children:K,mainAxisSize:"min"})})})})}}class _f1 extends d1{props;constructor(J){super({key:J.key});this.props=J}createState(){return new fH6(this.props.autofocus??!0)}}class fH6 extends u1{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=B0.of(J).colorScheme,Z=(K)=>{if(K.key==="Enter"||K.key==="Escape"||K.ctrlKey&&K.key==="c")return this.widget.props.onClose(),"handled";return"ignored"},Y=d0.sizeOf(J),X=Math.min(60,Y.width-4),G=Y.height-4,V=[];if(V.push(new J1({text:new y("Ads make Amp Free possible",new g({bold:!0}))})),this.widget.props.provider)V.push(new j1({height:1}),new J1({text:new y(`Ad source: ${this.widget.props.provider}`,new g({dim:!0}))}));return V.push(new j1({height:1}),new J1({text:new y("Escape to close",new g({dim:!0}))})),new b0({child:new m1({constraints:new D0(X,X,0,G),decoration:new K6(Q.background,new y0(new I0(Q.primary,1,"rounded"),new I0(Q.primary,1,"rounded"),new I0(Q.primary,1,"rounded"),new I0(Q.primary,1,"rounded"))),padding:new I1(2,2,2,2),child:new A6({autofocus:this.autofocus,onKey:Z,child:new S1({children:V,mainAxisSize:"min"})})})})}}class Sf1 extends d1{questions;onSubmit;onCancel;constructor({key:J,questions:Q,onSubmit:Z,onCancel:Y}){super(J?{key:J}:{});this.questions=Q,this.onSubmit=Z,this.onCancel=Y}createState(){return new mH6}}var hH6=8;class mH6 extends u1{focusNode=new n6({debugLabel:"AskWidget"});currentQuestionIndex=0;focusedOptionIndex=new Map;selectedOptions=new Map;otherInputActive=new Map;otherInputValues=new Map;otherTextController=new D3;scrollController=new k4;viewportHeight=hH6;initState(){super.initState(),this.focusNode.addKeyHandler(this.handleKeyEvent.bind(this));for(let J=0;J<this.widget.questions.length;J++)this.focusedOptionIndex.set(J,0),this.selectedOptions.set(J,new Set),this.otherInputActive.set(J,!1),this.otherInputValues.set(J,"");this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0),this.scrollToIndex(0)}dispose(){this.focusNode.dispose(),this.otherTextController.dispose(),this.scrollController.dispose(),super.dispose()}get currentQuestion(){return this.widget.questions[this.currentQuestionIndex]}get currentSelections(){return this.selectedOptions.get(this.currentQuestionIndex)??new Set}get currentFocusedIndex(){return this.focusedOptionIndex.get(this.currentQuestionIndex)??0}set currentFocusedIndex(J){this.focusedOptionIndex.set(this.currentQuestionIndex,J)}get isOtherActive(){return this.otherInputActive.get(this.currentQuestionIndex)??!1}handleKeyEvent(J){if(this.isOtherActive)return this.handleOtherInputKeyEvent(J);let Q=(Y,X)=>{return J.key===Y&&J.ctrlKey===(X?.ctrl??!1)&&J.shiftKey===(X?.shift??!1)};if(Q("ArrowDown")||Q("j"))return this.moveSelection(1),"handled";if(Q("ArrowUp")||Q("k"))return this.moveSelection(-1),"handled";if(Q("ArrowRight")||Q("Tab")||Q("l"))return this.nextQuestion(),"handled";if(Q("ArrowLeft")||Q("Tab",{shift:!0})||Q("h"))return this.prevQuestion(),"handled";if(Q(" "))return this.toggleCurrentSelection(),"handled";if(Q("Enter")){if(this.isOnOtherOption()&&!this.otherInputValues.get(this.currentQuestionIndex))this.activateOtherInput();else this.submitAnswers();return"handled"}if(Q("Escape"))return this.widget.onCancel(),"handled";if(Q("o"))return this.activateOtherInput(),"handled";let Z=parseInt(J.key,10);if(!isNaN(Z)&&Z>=1&&Z<=this.currentQuestion.options.length+1)return this.selectOption(Z-1),"handled";return"ignored"}handleOtherInputKeyEvent(J){if(J.key==="Escape")return this.setState(()=>{this.otherInputActive.set(this.currentQuestionIndex,!1)}),"handled";return"ignored"}moveSelection(J){let Q=this.currentQuestion.options.length+1,Z=this.currentFocusedIndex+J;if(Z<0)Z=Q-1;if(Z>=Q)Z=0;this.setState(()=>{if(this.currentFocusedIndex=Z,!this.currentQuestion.multiSelect)this.currentSelections.clear(),this.currentSelections.add(Z);this.scrollToIndex(Z)})}scrollToIndex(J){let Z=J*2,Y=Z+2,X=this.scrollController.offset;if(Z<X)this.scrollController.jumpTo(Z);else if(Y>X+this.viewportHeight)this.scrollController.jumpTo(Y-this.viewportHeight)}toggleCurrentSelection(){let J=this.currentFocusedIndex;this.setState(()=>{if(this.currentQuestion.multiSelect)if(this.currentSelections.has(J))this.currentSelections.delete(J);else this.currentSelections.add(J)})}selectOption(J){this.setState(()=>{if(this.currentFocusedIndex=J,this.currentQuestion.multiSelect)if(this.currentSelections.has(J))this.currentSelections.delete(J);else this.currentSelections.add(J);else this.currentSelections.clear(),this.currentSelections.add(J)})}isOnOtherOption(){return this.currentFocusedIndex===this.currentQuestion.options.length}activateOtherInput(){this.setState(()=>{this.otherInputActive.set(this.currentQuestionIndex,!0),this.otherTextController.text=this.otherInputValues.get(this.currentQuestionIndex)??""})}nextQuestion(){if(this.currentQuestionIndex<this.widget.questions.length-1)this.setState(()=>{this.currentQuestionIndex++;let J=this.currentSelections,Q=J.size>0?Math.max(...Array.from(J)):0;this.scrollToIndex(Q)})}prevQuestion(){if(this.currentQuestionIndex>0)this.setState(()=>{this.currentQuestionIndex--;let J=this.currentSelections,Q=J.size>0?Math.max(...Array.from(J)):0;this.scrollToIndex(Q)})}submitAnswers(){for(let Q=0;Q<this.widget.questions.length;Q++){let Z=this.selectedOptions.get(Q)??new Set,Y=this.otherInputValues.get(Q);if(Z.size===0&&!Y){this.setState(()=>{this.currentQuestionIndex=Q,this.scrollToIndex(this.currentFocusedIndex)});return}}let J={};for(let Q=0;Q<this.widget.questions.length;Q++){let Z=this.widget.questions[Q],Y=this.selectedOptions.get(Q)??new Set,X=[];for(let G of Y)if(G<Z.options.length)X.push(Z.options[G].label);else{let V=this.otherInputValues.get(Q)??"";if(V)X.push(V)}J[Z.question]=X.join(", ")||"No selection"}this.widget.onSubmit(J)}build(J){let Z=B0.of(J).colorScheme,Y=v1.of(J),X=[this.buildHeader(Z)];if(this.widget.questions.length>1)X.push(this.buildQuestionTabs(Z));let G=new S1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:X}),V=this.buildQuestionContent(Z),K=this.isOtherActive?V:new m1({constraints:new D0({maxHeight:hH6}),child:new Z0({crossAxisAlignment:"stretch",children:[new L0({child:new e6({controller:this.scrollController,autofocus:!1,child:V})}),new A9({controller:this.scrollController,thumbColor:Y.app.scrollbarThumb,trackColor:Y.app.scrollbarTrack,getScrollInfo:()=>{let W=this.scrollController.maxScrollExtent,H=this.scrollController.offset,z=W+this.viewportHeight;return{totalContentHeight:Math.max(z,0),viewportHeight:Math.max(this.viewportHeight,1),scrollOffset:Math.max(H,0)}}})]})}),q=new S1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[G,K,this.buildFooter(Z)]});return new A6({focusNode:this.focusNode,autofocus:!0,child:new m1({decoration:new K6(Z.background,y0.all(new I0(Z.primary,1,"rounded"))),child:new s1({padding:I1.symmetric(1,0),child:q})})})}buildHeader(J){let Q=this.currentQuestion,Z=[new y("? ",new g({color:J.primary,bold:!0})),new y(Q.question,new g({color:J.foreground,bold:!0}))];if(Q.multiSelect)Z.push(new y(" (multi-select)",new g({color:J.secondary})));return new J1({text:new y("",void 0,Z)})}buildQuestionTabs(J){let Q=[];for(let Z=0;Z<this.widget.questions.length;Z++){let Y=this.widget.questions[Z],X=Z===this.currentQuestionIndex,G=Y.header.length>12?Y.header.slice(0,11)+"…":Y.header,V=X?new g({color:J.primary,bold:!0}):new g({color:J.secondary}),K=X?"▸ ":" ";if(Q.push(new J1({text:new y(K+G,V)})),Z<this.widget.questions.length-1)Q.push(new j1({width:2}))}return new Z0({mainAxisAlignment:"start",children:Q})}buildQuestionContent(J){let Q=this.currentQuestion,Z=this.currentSelections,Y=this.currentFocusedIndex;if(this.isOtherActive)return this.buildOtherInput(J);let X=[];for(let q=0;q<Q.options.length;q++){let W=Q.options[q],H=Z.has(q),z=Y===q;X.push(this.buildOption(q,W.label,W.description,H,z,J))}let G=this.otherInputValues.get(this.currentQuestionIndex)??"",V=Z.has(Q.options.length),K=Y===Q.options.length;return X.push(this.buildOption(Q.options.length,G?`Other: ${G}`:"Other...","Provide a custom answer",V,K,J)),new S1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:X})}buildOption(J,Q,Z,Y,X,G){let K=this.currentQuestion.multiSelect?Y?"[x]":"[ ]":Y?"●":"○",q=Y?G.primary:G.secondary,W=X?G.primary:G.foreground,H=X?"▸":" ",z=J<9?`${J+1}`:"";return new s1({padding:I1.symmetric(0,0),child:new Z0({crossAxisAlignment:"start",children:[new J1({text:new y(H,new g({color:G.primary}))}),new J1({text:new y(K,new g({color:q}))}),new j1({width:1}),new L0({child:new S1({crossAxisAlignment:"start",mainAxisSize:"min",children:[new J1({text:new y("",void 0,[new y(Q,new g({color:W,bold:X})),z?new y(` [${z}]`,new g({color:G.secondary,dim:!0})):new y("")])}),new J1({text:new y(Z,new g({color:G.secondary,dim:!0}))})]})})]})})}confirmOtherInput(){let J=this.otherTextController.text;this.otherInputValues.set(this.currentQuestionIndex,J),this.otherInputActive.set(this.currentQuestionIndex,!1);let Q=this.currentSelections;Q.clear(),Q.add(this.currentQuestion.options.length),this.submitAnswers()}buildOtherInput(J){return new S1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new J1({text:new y("Enter your custom answer:",new g({color:J.foreground,bold:!0}))}),new j1({height:1}),new Z0({crossAxisAlignment:"center",children:[new J1({text:new y("▸ ",new g({color:J.primary}))}),new L0({child:new kZ({controller:this.otherTextController,autofocus:!0,placeholder:"Type your answer...",onSubmitted:()=>this.confirmOtherInput()})})]}),new j1({height:1}),new J1({text:new y("Press Enter to confirm, Esc to go back",new g({color:J.secondary,dim:!0}))})]})}buildFooter(J){let Q=[];if(this.isOtherActive)Q.push("Enter to confirm","Esc to cancel");else{if(Q.push("↑↓ navigate"),this.currentQuestion.multiSelect)Q.push("Space select");if(this.widget.questions.length>1)Q.push("←→ questions");Q.push("Enter submit","Esc cancel")}return new J1({text:new y(Q.join(" • "),new g({color:J.secondary,dim:!0}))})}}b1();import{execSync as z_8}from"node:child_process";GR();V2();r9();J3();nB();rG();XQ();r2();YX();KQ();T6();Wh();QS();K0();var Lz6=U0(vq(),1);import{writeFile as Uz6}from"fs/promises";import Dz6 from"path";b1();XQ();class kf1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;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(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1769716999-gdf283f"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Fr(Q,this.configService)}catch(Q){E.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class GD extends d1{props;constructor(J){super();this.props=J}createState(){return new gH6}}class gH6 extends u1{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Z)=>{this.setState(()=>{this._state=Z(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class uH6 extends u1{controller=new D3;focusNode=new n6({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 Q=v1.of(J),{colors:Z,app:Y}=Q,X=this.widget.props.isRequiredArg??!0,G=this.controller.text.trim().length>0,V=!X||G,K=y0.all(new I0(Z.foreground,1,"solid")),q=new kZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(U)=>{let D=U.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Z.foreground,border:null},maxLines:1}),W=new Z0({children:[new m1({decoration:{color:Z.background},child:new J1({text:new y(">",new g({color:Z.foreground}))})}),new L0({child:q})]}),H=new m1({padding:I1.symmetric(1,0),child:new J1({text:new y("",void 0,[new y("Command: ",new g({color:Z.foreground})),new y(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),z=[];if(V)z.push(new y("Enter",new g({color:Y.keybind}))),z.push(new y(" to submit, ",new g({color:Z.foreground,dim:!0})));z.push(new y("Esc",new g({color:Y.keybind}))),z.push(new y(" to cancel",new g({color:Z.foreground,dim:!0})));let F=new m1({padding:I1.symmetric(1,0),child:new J1({text:new y("",void 0,z)})});return new m1({decoration:{border:K,color:Z.background},padding:I1.all(1),child:new S1({children:[H,new j1({height:1}),W,new j8,F]})})}}class m71 extends d1{props;constructor(J){super();this.props=J}createState(){return new uH6}}import{isDeepStrictEqual as sC8}from"node:util";var aC8=/[\\/_ +.#"@[({&]/,oC8=/[\\/_ +.#"@[({&]/g,rC8=/[\s-]/,pH6=/[\s-]/g;function u71(J,Q,Z,Y,X,G,V){if(G===Q.length){if(X===J.length)return 1;return 0.99}let K=`${X},${G}`;if(V[K]!==void 0)return V[K];let q=Y.charAt(G),W=Z.indexOf(q,X),H=0,z,F,U,D;while(W>=0){if(z=u71(J,Q,Z,Y,W+1,G+1,V),z>H){if(W===X)z*=1;else if(rC8.test(J.charAt(W-1))){if(z*=0.9,D=J.slice(X,W-1).match(pH6),D&&X>0)z*=0.999**D.length}else if(aC8.test(J.charAt(W-1))){if(z*=0.8,U=J.slice(X,W-1).match(oC8),U&&X>0)z*=0.999**U.length}else if(z*=0.3,X>0)z*=0.999**(W-X);if(J.charAt(W)!==Q.charAt(G))z*=0.9999}if(z<0.1&&(Z.charAt(W-1)===Y.charAt(G+1)||Y.charAt(G+1)===Y.charAt(G)&&Z.charAt(W-1)!==Y.charAt(G))){if(F=u71(J,Q,Z,Y,W+1,G+2,V),F*0.1>z)z=F*0.1}if(z>H)H=z;W=Z.indexOf(q,W+1)}return V[K]=H,H}function g71(J){return J.toLowerCase().replace(pH6," ")}function dH6(J,Q){let Z=u71(J,Q,g71(J),g71(Q),0,0,{}),Y=Q.trim().split(/\s+/);if(Y.length>1){let X=0,G=0;for(let K of Y){let q=u71(J,K,g71(J),g71(K),0,0,{});if(q===0)return Z;X+=q,G+=K.length}let V=X/Y.length*0.95;return Math.max(Z,V)}return Z}class jT{}class ET{}class p71{}class d71{}class cH6 extends d1{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new lH6}}class lH6 extends u1{build(J){return this.widget.onContext(J),this.widget.child}}function tC8(J,Q){if(J==="")return{matches:!0,score:1};let Z=dH6(Q,J);return{matches:Z>0.15,score:Z}}class R7 extends d1{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new iH6}}class iH6 extends u1{controller=new D3;focusNode;scrollController=new k4;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new n6({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let Q=this.cachedFiltered;this.widget.props.onSelectionChange?.(Q[0]??null)}),this.recomputeFilteredItems();let J=this.cachedFiltered;this.widget.props.onSelectionChange?.(J[0]??null),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!sC8(J.props.items,this.widget.props.items)){this.recomputeFilteredItems(),this.ensureSelectedItemVisible();let Q=this.cachedFiltered;this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)}}dispose(){this.widget.props.onSelectionChange?.(null),this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof jT){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof ET){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof p71){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length){let Z=Q[this.selectedIndex];if(Z){if(!(this.widget.props.isItemDisabled?.(Z)??!1))this.widget.props.onAccept(Z,{hasUserInteracted:this.hasUserInteracted})}}return"handled"}if(J instanceof d71)return this.widget.props.onDismiss?.(),"handled";return"ignored"};recomputeFilteredItems(){let J=this.controller.text,Q=this.widget.props.items,Z=this.widget.props.normalizeQuery?.(J)??J,Y=Q.filter((X)=>!this.widget.props.filterItem||this.widget.props.filterItem(X,J)).map((X)=>({item:X,...tC8(Z,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,G)=>this.widget.props.sortItems(X,G,J):(X,G)=>G.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Q,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.controller.text,Q=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Q)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Z=0,Y=Q.size.height;UP(J,{top:Z,bottom:Y},{padding:1})}handleScroll=(J)=>{let Q=this.getFilteredItems();if(Q.length===0)return;if(J.direction==="down")if(this.selectedIndex<Q.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return;this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)};handleItemClick=(J,Q)=>{let Z=this.getFilteredItems();if(J>=0&&J<Z.length){let Y=Z[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Q===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Z[this.selectedIndex]??null);else if(Q===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Q=v1.of(J),{colors:Z}=Q,Y=this.getFilteredItems(),X=y0.all(new I0(Z.foreground,1,"solid")),G=this.widget.props.enabled??!0,V=new kZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:G,style:{backgroundColor:Z.background,textColor:Z.foreground,cursorColor:Z.cursor,placeholderColor:Z.mutedForeground,border:null},maxLines:1}),K=new d7({shortcuts:new Map([[new v0("ArrowDown"),new jT],[new v0("ArrowUp"),new ET],[new v0("Tab"),new jT],[new v0("Tab",{shift:!0}),new ET],[new v0("n",{ctrl:!0}),new jT],[new v0("p",{ctrl:!0}),new ET],[new v0("Enter"),new p71],[new v0("Escape"),new d71]]),focusNode:this.focusNode,child:V}),q=new N5({actions:new Map([[jT,new M6(this.invoke)],[ET,new M6(this.invoke)],[p71,new M6(this.invoke)],[d71,new M6(this.invoke)]]),child:K}),W=new Z0({children:[new m1({decoration:{color:Z.background},child:new J1({text:new y(">",new g({color:Z.foreground}))})}),new L0({child:q})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let B=this.widget.props.loadingText??"Loading...";H=new j1({height:10,child:new b0({child:new J1({text:new y(B,new g({color:Z.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)H=new L0({child:new b0({child:new J1({text:new y(this.widget.props.emptyStateText,new g({color:Z.foreground,dim:!0}))})})});else{let B=Y.map((N,M)=>{let L=M===this.selectedIndex,w=this.widget.props.isItemDisabled?.(N)??!1,O;if(this.widget.props.renderItem)O=this.widget.props.renderItem(N,L,w,J);else{let A=L?Q.app.selectionBackground:void 0,R=L?Q.app.selectionForeground:Z.foreground;O=new m1({decoration:A?{color:A}:void 0,padding:I1.symmetric(2,0),child:new J1({text:new y(this.widget.props.getLabel(N),new g({color:R,dim:w}))})})}return new cH6(new B6({onClick:(A)=>this.handleItemClick(M,A.clickCount),child:O}),(A)=>{this.itemContexts[M]=A})});H=new S1({children:B,crossAxisAlignment:"start"})}let z=new B6({onScroll:this.handleScroll,opaque:!1,child:new e6({controller:this.scrollController,autofocus:!1,child:H})}),F=[];if(this.widget.props.title){let B=new m1({padding:I1.symmetric(1,0),child:new J1({text:new y(this.widget.props.title,new g({color:Q.app.command,bold:!0}))})});F.push(B)}if(F.push(W,new j1({height:1})),this.controller.text!==""){let B=Y.length>0?Y[this.selectedIndex]:void 0,N=B&&this.widget.props.buildDisabledReasonWidget?.(B,J);F.push(new L0({child:new S1({mainAxisAlignment:"spaceBetween",children:[new L0({child:z}),new m1({padding:I1.only({top:1}),child:new b0({child:N??new j1({height:1})})})]})}))}else F.push(new L0({child:z}));if(this.widget.props.footer)F.push(this.widget.props.footer);return new m1({decoration:{border:X,color:Z.background},padding:I1.symmetric(1,0),child:new S1({children:F})})}}function nH6(J){let Z=new Date().getTime()-J.getTime(),Y=Math.floor(Z/60000),X=Math.floor(Z/3600000),G=Math.floor(Z/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class yf1 extends _0{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Z=Math.max(0,...Q.map((X)=>nH6(X.pubDate).length));return new R7({items:Q,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,G,V,K)=>{let q=v1.of(K),{colors:W}=q,H=q.app,z=G?H.selectionBackground:void 0,F=G?H.selectionForeground:W.foreground,U=W.mutedForeground,D=(B,N)=>new j1({width:N,child:Z0.end([new J1({text:new y(B,new g({color:U}))})])});return new m1({decoration:z?{color:z}:void 0,padding:I1.symmetric(2,0),child:new Z0({children:[new L0({child:new J1({text:new y(X.title,new g({color:F})),overflow:"ellipsis",maxLines:1})}),new j1({width:2}),D(nH6(X.pubDate),Z)]})})}})}}T6();class xf1 extends d1{createState(){return new aH6}}class aH6 extends u1{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 Z=v1.of(J).colors;return new J1({text:new y("●",new g({color:this.isGreen?Z.success:Z.mutedForeground,bold:!0})),maxLines:1})}}var eC8=/\/threads\/(T-[^/?#\s<>]+)/i;function J_8(J){let Q=J.trim(),Y=Q.match(eC8)?.[1];if(Y&&D9(Y))return Y;let X=Q.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(D9(X))return X;return null}function Q_8(J){let Q=new Map,Z=new Map,Y=new Map,X=[];for(let V of J)Q.set(V.id,V);for(let V of J){let K=V.parentRelationships.find((q)=>q.role==="child"&&Q.has(q.threadID)&&(q.type==="fork"||q.type==="handoff"));if(K){Y.set(V.id,K.type);let q=K.threadID,W=Z.get(q)||[];W.push(V),Z.set(q,W)}else X.push(V)}return M71.flatten(X,(V)=>Z.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function vf1(J,Q,Z){return new J1({text:new y(`${J}${Q}`,new g({color:Z})),maxLines:1})}function Z_8(J,Q,Z,Y){return[vf1("+",J,Y.success),j8.horizontal(1),vf1("~",Q,Y.warning),j8.horizontal(1),vf1("-",Z,Y.destructive)]}class c71 extends _0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((D)=>D.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((D)=>D.id!==this.props.currentThreadID);let Z=this.props.recentThreadIDs||[],Y=new Set(Z),X=this.props.currentThreadID,G=[...Q].sort((D,B)=>{if(X){if(D.id===X)return-1;if(B.id===X)return 1}let N=Z.indexOf(D.id),M=Z.indexOf(B.id);if(N!==-1&&M!==-1)return N-M;if(N!==-1)return-1;if(M!==-1)return 1;return 0}),V=Q_8(G),K=Math.max(0,...V.map((D)=>D.description.timeAgo.length)),q=v1.of(J),W=new s1({padding:I1.symmetric(0,1),child:new b0({child:new J1({text:new y("",new g({color:q.colors.foreground,dim:!0}),[new y("Ctrl+T",new g({color:q.colors.primary,dim:!0})),new y(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:q.colors.foreground,dim:!0}))])})})}),H="",z=null,F=(D)=>{if(D!==H)H=D,z=J_8(D);return z};return new R7({items:V,getLabel:(D)=>`${D.title} ${D.id}`,filterItem:(D,B)=>{let N=F(B);if(N)return D.id.toLowerCase()===N.toLowerCase();return!0},normalizeQuery:(D)=>F(D)?"":D,onAccept:(D,B)=>this.props.onSelect?.(D.id,B),onDismiss:this.props.onDismiss,onSelectionChange:(D)=>{if(this.props.previewController){if(D)this.props.previewController.select(D.id)}},title:this.props.title,isLoading:this.props.isLoading,loadingText:"Loading threads...",emptyStateText:"No threads match your filter",maxRenderItems:200,footer:this.props.isLoading?void 0:W,renderItem:(D,B,N,M)=>{let L=v1.of(M),{app:w,colors:O}=L,A=B?w.selectionBackground:void 0,R=B?w.selectionForeground:O.foreground,j=O.mutedForeground,T=(c,h)=>new j1({width:h,child:Z0.end([new J1({text:new y(c,new g({color:j}))})])}),C=this.props.threadViewStates[D.id],S=[],b=D.relationshipType==="handoff",u=new Hu({connectorColor:O.mutedForeground});if(D.depth>0){let c=[],h=D.ancestorsAreLast.slice(1);for(let o of h)c.push(new y(u.getAncestorPrefix(o),new g({color:u.connectorColor,dim:u.connectorDim})));let i=D.isLast?u.elbow:u.tee,p=u.getConnectorText(i);c.push(new y(p,new g({color:u.connectorColor,dim:u.connectorDim}))),S.push(new J1({text:new y("",void 0,c)}))}let m=[],k=X===D.id?new y("(current) ",new g({color:O.success})):Y.has(D.id)?new y("(visited) ",new g({color:O.foreground,dim:!0})):null;if(k)m.push(new J1({text:k}));if(XL(C))m.push(new xf1),m.push(new j1({width:1}));let v=D.title;if(D.relationshipType==="fork"){let c=v.match(/^Forked\((\d+)\): /);if(c)v=v.slice(c[0].length);else while(v.startsWith("Forked: "))v=v.slice(8);m.push(new J1({text:new y("[fork] ",new g({color:O.primary}))}))}else if(b)m.push(new J1({text:new y("[handoff] ",new g({color:O.accent}))}));if(m.push(new L0({child:new J1({text:new y(v,new g({color:R})),overflow:"ellipsis",maxLines:1})})),m.push(new j1({width:2})),D.diffStats&&(D.diffStats.added>0||D.diffStats.changed>0||D.diffStats.deleted>0)){let c=B?{success:j,warning:j,destructive:j}:O;m.push(...Z_8(D.diffStats.added,D.diffStats.changed,D.diffStats.deleted,c)),m.push(new j1({width:2}))}return m.push(T(D.description.timeAgo,K)),new m1({decoration:A?{color:A}:void 0,padding:I1.symmetric(2,0),child:new Z0({children:[...S,...m]})})}})}}class rH6 extends d1{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new sH6}}class sH6 extends u1{build(J){return this.widget.onContext(J),this.widget.child}}var oH6=30,$_8=30;class IT{}class PT{}class l71{}class i71{}class bf1 extends d1{props;constructor(J){super();this.props=J}createState(){return new tH6}}class tH6 extends u1{highlightedIndex=0;controller=new D3;focusNode;scrollController=new k4;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new n6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),Y4.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 Q=J.findRenderObject();if(!Q)return;let Z=0,Y=Q.size.height;UP(J,{top:Z,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Q}=this.widget.props;if(!J)this.filteredClusters=[...Q];else this.filteredClusters=Q.filter((Z)=>Z.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof IT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof PT){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof l71){let Q=this.filteredClusters[this.highlightedIndex];if(Q)this.widget.props.onAccept(Q);return"handled"}if(J instanceof i71)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Q)=>{if(J>=0&&J<this.filteredClusters.length){if(Q===1)this.highlightedIndex=J,this.setState();else if(Q===2){let Z=this.filteredClusters[J];if(Z)this.widget.props.onAccept(Z)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return;else if(this.highlightedIndex>0)this.highlightedIndex--;else return;this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})};build(J){let{currentThreadID:Q}=this.widget.props,Z=v1.of(J),{colors:Y,app:X}=Z,K=d0.of(J).size.width>=$_8+oH6,q=y0.all(new I0(Y.foreground,1,"solid")),W=this.filteredClusters[this.highlightedIndex]??null,H=new m1({padding:I1.symmetric(1,0),child:new J1({text:new y("Select a cluster",new g({color:X.command,bold:!0}))})}),z=new kZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),F=new d7({shortcuts:new Map([[new v0("ArrowDown"),new IT],[new v0("ArrowUp"),new PT],[new v0("Tab"),new IT],[new v0("Tab",{shift:!0}),new PT],[new v0("n",{ctrl:!0}),new IT],[new v0("p",{ctrl:!0}),new PT],[new v0("Enter"),new l71],[new v0("Escape"),new i71]]),focusNode:this.focusNode,child:z}),U=new N5({actions:new Map([[IT,new M6(this.invoke)],[PT,new M6(this.invoke)],[l71,new M6(this.invoke)],[i71,new M6(this.invoke)]]),child:F}),D=new Z0({children:[new m1({decoration:{color:Y.background},child:new J1({text:new y(">",new g({color:Y.foreground}))})}),new L0({child:U})]});this.itemContexts=[];let B=this.filteredClusters.map((A,R)=>{let j=R===this.highlightedIndex,T=Q?A.threads.some((u)=>u.id===Q):!1,C=j?X.selectionBackground:void 0,S=j?X.selectionForeground:Y.foreground,b=[new y(A.label,new g({color:S})),new y(` (${A.threads.length})`,new g({color:S,dim:!0}))];if(T)b.push(new y(" (current)",new g({color:j?X.selectionForeground:Y.success})));return new rH6(new B6({onClick:(u)=>this.handleItemClick(R,u.clickCount),child:new m1({decoration:C?{color:C}:void 0,padding:I1.symmetric(2,0),child:new J1({text:new y("",void 0,b)})})}),(u)=>{this.itemContexts[R]=u})}),N=new S1({children:B,crossAxisAlignment:"start"}),M=new L0({child:new B6({onScroll:this.handleScroll,child:new e6({controller:this.scrollController,autofocus:!1,child:N})})}),L=W?W.threads.map((A)=>({id:A.id,title:A.title,parentID:A.parentID,updatedAt:A.updatedAt})):[],w=W?new m1({padding:I1.all(1),child:new Sw({threads:L,autofocus:!1,offsetY:2})}):null,O;if(K){let A=w?new L0({child:w}):new j1({width:oH6});O=new Z0({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[M,A]})}else{let A=[new L0({child:new B6({onScroll:this.handleScroll,child:new e6({controller:this.scrollController,autofocus:!1,child:N})})})];if(w)A.push(new L0({child:w}));O=new S1({crossAxisAlignment:"stretch",children:A})}return new m1({decoration:{border:q,color:Y.background},padding:I1.symmetric(1,0),child:new S1({children:[H,D,new j1({height:1}),new L0({child:O})]})})}}b1();class eH6 extends u1{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){E.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){E.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Q=J.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))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((Q)=>!J.includes(Q.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Q=J.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let Z=this.widget.props.currentLabels||[],Y=this.labels.some((G)=>G.name===Q),X=Z.includes(Q);return!Y&&!X}build(J){let Q=v1.of(J),{app:Z,colors:Y}=Q,X=this.currentQuery.trim().toLowerCase(),G=X.length>0?this.getValidationError(X):null,V=this.getAvailableLabels(),q=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...V];return new R7({title:"Add Label",items:q,getLabel:(W)=>{if("__isCreateMarker"in W)return this.currentQuery.trim().toLowerCase();return W.name},onAccept:(W)=>{if("__isCreateMarker"in W)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(W.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:G||"Type to create a new label",renderItem:(W,H,z,F)=>{let U=H?Z.selectionBackground:void 0,D=H?Z.selectionForeground:Y.foreground;if("__isCreateMarker"in W&&W.__isCreateMarker){let N=this.currentQuery.trim().toLowerCase();return new m1({decoration:U?{color:U}:void 0,padding:I1.symmetric(2,0),child:new J1({text:new y("",void 0,[new y("Create new label: ",new g({color:D})),new y(N,new g({color:D,bold:!0}))])})})}return new m1({decoration:U?{color:U}:void 0,padding:I1.symmetric(2,0),child:new J1({text:new y(W.name,new g({color:D}))})})},filterItem:(W,H)=>{if(this.currentQuery!==H)this.currentQuery=H,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in W&&W.__isCreateMarker)return this.shouldShowCreateMarker(H);let F=H.trim().toLowerCase();return F.length===0||W.name.includes(F)},sortItems:(W,H,z)=>{let F="__isCreateMarker"in W.item&&W.item.__isCreateMarker,U="__isCreateMarker"in H.item&&H.item.__isCreateMarker;if(F&&!U)return-1;if(!F&&U)return 1;return H.score-W.score}})}}class ff1 extends d1{props;constructor(J){super();this.props=J}createState(){return new eH6}}class VD extends d1{props;constructor(J){super();this.props=J}createState(){return new Jz6}}class Jz6 extends u1{_spinner=new r3;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 Q=v1.of(J),{colors:Z,app:Y}=Q,X=y0.all(new I0(Z.foreground,1,"solid")),G=this._spinner.toBraille(),V=new J1({textAlign:"center",text:new y("",void 0,[new y(G,new g({color:Y.processing})),new y(" ",void 0),new y(this.widget.props.message,new g({color:Z.foreground}))])}),q=[new L0({child:new S1({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[V]})})];if(this.widget.props.onAbort)q.push(new j1({height:2,child:new m1({padding:I1.symmetric(2,0),child:new J1({text:new y("",new g({dim:!0}),[new y("Press ",new g({color:Z.foreground})),new y("Esc",new g({color:Z.info})),new y(" to cancel",new g({color:Z.foreground}))])})})}));let W=new m1({decoration:new K6(Z.background,X),child:new j1({width:60,height:7,child:new S1({mainAxisAlignment:"start",children:q})})});if(this.widget.props.onAbort)return new A6({debugLabel:"LoadingDialog",autofocus:!0,onKey:(H)=>{if(H.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:W});return W}}class kw extends d1{props;constructor(J){super();this.props=J}createState(){return new Qz6}}class Qz6 extends u1{scrollController=new k4;scrollAreaKey=new U3("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 dZ}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let Z=Q.size;if(typeof Z.height==="number"&&Z.height>0)return this.viewportHeight=Z.height,Z.height}return this.viewportHeight}build(J){let Q=v1.of(J),Z=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Z))return{title:Z.title,type:Z.type};if(Z instanceof Error&&Z.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Z.message};if(Z instanceof Error&&Z.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Z.message};let H=N71(Z);return{title:H.title,type:H.type,description:H.description}})(),X=Y.type==="error"?Q.app.toolError:Q.app.command,G=y0.all(new I0(Q.colors.border,1,"solid")),V=new m1({padding:I1.symmetric(1,0),child:new J1({text:new y(Y.title,new g({color:X,bold:!0}))})}),K=this.isWidgetMessage(Z)?Z.widget:new J1({text:new y(Y.description,new g({color:Q.colors.foreground})),selectable:!0}),q=new L0({child:new oX({child:new m1({padding:I1.symmetric(1,0),child:new Z0({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new L0({child:new e6({controller:this.scrollController,autofocus:!0,child:K})}),new A9({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let H=this.scrollController.maxScrollExtent,z=this.scrollController.offset,F=this.getViewportHeight(),U=H+F;return{totalContentHeight:Math.max(U,0),viewportHeight:Math.max(F,1),scrollOffset:Math.max(z,0)}}})]})})})}),W=new m1({padding:I1.symmetric(1,0),child:new J1({text:(()=>{if(this.widget.props.onRetry)return new y("",void 0,[new y("Press ",new g({color:Q.colors.foreground,dim:!0})),new y("R",new g({color:Q.app.keybind})),new y(" to retry, ",new g({color:Q.colors.foreground,dim:!0})),new y("Esc",new g({color:Q.app.keybind})),new y(" to cancel",new g({color:Q.colors.foreground,dim:!0}))]);let H=this.resolveFooterStyle(this.widget.props.message);if(H==="none")return new y("",new g({color:Q.colors.foreground,dim:!0}));if(H==="help"){let z=new g({color:Q.app.keybind}),F=new g({color:Q.colors.foreground,dim:!0});return new y("",F,[new y("Press ",F),new y("Escape",z),new y(" to close • Use ",F),new y("↑↓",z),new y(" or ",F),new y("j/k",z),new y(" to scroll",F)])}return new y("Press any key to close",new g({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new A6({onKey:(H)=>{if(this.widget.props.onRetry&&H.key==="r")return this.widget.props.onRetry(),"handled";if(H.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 m1({decoration:{border:G,color:Q.colors.background},padding:I1.all(1),child:new S1({mainAxisAlignment:"center",children:[V,new j1({height:1}),q,W]})})})}}class hf1 extends _0{build(J){let Q=v1.of(J),{colors:Z,app:Y}=Q;return new b0({child:new J1({text:new y("",void 0,[new y(`✓ Thread Shared
8550
+ `,N)])}),R];if(!q&&!F&&W.url){let S=W.url.replace(/^https?:\/\//,"");T.push(new z8({uri:W.url,text:S,style:new g({color:Z.secondary,underline:!0})}))}if(A&&!F)T.push(A);if(this.widget.deprecatedCommandPaths&&this.widget.deprecatedCommandPaths.length>0&&!q&&!F){let S=new g({color:Z.destructive});T.push(new j1({height:1}),new J1({text:new y("Custom commands have been removed. See how to migrate them to skills:",S)}),new z8({uri:"https://ampcode.com/news/slashing-custom-commands",text:"ampcode.com/news/slashing-custom-commands",style:new g({color:Z.secondary,underline:!0})}))}let C=new j1({width:50,child:new S1({crossAxisAlignment:"start",mainAxisSize:"min",children:T})});return b0.child(new Z0({mainAxisAlignment:"center",crossAxisAlignment:"center",mainAxisSize:"min",children:[new _b1({width:Rf1,height:jf1,agentMode:this.widget.agentMode,glow:this._glow,backgroundColor:Z.background,t:H,fps:0,shockwaves:this._shockwaves,onShockwave:w,...V==="disabled"&&{seed:42}}),new j1({width:2}),C]}))}}T6();O6();T6();K0();class Ef1{threadService;workers=new Map;threadsMap=new Map;mainThreadSubs=new Map;workerStatusSubs=new Map;mainThreadObservable;workerStatusObservable;emitMainThread=null;emitWorkerStatus=null;constructor(J){this.threadService=J;this.mainThreadObservable=new T1((Q)=>{return this.emitMainThread=(Z)=>Q.next(Z),()=>{this.emitMainThread=null}}),this.workerStatusObservable=new T1((Q)=>{return this.emitWorkerStatus=(Z)=>Q.next(Z),()=>{this.emitWorkerStatus=null}})}registerWorker(J){let Q=J.thread.id;if(this.workers.has(Q))this.unregisterWorker(Q);this.threadsMap.set(Q,J.thread),this.workers.set(Q,{state:"initial"});let Z=this.threadService.observePatches(Q).pipe(eA()).subscribe((X)=>{this.threadsMap.set(Q,X);let G=this.workers.get(Q)||{state:"initial"};if(this.emitMainThread)this.emitMainThread({threadID:Q,mainThread:X,workerStatus:G})});this.mainThreadSubs.set(Q,Z);let Y=J.status.subscribe((X)=>{if(this.workers.set(Q,X),this.emitWorkerStatus)this.emitWorkerStatus({threadID:Q,status:X})});this.workerStatusSubs.set(Q,Y)}unregisterWorker(J){let Q=this.mainThreadSubs.get(J);if(Q)Q.unsubscribe(),this.mainThreadSubs.delete(J);let Z=this.workerStatusSubs.get(J);if(Z)Z.unsubscribe(),this.workerStatusSubs.delete(J);this.workers.delete(J),this.threadsMap.delete(J)}observeThread(J){return{mainThread:new T1((Q)=>{return this.mainThreadObservable.subscribe((Z)=>{if(Z.threadID===J)Q.next(Z)})}),workerStatus:new T1((Q)=>{return this.workerStatusObservable.subscribe((Z)=>{if(Z.threadID===J)Q.next(Z)})})}}get threadViewStates(){let J={};for(let[Q,Z]of this.threadsMap){let Y=this.workers.get(Q);if(Y)J[Q]=LW(Z,Y)}return J}get threadTitles(){let J={};for(let[Q,Z]of this.threadsMap)J[Q]=Z.title;return J}dispose(){for(let J of this.mainThreadSubs.values())J.unsubscribe();for(let J of this.workerStatusSubs.values())J.unsubscribe();this.mainThreadSubs.clear(),this.workerStatusSubs.clear(),this.workers.clear(),this.threadsMap.clear()}}function nC8(J,Q){switch(Q.type){case"main-thread-patch":{let{thread:Z,workerStatus:Y}=Q,{items:X}=h71(Z),G=LW(Z,Y),V=sH({messages:Z.messages}),K=Array.isArray(V)?V:[];return{...J,items:X,viewState:G,todosList:K,mainThread:Z}}case"worker-status-change":{if(!J.mainThread)return J;let Z=LW(J.mainThread,Q.workerStatus);if(Z===J.viewState)return J;return{...J,viewState:Z}}default:return J}}function h71(J){let Q=[],Z=new Map,Y=new Set;for(let[X,G]of J.messages.entries()){let V=`${G.role}-${X}`;switch(G.role){case"assistant":{let K=G.state.type==="streaming";for(let W of G.content)if(W.type==="tool_use"){if(Z.set(W.id,W),K)Y.add(W.id)}if(G.content.some((W)=>W.type==="text"&&W.text.trim()||W.type==="thinking"))Q.push({type:"message",id:V,message:G});for(let W of G.content)if(W.type==="tool_use"){let H=!1;for(let z=X+1;z<J.messages.length;z++){let F=J.messages[z];if(F){for(let U of F.content)if(U.type==="tool_result"&&U.toolUseID===W.id){H=!0;break}}if(H)break}if(!H)Q.push({type:"toolResult",id:W.id,toolUse:W,toolResult:{type:"tool_result",toolUseID:W.id,run:{status:K?"in-progress":"queued"}}})}break}case"info":{if(G.content.some((q)=>q.type==="manual_bash_invocation"||q.type==="summary"&&q.summary.type==="message"))Q.push({type:"message",id:V,message:G});break}case"user":{let K=G.content.some((q)=>q.type==="text"&&q.text.trim()||q.type==="image");for(let q of G.content)if(q.type==="tool_result"){let W=Z.get(q.toolUseID)??i2(J,q.toolUseID);if(!W)throw Error(`(bug) tool use ${q.toolUseID} not found`);Q.push({type:"toolResult",id:q.toolUseID,toolUse:W,toolResult:q})}if(K)Q.push({type:"message",id:V,message:G});break}}}return{items:Q}}class If1 extends d1{props;constructor(J){super();this.props=J}createState(){return new yH6}}class yH6 extends u1{state={items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null};workerController;subscriptions=[];recentThreadIDs=[];currentWorker;constructor(){super();this.workerController=null,this.currentWorker=null}addToRecentThreads(J){this.setState(()=>{let Q=this.recentThreadIDs.indexOf(J);if(Q!==-1)this.recentThreadIDs.splice(Q,1);if(this.recentThreadIDs.unshift(J),this.recentThreadIDs.length>50)this.recentThreadIDs.pop()})}initState(){let{threadService:J,worker:Q}=this.widget.props;this.workerController=new Ef1(J),this.currentWorker=Q,this.setupSubscriptions(Q),this.addToRecentThreads(Q.thread.id)}dispose(){this.cleanup()}didUpdateWidget(J){if(J.props.threadService!==this.widget.props.threadService||J.props.worker!==this.widget.props.worker)this.cleanup(),this.setupSubscriptions(this.widget.props.worker)}setupSubscriptions(J){this.workerController.registerWorker(J);let Q=this.workerController.observeThread(J.thread.id),Z=Q.mainThread.subscribe((X)=>{this.dispatch({type:"main-thread-patch",thread:X.mainThread,workerStatus:X.workerStatus})});this.subscriptions.push(Z);let Y=Q.workerStatus.subscribe((X)=>{this.dispatch({type:"worker-status-change",workerStatus:X.status})});this.subscriptions.push(Y)}cleanup(){this.subscriptions.forEach((J)=>J.unsubscribe()),this.subscriptions=[]}switchWorker(J){this.cleanup(),this.setState(()=>{this.currentWorker=J}),this.setState(()=>{this.state={items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null}}),this.setupSubscriptions(J),this.addToRecentThreads(J.thread.id)}dispatch(J){this.setState(()=>{this.state=nC8(this.state,J)})}getThreadData(){let J=(X)=>X===t8||X===R4||X===eY||X===f2,Q=new Map;for(let X of this.state.items)if(X.type==="toolResult"&&J(X.toolUse.name))Q.set(X.toolUse.id,{toolUseId:X.toolUse.id,toolName:X.toolUse.name,toolRun:X.toolResult.run});let Z=Array.from(Q.values()),Y={};for(let{toolUseId:X,toolRun:G}of Z){let V=[],K;if(G.status==="in-progress"||G.status==="done"||G.status==="error"||G.status==="cancelled")K=G.progress;if(Array.isArray(K)){let q=0;for(let W of K)if(W.tool_uses)for(let H of W.tool_uses){let z=`${X}:progress:${q++}`,F=H.status==="done"&&H.result!==void 0?{status:"done",result:H.result}:{status:H.status},U=H.normalized_name??H.tool_name;V.push({toolUse:tA(U,H.input,z),toolRun:F})}}Y[X]=V}return{...this.state,subagentToolsByParentID:Y}}build(J){let Q=this.getThreadData();return this.widget.props.builder(J,Q,this.workerController,(Z)=>this.switchWorker(Z),()=>this.currentWorker,this.recentThreadIDs)}}class Pf1 extends d1{props;constructor(J){super({key:J.key});this.props=J}createState(){return new xH6}}class xH6 extends u1{build(J){let Z=v1.of(J).colors,{todos:Y,title:X="TODOs"}=this.widget.props;if(!Array.isArray(Y)||Y.length===0)return new j1({width:0,height:0});let G=Y.map((V)=>this.buildTodoItem(V,Z));return new m1({child:new s1({padding:I1.symmetric(1,0),child:new S1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new J1({text:new y(X,new g({bold:!0,color:Z.foreground}))}),...G]})})})}buildTodoItem(J,Q){let Z=this.getStatusIcon(J.status),Y=J.status==="completed",X=new g({bold:J.status==="in-progress",color:Q.foreground,dim:Y}),G=new g({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Q.foreground,dim:Y});return new Z0({crossAxisAlignment:"start",children:[new J1({text:new y(Z,X)}),new j1({width:1}),new L0({child:new J1({text:new y(J.content,G)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class Tf1 extends d1{ad;onDismiss;onButtonClick;onImpression;onAdInfoClick;constructor({key:J,ad:Q,onDismiss:Z,onButtonClick:Y,onImpression:X,onAdInfoClick:G}){super({key:J});this.ad=Q,this.onDismiss=Z,this.onButtonClick=Y,this.onImpression=X,this.onAdInfoClick=G}createState(){return new vH6}}class vH6 extends u1{lastTrackedAdId=null;initState(){super.initState(),this.fireImpressionIfNeeded()}didUpdateWidget(J){super.didUpdateWidget(J),this.fireImpressionIfNeeded()}fireImpressionIfNeeded(){let J=this.widget.ad;if(J.id!==this.lastTrackedAdId)this.lastTrackedAdId=J.id,this.widget.onImpression?.(J)}build(J){let Q=v1.of(J),Z=Q.colors.primary,Y=Q.colors.foreground,X=Q.colors.background,G=this.widget.ad;return new m1({decoration:new K6(X,new y0(new I0(Z,1,"rounded"),new I0(Z,1,"rounded"),void 0,new I0(Z,1,"rounded"))),child:new s1({padding:I1.horizontal(1),child:new S1({children:[new Z0({crossAxisAlignment:"start",children:[new L0({child:new J1({text:new y(G.content,new g({color:Y}))})}),new j1({width:4}),new B6({onClick:()=>this.widget.onAdInfoClick?.(),cursor:"pointer",child:new J1({text:new y("Ad",new g({color:Y,dim:!0}))})})]}),new Z0({crossAxisAlignment:"start",children:[new fm({text:G.buttonLabel,onPressed:()=>this.widget.onButtonClick?.(),padding:I1.horizontal(1),color:Z,reverse:!0}),new j1({width:2}),new J1({text:new y(G.destinationUrlHostname,new g({color:Y,dim:!0}))})]})]})})})}}class Cf1 extends d1{props;constructor(J){super({key:J.key});this.props=J}createState(){return new bH6(this.props.autofocus??!0)}}class bH6 extends u1{autofocus;constructor(J){super();this.autofocus=J}build(J){let Z=B0.of(J).colorScheme,Y=(W)=>{if(W.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(W.ctrlKey&&W.key==="c"||W.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},X=d0.sizeOf(J),G=Math.min(60,X.width-4),V=X.height-4,K=[];if(this.widget.props.title)K.push(new J1({text:new y(this.widget.props.title,new g({bold:!0,color:Z.primary}))}),new j1({height:1}));if(this.widget.props.message)K.push(new J1({text:new y(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)K.push(new j1({height:1}));let q=[];if(this.widget.props.showCopyOption)q.push(new J1({text:new y("Enter to copy",new g({dim:!0}))}));return q.push(new J1({text:new y("Escape to close",new g({dim:!0}))})),K.push(new Z0({children:q.flatMap((W,H)=>H<q.length-1?[W,new j1({width:1}),new J1({text:new y("•",new g({dim:!0}))}),new j1({width:1})]:[W]),mainAxisSize:"min"})),new b0({child:new m1({constraints:new D0(G,G,0,V),decoration:new K6(Z.background,new y0(new I0(Z.primary,1,"rounded"),new I0(Z.primary,1,"rounded"),new I0(Z.primary,1,"rounded"),new I0(Z.primary,1,"rounded"))),padding:new I1(2,2,2,2),child:new A6({autofocus:this.autofocus,onKey:Y,child:new S1({children:K,mainAxisSize:"min"})})})})}}class _f1 extends d1{props;constructor(J){super({key:J.key});this.props=J}createState(){return new fH6(this.props.autofocus??!0)}}class fH6 extends u1{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=B0.of(J).colorScheme,Z=(K)=>{if(K.key==="Enter"||K.key==="Escape"||K.ctrlKey&&K.key==="c")return this.widget.props.onClose(),"handled";return"ignored"},Y=d0.sizeOf(J),X=Math.min(60,Y.width-4),G=Y.height-4,V=[];if(V.push(new J1({text:new y("Ads make Amp Free possible",new g({bold:!0}))})),this.widget.props.provider)V.push(new j1({height:1}),new J1({text:new y(`Ad source: ${this.widget.props.provider}`,new g({dim:!0}))}));return V.push(new j1({height:1}),new J1({text:new y("Escape to close",new g({dim:!0}))})),new b0({child:new m1({constraints:new D0(X,X,0,G),decoration:new K6(Q.background,new y0(new I0(Q.primary,1,"rounded"),new I0(Q.primary,1,"rounded"),new I0(Q.primary,1,"rounded"),new I0(Q.primary,1,"rounded"))),padding:new I1(2,2,2,2),child:new A6({autofocus:this.autofocus,onKey:Z,child:new S1({children:V,mainAxisSize:"min"})})})})}}class Sf1 extends d1{questions;onSubmit;onCancel;constructor({key:J,questions:Q,onSubmit:Z,onCancel:Y}){super(J?{key:J}:{});this.questions=Q,this.onSubmit=Z,this.onCancel=Y}createState(){return new mH6}}var hH6=8;class mH6 extends u1{focusNode=new n6({debugLabel:"AskWidget"});currentQuestionIndex=0;focusedOptionIndex=new Map;selectedOptions=new Map;otherInputActive=new Map;otherInputValues=new Map;otherTextController=new D3;scrollController=new k4;viewportHeight=hH6;initState(){super.initState(),this.focusNode.addKeyHandler(this.handleKeyEvent.bind(this));for(let J=0;J<this.widget.questions.length;J++)this.focusedOptionIndex.set(J,0),this.selectedOptions.set(J,new Set),this.otherInputActive.set(J,!1),this.otherInputValues.set(J,"");this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0),this.scrollToIndex(0)}dispose(){this.focusNode.dispose(),this.otherTextController.dispose(),this.scrollController.dispose(),super.dispose()}get currentQuestion(){return this.widget.questions[this.currentQuestionIndex]}get currentSelections(){return this.selectedOptions.get(this.currentQuestionIndex)??new Set}get currentFocusedIndex(){return this.focusedOptionIndex.get(this.currentQuestionIndex)??0}set currentFocusedIndex(J){this.focusedOptionIndex.set(this.currentQuestionIndex,J)}get isOtherActive(){return this.otherInputActive.get(this.currentQuestionIndex)??!1}handleKeyEvent(J){if(this.isOtherActive)return this.handleOtherInputKeyEvent(J);let Q=(Y,X)=>{return J.key===Y&&J.ctrlKey===(X?.ctrl??!1)&&J.shiftKey===(X?.shift??!1)};if(Q("ArrowDown")||Q("j"))return this.moveSelection(1),"handled";if(Q("ArrowUp")||Q("k"))return this.moveSelection(-1),"handled";if(Q("ArrowRight")||Q("Tab")||Q("l"))return this.nextQuestion(),"handled";if(Q("ArrowLeft")||Q("Tab",{shift:!0})||Q("h"))return this.prevQuestion(),"handled";if(Q(" "))return this.toggleCurrentSelection(),"handled";if(Q("Enter")){if(this.isOnOtherOption()&&!this.otherInputValues.get(this.currentQuestionIndex))this.activateOtherInput();else this.submitAnswers();return"handled"}if(Q("Escape"))return this.widget.onCancel(),"handled";if(Q("o"))return this.activateOtherInput(),"handled";let Z=parseInt(J.key,10);if(!isNaN(Z)&&Z>=1&&Z<=this.currentQuestion.options.length+1)return this.selectOption(Z-1),"handled";return"ignored"}handleOtherInputKeyEvent(J){if(J.key==="Escape")return this.setState(()=>{this.otherInputActive.set(this.currentQuestionIndex,!1)}),"handled";return"ignored"}moveSelection(J){let Q=this.currentQuestion.options.length+1,Z=this.currentFocusedIndex+J;if(Z<0)Z=Q-1;if(Z>=Q)Z=0;this.setState(()=>{if(this.currentFocusedIndex=Z,!this.currentQuestion.multiSelect)this.currentSelections.clear(),this.currentSelections.add(Z);this.scrollToIndex(Z)})}scrollToIndex(J){let Z=J*2,Y=Z+2,X=this.scrollController.offset;if(Z<X)this.scrollController.jumpTo(Z);else if(Y>X+this.viewportHeight)this.scrollController.jumpTo(Y-this.viewportHeight)}toggleCurrentSelection(){let J=this.currentFocusedIndex;this.setState(()=>{if(this.currentQuestion.multiSelect)if(this.currentSelections.has(J))this.currentSelections.delete(J);else this.currentSelections.add(J)})}selectOption(J){this.setState(()=>{if(this.currentFocusedIndex=J,this.currentQuestion.multiSelect)if(this.currentSelections.has(J))this.currentSelections.delete(J);else this.currentSelections.add(J);else this.currentSelections.clear(),this.currentSelections.add(J)})}isOnOtherOption(){return this.currentFocusedIndex===this.currentQuestion.options.length}activateOtherInput(){this.setState(()=>{this.otherInputActive.set(this.currentQuestionIndex,!0),this.otherTextController.text=this.otherInputValues.get(this.currentQuestionIndex)??""})}nextQuestion(){if(this.currentQuestionIndex<this.widget.questions.length-1)this.setState(()=>{this.currentQuestionIndex++;let J=this.currentSelections,Q=J.size>0?Math.max(...Array.from(J)):0;this.scrollToIndex(Q)})}prevQuestion(){if(this.currentQuestionIndex>0)this.setState(()=>{this.currentQuestionIndex--;let J=this.currentSelections,Q=J.size>0?Math.max(...Array.from(J)):0;this.scrollToIndex(Q)})}submitAnswers(){for(let Q=0;Q<this.widget.questions.length;Q++){let Z=this.selectedOptions.get(Q)??new Set,Y=this.otherInputValues.get(Q);if(Z.size===0&&!Y){this.setState(()=>{this.currentQuestionIndex=Q,this.scrollToIndex(this.currentFocusedIndex)});return}}let J={};for(let Q=0;Q<this.widget.questions.length;Q++){let Z=this.widget.questions[Q],Y=this.selectedOptions.get(Q)??new Set,X=[];for(let G of Y)if(G<Z.options.length)X.push(Z.options[G].label);else{let V=this.otherInputValues.get(Q)??"";if(V)X.push(V)}J[Z.question]=X.join(", ")||"No selection"}this.widget.onSubmit(J)}build(J){let Z=B0.of(J).colorScheme,Y=v1.of(J),X=[this.buildHeader(Z)];if(this.widget.questions.length>1)X.push(this.buildQuestionTabs(Z));let G=new S1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:X}),V=this.buildQuestionContent(Z),K=this.isOtherActive?V:new m1({constraints:new D0({maxHeight:hH6}),child:new Z0({crossAxisAlignment:"stretch",children:[new L0({child:new e6({controller:this.scrollController,autofocus:!1,child:V})}),new A9({controller:this.scrollController,thumbColor:Y.app.scrollbarThumb,trackColor:Y.app.scrollbarTrack,getScrollInfo:()=>{let W=this.scrollController.maxScrollExtent,H=this.scrollController.offset,z=W+this.viewportHeight;return{totalContentHeight:Math.max(z,0),viewportHeight:Math.max(this.viewportHeight,1),scrollOffset:Math.max(H,0)}}})]})}),q=new S1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[G,K,this.buildFooter(Z)]});return new A6({focusNode:this.focusNode,autofocus:!0,child:new m1({decoration:new K6(Z.background,y0.all(new I0(Z.primary,1,"rounded"))),child:new s1({padding:I1.symmetric(1,0),child:q})})})}buildHeader(J){let Q=this.currentQuestion,Z=[new y("? ",new g({color:J.primary,bold:!0})),new y(Q.question,new g({color:J.foreground,bold:!0}))];if(Q.multiSelect)Z.push(new y(" (multi-select)",new g({color:J.secondary})));return new J1({text:new y("",void 0,Z)})}buildQuestionTabs(J){let Q=[];for(let Z=0;Z<this.widget.questions.length;Z++){let Y=this.widget.questions[Z],X=Z===this.currentQuestionIndex,G=Y.header.length>12?Y.header.slice(0,11)+"…":Y.header,V=X?new g({color:J.primary,bold:!0}):new g({color:J.secondary}),K=X?"▸ ":" ";if(Q.push(new J1({text:new y(K+G,V)})),Z<this.widget.questions.length-1)Q.push(new j1({width:2}))}return new Z0({mainAxisAlignment:"start",children:Q})}buildQuestionContent(J){let Q=this.currentQuestion,Z=this.currentSelections,Y=this.currentFocusedIndex;if(this.isOtherActive)return this.buildOtherInput(J);let X=[];for(let q=0;q<Q.options.length;q++){let W=Q.options[q],H=Z.has(q),z=Y===q;X.push(this.buildOption(q,W.label,W.description,H,z,J))}let G=this.otherInputValues.get(this.currentQuestionIndex)??"",V=Z.has(Q.options.length),K=Y===Q.options.length;return X.push(this.buildOption(Q.options.length,G?`Other: ${G}`:"Other...","Provide a custom answer",V,K,J)),new S1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:X})}buildOption(J,Q,Z,Y,X,G){let K=this.currentQuestion.multiSelect?Y?"[x]":"[ ]":Y?"●":"○",q=Y?G.primary:G.secondary,W=X?G.primary:G.foreground,H=X?"▸":" ",z=J<9?`${J+1}`:"";return new s1({padding:I1.symmetric(0,0),child:new Z0({crossAxisAlignment:"start",children:[new J1({text:new y(H,new g({color:G.primary}))}),new J1({text:new y(K,new g({color:q}))}),new j1({width:1}),new L0({child:new S1({crossAxisAlignment:"start",mainAxisSize:"min",children:[new J1({text:new y("",void 0,[new y(Q,new g({color:W,bold:X})),z?new y(` [${z}]`,new g({color:G.secondary,dim:!0})):new y("")])}),new J1({text:new y(Z,new g({color:G.secondary,dim:!0}))})]})})]})})}confirmOtherInput(){let J=this.otherTextController.text;this.otherInputValues.set(this.currentQuestionIndex,J),this.otherInputActive.set(this.currentQuestionIndex,!1);let Q=this.currentSelections;Q.clear(),Q.add(this.currentQuestion.options.length),this.submitAnswers()}buildOtherInput(J){return new S1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new J1({text:new y("Enter your custom answer:",new g({color:J.foreground,bold:!0}))}),new j1({height:1}),new Z0({crossAxisAlignment:"center",children:[new J1({text:new y("▸ ",new g({color:J.primary}))}),new L0({child:new kZ({controller:this.otherTextController,autofocus:!0,placeholder:"Type your answer...",onSubmitted:()=>this.confirmOtherInput()})})]}),new j1({height:1}),new J1({text:new y("Press Enter to confirm, Esc to go back",new g({color:J.secondary,dim:!0}))})]})}buildFooter(J){let Q=[];if(this.isOtherActive)Q.push("Enter to confirm","Esc to cancel");else{if(Q.push("↑↓ navigate"),this.currentQuestion.multiSelect)Q.push("Space select");if(this.widget.questions.length>1)Q.push("←→ questions");Q.push("Enter submit","Esc cancel")}return new J1({text:new y(Q.join(" • "),new g({color:J.secondary,dim:!0}))})}}b1();import{execSync as z_8}from"node:child_process";GR();V2();r9();J3();nB();rG();XQ();r2();YX();KQ();T6();Wh();QS();K0();var Lz6=U0(vq(),1);import{writeFile as Uz6}from"fs/promises";import Dz6 from"path";b1();XQ();class kf1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;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(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1769719558-g98dc3a"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Fr(Q,this.configService)}catch(Q){E.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class GD extends d1{props;constructor(J){super();this.props=J}createState(){return new gH6}}class gH6 extends u1{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Z)=>{this.setState(()=>{this._state=Z(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class uH6 extends u1{controller=new D3;focusNode=new n6({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 Q=v1.of(J),{colors:Z,app:Y}=Q,X=this.widget.props.isRequiredArg??!0,G=this.controller.text.trim().length>0,V=!X||G,K=y0.all(new I0(Z.foreground,1,"solid")),q=new kZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(U)=>{let D=U.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Z.foreground,border:null},maxLines:1}),W=new Z0({children:[new m1({decoration:{color:Z.background},child:new J1({text:new y(">",new g({color:Z.foreground}))})}),new L0({child:q})]}),H=new m1({padding:I1.symmetric(1,0),child:new J1({text:new y("",void 0,[new y("Command: ",new g({color:Z.foreground})),new y(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),z=[];if(V)z.push(new y("Enter",new g({color:Y.keybind}))),z.push(new y(" to submit, ",new g({color:Z.foreground,dim:!0})));z.push(new y("Esc",new g({color:Y.keybind}))),z.push(new y(" to cancel",new g({color:Z.foreground,dim:!0})));let F=new m1({padding:I1.symmetric(1,0),child:new J1({text:new y("",void 0,z)})});return new m1({decoration:{border:K,color:Z.background},padding:I1.all(1),child:new S1({children:[H,new j1({height:1}),W,new j8,F]})})}}class m71 extends d1{props;constructor(J){super();this.props=J}createState(){return new uH6}}import{isDeepStrictEqual as sC8}from"node:util";var aC8=/[\\/_ +.#"@[({&]/,oC8=/[\\/_ +.#"@[({&]/g,rC8=/[\s-]/,pH6=/[\s-]/g;function u71(J,Q,Z,Y,X,G,V){if(G===Q.length){if(X===J.length)return 1;return 0.99}let K=`${X},${G}`;if(V[K]!==void 0)return V[K];let q=Y.charAt(G),W=Z.indexOf(q,X),H=0,z,F,U,D;while(W>=0){if(z=u71(J,Q,Z,Y,W+1,G+1,V),z>H){if(W===X)z*=1;else if(rC8.test(J.charAt(W-1))){if(z*=0.9,D=J.slice(X,W-1).match(pH6),D&&X>0)z*=0.999**D.length}else if(aC8.test(J.charAt(W-1))){if(z*=0.8,U=J.slice(X,W-1).match(oC8),U&&X>0)z*=0.999**U.length}else if(z*=0.3,X>0)z*=0.999**(W-X);if(J.charAt(W)!==Q.charAt(G))z*=0.9999}if(z<0.1&&(Z.charAt(W-1)===Y.charAt(G+1)||Y.charAt(G+1)===Y.charAt(G)&&Z.charAt(W-1)!==Y.charAt(G))){if(F=u71(J,Q,Z,Y,W+1,G+2,V),F*0.1>z)z=F*0.1}if(z>H)H=z;W=Z.indexOf(q,W+1)}return V[K]=H,H}function g71(J){return J.toLowerCase().replace(pH6," ")}function dH6(J,Q){let Z=u71(J,Q,g71(J),g71(Q),0,0,{}),Y=Q.trim().split(/\s+/);if(Y.length>1){let X=0,G=0;for(let K of Y){let q=u71(J,K,g71(J),g71(K),0,0,{});if(q===0)return Z;X+=q,G+=K.length}let V=X/Y.length*0.95;return Math.max(Z,V)}return Z}class jT{}class ET{}class p71{}class d71{}class cH6 extends d1{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new lH6}}class lH6 extends u1{build(J){return this.widget.onContext(J),this.widget.child}}function tC8(J,Q){if(J==="")return{matches:!0,score:1};let Z=dH6(Q,J);return{matches:Z>0.15,score:Z}}class R7 extends d1{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new iH6}}class iH6 extends u1{controller=new D3;focusNode;scrollController=new k4;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new n6({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let Q=this.cachedFiltered;this.widget.props.onSelectionChange?.(Q[0]??null)}),this.recomputeFilteredItems();let J=this.cachedFiltered;this.widget.props.onSelectionChange?.(J[0]??null),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!sC8(J.props.items,this.widget.props.items)){this.recomputeFilteredItems(),this.ensureSelectedItemVisible();let Q=this.cachedFiltered;this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)}}dispose(){this.widget.props.onSelectionChange?.(null),this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof jT){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof ET){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof p71){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length){let Z=Q[this.selectedIndex];if(Z){if(!(this.widget.props.isItemDisabled?.(Z)??!1))this.widget.props.onAccept(Z,{hasUserInteracted:this.hasUserInteracted})}}return"handled"}if(J instanceof d71)return this.widget.props.onDismiss?.(),"handled";return"ignored"};recomputeFilteredItems(){let J=this.controller.text,Q=this.widget.props.items,Z=this.widget.props.normalizeQuery?.(J)??J,Y=Q.filter((X)=>!this.widget.props.filterItem||this.widget.props.filterItem(X,J)).map((X)=>({item:X,...tC8(Z,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,G)=>this.widget.props.sortItems(X,G,J):(X,G)=>G.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Q,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.controller.text,Q=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Q)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Z=0,Y=Q.size.height;UP(J,{top:Z,bottom:Y},{padding:1})}handleScroll=(J)=>{let Q=this.getFilteredItems();if(Q.length===0)return;if(J.direction==="down")if(this.selectedIndex<Q.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return;this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)};handleItemClick=(J,Q)=>{let Z=this.getFilteredItems();if(J>=0&&J<Z.length){let Y=Z[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Q===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Z[this.selectedIndex]??null);else if(Q===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Q=v1.of(J),{colors:Z}=Q,Y=this.getFilteredItems(),X=y0.all(new I0(Z.foreground,1,"solid")),G=this.widget.props.enabled??!0,V=new kZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:G,style:{backgroundColor:Z.background,textColor:Z.foreground,cursorColor:Z.cursor,placeholderColor:Z.mutedForeground,border:null},maxLines:1}),K=new d7({shortcuts:new Map([[new v0("ArrowDown"),new jT],[new v0("ArrowUp"),new ET],[new v0("Tab"),new jT],[new v0("Tab",{shift:!0}),new ET],[new v0("n",{ctrl:!0}),new jT],[new v0("p",{ctrl:!0}),new ET],[new v0("Enter"),new p71],[new v0("Escape"),new d71]]),focusNode:this.focusNode,child:V}),q=new N5({actions:new Map([[jT,new M6(this.invoke)],[ET,new M6(this.invoke)],[p71,new M6(this.invoke)],[d71,new M6(this.invoke)]]),child:K}),W=new Z0({children:[new m1({decoration:{color:Z.background},child:new J1({text:new y(">",new g({color:Z.foreground}))})}),new L0({child:q})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let B=this.widget.props.loadingText??"Loading...";H=new j1({height:10,child:new b0({child:new J1({text:new y(B,new g({color:Z.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)H=new L0({child:new b0({child:new J1({text:new y(this.widget.props.emptyStateText,new g({color:Z.foreground,dim:!0}))})})});else{let B=Y.map((N,M)=>{let L=M===this.selectedIndex,w=this.widget.props.isItemDisabled?.(N)??!1,O;if(this.widget.props.renderItem)O=this.widget.props.renderItem(N,L,w,J);else{let A=L?Q.app.selectionBackground:void 0,R=L?Q.app.selectionForeground:Z.foreground;O=new m1({decoration:A?{color:A}:void 0,padding:I1.symmetric(2,0),child:new J1({text:new y(this.widget.props.getLabel(N),new g({color:R,dim:w}))})})}return new cH6(new B6({onClick:(A)=>this.handleItemClick(M,A.clickCount),child:O}),(A)=>{this.itemContexts[M]=A})});H=new S1({children:B,crossAxisAlignment:"start"})}let z=new B6({onScroll:this.handleScroll,opaque:!1,child:new e6({controller:this.scrollController,autofocus:!1,child:H})}),F=[];if(this.widget.props.title){let B=new m1({padding:I1.symmetric(1,0),child:new J1({text:new y(this.widget.props.title,new g({color:Q.app.command,bold:!0}))})});F.push(B)}if(F.push(W,new j1({height:1})),this.controller.text!==""){let B=Y.length>0?Y[this.selectedIndex]:void 0,N=B&&this.widget.props.buildDisabledReasonWidget?.(B,J);F.push(new L0({child:new S1({mainAxisAlignment:"spaceBetween",children:[new L0({child:z}),new m1({padding:I1.only({top:1}),child:new b0({child:N??new j1({height:1})})})]})}))}else F.push(new L0({child:z}));if(this.widget.props.footer)F.push(this.widget.props.footer);return new m1({decoration:{border:X,color:Z.background},padding:I1.symmetric(1,0),child:new S1({children:F})})}}function nH6(J){let Z=new Date().getTime()-J.getTime(),Y=Math.floor(Z/60000),X=Math.floor(Z/3600000),G=Math.floor(Z/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class yf1 extends _0{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Z=Math.max(0,...Q.map((X)=>nH6(X.pubDate).length));return new R7({items:Q,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,G,V,K)=>{let q=v1.of(K),{colors:W}=q,H=q.app,z=G?H.selectionBackground:void 0,F=G?H.selectionForeground:W.foreground,U=W.mutedForeground,D=(B,N)=>new j1({width:N,child:Z0.end([new J1({text:new y(B,new g({color:U}))})])});return new m1({decoration:z?{color:z}:void 0,padding:I1.symmetric(2,0),child:new Z0({children:[new L0({child:new J1({text:new y(X.title,new g({color:F})),overflow:"ellipsis",maxLines:1})}),new j1({width:2}),D(nH6(X.pubDate),Z)]})})}})}}T6();class xf1 extends d1{createState(){return new aH6}}class aH6 extends u1{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 Z=v1.of(J).colors;return new J1({text:new y("●",new g({color:this.isGreen?Z.success:Z.mutedForeground,bold:!0})),maxLines:1})}}var eC8=/\/threads\/(T-[^/?#\s<>]+)/i;function J_8(J){let Q=J.trim(),Y=Q.match(eC8)?.[1];if(Y&&D9(Y))return Y;let X=Q.replace(/^[<("'`]+|[>")'`,.]+$/g,"");if(D9(X))return X;return null}function Q_8(J){let Q=new Map,Z=new Map,Y=new Map,X=[];for(let V of J)Q.set(V.id,V);for(let V of J){let K=V.parentRelationships.find((q)=>q.role==="child"&&Q.has(q.threadID)&&(q.type==="fork"||q.type==="handoff"));if(K){Y.set(V.id,K.type);let q=K.threadID,W=Z.get(q)||[];W.push(V),Z.set(q,W)}else X.push(V)}return M71.flatten(X,(V)=>Z.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function vf1(J,Q,Z){return new J1({text:new y(`${J}${Q}`,new g({color:Z})),maxLines:1})}function Z_8(J,Q,Z,Y){return[vf1("+",J,Y.success),j8.horizontal(1),vf1("~",Q,Y.warning),j8.horizontal(1),vf1("-",Z,Y.destructive)]}class c71 extends _0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((D)=>D.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((D)=>D.id!==this.props.currentThreadID);let Z=this.props.recentThreadIDs||[],Y=new Set(Z),X=this.props.currentThreadID,G=[...Q].sort((D,B)=>{if(X){if(D.id===X)return-1;if(B.id===X)return 1}let N=Z.indexOf(D.id),M=Z.indexOf(B.id);if(N!==-1&&M!==-1)return N-M;if(N!==-1)return-1;if(M!==-1)return 1;return 0}),V=Q_8(G),K=Math.max(0,...V.map((D)=>D.description.timeAgo.length)),q=v1.of(J),W=new s1({padding:I1.symmetric(0,1),child:new b0({child:new J1({text:new y("",new g({color:q.colors.foreground,dim:!0}),[new y("Ctrl+T",new g({color:q.colors.primary,dim:!0})),new y(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:q.colors.foreground,dim:!0}))])})})}),H="",z=null,F=(D)=>{if(D!==H)H=D,z=J_8(D);return z};return new R7({items:V,getLabel:(D)=>`${D.title} ${D.id}`,filterItem:(D,B)=>{let N=F(B);if(N)return D.id.toLowerCase()===N.toLowerCase();return!0},normalizeQuery:(D)=>F(D)?"":D,onAccept:(D,B)=>this.props.onSelect?.(D.id,B),onDismiss:this.props.onDismiss,onSelectionChange:(D)=>{if(this.props.previewController){if(D)this.props.previewController.select(D.id)}},title:this.props.title,isLoading:this.props.isLoading,loadingText:"Loading threads...",emptyStateText:"No threads match your filter",maxRenderItems:200,footer:this.props.isLoading?void 0:W,renderItem:(D,B,N,M)=>{let L=v1.of(M),{app:w,colors:O}=L,A=B?w.selectionBackground:void 0,R=B?w.selectionForeground:O.foreground,j=O.mutedForeground,T=(c,h)=>new j1({width:h,child:Z0.end([new J1({text:new y(c,new g({color:j}))})])}),C=this.props.threadViewStates[D.id],S=[],b=D.relationshipType==="handoff",u=new Hu({connectorColor:O.mutedForeground});if(D.depth>0){let c=[],h=D.ancestorsAreLast.slice(1);for(let o of h)c.push(new y(u.getAncestorPrefix(o),new g({color:u.connectorColor,dim:u.connectorDim})));let i=D.isLast?u.elbow:u.tee,p=u.getConnectorText(i);c.push(new y(p,new g({color:u.connectorColor,dim:u.connectorDim}))),S.push(new J1({text:new y("",void 0,c)}))}let m=[],k=X===D.id?new y("(current) ",new g({color:O.success})):Y.has(D.id)?new y("(visited) ",new g({color:O.foreground,dim:!0})):null;if(k)m.push(new J1({text:k}));if(XL(C))m.push(new xf1),m.push(new j1({width:1}));let v=D.title;if(D.relationshipType==="fork"){let c=v.match(/^Forked\((\d+)\): /);if(c)v=v.slice(c[0].length);else while(v.startsWith("Forked: "))v=v.slice(8);m.push(new J1({text:new y("[fork] ",new g({color:O.primary}))}))}else if(b)m.push(new J1({text:new y("[handoff] ",new g({color:O.accent}))}));if(m.push(new L0({child:new J1({text:new y(v,new g({color:R})),overflow:"ellipsis",maxLines:1})})),m.push(new j1({width:2})),D.diffStats&&(D.diffStats.added>0||D.diffStats.changed>0||D.diffStats.deleted>0)){let c=B?{success:j,warning:j,destructive:j}:O;m.push(...Z_8(D.diffStats.added,D.diffStats.changed,D.diffStats.deleted,c)),m.push(new j1({width:2}))}return m.push(T(D.description.timeAgo,K)),new m1({decoration:A?{color:A}:void 0,padding:I1.symmetric(2,0),child:new Z0({children:[...S,...m]})})}})}}class rH6 extends d1{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new sH6}}class sH6 extends u1{build(J){return this.widget.onContext(J),this.widget.child}}var oH6=30,$_8=30;class IT{}class PT{}class l71{}class i71{}class bf1 extends d1{props;constructor(J){super();this.props=J}createState(){return new tH6}}class tH6 extends u1{highlightedIndex=0;controller=new D3;focusNode;scrollController=new k4;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new n6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),Y4.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 Q=J.findRenderObject();if(!Q)return;let Z=0,Y=Q.size.height;UP(J,{top:Z,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Q}=this.widget.props;if(!J)this.filteredClusters=[...Q];else this.filteredClusters=Q.filter((Z)=>Z.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof IT){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof PT){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof l71){let Q=this.filteredClusters[this.highlightedIndex];if(Q)this.widget.props.onAccept(Q);return"handled"}if(J instanceof i71)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Q)=>{if(J>=0&&J<this.filteredClusters.length){if(Q===1)this.highlightedIndex=J,this.setState();else if(Q===2){let Z=this.filteredClusters[J];if(Z)this.widget.props.onAccept(Z)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return;else if(this.highlightedIndex>0)this.highlightedIndex--;else return;this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})};build(J){let{currentThreadID:Q}=this.widget.props,Z=v1.of(J),{colors:Y,app:X}=Z,K=d0.of(J).size.width>=$_8+oH6,q=y0.all(new I0(Y.foreground,1,"solid")),W=this.filteredClusters[this.highlightedIndex]??null,H=new m1({padding:I1.symmetric(1,0),child:new J1({text:new y("Select a cluster",new g({color:X.command,bold:!0}))})}),z=new kZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),F=new d7({shortcuts:new Map([[new v0("ArrowDown"),new IT],[new v0("ArrowUp"),new PT],[new v0("Tab"),new IT],[new v0("Tab",{shift:!0}),new PT],[new v0("n",{ctrl:!0}),new IT],[new v0("p",{ctrl:!0}),new PT],[new v0("Enter"),new l71],[new v0("Escape"),new i71]]),focusNode:this.focusNode,child:z}),U=new N5({actions:new Map([[IT,new M6(this.invoke)],[PT,new M6(this.invoke)],[l71,new M6(this.invoke)],[i71,new M6(this.invoke)]]),child:F}),D=new Z0({children:[new m1({decoration:{color:Y.background},child:new J1({text:new y(">",new g({color:Y.foreground}))})}),new L0({child:U})]});this.itemContexts=[];let B=this.filteredClusters.map((A,R)=>{let j=R===this.highlightedIndex,T=Q?A.threads.some((u)=>u.id===Q):!1,C=j?X.selectionBackground:void 0,S=j?X.selectionForeground:Y.foreground,b=[new y(A.label,new g({color:S})),new y(` (${A.threads.length})`,new g({color:S,dim:!0}))];if(T)b.push(new y(" (current)",new g({color:j?X.selectionForeground:Y.success})));return new rH6(new B6({onClick:(u)=>this.handleItemClick(R,u.clickCount),child:new m1({decoration:C?{color:C}:void 0,padding:I1.symmetric(2,0),child:new J1({text:new y("",void 0,b)})})}),(u)=>{this.itemContexts[R]=u})}),N=new S1({children:B,crossAxisAlignment:"start"}),M=new L0({child:new B6({onScroll:this.handleScroll,child:new e6({controller:this.scrollController,autofocus:!1,child:N})})}),L=W?W.threads.map((A)=>({id:A.id,title:A.title,parentID:A.parentID,updatedAt:A.updatedAt})):[],w=W?new m1({padding:I1.all(1),child:new Sw({threads:L,autofocus:!1,offsetY:2})}):null,O;if(K){let A=w?new L0({child:w}):new j1({width:oH6});O=new Z0({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[M,A]})}else{let A=[new L0({child:new B6({onScroll:this.handleScroll,child:new e6({controller:this.scrollController,autofocus:!1,child:N})})})];if(w)A.push(new L0({child:w}));O=new S1({crossAxisAlignment:"stretch",children:A})}return new m1({decoration:{border:q,color:Y.background},padding:I1.symmetric(1,0),child:new S1({children:[H,D,new j1({height:1}),new L0({child:O})]})})}}b1();class eH6 extends u1{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){E.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){E.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Q=J.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))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((Q)=>!J.includes(Q.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Q=J.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let Z=this.widget.props.currentLabels||[],Y=this.labels.some((G)=>G.name===Q),X=Z.includes(Q);return!Y&&!X}build(J){let Q=v1.of(J),{app:Z,colors:Y}=Q,X=this.currentQuery.trim().toLowerCase(),G=X.length>0?this.getValidationError(X):null,V=this.getAvailableLabels(),q=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...V];return new R7({title:"Add Label",items:q,getLabel:(W)=>{if("__isCreateMarker"in W)return this.currentQuery.trim().toLowerCase();return W.name},onAccept:(W)=>{if("__isCreateMarker"in W)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(W.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:G||"Type to create a new label",renderItem:(W,H,z,F)=>{let U=H?Z.selectionBackground:void 0,D=H?Z.selectionForeground:Y.foreground;if("__isCreateMarker"in W&&W.__isCreateMarker){let N=this.currentQuery.trim().toLowerCase();return new m1({decoration:U?{color:U}:void 0,padding:I1.symmetric(2,0),child:new J1({text:new y("",void 0,[new y("Create new label: ",new g({color:D})),new y(N,new g({color:D,bold:!0}))])})})}return new m1({decoration:U?{color:U}:void 0,padding:I1.symmetric(2,0),child:new J1({text:new y(W.name,new g({color:D}))})})},filterItem:(W,H)=>{if(this.currentQuery!==H)this.currentQuery=H,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in W&&W.__isCreateMarker)return this.shouldShowCreateMarker(H);let F=H.trim().toLowerCase();return F.length===0||W.name.includes(F)},sortItems:(W,H,z)=>{let F="__isCreateMarker"in W.item&&W.item.__isCreateMarker,U="__isCreateMarker"in H.item&&H.item.__isCreateMarker;if(F&&!U)return-1;if(!F&&U)return 1;return H.score-W.score}})}}class ff1 extends d1{props;constructor(J){super();this.props=J}createState(){return new eH6}}class VD extends d1{props;constructor(J){super();this.props=J}createState(){return new Jz6}}class Jz6 extends u1{_spinner=new r3;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 Q=v1.of(J),{colors:Z,app:Y}=Q,X=y0.all(new I0(Z.foreground,1,"solid")),G=this._spinner.toBraille(),V=new J1({textAlign:"center",text:new y("",void 0,[new y(G,new g({color:Y.processing})),new y(" ",void 0),new y(this.widget.props.message,new g({color:Z.foreground}))])}),q=[new L0({child:new S1({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[V]})})];if(this.widget.props.onAbort)q.push(new j1({height:2,child:new m1({padding:I1.symmetric(2,0),child:new J1({text:new y("",new g({dim:!0}),[new y("Press ",new g({color:Z.foreground})),new y("Esc",new g({color:Z.info})),new y(" to cancel",new g({color:Z.foreground}))])})})}));let W=new m1({decoration:new K6(Z.background,X),child:new j1({width:60,height:7,child:new S1({mainAxisAlignment:"start",children:q})})});if(this.widget.props.onAbort)return new A6({debugLabel:"LoadingDialog",autofocus:!0,onKey:(H)=>{if(H.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:W});return W}}class kw extends d1{props;constructor(J){super();this.props=J}createState(){return new Qz6}}class Qz6 extends u1{scrollController=new k4;scrollAreaKey=new U3("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 dZ}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let Z=Q.size;if(typeof Z.height==="number"&&Z.height>0)return this.viewportHeight=Z.height,Z.height}return this.viewportHeight}build(J){let Q=v1.of(J),Z=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Z))return{title:Z.title,type:Z.type};if(Z instanceof Error&&Z.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Z.message};if(Z instanceof Error&&Z.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Z.message};let H=N71(Z);return{title:H.title,type:H.type,description:H.description}})(),X=Y.type==="error"?Q.app.toolError:Q.app.command,G=y0.all(new I0(Q.colors.border,1,"solid")),V=new m1({padding:I1.symmetric(1,0),child:new J1({text:new y(Y.title,new g({color:X,bold:!0}))})}),K=this.isWidgetMessage(Z)?Z.widget:new J1({text:new y(Y.description,new g({color:Q.colors.foreground})),selectable:!0}),q=new L0({child:new oX({child:new m1({padding:I1.symmetric(1,0),child:new Z0({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new L0({child:new e6({controller:this.scrollController,autofocus:!0,child:K})}),new A9({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let H=this.scrollController.maxScrollExtent,z=this.scrollController.offset,F=this.getViewportHeight(),U=H+F;return{totalContentHeight:Math.max(U,0),viewportHeight:Math.max(F,1),scrollOffset:Math.max(z,0)}}})]})})})}),W=new m1({padding:I1.symmetric(1,0),child:new J1({text:(()=>{if(this.widget.props.onRetry)return new y("",void 0,[new y("Press ",new g({color:Q.colors.foreground,dim:!0})),new y("R",new g({color:Q.app.keybind})),new y(" to retry, ",new g({color:Q.colors.foreground,dim:!0})),new y("Esc",new g({color:Q.app.keybind})),new y(" to cancel",new g({color:Q.colors.foreground,dim:!0}))]);let H=this.resolveFooterStyle(this.widget.props.message);if(H==="none")return new y("",new g({color:Q.colors.foreground,dim:!0}));if(H==="help"){let z=new g({color:Q.app.keybind}),F=new g({color:Q.colors.foreground,dim:!0});return new y("",F,[new y("Press ",F),new y("Escape",z),new y(" to close • Use ",F),new y("↑↓",z),new y(" or ",F),new y("j/k",z),new y(" to scroll",F)])}return new y("Press any key to close",new g({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new A6({onKey:(H)=>{if(this.widget.props.onRetry&&H.key==="r")return this.widget.props.onRetry(),"handled";if(H.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 m1({decoration:{border:G,color:Q.colors.background},padding:I1.all(1),child:new S1({mainAxisAlignment:"center",children:[V,new j1({height:1}),q,W]})})})}}class hf1 extends _0{build(J){let Q=v1.of(J),{colors:Z,app:Y}=Q;return new b0({child:new J1({text:new y("",void 0,[new y(`✓ Thread Shared
8551
8551
 
8552
8552
  `,new g({color:Y.toolSuccess,bold:!0})),new y(`This thread has been shared with Amp support for debugging and bug prioritization.
8553
8553
  `,new g({color:Z.foreground})),new y(`This is not a support request.
@@ -8926,7 +8926,7 @@ ${X}`,Q);this.line=Z,this.column=Y,this.codeblock=X}}/*!
8926
8926
 
8927
8927
  To use Sonnet 4.5, use large mode instead: amp --mode large
8928
8928
  Learn more: https://ampcode.com/news/large-mode
8929
- `),process.exit(1);if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")tJ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")tJ("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli")tJ("systemPrompt",Q.systemPrompt)}function Bb8(J){return!!(J&&(J.endsWith("@sourcegraph.com")||J.endsWith("@ampcode.com")||J==="auth-bypass-user@example.com"))}var WN6=[{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??UY,description:`Custom settings file path (overrides the default location ${UY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(E).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${yL})`},{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:L7(),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:"useSonnet",long:"use-sonnet",type:"flag",description:(J)=>J?"Use Claude Sonnet 4.5 instead of Claude Opus 4.5":"Use default model (Claude Opus 4.5)",hidden:!0},{name:"mode",long:"mode",short:"m",type:"option",default:EA.SMART.key,description:`Set the agent mode (${hJ().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:hJ().map((J)=>J.mode).concat("large","deep")},{name:"newTui",long:"new-tui",type:"switch",default:!1,description:"Use experimental New TUI (REST + WebSocket server-side agent loop)",hidden:!0},{name:"newTuiExecutor",long:"new-tui-executor",type:"flag",description:"Start New TUI as executor (tool runner)",hidden:!0},{name:"newTuiObserver",long:"new-tui-observer",type:"option",description:"Start New TUI as observer for an existing thread",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:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text to append (SDK use only)",hidden:!0}],HN6=(J)=>("deprecated"in J)&&J.deprecated===!0,Nb8=(J)=>("hidden"in J)&&J.hidden===!0,Mb8=(J)=>("default"in J),Lb8=(J)=>("default"in J)?J.default:void 0;function wb8(J,Q){let Z=Q.args[0],Y=Q.commands.map((G)=>G.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let G=Y.filter((K)=>Z.includes(K)||K.includes(Z)),V="Run amp --help for a list of available commands.";if(G.length>0)V=`Did you mean: ${G.join(", ")}? Or run amp --help for all commands.`;throw new v6(EZ.unknownCommand(Z),1,V)}}var FN6=null;function v67(){return FN6}async function lw(J){return{...J,getThreadEnvironment:sF,vfs:wr({os:J.fileSystem},J.configService.config),skillService:J.skillService,fileChangeTrackerStorage:new mz(J.fileSystem),generateThreadTitle:Ar0,deleteThread:(Q)=>J.threadService.delete(Q),getServerStatus:()=>s2(J.configService)}}var oT=Q0.file(Fb8.homedir()),Jp=process.env.XDG_CONFIG_HOME?Q0.file(process.env.XDG_CONFIG_HOME):r1.joinPath(oT,".config");async function E7(J,Q){bM0("0.0.1769716999-gdf283f");let Z=GN({storage:J.settings,secretStorage:J.secrets,workspaceRoots:T1.of([Q0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:oT,userConfigDir:Jp}),Y=P0(s2(Z).pipe(g8((m)=>m!=="pending")));KK6(Z);let X=await Z.getLatest();E.debug("Global configuration initialized",{settingsKeys:Object.keys(X.settings)});let{toolService:G,dispose:V}=F06({configService:Z}),K=new Map,q=()=>K.clear(),W=new TN1(Z,J.settings.getWorkspaceRootPath()),H=Bk0({configService:Z,filesystem:C4}),z=rT0({configService:Z,trustStore:W,skillMCPServers:H.skillMCPServers,createOAuthProvider:async(m,k,v)=>{let f=`${m}:${k}`,c=K.get(f);if(c)return E.debug("Reusing existing OAuth provider for server",{serverName:m,serverUrl:k}),c;E.debug("Creating OAuth provider for server",{serverName:m,serverUrl:k});let h=(async()=>{let i=new RN(J.secrets),p=await i.getClientInfo(m,k),o=v?.scopes??p?.scopes,q1=FY6();E.info("OAuth headless mode check",{useHeadless:q1,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:P8.isTTY});let l;if(q1)l=J.executeMode?zY6():HY6(m);let Q1=new aB1({storage:i,serverName:m,serverUrl:k,clientId:v?.clientId??p?.clientId,clientSecret:v?.clientSecret??p?.clientSecret,authUrl:v?.authUrl??p?.authUrl,tokenUrl:v?.tokenUrl??p?.tokenUrl,scopes:o,headlessAuthHandler:l});return E.debug("OAuth provider created",{serverName:m,serverUrl:k,hasManualClientId:!!(v?.clientId??p?.clientId),willUseDCR:!(v?.clientId??p?.clientId),scopes:o,headlessMode:q1,executeMode:J.executeMode}),Q1})();return K.set(f,h),h}}),F=O61({configService:Z,filesystem:C4,spawn:Ah}),U;if(J.executeMode){let m=await xt0({toolService:G,providers:[z,F],initialTimeout:15000});U=m.registrations;for(let[k,v]of m.initErrors)E.warn(`${k} provider initialization slow or failed:`,v)}else U=nP1({toolService:G,providers:[z,F]});if(Q.jetbrains)$R("JetBrains");else if(Q.ide&&C76())$R("VS Code");else if(Q.ide&&_76())$R("Neovim");if(J.executeMode)fM0(!0);let D,B=s9.status.pipe(H0((m)=>Boolean(m.connected&&m.authenticated)),W6()).subscribe((m)=>{if(m){if(!D)D=G.registerTool(yt0)}else D?.dispose(),D=void 0}),N;if(!J.executeMode){let m=await J.settings.get("fuzzy.alwaysIncludePaths")??[];N=new eI(process.cwd(),{alwaysIncludePaths:m},!0)}else N=new class extends eI{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(P8.write(`No API key found. Starting login flow...
8929
+ `),process.exit(1);if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")tJ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")tJ("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli")tJ("systemPrompt",Q.systemPrompt)}function Bb8(J){return!!(J&&(J.endsWith("@sourcegraph.com")||J.endsWith("@ampcode.com")||J==="auth-bypass-user@example.com"))}var WN6=[{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??UY,description:`Custom settings file path (overrides the default location ${UY})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(E).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${yL})`},{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:L7(),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:"useSonnet",long:"use-sonnet",type:"flag",description:(J)=>J?"Use Claude Sonnet 4.5 instead of Claude Opus 4.5":"Use default model (Claude Opus 4.5)",hidden:!0},{name:"mode",long:"mode",short:"m",type:"option",default:EA.SMART.key,description:`Set the agent mode (${hJ().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:hJ().map((J)=>J.mode).concat("large","deep")},{name:"newTui",long:"new-tui",type:"switch",default:!1,description:"Use experimental New TUI (REST + WebSocket server-side agent loop)",hidden:!0},{name:"newTuiExecutor",long:"new-tui-executor",type:"flag",description:"Start New TUI as executor (tool runner)",hidden:!0},{name:"newTuiObserver",long:"new-tui-observer",type:"option",description:"Start New TUI as observer for an existing thread",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:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text to append (SDK use only)",hidden:!0}],HN6=(J)=>("deprecated"in J)&&J.deprecated===!0,Nb8=(J)=>("hidden"in J)&&J.hidden===!0,Mb8=(J)=>("default"in J),Lb8=(J)=>("default"in J)?J.default:void 0;function wb8(J,Q){let Z=Q.args[0],Y=Q.commands.map((G)=>G.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let G=Y.filter((K)=>Z.includes(K)||K.includes(Z)),V="Run amp --help for a list of available commands.";if(G.length>0)V=`Did you mean: ${G.join(", ")}? Or run amp --help for all commands.`;throw new v6(EZ.unknownCommand(Z),1,V)}}var FN6=null;function v67(){return FN6}async function lw(J){return{...J,getThreadEnvironment:sF,vfs:wr({os:J.fileSystem},J.configService.config),skillService:J.skillService,fileChangeTrackerStorage:new mz(J.fileSystem),generateThreadTitle:Ar0,deleteThread:(Q)=>J.threadService.delete(Q),getServerStatus:()=>s2(J.configService)}}var oT=Q0.file(Fb8.homedir()),Jp=process.env.XDG_CONFIG_HOME?Q0.file(process.env.XDG_CONFIG_HOME):r1.joinPath(oT,".config");async function E7(J,Q){bM0("0.0.1769719558-g98dc3a");let Z=GN({storage:J.settings,secretStorage:J.secrets,workspaceRoots:T1.of([Q0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:oT,userConfigDir:Jp}),Y=P0(s2(Z).pipe(g8((m)=>m!=="pending")));KK6(Z);let X=await Z.getLatest();E.debug("Global configuration initialized",{settingsKeys:Object.keys(X.settings)});let{toolService:G,dispose:V}=F06({configService:Z}),K=new Map,q=()=>K.clear(),W=new TN1(Z,J.settings.getWorkspaceRootPath()),H=Bk0({configService:Z,filesystem:C4}),z=rT0({configService:Z,trustStore:W,skillMCPServers:H.skillMCPServers,createOAuthProvider:async(m,k,v)=>{let f=`${m}:${k}`,c=K.get(f);if(c)return E.debug("Reusing existing OAuth provider for server",{serverName:m,serverUrl:k}),c;E.debug("Creating OAuth provider for server",{serverName:m,serverUrl:k});let h=(async()=>{let i=new RN(J.secrets),p=await i.getClientInfo(m,k),o=v?.scopes??p?.scopes,q1=FY6();E.info("OAuth headless mode check",{useHeadless:q1,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:P8.isTTY});let l;if(q1)l=J.executeMode?zY6():HY6(m);let Q1=new aB1({storage:i,serverName:m,serverUrl:k,clientId:v?.clientId??p?.clientId,clientSecret:v?.clientSecret??p?.clientSecret,authUrl:v?.authUrl??p?.authUrl,tokenUrl:v?.tokenUrl??p?.tokenUrl,scopes:o,headlessAuthHandler:l});return E.debug("OAuth provider created",{serverName:m,serverUrl:k,hasManualClientId:!!(v?.clientId??p?.clientId),willUseDCR:!(v?.clientId??p?.clientId),scopes:o,headlessMode:q1,executeMode:J.executeMode}),Q1})();return K.set(f,h),h}}),F=O61({configService:Z,filesystem:C4,spawn:Ah}),U;if(J.executeMode){let m=await xt0({toolService:G,providers:[z,F],initialTimeout:15000});U=m.registrations;for(let[k,v]of m.initErrors)E.warn(`${k} provider initialization slow or failed:`,v)}else U=nP1({toolService:G,providers:[z,F]});if(Q.jetbrains)$R("JetBrains");else if(Q.ide&&C76())$R("VS Code");else if(Q.ide&&_76())$R("Neovim");if(J.executeMode)fM0(!0);let D,B=s9.status.pipe(H0((m)=>Boolean(m.connected&&m.authenticated)),W6()).subscribe((m)=>{if(m){if(!D)D=G.registerTool(yt0)}else D?.dispose(),D=void 0}),N;if(!J.executeMode){let m=await J.settings.get("fuzzy.alwaysIncludePaths")??[];N=new eI(process.cwd(),{alwaysIncludePaths:m},!0)}else N=new class extends eI{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(P8.write(`No API key found. Starting login flow...
8930
8930
  `),!await Ob8(J))await xL(),process.exit(1)}let M=await Ak0({isDevelopment:!1}),L=await Y,w=A5(L)&&L.features.some((m)=>m.name===tG.LIVE_SYNC&&m.enabled),O=new kP1(M,Z,w),A=new wP1(M,{lazy:!0}),R=Q.notifications!==void 0?Q.notifications:!J.executeMode,j=L06({playNotificationSound:async(m)=>{if(R){M06(m);let k=z81(),v=OS1();if((!k||v||S76())&&X.settings["notifications.system.enabled"]!==!1){if(m==="idle")process.stdout.write(jW("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(m==="requires-user-input")process.stdout.write(jW("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(z81()),threadService:O,configService:Z});E.info("Starting Amp background services");let T=Tr0({threadService:O,threadHistoryService:A,configService:Z,isExtensionDevelopment:!1,liveSyncEnabled:w,fileChangeTrackerStorage:new mz(C4),fileSystem:C4,getServerStatus:()=>s2(Z)}),C;s9.status.subscribe((m)=>{C=m});let S=new rz1({workspaceRoots:[Q0.file(process.cwd())],getCurrentFile:()=>{if(!C?.openFile)return;try{return Q0.parse(C.openFile)}catch(m){E.warn("Failed to parse current file URI",{uri:C.openFile,error:m});return}},getOpenFiles:()=>{if(!C?.visibleFiles?.length)return[];let m=C.openFile;return C.visibleFiles.filter((k)=>k!==m).map((k)=>{try{return Q0.parse(k)}catch(v){return E.warn("Failed to parse visible file URI",{uri:k,error:v}),null}}).filter((k)=>k!==null)}}),b=new av1,u={codebaseContextService:S,configService:Z,toolService:G,mcpService:z,skillService:H,toolboxService:F,trustStore:W,threadService:O,threadHistoryService:A,threadSyncService:T,threadStorage:M,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:N,notificationService:j,fileSystem:Q.jetbrains||Q.ide?NC0:C4,terminal:b,serverStatus:L};return{...u,async asyncDispose(){if(u.mcpService.hasAuthenticatingClients())E.info("Waiting for OAuth authentication to complete before exit..."),await u.mcpService.waitForAuthentication();for(let m of U.values())m.dispose();await u.mcpService.dispose(),q(),await u.threadService.asyncDispose(),await u.threadSyncService.flushFileChanges(),u.configService.unsubscribe(),V(),u.fuzzyServer.dispose(),u.threadSyncService.dispose(),u.settingsStorage[Symbol.dispose](),B.unsubscribe(),D?.dispose()}}}async function Ob8(J){if(!J.executeMode){if(!await ox1("Would you like to log in to Amp? [(y)es, (n)o]: "))return P8.write(`Login cancelled. Run the command again to retry.
8931
8931
  `),!1}return await UN6(J)}async function UN6(J){let Q=Hb8(32).toString("hex"),Z=await ax1(J.ampURL,Q),Y=new AbortController;try{await eH(Z,Y.signal)}catch(G){E.error("Error opening browser",{error:G})}let X=await ax1(J.ampURL,Q,!1);P8.write(`If your browser does not open automatically, visit:
8932
8932
 
@@ -8934,7 +8934,7 @@ ${p1.blue.bold(X)}
8934
8934
 
8935
8935
  `);try{return await zX6(J.ampURL,Q,J.secrets,Y),P8.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(G){return E.error("Login failed",{error:G}),J2.write(`
8936
8936
  Login failed: ${G instanceof Error?G.message:String(G)}
8937
- `),!1}}function Ab8(){let J=new nV().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((U)=>{if(U.code==="commander.help"||U.code==="commander.version"||U.exitCode===0)vL(),process.exit(0);let D=U.originalError??U;x41(D)}),J.option("-V, --version","Print the version number and exit",()=>{let D;try{D=`, ${Rz(new Date("2026-01-29T20:08:22.760Z"))} ago`}catch{}P8.write(`0.0.1769716999-gdf283f (released 2026-01-29T20:08:22.760Z${D??""})
8937
+ `),!1}}function Ab8(){let J=new nV().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((U)=>{if(U.code==="commander.help"||U.code==="commander.version"||U.exitCode===0)vL(),process.exit(0);let D=U.originalError??U;x41(D)}),J.option("-V, --version","Print the version number and exit",()=>{let D;try{D=`, ${Rz(new Date("2026-01-29T20:51:01.893Z"))} ago`}catch{}P8.write(`0.0.1769719558-g98dc3a (released 2026-01-29T20:51:01.893Z${D??""})
8938
8938
  `),process.exit(0)}),J.addHelpText("after",pY6()),J.configureHelp({formatHelp:dY6}),J.command("logout").description("Log out by removing stored API key").action(async(U,D)=>{let B=D.optsWithGlobals(),N=await I9(B);await Ib8(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(U,D)=>{let B=D.optsWithGlobals(),N=await I9(B);await Eb8(N,await _x1(B,N.settings))});let Q=async(U,D,B)=>{GN({storage:D.settings,secretStorage:D.secrets,workspaceRoots:T1.of([Q0.file(process.cwd())]),defaultAmpURL:D.ampURL,homeDir:oT,userConfigDir:Jp});let N={...D,executeMode:!1};await q21(N,{...U,openThreadSwitcher:!0},B)},Z=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(U,D)=>{let B=D.optsWithGlobals(),N=await I9(B);await zN6(B,N,D)});Z.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(U,D)=>{let B=D.optsWithGlobals(),N=await I9(B);await bb8(B,N,D)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, shows an interactive picker with the most recently used thread at the top. Use --last to continue the last thread directly without the picker.").option("--last","Continue the last thread directly without showing the picker").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(U,D,B)=>{let N=B.optsWithGlobals(),M=await I9(N);if(D.pick)J2.write(`${p1.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
8939
8939
  `);if(D.last||U||M.executeMode)await vb8(N,M,U,B);else await Q(N,M,B)});let Y=new nV("fork").argument("[threadId]").alias("f").action(async()=>{J2.write(`\x1B[31mThe fork command has been deprecated.\x1B[0m
8940
8940
 
@@ -8957,13 +8957,13 @@ Examples:
8957
8957
  amp threads handoff T-xxx --goal "Continue working on the auth feature"
8958
8958
  amp threads handoff --goal "Fix the remaining tests" # Uses last thread
8959
8959
 
8960
- By default, opens the new thread in the TUI. Use --print to just print the thread ID.`).option("-g, --goal <goal>","Goal/prompt for the handoff (alternative to stdin)").option("-p, --print","Print the thread ID instead of opening the TUI").action(async(U,D,B)=>{let N=B.optsWithGlobals(),M=await I9(N);await xb8(N,M,U??null,D.goal,!D.print,B)}),Z.command("markdown <threadId>").alias("md").summary("Render thread as markdown").description("Render a thread as markdown. This outputs the entire conversation history in a readable markdown format.").action(async(U,D,B)=>{let N=B.optsWithGlobals(),M=await I9(N);await _b8(N,M,U,B)}),Z.command("export <threadId>",{hidden:!0}).summary("Export a thread as JSON").description("Export a thread as JSON. This outputs the full thread payload.").action(async(U,D,B)=>{let N=B.optsWithGlobals(),M=await I9(N);await Sb8(N,M,U,B)}),Z.command("replay <threadId>").alias("p").summary("Replay a thread").description("Replay a thread by downloading it and playing through all interactions. User messages are simulated with variable typing speed.").option("--wpm <wpm>","Typing speed in words per minute (default: 120)","120").option("--no-typing","Disable typing simulation and display messages instantly").option("--message-delay <ms>","Delay between messages in milliseconds (default: 1000)","1000").option("--tool-progress-delay <ms>","Delay to show tool in-progress state in milliseconds (default: 800)","800").option("--exit-delay <seconds>","Delay in seconds before exiting after replay completes (default: 3)","3").option("--no-indicator","Hide the replay progress indicator").action(async(U,D,B)=>{let N=B.optsWithGlobals(),M=await I9(N);await kb8(N,M,U,D,B)}),C66(Z,I9,o7,E7,W21,RD,I7),wK6(J,async(U,D)=>{let B=await I9(D);o7(U,D);let N=await E7(B,D);return{context:B,mcpService:N.mcpService,toolService:N.toolService,toolServices:N.toolService,toolboxService:N.toolboxService,configService:N.configService,cleanupTerminal:vL,asyncDispose:N.asyncDispose.bind(N)}}),XK6(J,async(U,D)=>{let B=await I9(D);return o7(U,D),{configService:GN({storage:B.settings,secretStorage:B.secrets,workspaceRoots:T1.of([Q0.file(process.cwd())]),defaultAmpURL:B.ampURL,homeDir:oT,userConfigDir:Jp}),asyncDispose:async()=>{}}}),tV6(J,async(U)=>{let D=U.optsWithGlobals(),B=await I9(D);o7(U,D);let N=await E7(B,D);return{toolService:N.toolService,mcpService:N.mcpService,configService:N.configService,cleanupTerminal:vL,asyncDispose:N.asyncDispose.bind(N)}}),$K6(J,async(U)=>{let D=U.optsWithGlobals(),B=await I9(D);o7(U,D);let N=await E7(B,D);return{settings:B.settings,configService:N.configService,skillService:N.skillService,asyncDispose:N.asyncDispose.bind(N)}}),IX6(J,async(U)=>{let D=U.optsWithGlobals();return await I9(D)}),MX6(J,async(U)=>{let D=await I9(U);return{settings:D.settings,secretStorage:D.secrets,getThreadDeps:async(B)=>{o7(B,U);let N=await E7(D,U);return{mcpService:N.mcpService,settings:D.settings,asyncDispose:N.asyncDispose.bind(N)}}}}),gV6(J,async(U,D)=>{let B=await I9(D);o7(U,D);let N=GN({storage:B.settings,secretStorage:B.secrets,workspaceRoots:T1.of([Q0.file(process.cwd())]),defaultAmpURL:B.ampURL,homeDir:oT,userConfigDir:Jp}),M=await P0(s2(N).pipe(g8((w)=>w!=="pending"))),L=A5(M)?M.features:[];return{ampURL:B.ampURL,secretStorage:B.secrets,features:L,asyncDispose:async()=>{}}},async(U,D)=>{let B=await I9(D);o7(U,D);let N=await E7(B,D),M=await lw(N),{serverStatus:L}=N,w=A5(L)?L.features:[],O=await N.secretStorage.get("apiKey",B.ampURL);if(!O)throw new v6("API key required for runner mode. Please run `amp login` first.",1);return{ampURL:B.ampURL,apiKey:O,version:"0.0.1769716999-gdf283f",dependencies:N,workerDeps:M,features:w,asyncDispose:N.asyncDispose.bind(N)}}),pV6(J,async(U,D)=>{let B=await I9(D);o7(U,D);let N=await E7(B,D),M=await lw(N),{serverStatus:L}=N,w=A5(L)?L.features:[],O=await N.secretStorage.get("apiKey",B.ampURL);if(!O)throw new v6("API key required for runner mode. Please run `amp login` first.",1);return{ampURL:B.ampURL,apiKey:O,version:"0.0.1769716999-gdf283f",dependencies:N,workerDeps:M,features:w,asyncDispose:N.asyncDispose.bind(N)}}),dF6(J,I9,oT,Jp);function G(U,D,B){let M=typeof U.description==="string"?U.description:B===void 0?U.description(!0):U.description(B),L=new aV(D,M),w=Lb8(U);if(w)L.default(w);if(L.hidden=Nb8(U)||HN6(U),"choices"in U)L.choices([...U.choices]);return L}for(let U of WN6)switch(U.type){case"flag":{J.addOption(G(U,`--${U.long}`)),J.addOption(G(U,`--no-${U.long}`,!1));break}case"switch":{J.addOption(G(U,`--${U.long}`,!0));break}case"optional-option":{J.addOption(G(U,`${"short"in U?`-${U.short}, `:""}--${U.long} [value]`));break}default:{J.addOption(G(U,`${"short"in U?`-${U.short}, `:""}--${U.long} <value>`));break}}let V=new aV("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);J.addOption(V);let K=new aV("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(K);let q=new aV("--stream-json","When used with --execute, output in Claude Code-compatible stream JSON format instead of plain text.").default(!1);J.addOption(q);let W=new aV("--stream-json-thinking","Include thinking blocks in stream JSON output (non-Claude Code extension). Implies --stream-json.").default(!1);J.addOption(W);let H=new aV("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(H);let z=new aV("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);J.addOption(z);let F=new aV("-l, --label <label>","When used with --execute, add a label to the thread. Can be used multiple times.").argParser((U,D)=>{if(D===void 0)return[U];return[...D,U]});if(J.addOption(F),process.env.AMP_CONNECT==="1"){let U=new aV("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(U)}return J.action(async(U,D)=>{let B=U,N=await I9(B);if(Object.keys(B).forEach((M)=>{let L=WN6.find((w)=>w.name===M);if(L&&HN6(L)&&!Mb8(L))J2.write(p1.yellow(`Warning: '--${M}' flag is deprecated
8960
+ By default, opens the new thread in the TUI. Use --print to just print the thread ID.`).option("-g, --goal <goal>","Goal/prompt for the handoff (alternative to stdin)").option("-p, --print","Print the thread ID instead of opening the TUI").action(async(U,D,B)=>{let N=B.optsWithGlobals(),M=await I9(N);await xb8(N,M,U??null,D.goal,!D.print,B)}),Z.command("markdown <threadId>").alias("md").summary("Render thread as markdown").description("Render a thread as markdown. This outputs the entire conversation history in a readable markdown format.").action(async(U,D,B)=>{let N=B.optsWithGlobals(),M=await I9(N);await _b8(N,M,U,B)}),Z.command("export <threadId>",{hidden:!0}).summary("Export a thread as JSON").description("Export a thread as JSON. This outputs the full thread payload.").action(async(U,D,B)=>{let N=B.optsWithGlobals(),M=await I9(N);await Sb8(N,M,U,B)}),Z.command("replay <threadId>").alias("p").summary("Replay a thread").description("Replay a thread by downloading it and playing through all interactions. User messages are simulated with variable typing speed.").option("--wpm <wpm>","Typing speed in words per minute (default: 120)","120").option("--no-typing","Disable typing simulation and display messages instantly").option("--message-delay <ms>","Delay between messages in milliseconds (default: 1000)","1000").option("--tool-progress-delay <ms>","Delay to show tool in-progress state in milliseconds (default: 800)","800").option("--exit-delay <seconds>","Delay in seconds before exiting after replay completes (default: 3)","3").option("--no-indicator","Hide the replay progress indicator").action(async(U,D,B)=>{let N=B.optsWithGlobals(),M=await I9(N);await kb8(N,M,U,D,B)}),C66(Z,I9,o7,E7,W21,RD,I7),wK6(J,async(U,D)=>{let B=await I9(D);o7(U,D);let N=await E7(B,D);return{context:B,mcpService:N.mcpService,toolService:N.toolService,toolServices:N.toolService,toolboxService:N.toolboxService,configService:N.configService,cleanupTerminal:vL,asyncDispose:N.asyncDispose.bind(N)}}),XK6(J,async(U,D)=>{let B=await I9(D);return o7(U,D),{configService:GN({storage:B.settings,secretStorage:B.secrets,workspaceRoots:T1.of([Q0.file(process.cwd())]),defaultAmpURL:B.ampURL,homeDir:oT,userConfigDir:Jp}),asyncDispose:async()=>{}}}),tV6(J,async(U)=>{let D=U.optsWithGlobals(),B=await I9(D);o7(U,D);let N=await E7(B,D);return{toolService:N.toolService,mcpService:N.mcpService,configService:N.configService,cleanupTerminal:vL,asyncDispose:N.asyncDispose.bind(N)}}),$K6(J,async(U)=>{let D=U.optsWithGlobals(),B=await I9(D);o7(U,D);let N=await E7(B,D);return{settings:B.settings,configService:N.configService,skillService:N.skillService,asyncDispose:N.asyncDispose.bind(N)}}),IX6(J,async(U)=>{let D=U.optsWithGlobals();return await I9(D)}),MX6(J,async(U)=>{let D=await I9(U);return{settings:D.settings,secretStorage:D.secrets,getThreadDeps:async(B)=>{o7(B,U);let N=await E7(D,U);return{mcpService:N.mcpService,settings:D.settings,asyncDispose:N.asyncDispose.bind(N)}}}}),gV6(J,async(U,D)=>{let B=await I9(D);o7(U,D);let N=GN({storage:B.settings,secretStorage:B.secrets,workspaceRoots:T1.of([Q0.file(process.cwd())]),defaultAmpURL:B.ampURL,homeDir:oT,userConfigDir:Jp}),M=await P0(s2(N).pipe(g8((w)=>w!=="pending"))),L=A5(M)?M.features:[];return{ampURL:B.ampURL,secretStorage:B.secrets,features:L,asyncDispose:async()=>{}}},async(U,D)=>{let B=await I9(D);o7(U,D);let N=await E7(B,D),M=await lw(N),{serverStatus:L}=N,w=A5(L)?L.features:[],O=await N.secretStorage.get("apiKey",B.ampURL);if(!O)throw new v6("API key required for runner mode. Please run `amp login` first.",1);return{ampURL:B.ampURL,apiKey:O,version:"0.0.1769719558-g98dc3a",dependencies:N,workerDeps:M,features:w,asyncDispose:N.asyncDispose.bind(N)}}),pV6(J,async(U,D)=>{let B=await I9(D);o7(U,D);let N=await E7(B,D),M=await lw(N),{serverStatus:L}=N,w=A5(L)?L.features:[],O=await N.secretStorage.get("apiKey",B.ampURL);if(!O)throw new v6("API key required for runner mode. Please run `amp login` first.",1);return{ampURL:B.ampURL,apiKey:O,version:"0.0.1769719558-g98dc3a",dependencies:N,workerDeps:M,features:w,asyncDispose:N.asyncDispose.bind(N)}}),dF6(J,I9,oT,Jp);function G(U,D,B){let M=typeof U.description==="string"?U.description:B===void 0?U.description(!0):U.description(B),L=new aV(D,M),w=Lb8(U);if(w)L.default(w);if(L.hidden=Nb8(U)||HN6(U),"choices"in U)L.choices([...U.choices]);return L}for(let U of WN6)switch(U.type){case"flag":{J.addOption(G(U,`--${U.long}`)),J.addOption(G(U,`--no-${U.long}`,!1));break}case"switch":{J.addOption(G(U,`--${U.long}`,!0));break}case"optional-option":{J.addOption(G(U,`${"short"in U?`-${U.short}, `:""}--${U.long} [value]`));break}default:{J.addOption(G(U,`${"short"in U?`-${U.short}, `:""}--${U.long} <value>`));break}}let V=new aV("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);J.addOption(V);let K=new aV("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(K);let q=new aV("--stream-json","When used with --execute, output in Claude Code-compatible stream JSON format instead of plain text.").default(!1);J.addOption(q);let W=new aV("--stream-json-thinking","Include thinking blocks in stream JSON output (non-Claude Code extension). Implies --stream-json.").default(!1);J.addOption(W);let H=new aV("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(H);let z=new aV("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);J.addOption(z);let F=new aV("-l, --label <label>","When used with --execute, add a label to the thread. Can be used multiple times.").argParser((U,D)=>{if(D===void 0)return[U];return[...D,U]});if(J.addOption(F),process.env.AMP_CONNECT==="1"){let U=new aV("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(U)}return J.action(async(U,D)=>{let B=U,N=await I9(B);if(Object.keys(B).forEach((M)=>{let L=WN6.find((w)=>w.name===M);if(L&&HN6(L)&&!Mb8(L))J2.write(p1.yellow(`Warning: '--${M}' flag is deprecated
8961
8961
  `))}),D.args.length>0)wb8(N,D);await q21(N,B,D)}),WX6(J),J}async function K21(J,Q){let{thread:Z,visibility:Y}=Q,X=Z?.id??l2(),G=await lw(J);if(Z)await J.threadStorage.set(X,Z);let V=await L4.getOrCreateForThread(G,X),K=await J.threadStorage.get(X);if(Q.agentMode&&!K?.agentMode&&(!K||o9(K)===0))await V.handle({type:"agent-mode",mode:Q.agentMode});if(Y)await J.threadSyncService.updateThreadMeta(X,n91(Y));let q=J.threadService.observe(X).subscribe(async(W)=>{if(S9(W,"assistant")){let z=await gW();await uW({...z,lastThreadId:X}),q.unsubscribe()}});return await V.resume(),V}async function q21(J,Q,Z){let Y=i91(Q);if(Y instanceof Error)I7(Y.message);let X,G=null;if(Q.streamJsonInput)X="";else if(typeof Q.execute==="string"){X=Q.execute;let k=(await R51()).trimEnd();if(k)G=k}else X=(await R51()).trimEnd();let V=!!Q.streamJson||!!Q.streamJsonThinking;if(Q.remote&&!J.executeMode)throw new v6("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(V&&!J.executeMode)throw new v6("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new v6("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!V)throw new v6("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.stats&&!J.executeMode)throw new v6("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(Q.streamJsonInput&&typeof Q.execute==="string"&&Q.execute.trim()!=="")throw new v6("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(J.executeMode&&X===""&&!Q.streamJsonInput&&!Q.newTui&&!Q.headless)throw new v6("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"
8962
- Or pipe via stdin: echo "your message" | amp --execute`);o7(Z,Q);let K=await E7(J,Q);FN6=K;let q=await lw(K),{serverStatus:W}=K;if(pT0(W))throw new v6(EZ.invalidAPIKey,1);let H=A5(W)?W.user.email:void 0,z=A5(W)?W.features:[],F=A5(W)?W.workspace:null,U=Bb8(H);if((J.executeMode||V)&&m5(Q.mode)&&!U)throw new v6(`Execute mode is not permitted with --mode '${Q.mode}'`,1);if(Q.headless){if(!H||!ez1(H))throw new v6("Headless DTW mode is only available for Amp employees",1);let k=await K.secretStorage.get("apiKey",J.ampURL);if(!k)throw new v6("API key required for headless mode. Please run `amp login` first.",1);let v=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(v&&!D9(v))throw new v6(`Invalid thread ID: ${v}`,1);await WY6({ampURL:J.ampURL,apiKey:k,workspaceRoot:process.cwd(),threadId:v,configService:K.configService,mcpService:K.mcpService,toolService:K.toolService,fileSystem:K.fileSystem}),await K.asyncDispose(),process.exit(0)}if(Q.newTui||Q.newTuiExecutor||Q.newTuiObserver){if(!H||!ez1(H))throw new v6("New TUI mode is only available for Amp employees",1);if(Q.newTuiExecutor&&Q.newTuiObserver)throw new v6("Use only one of --new-tui-executor or --new-tui-observer",1);let k=await K.secretStorage.get("apiKey",J.ampURL);if(!k)throw new v6("API key required for New TUI mode. Please run `amp login` first.",1);let v=Q.newTuiObserver?"observer":"executor";if(v==="observer"&&!Q.newTuiObserver)throw new v6("Observer mode requires a thread ID",1);if(Q.newTuiObserver&&!D9(Q.newTuiObserver))throw new v6("Observer mode requires a valid thread ID",1);let f=Q.newTuiObserver;await KY6({ampURL:J.ampURL,apiKey:k,workspaceRoot:process.cwd(),mode:v,threadId:f,configService:K.configService,mcpService:K.mcpService,toolService:K.toolService,fileSystem:K.fileSystem}),await K.asyncDispose(),process.exit(0)}let D=async(k)=>{let v=await zb8(k,"utf-8"),f=JSON.parse(v);if(!D9(f.id))throw new v6(EZ.invalidThreadId);return K21(K,{visibility:Y,agentMode:Q.mode,thread:f})},B=async(k)=>{let v=Date.now(),[f,c]=await Promise.all([$4.getThreadLinkInfo({thread:k},{config:K.configService}),$4.getUserInfo({},{config:K.configService})]);if(E.info(`[fetchAndStartThread] Ownership check in ${Date.now()-v}ms`),f.ok&&c.ok){let h=f.result.creatorUserID,i=c.result.id;if(h&&h!==i&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new v6(`Cannot resume thread created by another user.
8962
+ Or pipe via stdin: echo "your message" | amp --execute`);o7(Z,Q);let K=await E7(J,Q);FN6=K;let q=await lw(K),{serverStatus:W}=K;if(pT0(W))throw new v6(EZ.invalidAPIKey,1);let H=A5(W)?W.user.email:void 0,z=A5(W)?W.features:[],F=A5(W)?W.workspace:null,U=Bb8(H);if((J.executeMode||V)&&m5(Q.mode)&&!U)throw new v6(`Execute mode is not permitted with --mode '${Q.mode}'`,1);if(Q.headless){if(!H||!ez1(H))throw new v6("Headless DTW mode is only available for Amp employees",1);let k=await K.secretStorage.get("apiKey",J.ampURL);if(!k)throw new v6("API key required for headless mode. Please run `amp login` first.",1);let v=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(v&&!D9(v))throw new v6(`Invalid thread ID: ${v}`,1);await WY6({ampURL:J.ampURL,apiKey:k,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:v,configService:K.configService,mcpService:K.mcpService,toolService:K.toolService,fileSystem:K.fileSystem}),await K.asyncDispose(),process.exit(0)}if(Q.newTui||Q.newTuiExecutor||Q.newTuiObserver){if(!H||!ez1(H))throw new v6("New TUI mode is only available for Amp employees",1);if(Q.newTuiExecutor&&Q.newTuiObserver)throw new v6("Use only one of --new-tui-executor or --new-tui-observer",1);let k=await K.secretStorage.get("apiKey",J.ampURL);if(!k)throw new v6("API key required for New TUI mode. Please run `amp login` first.",1);let v=Q.newTuiObserver?"observer":"executor";if(v==="observer"&&!Q.newTuiObserver)throw new v6("Observer mode requires a thread ID",1);if(Q.newTuiObserver&&!D9(Q.newTuiObserver))throw new v6("Observer mode requires a valid thread ID",1);let f=Q.newTuiObserver;await KY6({ampURL:J.ampURL,apiKey:k,workspaceRoot:process.cwd(),mode:v,threadId:f,configService:K.configService,mcpService:K.mcpService,toolService:K.toolService,fileSystem:K.fileSystem}),await K.asyncDispose(),process.exit(0)}let D=async(k)=>{let v=await zb8(k,"utf-8"),f=JSON.parse(v);if(!D9(f.id))throw new v6(EZ.invalidThreadId);return K21(K,{visibility:Y,agentMode:Q.mode,thread:f})},B=async(k)=>{let v=Date.now(),[f,c]=await Promise.all([$4.getThreadLinkInfo({thread:k},{config:K.configService}),$4.getUserInfo({},{config:K.configService})]);if(E.info(`[fetchAndStartThread] Ownership check in ${Date.now()-v}ms`),f.ok&&c.ok){let h=f.result.creatorUserID,i=c.result.id;if(h&&h!==i&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new v6(`Cannot resume thread created by another user.
8963
8963
 
8964
8964
  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.`)}},N=async(k,{nonBlockingOwnershipCheck:v=!1,onOwnershipError:f}={})=>{if(!D9(k))throw new v6(EZ.invalidThreadId);let c=Date.now();if(E.info(`[fetchAndStartThread] Begin switch to thread ${k}`),v)B(k).catch((q1)=>{if(q1 instanceof v6){if(f){f(q1,k);return}rI(q1,k);return}E.warn("Failed to validate thread ownership in CLI, allowing to open",{error:q1})});else try{await B(k)}catch(q1){if(q1 instanceof v6)throw q1;E.warn("Failed to validate thread ownership in CLI, allowing to open",{error:q1})}let h=Date.now(),i=await K.threadService.get(k)??void 0;E.info(`[fetchAndStartThread] Loaded thread in ${Date.now()-h}ms`),E.info(`[fetchAndStartThread] Loaded thread ${k}, agentMode: ${i?.agentMode??"undefined"}`);let p=Date.now(),o=await K21(K,{visibility:Y,agentMode:i?void 0:Q.mode,thread:i});return E.info(`[fetchAndStartThread] Started worker in ${Date.now()-p}ms (total ${Date.now()-c}ms)`),o},M=async()=>{try{if(Q.threadId)return N(Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck??!1});else return K21(K,{visibility:Y,agentMode:Q.mode})}catch(k){if(k instanceof v6)throw k;throw await rI(k,Q.threadId),Error("handleError should have called process.exit()")}},L=async()=>{return K21(K,{visibility:Y,agentMode:Q.mode})};if(Q.format==="jsonl")J2.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
8965
- `),await xL(),process.exit(1);if(J.executeMode&&Q.remote)await PX6(X,G,K.configService),await K.asyncDispose(),process.exit(0);let w=(async()=>{try{let k=await K.configService.getLatest(),v=zi(k),f=await $4.getUserFreeTierStatus({},{config:K.configService,signal:AbortSignal.timeout(v)});if(f.ok)return E.info("User free tier status:",f),f.result}catch(k){throw E.error("Failed to fetch free tier status:",k),k}})(),O=await M();if(J.executeMode)AX6(K.mcpService,J.settings),await e56({worker:O,threadID:O.threadID,userInput:X,stdinInput:G,dependencies:K,streamJson:V,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:J.ampURL,isDogfooding:U,agentMode:Q.mode,labels:Q.label}),await K.asyncDispose(),process.exit(0);let A=!1,R=!1,j=!1;if(Q.jetbrains||Q.ide){await aM0();let k=KR({jetbrainsOnly:Q.jetbrains});if(k.length===0){if(Q.jetbrains)R=!await K.configService.get("jetbrains.skipInstall")}else if(k.length===1){let v=k[0];if(v)s9.selectConfig(v)}else j=!0}let T=c91("0.0.1769716999-gdf283f",K.settingsStorage),C=new n01(K.threadStorage),S=new l91(K.mcpService,J.settings.getWorkspaceRootPath());if(X)O.handle({type:"user:message",message:{content:[{type:"text",text:X}]}});let b=await gW();E.info("Loaded session state:",b);let u={...b,launchCount:b.launchCount+1};uW(u);let m=new w31(K.threadService);try{await xh1({codebaseContextService:K.codebaseContextService,stdout:process.stdout,history:new f41,fuzzyServer:K.fuzzyServer,settingsStorage:K.settingsStorage,threadService:K.threadService,threadHistoryService:K.threadHistoryService,threadSyncService:K.threadSyncService,threadID:O.threadID,threadFuzzyIndexer:C,worker:O,workerDeps:q,globalWorkerRegistry:m,skillService:K.skillService,configService:K.configService,internalAPIClient:$4,ampURL:J.ampURL,startNewThread:L,switchToThread:(k,v)=>N(k,{nonBlockingOwnershipCheck:v?.nonBlockingOwnershipCheck??!1,onOwnershipError:v?.onOwnershipError}),ideClient:s9,mcpService:K.mcpService,toolboxService:K.toolboxService,mcpTrustHandler:S,showJetBrainsInstaller:R,showIdePicker:A,showIdePickerHint:j,openThreadSwitcher:Q.openThreadSwitcher,updateService:T,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:u,freeTierStatusPromise:w,workspace:F??null,features:z,isDogfooding:U,threadDependencies:K,initialAgentMode:Z.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,buildTimestamp:"2026-01-29T20:08:22.760Z"})}finally{m.dispose()}await K.asyncDispose(),process.exit(0)}async function I9(J){if(J.interactive)J2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
8966
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,Y=await IY6({...J,workspaceTrust:{current:!0,changes:$S},getHook:process.env.AMP_URL?(V,K)=>{if(V==="url")return Promise.resolve(process.env.AMP_URL);return K()}:void 0});if(J.mcpConfig){let V=await wX6(J.mcpConfig);Y=OX6(Y,V)}let X=Ub8.dirname(Y.getSettingsFilePath());N06(Ag,X);let G=await Y.get("url","global");if(!G)G=q2;if(!Jz(G))E.info("Targeting custom Amp server",{ampURL:G});return Y=CM0(Y),{executeMode:Q,isTTY:Z,ampURL:G,settings:Y,secrets:eV6(await _x1(J,Y))}}function Rb8(J){let Q={};for(let Z=0;Z<J.length;Z++){let Y=J[Z];if(Y?.startsWith("--")){let G=Y.slice(2).replace(/-([a-z])/g,(K,q)=>q.toUpperCase()),V=J[Z+1];if(V&&!V.startsWith("--"))Q[G]=V,Z++}}return Q}async function jb8(){let J=Rb8(process.argv);u56({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE});let Q=process.argv.includes("--no-color"),Z=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!Z&&!Y)p1.level=0;if(Db8(E),E.info("Starting Amp CLI.",{version:"0.0.1769716999-gdf283f",buildTimestamp:"2026-01-29T20:08:22.760Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new v6(EZ.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Ab8().parseAsync(process.argv)}D06().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await jb8().catch(rI)});async function Eb8(J,Q){let Z=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Z)await J.settings.set("url",process.env.AMP_URL,"global"),P8.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
8965
+ `),await xL(),process.exit(1);if(J.executeMode&&Q.remote)await PX6(X,G,K.configService),await K.asyncDispose(),process.exit(0);let w=(async()=>{try{let k=await K.configService.getLatest(),v=zi(k),f=await $4.getUserFreeTierStatus({},{config:K.configService,signal:AbortSignal.timeout(v)});if(f.ok)return E.info("User free tier status:",f),f.result}catch(k){throw E.error("Failed to fetch free tier status:",k),k}})(),O=await M();if(J.executeMode)AX6(K.mcpService,J.settings),await e56({worker:O,threadID:O.threadID,userInput:X,stdinInput:G,dependencies:K,streamJson:V,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:J.ampURL,isDogfooding:U,agentMode:Q.mode,labels:Q.label}),await K.asyncDispose(),process.exit(0);let A=!1,R=!1,j=!1;if(Q.jetbrains||Q.ide){await aM0();let k=KR({jetbrainsOnly:Q.jetbrains});if(k.length===0){if(Q.jetbrains)R=!await K.configService.get("jetbrains.skipInstall")}else if(k.length===1){let v=k[0];if(v)s9.selectConfig(v)}else j=!0}let T=c91("0.0.1769719558-g98dc3a",K.settingsStorage),C=new n01(K.threadStorage),S=new l91(K.mcpService,J.settings.getWorkspaceRootPath());if(X)O.handle({type:"user:message",message:{content:[{type:"text",text:X}]}});let b=await gW();E.info("Loaded session state:",b);let u={...b,launchCount:b.launchCount+1};uW(u);let m=new w31(K.threadService);try{await xh1({codebaseContextService:K.codebaseContextService,stdout:process.stdout,history:new f41,fuzzyServer:K.fuzzyServer,settingsStorage:K.settingsStorage,threadService:K.threadService,threadHistoryService:K.threadHistoryService,threadSyncService:K.threadSyncService,threadID:O.threadID,threadFuzzyIndexer:C,worker:O,workerDeps:q,globalWorkerRegistry:m,skillService:K.skillService,configService:K.configService,internalAPIClient:$4,ampURL:J.ampURL,startNewThread:L,switchToThread:(k,v)=>N(k,{nonBlockingOwnershipCheck:v?.nonBlockingOwnershipCheck??!1,onOwnershipError:v?.onOwnershipError}),ideClient:s9,mcpService:K.mcpService,toolboxService:K.toolboxService,mcpTrustHandler:S,showJetBrainsInstaller:R,showIdePicker:A,showIdePickerHint:j,openThreadSwitcher:Q.openThreadSwitcher,updateService:T,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:u,freeTierStatusPromise:w,workspace:F??null,features:z,isDogfooding:U,threadDependencies:K,initialAgentMode:Z.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,buildTimestamp:"2026-01-29T20:51:01.893Z"})}finally{m.dispose()}await K.asyncDispose(),process.exit(0)}async function I9(J){if(J.interactive)J2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
8966
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,Y=await IY6({...J,workspaceTrust:{current:!0,changes:$S},getHook:process.env.AMP_URL?(V,K)=>{if(V==="url")return Promise.resolve(process.env.AMP_URL);return K()}:void 0});if(J.mcpConfig){let V=await wX6(J.mcpConfig);Y=OX6(Y,V)}let X=Ub8.dirname(Y.getSettingsFilePath());N06(Ag,X);let G=await Y.get("url","global");if(!G)G=q2;if(!Jz(G))E.info("Targeting custom Amp server",{ampURL:G});return Y=CM0(Y),{executeMode:Q,isTTY:Z,ampURL:G,settings:Y,secrets:eV6(await _x1(J,Y))}}function Rb8(J){let Q={};for(let Z=0;Z<J.length;Z++){let Y=J[Z];if(Y?.startsWith("--")){let G=Y.slice(2).replace(/-([a-z])/g,(K,q)=>q.toUpperCase()),V=J[Z+1];if(V&&!V.startsWith("--"))Q[G]=V,Z++}}return Q}async function jb8(){let J=Rb8(process.argv);u56({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE});let Q=process.argv.includes("--no-color"),Z=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!Z&&!Y)p1.level=0;if(Db8(E),E.info("Starting Amp CLI.",{version:"0.0.1769719558-g98dc3a",buildTimestamp:"2026-01-29T20:51:01.893Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new v6(EZ.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Ab8().parseAsync(process.argv)}D06().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await jb8().catch(rI)});async function Eb8(J,Q){let Z=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Z)await J.settings.set("url",process.env.AMP_URL,"global"),P8.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
8967
8967
  `);else if(!Jz(J.ampURL))P8.write(`Logging in to ${new URL(J.ampURL).hostname}
8968
8968
  `);let Y=process.env.AMP_API_KEY;if(Y)P8.write(`API key found in environment variable, storing...
8969
8969
  `),await Q.set("apiKey",Y,J.ampURL),P8.write(`API key successfully stored.
@@ -8979,7 +8979,7 @@ This thread belongs to a different user and cannot be continued for security rea
8979
8979
  `)),await X.asyncDispose(),process.exit(0)}catch(G){await X.asyncDispose(),I7(`Failed to ${Y?"archive":"unarchive"} thread: ${G instanceof Error?G.message:String(G)}`)}}async function Cb8(J,Q,Z){let Y=await E7(Q,J);try{let X=iw(Z);if(!X)nw(Z);await Y.threadService.delete(X),P8.write(p1.green(`✓ Thread ${X} deleted
8980
8980
  `)),await Y.asyncDispose(),process.exit(0)}catch(X){await Y.asyncDispose(),I7(`Failed to delete thread: ${X instanceof Error?X.message:String(X)}`)}}async function _b8(J,Q,Z,Y){o7(Y,J);let X=await E7(Q,J);try{let G=iw(Z);if(!G)nw(Z);let K=await RD(G,X),q=gF(K);P8.write(q+`
8981
8981
  `),await X.asyncDispose(),process.exit(0)}catch(G){await X.asyncDispose();let V=`Failed to render thread as markdown: ${G instanceof Error?G.message:String(G)}`;I7(V)}}async function Sb8(J,Q,Z,Y){o7(Y,J);let X=await E7(Q,J);try{let G=iw(Z);if(!G)nw(Z);let K=await RD(G,X),q=JSON.stringify(K,null,2);P8.write(q+`
8982
- `),await X.asyncDispose(),process.exit(0)}catch(G){await X.asyncDispose();let V=`Failed to export thread: ${G instanceof Error?G.message:String(G)}`;I7(V)}}async function kb8(J,Q,Z,Y,X){o7(X,J);let G=await E7(Q,J);try{let V=await W21(Z),K=await RD(V,G),q=Y.typing!==!1,W=parseInt(Y.wpm||"120",10),H=parseInt(Y.messageDelay||"1000",10),z=parseInt(Y.toolProgressDelay||"800",10),F=parseInt(Y.exitDelay||"3",10)*1000,U=Y.indicator!==!1,D=await lw(G),B=K.id;await G.threadStorage.set(B,K);let N=await L4.getOrCreateForThread(D,B);await N.resume();let M=i01.fromWorker(N),L=new n01(G.threadStorage),w=new l91(G.mcpService,Q.settings.getWorkspaceRootPath()),O=c91("0.0.1769716999-gdf283f",G.settingsStorage),A=O61({configService:G.configService,filesystem:C4,spawn:Ah}),R=new w31(G.threadService);try{await xh1({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new f41,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadHistoryService:G.threadHistoryService,threadSyncService:G.threadSyncService,threadID:B,threadFuzzyIndexer:L,worker:M,workerDeps:D,globalWorkerRegistry:R,skillService:G.skillService,configService:G.configService,internalAPIClient:$4,ampURL:Q.ampURL,startNewThread:async()=>M,switchToThread:async()=>M,ideClient:s9,mcpService:G.mcpService,toolboxService:A,mcpTrustHandler:w,showJetBrainsInstaller:!1,updateService:O,isDogfooding:!1,replayMode:{thread:K,typingEnabled:q,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:z,exitDelayMs:F,showIndicator:U},freeTierStatusPromise:Promise.resolve({canUseAmpFree:!0,isDailyGrantEnabled:!1}),features:[],buildTimestamp:"2026-01-29T20:08:22.760Z"})}finally{R.dispose()}await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),await rI(V,Z)}}async function yb8(J,Q,Z,Y,X){o7(Y,J);let G=await E7(Q,J);try{let V=iw(Z);if(!V)nw(Z);let K=V,q=await $4.getUserInfo({},{config:G.configService}),W=q.ok?q.result:null,H=i91(J,W);if(!H&&!X)I7("Must specify either --visibility or --support");if(H&&X)I7("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)I7(H.message);if(H)await G.threadSyncService.updateThreadMeta(K,n91(H)),P8.write(p1.green("✓ ")+`Thread ${K} visibility changed to ${H}.
8982
+ `),await X.asyncDispose(),process.exit(0)}catch(G){await X.asyncDispose();let V=`Failed to export thread: ${G instanceof Error?G.message:String(G)}`;I7(V)}}async function kb8(J,Q,Z,Y,X){o7(X,J);let G=await E7(Q,J);try{let V=await W21(Z),K=await RD(V,G),q=Y.typing!==!1,W=parseInt(Y.wpm||"120",10),H=parseInt(Y.messageDelay||"1000",10),z=parseInt(Y.toolProgressDelay||"800",10),F=parseInt(Y.exitDelay||"3",10)*1000,U=Y.indicator!==!1,D=await lw(G),B=K.id;await G.threadStorage.set(B,K);let N=await L4.getOrCreateForThread(D,B);await N.resume();let M=i01.fromWorker(N),L=new n01(G.threadStorage),w=new l91(G.mcpService,Q.settings.getWorkspaceRootPath()),O=c91("0.0.1769719558-g98dc3a",G.settingsStorage),A=O61({configService:G.configService,filesystem:C4,spawn:Ah}),R=new w31(G.threadService);try{await xh1({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new f41,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadHistoryService:G.threadHistoryService,threadSyncService:G.threadSyncService,threadID:B,threadFuzzyIndexer:L,worker:M,workerDeps:D,globalWorkerRegistry:R,skillService:G.skillService,configService:G.configService,internalAPIClient:$4,ampURL:Q.ampURL,startNewThread:async()=>M,switchToThread:async()=>M,ideClient:s9,mcpService:G.mcpService,toolboxService:A,mcpTrustHandler:w,showJetBrainsInstaller:!1,updateService:O,isDogfooding:!1,replayMode:{thread:K,typingEnabled:q,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:z,exitDelayMs:F,showIndicator:U},freeTierStatusPromise:Promise.resolve({canUseAmpFree:!0,isDailyGrantEnabled:!1}),features:[],buildTimestamp:"2026-01-29T20:51:01.893Z"})}finally{R.dispose()}await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),await rI(V,Z)}}async function yb8(J,Q,Z,Y,X){o7(Y,J);let G=await E7(Q,J);try{let V=iw(Z);if(!V)nw(Z);let K=V,q=await $4.getUserInfo({},{config:G.configService}),W=q.ok?q.result:null,H=i91(J,W);if(!H&&!X)I7("Must specify either --visibility or --support");if(H&&X)I7("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)I7(H.message);if(H)await G.threadSyncService.updateThreadMeta(K,n91(H)),P8.write(p1.green("✓ ")+`Thread ${K} visibility changed to ${H}.
8983
8983
  `);if(X){await RD(K,G);let z=typeof X==="string"?X:void 0;await uT0(G.threadService,K,G.configService,z),P8.write(p1.green("✓ ")+`Thread ${K} has been shared with Amp support. These thread reports will be aggregated and analysed.
8984
8984
  `)}await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),I7(`Failed to update thread: ${V instanceof Error?V.message:String(V)}`)}}async function xb8(J,Q,Z,Y,X,G){o7(G,J);let V=await E7(Q,J);try{let K=await W21(Z);await RD(K,V);let q=Y;if(!q){let B=(await R51()).trimEnd();if(B)q=B}if(!q)I7(`Goal must be provided via stdin or --goal argument.
8985
8985
  Example: echo "Continue the auth work" | amp threads handoff T-xxx
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1769716999-gdf283f",
3
+ "version": "0.0.1769719558-g98dc3a",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {