@sourcegraph/amp 0.0.1764247992-g8296f8 → 0.0.1764248660-g87fd50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +11 -11
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -4101,15 +4101,15 @@ Actual: ${G}`)}async function gG8(J,Q,Y){let{execSync:X}=await import("node:ch
|
|
|
4101
4101
|
${N}`;if(G==="pnpm"&&N.includes("Unable to find the global bin directory"))M+=`
|
|
4102
4102
|
|
|
4103
4103
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
4104
|
-
npm install -g @sourcegraph/amp`;V(Error(M))}},error:(U)=>{if(!H)H=!0,V(Error(`Failed to spawn ${G}: ${U.message}`))},complete:()=>{if(!H)H=!0,q()}})})}L0();L0();async function T61(J,Q){let X=Q||"https://registry.npmjs.org";try{let G=new AbortController,Z=setTimeout(()=>G.abort(),5000),q=await fetch(`${X}/@sourcegraph/amp`,{signal:G.signal});if(clearTimeout(Z),!q.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let V=await q.json(),K=V["dist-tags"]?.latest;if(!K)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=cG8(J,K),H=W<0,z,U;if(V.time){let N=V.time[J],M=V.time[K],L=Date.now();if(N)z=Math.floor((L-new Date(N).getTime())/3600000);if(M)U=Math.floor((L-new Date(M).getTime())/3600000)}return f.info("NPM version comparison",{currentVersion:J,latestVersion:K,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:U}),{hasUpdate:H,latestVersion:K,currentVersion:J,currentVersionAge:z,latestVersionAge:U,source:"npm"}}catch(G){return f.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function cG8(J,Q){let Y=(q)=>{let[V,K]=q.split("-");return{parts:V?.split(".").map(Number)||[],label:K}},X=Y(J),G=Y(Q),Z=Math.max(X.parts.length,G.parts.length);for(let q=0;q<Z;q++){let V=X.parts[q]||0,K=G.parts[q]||0;if(V<K)return-1;if(V>K)return 1}if(X.label===G.label)return 0;if(!X.label&&G.label)return 1;if(X.label&&!G.label)return-1;if(X.label&&G.label)return X.label<G.label?-1:1;return 0}o0();function R61(J,Q){let Y=new y4,X=Y.pipe(o8({shouldCountRefs:!1}));return setImmediate(async()=>{let G=new AV().scoped("update"),Z=X.subscribe({next:(q)=>{G.debug("emit new state",q)}});try{let q=process.env.AMP_TEST_UPDATE_STATUS;if(q){G.debug("using fake update status for testing",{status:q}),await _U(500),Y.next(q);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){G.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let V=await Q.get("updates.mode");if(V==="disabled"){G.debug("checking disabled");return}G.debug("checking",{currentVersion:J,mode:V});let K=uA(),W=await T61(J,K);if(!(W.latestVersion&&W.hasUpdate)){G.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,N=0.5;if(Math.abs(U)<0.5)return G.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:U}),!0}return!1},z=await P61();if(!V)V=z==="pnpm"?"warn":"auto",G.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:V});if(V==="warn"){if(!H())Y.next("update-available");return}if(!z){if(G.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}try{await Tg(W.latestVersion,z);let U=await lB(W.latestVersion),N={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")G.info("success",N),Y.next("updated");else G.warn("success with warning",N),Y.next("updated-with-warning")}catch(U){Y.next("update-error")}}catch(q){G.debug("check failed",{error:q})}finally{await _U(5000),Y.next("hidden"),Z.unsubscribe(),Y.complete()}}),{state:X}}import{stderr as jK}from"node:process";function E86(J){let Q=new RA().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(X)=>{await MR1(X.force||!1,X.verbose||!1,"0.0.
|
|
4104
|
+
npm install -g @sourcegraph/amp`;V(Error(M))}},error:(U)=>{if(!H)H=!0,V(Error(`Failed to spawn ${G}: ${U.message}`))},complete:()=>{if(!H)H=!0,q()}})})}L0();L0();async function T61(J,Q){let X=Q||"https://registry.npmjs.org";try{let G=new AbortController,Z=setTimeout(()=>G.abort(),5000),q=await fetch(`${X}/@sourcegraph/amp`,{signal:G.signal});if(clearTimeout(Z),!q.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let V=await q.json(),K=V["dist-tags"]?.latest;if(!K)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=cG8(J,K),H=W<0,z,U;if(V.time){let N=V.time[J],M=V.time[K],L=Date.now();if(N)z=Math.floor((L-new Date(N).getTime())/3600000);if(M)U=Math.floor((L-new Date(M).getTime())/3600000)}return f.info("NPM version comparison",{currentVersion:J,latestVersion:K,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:U}),{hasUpdate:H,latestVersion:K,currentVersion:J,currentVersionAge:z,latestVersionAge:U,source:"npm"}}catch(G){return f.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function cG8(J,Q){let Y=(q)=>{let[V,K]=q.split("-");return{parts:V?.split(".").map(Number)||[],label:K}},X=Y(J),G=Y(Q),Z=Math.max(X.parts.length,G.parts.length);for(let q=0;q<Z;q++){let V=X.parts[q]||0,K=G.parts[q]||0;if(V<K)return-1;if(V>K)return 1}if(X.label===G.label)return 0;if(!X.label&&G.label)return 1;if(X.label&&!G.label)return-1;if(X.label&&G.label)return X.label<G.label?-1:1;return 0}o0();function R61(J,Q){let Y=new y4,X=Y.pipe(o8({shouldCountRefs:!1}));return setImmediate(async()=>{let G=new AV().scoped("update"),Z=X.subscribe({next:(q)=>{G.debug("emit new state",q)}});try{let q=process.env.AMP_TEST_UPDATE_STATUS;if(q){G.debug("using fake update status for testing",{status:q}),await _U(500),Y.next(q);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){G.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let V=await Q.get("updates.mode");if(V==="disabled"){G.debug("checking disabled");return}G.debug("checking",{currentVersion:J,mode:V});let K=uA(),W=await T61(J,K);if(!(W.latestVersion&&W.hasUpdate)){G.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,N=0.5;if(Math.abs(U)<0.5)return G.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:U}),!0}return!1},z=await P61();if(!V)V=z==="pnpm"?"warn":"auto",G.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:V});if(V==="warn"){if(!H())Y.next("update-available");return}if(!z){if(G.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}try{await Tg(W.latestVersion,z);let U=await lB(W.latestVersion),N={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")G.info("success",N),Y.next("updated");else G.warn("success with warning",N),Y.next("updated-with-warning")}catch(U){Y.next("update-error")}}catch(q){G.debug("check failed",{error:q})}finally{await _U(5000),Y.next("hidden"),Z.unsubscribe(),Y.complete()}}),{state:X}}import{stderr as jK}from"node:process";function E86(J){let Q=new RA().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(X)=>{await MR1(X.force||!1,X.verbose||!1,"0.0.1764248660-g87fd50"),process.exit()});J.addCommand(Q,{hidden:!0});let Y=new RA("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(X)=>{await lG8(X.targetVersion)});J.addCommand(Y)}async function lG8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")jK.write(v4.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
4105
4105
|
|
|
4106
4106
|
`));try{if(!J){jK.write(v4.blue(`Checking for updates...
|
|
4107
|
-
`));let X=uA(),{hasUpdate:G,latestVersion:Z}=await T61("0.0.
|
|
4108
|
-
`));let V=await lB("0.0.
|
|
4107
|
+
`));let X=uA(),{hasUpdate:G,latestVersion:Z}=await T61("0.0.1764248660-g87fd50",X);if(!G){jK.write(v4.green(`✓ Amp CLI is already up to date: ${"0.0.1764248660-g87fd50"} (${"released"} ${"2025-11-27T13:09:46.800Z"})
|
|
4108
|
+
`));let V=await lB("0.0.1764248660-g87fd50");if(V.warning)jK.write(`
|
|
4109
4109
|
`+v4.yellow(V.warning)+`
|
|
4110
4110
|
`);process.exit(0)}if(!Z)jK.write(v4.yellow("[WARN] could not find latest version")),process.exit(0);J=Z}jK.write(v4.blue(`Updating to version ${J}...
|
|
4111
4111
|
`)),await Tg(J,void 0,(X)=>{jK.write(v4.dim(`Running: ${X}
|
|
4112
|
-
`))});let Q="released";jK.write(v4.green(`✓ Successfully updated to version ${J} (${Q} ${"2025-11-
|
|
4112
|
+
`))});let Q="released";jK.write(v4.green(`✓ Successfully updated to version ${J} (${Q} ${"2025-11-27T13:09:46.800Z"})
|
|
4113
4113
|
`));let Y=await lB(J);if(Y.warning)jK.write(`
|
|
4114
4114
|
`+v4.yellow(Y.warning)+`
|
|
4115
4115
|
`);process.exit(0)}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);jK.write(v4.red.bold("Error: ")+Y+`
|
|
@@ -4716,7 +4716,7 @@ exit code: ${Z}`,new H1({color:X.foreground,dim:!0,italic:!0})));if(q)V.push(new
|
|
|
4716
4716
|
(${q}, command and output not shown to agent)`,new H1({color:X.foreground,dim:!0,italic:!0})));else if(Q.hidden)V.push(new J1(`
|
|
4717
4717
|
|
|
4718
4718
|
(Command and output not shown to agent)`,new H1({color:X.foreground,dim:!0,italic:!0})));if(V.length===0)return null;return new d1({text:new J1("",void 0,V),selectable:!0})}function h81(J,Q){let Y=x6.of(Q),X=QN(J);if(X?.visibility===JN)return Y.app.shellModeHidden;if(X?.visibility===J81)return Y.app.shellMode;return O1.green}function lJ6(J,Q,Y){if(Q.length===0)return null;let G=x6.maybeOf(J)?.colors??d4.of(J).colorScheme,Z=[new J1("Images: ",new H1({color:G.foreground,dim:!0}))];for(let q=0;q<Q.length;q++)if(Z.push(new J1(`[image ${q+1}]`,Y)),q<Q.length-1)Z.push(new J1(" ",new H1({color:G.foreground,dim:!0})));return new c6({padding:f0.only({}),child:new d1({text:new J1("",void 0,Z),selectable:!0})})}function J_1(J,Q,Y){let X=[];if(X.push(new J1(J,Q)),Y)X.push(new J1(" (interrupted)",new H1({color:O1.yellow,italic:!0})));return new d1({text:new J1("",void 0,X),selectable:!0})}class jC extends I6{props;constructor(J){super();this.props=J}build(J){let Q=this.props.message,X=x6.of(J).colors,G="",Z,q,V=null;if(Q.role==="info"){let z=el(Q);if(!z)return new J6;G=`${Q81(z.hidden??!1)} ${z.args.cmd}`;let N=h81(G,J);Z=N,q=N,V=Y_1(J,z)}else G=f2(Q.content).trim(),q=Q.interrupted?O1.yellow:X.success,Z=Q.interrupted?O1.yellow:h81(G,J);let K=new H1({color:q,italic:!0}),W=[];if(Q.role==="user"){let z=Q.content.filter((N)=>N.type==="image"),U=lJ6(J,z,K);if(U)W.push(U)}if(G){if(W.length>0)W.push(new U0({height:1}));W.push(J_1(G,K,Q.role==="user"?Q.interrupted:void 0))}if(V){if(W.length>0)W.push(new U0({height:1}));W.push(V)}let H;if(W.length===0)H=new J6;else if(W.length===1)H=W[0];else H=new s0({mainAxisSize:"min",crossAxisAlignment:"start",children:W});return new J6({decoration:{border:new p4(void 0,void 0,void 0,new P4(Z,2,"solid"))},padding:f0.only({left:1}),child:H})}}class b81 extends I6{props;constructor(J){super();this.props=J}build(J){let Q=x6.of(J),Y=Q.colors,X=this.props.message,G="",Z=cJ6,q=null,V=el(X);if(V)G=`${V.hidden?"$$":"$"} ${V.args.cmd}`,Z=h81(G,J),q=Y_1(J,V);else G=f2(X.content).trim(),Z=h81(G,J);let K=new H1({color:Z,italic:!0}),W=[];if(X.role==="user"){let A=X.content.filter((P)=>P.type==="image"),E=lJ6(J,A,K);if(E)W.push(E)}if(G){if(W.length>0)W.push(new U0({height:1}));W.push(J_1(G,K,X.role==="user"?X.interrupted:void 0))}if(q){if(W.length>0)W.push(new U0({height:1}));W.push(q)}let H;if(W.length===0)H=new J6;else if(W.length===1)H=W[0];else H=new s0({mainAxisSize:"min",crossAxisAlignment:"start",children:W});let z=new J6({decoration:{border:p4.all(new P4(Z,2,"solid"))},padding:f0.only({left:1,right:1}),width:1/0,child:H});if(this.props.isShowingRestoreConfirmation){let L=new nJ6({affectedFiles:this.props.affectedFiles,onConfirm:this.props.onRestoreConfirm,onCancel:this.props.onRestoreCancel});return new s0({children:[new Q_1,new U0({height:1}),L,new U0({height:1}),new JG({forceDim:!0,child:new J6({decoration:{border:new p4(void 0,void 0,void 0,new P4(Z,2,"solid"))},padding:f0.only({left:1,right:1}),width:1/0,child:H})})]})}if(this.props.isShowingEditConfirmation){let L=new aJ6({affectedFiles:this.props.affectedFiles,onConfirm:this.props.onEditConfirm,onCancel:this.props.onEditCancel}),A=this.props.pendingEditText??G,E=J_1(A,K,void 0),P=new s0({mainAxisSize:"min",crossAxisAlignment:"start",children:[E,new U0({height:1}),L]});return new J6({decoration:{border:p4.all(new P4(Z,2,"solid"))},padding:f0.only({left:1,right:1}),width:1/0,child:P})}let U=Q.app,N=[new J1("e",new H1({color:U.keybind})),new J1(" to edit",new H1({color:Y.foreground,dim:!0}))],M=new v41({child:new e5({children:[z,new u3({left:2,right:0,bottom:0,child:new d1({text:new J1("",void 0,N)})})]})});if(!this.props.isFirstMessage)return new c6({padding:f0.only({}),child:M});return new c6({padding:f0.only({}),child:new s0({mainAxisSize:"min",crossAxisAlignment:"start",children:[new Q_1,new U0({height:1}),M]})})}}class Q_1 extends I6{build(J){let Q=x6.of(J),Y=Q.colors,X=Q.app,G=[new J1(" r",new H1({color:X.keybind})),new J1(" to restore, ",new H1({color:Y.foreground,dim:!0})),new J1("f",new H1({color:X.keybind})),new J1(" to fork ",new H1({color:Y.foreground,dim:!0}))];return new e5({children:[new J6({decoration:{border:new p4(new P4(Y.selection,2,"solid"),void 0,void 0,void 0)},width:1/0,height:1}),new u3({left:0,right:0,top:0,child:new H8({child:new d1({text:new J1("",void 0,G)})})})]})}}function iJ6(J,Q){if(Q.length===0)return null;let X=x6.of(J).colors,G=[];for(let Z=0;Z<Q.length;Z++){let q=Q[Z];if(Z>0)G.push(new J1(`
|
|
4719
|
-
`));G.push(new J1(` • ${q}`,new H1({color:X.foreground,dim:!0})))}return new d1({text:new J1("",void 0,G)})}class nJ6 extends I6{props;constructor(J){super();this.props=J}build(J){let Q=this.props.affectedFiles,Y=Q.length>0,G=[new d1({text:new J1(Y?"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.",new H1({color:O1.yellow,bold:!0}))}),new U0({height:1})],Z=iJ6(J,Q);if(Z)G.push(Z),G.push(new U0({height:1}));let q=[{value:"confirm",label:Y?"Delete and restore":"Delete"},{value:"cancel",label:"Cancel"}];return G.push(new cY({options:q,onSelect:(V)=>{if(V==="confirm")this.props.onConfirm();else this.props.onCancel()},padding:f0.all(0),showDismissalMessage:!1,enableMouseInteraction:!1,showBorder:!1})),new s0({mainAxisSize:"min",crossAxisAlignment:"start",children:G})}}class aJ6 extends I6{props;constructor(J){super();this.props=J}build(J){let Q=this.props.affectedFiles,Y=[],X=iJ6(J,Q);if(X)Y.push(new d1({text:new J1("This will restore the following files:",new H1({color:O1.yellow,bold:!0}))})),Y.push(new U0({height:1})),Y.push(X),Y.push(new U0({height:1}));let G=[{value:"confirm",label:"Confirm edit"},{value:"cancel",label:"Cancel"}];return Y.push(new cY({options:G,onSelect:(Z)=>{if(Z==="confirm")this.props.onConfirm();else this.props.onCancel()},padding:f0.all(0),showDismissalMessage:!1,enableMouseInteraction:!1,showBorder:!1})),new s0({mainAxisSize:"min",crossAxisAlignment:"start",children:Y})}}class g81 extends G6{initialText;onSubmitted;message;constructor(J){super();this.initialText=J.initialText,this.onSubmitted=J.onSubmitted,this.message=J.message}createState(){return new oJ6}}class oJ6 extends X6{controller=new fZ;currentShellModeStatus;initState(){this.controller.text=this.widget.initialText,this.controller.addListener(this.textChangeListener);let J=QN(this.widget.initialText);this.currentShellModeStatus=J?.visibility}dispose(){this.controller.removeListener(this.textChangeListener),this.controller.dispose(),super.dispose()}textChangeListener=()=>{let J=this.controller.text,Y=QN(J)?.visibility;if(Y!==this.currentShellModeStatus)this.currentShellModeStatus=Y,this.setState(()=>{})};handleSubmit=(J)=>{this.widget.onSubmitted(J)};build(J){let Q=x6.of(J),Y=Q.colors,X=Q.app,G=this.currentShellModeStatus?U26(Q,this.currentShellModeStatus):cJ6,Z=null,q=this.widget.message&&el(this.widget.message);if(q)Z=Y_1(J,q);let V=new NO({controller:this.controller,triggers:[],ampURL:"",onSubmitted:this.handleSubmit,theme:Y,placeholder:"",enabled:!0,autofocus:!0,shellPromptRules:Y81(Q),showMenuBelow:!1,imageAttachments:[],minLines:1,textColor:G}),K=[];if(K.push(V),Z)K.push(new U0({height:1})),K.push(Z);let W;if(K.length===1)W=K[0];else W=new s0({mainAxisSize:"min",crossAxisAlignment:"start",children:K});let H=new J6({decoration:{border:p4.all(new P4(G,2,"solid"))},padding:f0.only({left:1,right:1}),child:W}),z=[];if(this.currentShellModeStatus===JN)z.push(new J1("shell mode (incognito)",new H1({color:Q.app.shellModeHidden})));else if(this.currentShellModeStatus===J81)z.push(new J1("shell mode",new H1({color:Q.app.shellMode})));else z.push(new J1("esc",new H1({color:X.keybind})),new J1(" to cancel",new H1({color:Y.foreground,dim:!0})));let U=new u3({left:2,bottom:0,child:new d1({text:new J1("",void 0,z)})});return new v41({child:new e5({children:[H,U]})})}}class m81 extends a7{}class u81 extends a7{}class X_1 extends a7{}class G_1 extends a7{}class Z_1 extends a7{}class $_1 extends a7{}class q_1 extends a7{}class V_1 extends a7{}var KB8=0;function WB8(J,Q,Y){let G=x6.maybeOf(J)?.colors??d4.of(J).colorScheme,q=Q.trimStart().startsWith("You're absolutely right"),V=new i7(`${Y}-text`),K=[];if(q)K.push(new mS1({key:V,markdown:Q,defaultColor:G.foreground}));else K.push(new x7({key:V,markdown:Q}));if(K.length===1)return K[0];return new s0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:K})}function HB8(J,Q){let X=d4.of(J).colorScheme;if(Q.summary.type!=="message")return new J6;return new s0({crossAxisAlignment:"start",children:[new d1({text:new J1("Summary:",new H1({color:X.foreground,dim:!0,bold:!0,italic:!0})),selectable:!0}),new U0({height:1}),new x7({markdown:Q.summary.summary,styleScheme:{text:new H1({color:X.foreground,dim:!0,italic:!0}),inlineCode:new H1({color:X.foreground,dim:!0,italic:!0}),codeBlock:new H1({color:X.foreground,dim:!0,italic:!0}),tableBorder:X.foreground,link:new H1({color:X.foreground,dim:!0,italic:!0}),syntaxHighlight:{keyword:X.foreground,string:X.foreground,number:X.foreground,comment:X.foreground,function:X.foreground,variable:X.foreground,type:X.foreground,operator:X.foreground}}})]})}class p81 extends G6{items;subagentToolsByParentID;controller;autofocus;onNewMessage;showScrollbar;onCopy;onMessageEditSubmit;onShellCommandSubmit;onMessageRestoreSubmit;onMessageForkSubmit;getAffectedFiles;thread;focusNode;onDismissFocus;isInSelectionMode=!1;get userMessageIndices(){let J=[];for(let Q=0;Q<this.items.length;Q++){let Y=this.items[Q];if(Y?.type==="message"){if(Y.message.role==="user"||sE(Y.message))J.push(Q)}}return J}constructor({key:J,items:Q,subagentToolsByParentID:Y={},controller:X,autofocus:G=!1,onNewMessage:Z,showScrollbar:q=!0,onCopy:V,onMessageEditSubmit:K,onMessageRestoreSubmit:W,onMessageForkSubmit:H,getAffectedFiles:z,thread:U,focusNode:N,onDismissFocus:M,isInSelectionMode:L=!1}){super(J?{key:J}:{});this.items=Q,this.subagentToolsByParentID=Y,this.controller=X,this.autofocus=G,this.onNewMessage=Z,this.showScrollbar=q,this.onCopy=V,this.onMessageEditSubmit=K,this.onMessageRestoreSubmit=W,this.onMessageForkSubmit=H,this.getAffectedFiles=z,this.thread=U,this.focusNode=N,this.onDismissFocus=M,this.isInSelectionMode=L}createState(){return new rJ6}}class rJ6 extends X6{_controller=null;_isDisposed=!1;_thinkingBlockStates=new Map;_globalToggleListener;_streamingIndexes=new Set;_viewportHeight=25;_widgetCache=new Map;_lastCostDisplayState=null;_selectedUserMessageOrdinal=null;_editingMessageOrdinal=null;_isShowingRestoreConfirmation=!1;_isShowingEditConfirmation=!1;_pendingEditText=null;_affectedFiles=[];get controller(){return this._controller}dismiss(){J9.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._selectedUserMessageOrdinal,Q=J!==null?this.getUserMessageIndexFromOrdinal(J):null;this.setState(()=>{if(Q!=null)this._widgetCache.delete(Q);this._selectedUserMessageOrdinal=null})}_selectUserMessageByOrdinal(J){let Q=this._selectedUserMessageOrdinal,Y=J,X=Q!==null?this.getUserMessageIndexFromOrdinal(Q):null,G=this.getUserMessageIndexFromOrdinal(Y);if(X!==null)this._widgetCache.delete(X);if(G!==null)this._widgetCache.delete(G);if(this.setState(()=>{this._selectedUserMessageOrdinal=Y}),G!==null)J9.instance.addPostFrameCallback(()=>{this.scrollToMessage(G,{animated:!0,offset:KB8,edge:"top",duration:200})})}_selectEditingUserMessageByOrdinal(J){let Q=this._editingMessageOrdinal,Y=J,X=Q!==null?this.getUserMessageIndexFromOrdinal(Q):null,G=Y!==null?this.getUserMessageIndexFromOrdinal(Y):null;if(X!==null)this._widgetCache.delete(X);if(G!==null)this._widgetCache.delete(G);this.setState(()=>{this._editingMessageOrdinal=Y})}getUserMessageIndexFromOrdinal(J){return this.widget.userMessageIndices[J]??null}getOrdinalFromUserMessageIndex(J){let Y=this.widget.userMessageIndices.indexOf(J);return Y>=0?Y:null}getLatestUserMessageOrdinal(){let J=this.widget.userMessageIndices;return J.length>0?J.length-1:null}navigateToUserMessage(J){let Q=this._getUserCount(),Y=J==="up"?this._navigateUp(this._selectedUserMessageOrdinal,Q):this._navigateDown(this._selectedUserMessageOrdinal,Q);if(Y===null&&J==="down"){this._controller?.animateToBottom(100),this._clearSelectedUserMessage(),this.dismiss();return}if(Y!==null)this._selectUserMessageByOrdinal(Y)}handleNavigateUserMessageUp=()=>{if(this._editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("up"),"handled"};handleNavigateUserMessageDown=()=>{if(this._editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("down"),"handled"};handleEscape=()=>{if(this._editingMessageOrdinal!==null)return this.setState(()=>{let J=this._ordinalToIndex(this.widget.userMessageIndices,this._editingMessageOrdinal);if(J!=null)this._widgetCache.delete(J);this._editingMessageOrdinal=null}),"handled";else if(this._selectedUserMessageOrdinal!==null)return this._clearSelectedUserMessage(),this.setState(()=>{this._editingMessageOrdinal=null}),this.dismiss(),this._controller?.animateToBottom(100),"handled";return"ignored"};handleScrollDown=()=>{if(this._selectedUserMessageOrdinal!==null)return this._controller?.scrollDown(1),"handled";return"ignored"};handleScrollUp=()=>{if(this._selectedUserMessageOrdinal!==null)return this._controller?.scrollUp(1),"handled";return"ignored"};handleEditMessage=()=>{if(this._selectedUserMessageOrdinal!==null)return this._selectEditingUserMessageByOrdinal(this._selectedUserMessageOrdinal),"handled";return"ignored"};handleRestoreMessage=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(J===0)return"ignored";let Q=this.widget.items[J];if(Q?.type==="message"&&(Q.message.role==="user"||sE(Q.message)))this.showRestoreConfirmation(J)}return"handled"}return"ignored"};async showRestoreConfirmation(J){let Q=[];if(this.widget.getAffectedFiles)try{Q=await this.widget.getAffectedFiles(J)}catch{Q=[]}if(this.setState(()=>{this._widgetCache.clear(),this._isShowingRestoreConfirmation=!0,this._affectedFiles=Q}),this.controller.atBottom)J9.instance.addPostFrameCallback(()=>{this.scrollToMessage(J)})}handleRestoreConfirm=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(J===0)return"ignored";let Q=this.widget.items[J];if(Q?.type==="message"&&(Q.message.role==="user"||Q.message.role==="info"))this.widget.onMessageRestoreSubmit?.(Q.message),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._isShowingRestoreConfirmation=!1,this._affectedFiles=[]}),this.dismiss()}return"handled"}return"ignored"};handleRestoreCancel=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(this.setState(()=>{this._widgetCache.clear(),this._isShowingRestoreConfirmation=!1,this._affectedFiles=[]}),this.controller.atBottom)J9.instance.addPostFrameCallback(()=>{this.scrollToMessage(J)})}}return"handled"};handleForkMessage=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){let Q=this.widget.items[J];if(Q?.type==="message"&&(Q.message.role==="user"||sE(Q.message))){if(J===0)return"ignored";this.widget.onMessageForkSubmit?.(Q.message),this._clearSelectedUserMessage(),this.setState(()=>{}),this.dismiss()}}return"handled"}return"ignored"};handleEditConfirmationRequest=async(J)=>{if(J.trim()==="")return;if(this._editingMessageOrdinal!==null){let Q=this._ordinalToIndex(this.widget.userMessageIndices,this._editingMessageOrdinal);if(Q!=null){let Y=[];if(this.widget.getAffectedFiles)try{Y=await this.widget.getAffectedFiles(Q)}catch{Y=[]}if(this.setState(()=>{this._widgetCache.clear(),this._isShowingEditConfirmation=!0,this._pendingEditText=J,this._affectedFiles=Y,this._editingMessageOrdinal=null}),this.controller.atBottom)J9.instance.addPostFrameCallback(()=>{this.scrollToMessage(Q)})}}};handleEditConfirm=()=>{if(this._selectedUserMessageOrdinal!==null&&this._pendingEditText!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){let Q=this.widget.items[J];if(Q?.type==="message"&&(Q.message.role==="user"||Q.message.role==="info"))this.widget.onMessageEditSubmit?.(Q.message,this._pendingEditText),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._isShowingEditConfirmation=!1,this._pendingEditText=null,this._affectedFiles=[]}),this.dismiss(),this.controller.animateToBottom(100)}}};handleEditCancel=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(this.setState(()=>{this._widgetCache.clear(),this._isShowingEditConfirmation=!1,this._pendingEditText=null,this._affectedFiles=[]}),this.controller.atBottom)J9.instance.addPostFrameCallback(()=>{this.scrollToMessage(J)})}}};_signatureFor(J){if(J.type==="message"){let Q=J.message;if(Q.role==="user"){let Y=f2(Q.content),X=Q.content.filter((G)=>G.type==="image").length;return`${J.id}|user|${Q.interrupted?1:0}|${X}|${Y}`}else if(Q.role==="assistant"){let Y=f2(Q.content),X=Q.state.type==="complete",G=Q.content.filter((K)=>K.type==="thinking"),Z=Q.content.filter((K)=>K.type==="tool_use"),q=Q.usage,V=q?`${q.credits??""}|${q.inputTokens}|${q.outputTokens}|${q.cacheCreationInputTokens??""}|${q.cacheReadInputTokens??""}|${q.model??""}`:"no-usage";return`${J.id}|assistant|${X?1:0}|${G.length}|${Z.length}|${Y}|${V}`}else{let X=Q.content.map((G)=>G.type).join(",");return`${J.id}|info|${X}`}}else{let Y=J.toolResult.run.status,X=this.widget.thread&&Y==="done"?ts(this.widget.thread,J.toolUse.id):void 0;return`${J.id}|tool|${Y}|${J.toolUse.id}|${X??""}`}}getThinkingBlockExpanded(J,Q){let Y=`${J}-${Q}`;return this._thinkingBlockStates.get(Y)??OJ.instance.allExpanded}toggleThinkingBlock=(J,Q)=>{return(Y)=>{let X=`${J}-${Q}`;this.setState(()=>{this._thinkingBlockStates.set(X,Y),this._widgetCache.delete(J)})}};buildThinkingBlock(J,Q,Y,X){let G=Y===X.content.length-1,Z=X.state?.type==="streaming"&&G;return new FO({key:new i7(`thinking-${Q}-${Y}`),thinkingBlock:J,expanded:this.getThinkingBlockExpanded(Q,Y),onToggle:this.toggleThinkingBlock(Q,Y),isStreaming:Z})}buildAssistantMessageWidget(J,Q,Y,X){let G=Q.content.map((U,N)=>({block:U,index:N})).filter((U)=>U.block.type==="thinking"&&_81(U.block.thinking).length>0),Z=G.some(({block:U})=>_81(U.thinking).length>0),q=Q.content.filter((U)=>U.type==="text"),V=[];if(V.push(...G.map(({block:U,index:N})=>this.buildThinkingBlock(U,Y,N,Q))),Z&&q.length>0)V.push(new U0({height:1}));let K=f2(q);if(K.trim())V.push(WB8(J,K,X));let W=Dz(J),H=Q.usage!=null&&(Q.usage.inputTokens>0||Q.usage.outputTokens>0);if(W&&H){let N=x6.maybeOf(J)?.colors??d4.of(J).colorScheme,M=v76(Q.usage);V.push(new c6({padding:f0.only({top:1}),child:new d1({text:new J1(M,new H1({color:N.foreground,dim:!0}))})}))}let z;if(V.length===0)z=new J6;else if(V.length===1)z=V[0];else z=new s0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:V});return z}buildThreadItemWidget(J,Q,Y){let X=new i7(`thread-item-${Q.id}`);if(Q.type==="message"){let G=Q.message;if(G.role==="user"){if(!this.widget.isInSelectionMode)return new jC({message:G,isFirstMessage:Y>0});let Z=this.getOrdinalFromUserMessageIndex(Y);if(Z===null)return new jC({message:G,isFirstMessage:Y>0});if(this._editingMessageOrdinal===Z)return new g81({initialText:f2(G.content),message:G,onSubmitted:(V)=>{this.handleEditConfirmationRequest(V)}});if(this._selectedUserMessageOrdinal===Z)return new b81({message:G,isFirstMessage:Y>0,isShowingRestoreConfirmation:this._isShowingRestoreConfirmation,isShowingEditConfirmation:this._isShowingEditConfirmation,affectedFiles:this._affectedFiles,pendingEditText:this._pendingEditText??void 0,onRestoreConfirm:()=>{this.handleRestoreConfirm()},onRestoreCancel:()=>{this.handleRestoreCancel()},onEditConfirm:()=>{this.handleEditConfirm()},onEditCancel:()=>{this.handleEditCancel()}});else return new jC({message:G,isFirstMessage:Y>0})}else if(G.role==="assistant"){let Z=this.buildAssistantMessageWidget(J,G,Y,Q.id);return new J6({key:X,child:Z})}else{let Z=G,q=[],V=this.getOrdinalFromUserMessageIndex(Y),K=this.widget.isInSelectionMode&&V!==null&&this._selectedUserMessageOrdinal===V;for(let W of Z.content)if(W.type==="manual_bash_invocation")if(this._editingMessageOrdinal===V){let z=`${Q81(W.hidden??!1)}${W.args.cmd}`;q.push(new g81({initialText:z,message:Z,onSubmitted:(U)=>{this.handleEditConfirmationRequest(U)}}))}else if(!this.widget.isInSelectionMode||!K)q.push(new jC({message:Z,isFirstMessage:Y>0}));else q.push(new b81({message:Z,isFirstMessage:Y>0,isShowingRestoreConfirmation:this._isShowingRestoreConfirmation,isShowingEditConfirmation:this._isShowingEditConfirmation,affectedFiles:this._affectedFiles,pendingEditText:this._pendingEditText??void 0,onRestoreConfirm:()=>{this.handleRestoreConfirm()},onRestoreCancel:()=>{this.handleRestoreCancel()},onEditConfirm:()=>{this.handleEditConfirm()},onEditCancel:()=>{this.handleEditCancel()}}));else if(W.type==="summary"&&W.summary.type==="message")q.push(HB8(J,W));if(q.length===0)return new J6;if(q.length===1)return q[0];return new s0({crossAxisAlignment:"stretch",children:q})}}else{let G=new Oz({toolUse:Q.toolUse,toolRun:Q.toolResult.run,subagentTools:this.widget.subagentToolsByParentID[Q.toolUse.id],thread:this.widget.thread});return new J6({key:X,child:G})}return new J6}initState(){if(super.initState(),this._controller=this.widget.controller||new p3,this._globalToggleListener=()=>{this.setState(()=>{this._thinkingBlockStates.clear(),this._widgetCache.clear()})},OJ.instance.addListener(this._globalToggleListener),this.widget.items.length>0)J9.instance.requestFrame()}didUpdateWidget(J){if(super.didUpdateWidget(J),!J.isInSelectionMode&&this.widget.isInSelectionMode){this.widget.focusNode?.requestFocus();let Y=this.getLatestUserMessageOrdinal();if(Y!==null)this._selectUserMessageByOrdinal(Y)}if(J.items===this.widget.items)return;let Q=Math.min(J.items.length,this.widget.items.length);for(let Y=0;Y<Q;Y++){let X=J.items[Y],G=this.widget.items[Y];if(X&&G){if(X.type!==G.type){this._widgetCache.delete(Y);continue}if(X.type==="toolResult"&&G.type==="toolResult"){let Z=X.toolResult.run,q=G.toolResult.run;if(Z.status!==q.status||"result"in Z!=="result"in q||"error"in Z!=="error"in q)this._widgetCache.delete(Y)}if(X.type==="message"&&G.type==="message"){let Z=X.message,q=G.message;if(Z.content!==q.content)this._widgetCache.delete(Y)}}}if(this.widget.items.length<J.items.length)this._cleanupOrphanedCacheEntries();this._updateStreamingIndexes();for(let Y of this._streamingIndexes)if(Y>=this.widget.items.length)this._streamingIndexes.delete(Y)}_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 Y=this._isMessageStreaming(Q);if(Y&&!this._streamingIndexes.has(J))this._streamingIndexes.add(J);else if(!Y&&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._globalToggleListener)OJ.instance.removeListener(this._globalToggleListener);if(!this.widget.controller)this._controller?.dispose();this.widget.focusNode?.dispose(),super.dispose()}build(J){let Q=x6.of(J),Y=Dz(J);if(this._lastCostDisplayState!==null&&this._lastCostDisplayState!==Y)this._widgetCache.clear();this._lastCostDisplayState=Y;let X=this._getTotalItemCount(J),G=[];for(let U=0;U<X;U++)if(G.push(this._buildItemAtIndex(J,U)),U<X-1)G.push(new U0({height:1}));let Z=new O2({controller:this._controller,autofocus:this.widget.autofocus,position:"bottom",child:new s0({key:new i7("message-list-column"),crossAxisAlignment:"start",children:G})}),V=[new c6({padding:f0.only({left:2,right:this.widget.showScrollbar?3:2,bottom:1}),child:Z})];if(this.widget.showScrollbar&&this._controller){let U=new XG({controller:this._controller,getScrollInfo:()=>this._getScrollbarInfo(),thickness:1,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack});V.push(new u3({right:1,top:0,bottom:0,child:new U0({width:1,child:U})}))}let K=new e5({children:V}),W=new tA({key:new i7("message-view-selection-area"),child:K,onCopy:this.widget.onCopy}),H=new Map([[m81,new Q9(this.handleNavigateUserMessageUp)],[u81,new Q9(this.handleNavigateUserMessageDown)],[X_1,new Q9(this.handleEscape)],[G_1,new Q9(this.handleScrollDown)],[Z_1,new Q9(this.handleScrollUp)],[$_1,new Q9(this.handleEditMessage)],[q_1,new Q9(this.handleRestoreMessage)],[V_1,new Q9(this.handleForkMessage)]]),z=new Map([[B4.key("Tab"),new m81],[B4.shift("Tab"),new u81],[B4.key("Escape"),new X_1],[B4.key("j"),new G_1],[B4.key("k"),new Z_1],[B4.key("e"),new $_1],[B4.key("r"),new q_1],[B4.key("f"),new V_1]]);if(!c2())z.set(B4.key("ArrowUp"),new m81),z.set(B4.key("ArrowDown"),new u81);if(this.widget.focusNode)return new Y9({focusNode:this.widget.focusNode,child:new cQ({actions:H,child:new Pq({shortcuts:z,focusNode:this.widget.focusNode,child:W})})});return W}_getTotalItemCount(J){return this.widget.items.length}_shouldDimItem(J){if(this._isShowingRestoreConfirmation||this._isShowingEditConfirmation){let Q=this._selectedUserMessageOrdinal;if(Q===null)return!1;let Y=this.getUserMessageIndexFromOrdinal(Q);if(Y===null)return!1;return J>Y}if(this._editingMessageOrdinal!==null){let Q=this.getUserMessageIndexFromOrdinal(this._editingMessageOrdinal);if(Q===null)return!1;return J>Q}return!1}_buildItemAtIndex(J,Q){let Y=this.widget.items[Q];if(!Y)return new J6;let X=Y.type==="message"&&this._isMessageStreaming(Y),G=Y.type==="toolResult"&&(Y.toolResult.run.status==="queued"||Y.toolResult.run.status==="in-progress")&&!("result"in Y.toolResult.run)&&!("error"in Y.toolResult.run),Z=this._shouldDimItem(Q);if(!X&&!G){let K=`${this._signatureFor(Y)}|dim:${Z?1:0}`,W=this._widgetCache.get(Q);if(W&&W.sig===K)return W.widget;let H=this.buildThreadItemWidget(J,Y,Q),z=Z?new JG({forceDim:!0,child:H}):H;return this._widgetCache.set(Q,{sig:K,widget:z}),z}let V=this.buildThreadItemWidget(J,Y,Q);return Z?new JG({forceDim:!0,child:V}):V}onNewMessage(){if(this._isDisposed)return;this.widget.onNewMessage?.()}scrollToTop(){if(this._isDisposed||!this._controller)return;this._controller.scrollToTop()}scrollToMessage(J,{animated:Q=!1,offset:Y=0,edge:X="top",duration:G}={}){if(this._isDisposed||!this._controller)return!1;let Z=this._getMessageRelativeOffset(J,X);if(Z===null)return!1;let q=Z-Y;if(Q)this._controller.animateTo(q,G);else this._controller.jumpTo(q);return!0}_getColumnElement(){let J=this.context.element;if(!J)return null;let Q=new i7("message-list-column"),Y=(X)=>{if(X.widget.key?.equals(Q))return X;for(let G of X.children){let Z=Y(G);if(Z)return Z}return null};return Y(J)}_getMessageRelativeOffset(J,Q){let Y=this._getColumnElement();if(!Y)return null;let X=J*2,G=Y.children[X];if(!G?.renderObject)return null;let Z=G.renderObject,q=Y.renderObject;if(!q)return null;let V=Z.localToGlobal({x:0,y:0}),K=q.localToGlobal({x:0,y:0}),W=0;if(Q==="bottom")W=Z.size.height;return V.y+W-K.y}_getScrollbarInfo(){let J=this._controller?.maxScrollExtent??0,Q=this._getViewportHeight(),Y=this._controller?.offset??0,X=J+Q;return{totalContentHeight:Math.max(X,0),viewportHeight:Math.max(Q,1),scrollOffset:Math.max(Y,0)}}}class K_1 extends I6{thread;onExecute;onEdit;constructor({thread:J,onExecute:Q,onEdit:Y}){super();this.thread=J,this.onExecute=Q,this.onEdit=Y}build(J){if(this.thread.agentMode!=="plan")return new U0({width:0,height:0});let Q=x6.of(J),Y=Q.colors,X=vU(this.thread);if(!cA(this.thread))return new U0({width:0,height:0});let Z=[];return Z.push(new Q4({mainAxisSize:"max",mainAxisAlignment:"spaceBetween",crossAxisAlignment:"center",children:[new d1({text:new J1("\uD83D\uDCCB Plan",new H1({color:Y.foreground,bold:!0})),textAlign:"left"}),new Q4({mainAxisSize:"min",children:[new _8({onClick:this.onExecute,cursor:"pointer",child:new d1({text:new J1("[Execute]",new H1({color:Y.success})),textAlign:"right"})}),new U0({width:1,height:1}),new _8({onClick:this.onEdit,cursor:"pointer",child:new d1({text:new J1("[Edit]",new H1({color:Y.secondary})),textAlign:"right"})})]})]})),Z.push(l5.vertical(1)),Z.push(new x7({markdown:X,textAlign:"left",styleScheme:{text:new H1({color:Y.mutedForeground,dim:!0}),inlineCode:new H1({color:Y.secondary,bold:!0}),codeBlock:new H1({color:Y.mutedForeground,dim:!0}),tableBorder:Y.border,link:new H1({color:Y.secondary,underline:!0}),syntaxHighlight:Q.app.syntaxHighlight}})),Z.push(l5.vertical(1)),Z.push(new d1({text:new J1("",void 0,[new J1("Ctrl+O ",new H1({color:Y.secondary})),new J1("→ Execute Plan",new H1({color:Y.mutedForeground,dim:!0}))]),textAlign:"left"})),new s0({mainAxisSize:"min",mainAxisAlignment:"start",crossAxisAlignment:"start",children:Z})}}class d81 extends G6{props;constructor(J){super();this.props=J}createState(){return new sJ6}}class sJ6 extends X6{viewportHeight=1;scrollListenerAttached=!1;initState(){if(!this.scrollListenerAttached)this.widget.props.controller.addListener(()=>{this.updateViewportHeight()}),this.scrollListenerAttached=!0}build(J){let{thread:Q,onExecute:Y,onEdit:X,controller:G,appTheme:Z}=this.widget.props;return new Q4({crossAxisAlignment:"stretch",children:[new z4({child:new O2({controller:G,autofocus:!1,child:new K_1({thread:Q,onExecute:Y,onEdit:X})})}),new XG({controller:G,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let{maxScrollExtent:q,offset:V}=G,K=this.viewportHeight,W=q+K;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(K,1),scrollOffset:Math.max(V,0)}}})]})}updateViewportHeight(){let J=this.getViewportHeight();if(J!==this.viewportHeight)this.viewportHeight=J}getViewportHeight(){let J=this.context.findRenderObject();if(!J)return this.viewportHeight;let Q=(X,G=0)=>{if(X&&"size"in X&&"children"in X){let Z=X.children||[];for(let q of Z){if(q&&"size"in q){let K=q.size;if(typeof K?.height==="number"&&K.height>0)return K.height}let V=Q(q,G+1);if(V>0)return V}}return 0},Y=Q(J);if(Y>0)return Y;if("size"in J){let X=J.size;if(typeof X?.height==="number"&&X.height>0)return X.height}return this.viewportHeight}}class c81 extends I6{agentMode;constructor(J={}){super(J.key?{key:J.key}:{});this.agentMode=J.agentMode}build(J){let Y=d4.of(J).colorScheme,G=x6.of(J).app,q=U8.of(J).capabilities.animationSupport,K=this.agentMode==="smart"?{type:"opus",text:"Smart mode now uses Claude Opus 4.5.",url:"https://ampcode.com/news/try-opus"}:{type:"prompt",text:""},W=K.type==="quote"?new H1({color:Y.foreground,dim:!0}):K.type==="hint"?new H1({color:Y.secondary}):new H1({color:K.type==="prompt"||K.type==="note"||K.type==="opus"?Y.primary:Y.warning}),H=new H1({color:G.keybind}),z=new H1({color:G.command}),U=new H1({color:Y.secondary}),N=new H1({color:Y.foreground,dim:!0}),M=[];if(K.type==="hint"){let P=K.text.split(/(`[^`]+`)/g);for(let I of P)if(I.startsWith("`")&&I.endsWith("`")){let R=I.slice(1,-1);M.push(new J1(R,z))}else M.push(new J1(I,W))}else M.push(new J1(K.text,W));let L=[new J1("Welcome to Amp",new H1({color:Y.foreground})),new J1(`
|
|
4719
|
+
`));G.push(new J1(` • ${q}`,new H1({color:X.foreground,dim:!0})))}return new d1({text:new J1("",void 0,G)})}class nJ6 extends I6{props;constructor(J){super();this.props=J}build(J){let Q=this.props.affectedFiles,Y=Q.length>0,G=[new d1({text:new J1(Y?"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.",new H1({color:O1.yellow,bold:!0}))}),new U0({height:1})],Z=iJ6(J,Q);if(Z)G.push(Z),G.push(new U0({height:1}));let q=[{value:"confirm",label:Y?"Delete and restore":"Delete"},{value:"cancel",label:"Cancel"}];return G.push(new cY({options:q,onSelect:(V)=>{if(V==="confirm")this.props.onConfirm();else this.props.onCancel()},padding:f0.all(0),showDismissalMessage:!1,enableMouseInteraction:!1,showBorder:!1})),new s0({mainAxisSize:"min",crossAxisAlignment:"start",children:G})}}class aJ6 extends I6{props;constructor(J){super();this.props=J}build(J){let Q=this.props.affectedFiles,Y=[],X=iJ6(J,Q);if(X)Y.push(new d1({text:new J1("This will restore the following files:",new H1({color:O1.yellow,bold:!0}))})),Y.push(new U0({height:1})),Y.push(X),Y.push(new U0({height:1}));let G=[{value:"confirm",label:"Confirm edit"},{value:"cancel",label:"Cancel"}];return Y.push(new cY({options:G,onSelect:(Z)=>{if(Z==="confirm")this.props.onConfirm();else this.props.onCancel()},padding:f0.all(0),showDismissalMessage:!1,enableMouseInteraction:!1,showBorder:!1})),new s0({mainAxisSize:"min",crossAxisAlignment:"start",children:Y})}}class g81 extends G6{initialText;onSubmitted;message;constructor(J){super();this.initialText=J.initialText,this.onSubmitted=J.onSubmitted,this.message=J.message}createState(){return new oJ6}}class oJ6 extends X6{controller=new fZ;currentShellModeStatus;initState(){this.controller.text=this.widget.initialText,this.controller.addListener(this.textChangeListener);let J=QN(this.widget.initialText);this.currentShellModeStatus=J?.visibility}dispose(){this.controller.removeListener(this.textChangeListener),this.controller.dispose(),super.dispose()}textChangeListener=()=>{let J=this.controller.text,Y=QN(J)?.visibility;if(Y!==this.currentShellModeStatus)this.currentShellModeStatus=Y,this.setState(()=>{})};handleSubmit=(J)=>{this.widget.onSubmitted(J)};build(J){let Q=x6.of(J),Y=Q.colors,X=Q.app,G=this.currentShellModeStatus?U26(Q,this.currentShellModeStatus):cJ6,Z=null,q=this.widget.message&&el(this.widget.message);if(q)Z=Y_1(J,q);let V=new NO({controller:this.controller,triggers:[],ampURL:"",onSubmitted:this.handleSubmit,theme:Y,placeholder:"",enabled:!0,autofocus:!0,shellPromptRules:Y81(Q),showMenuBelow:!1,imageAttachments:[],minLines:1,textColor:G}),K=[];if(K.push(V),Z)K.push(new U0({height:1})),K.push(Z);let W;if(K.length===1)W=K[0];else W=new s0({mainAxisSize:"min",crossAxisAlignment:"start",children:K});let H=new J6({decoration:{border:p4.all(new P4(G,2,"solid"))},padding:f0.only({left:1,right:1}),child:W}),z=[];if(this.currentShellModeStatus===JN)z.push(new J1("shell mode (incognito)",new H1({color:Q.app.shellModeHidden})));else if(this.currentShellModeStatus===J81)z.push(new J1("shell mode",new H1({color:Q.app.shellMode})));else z.push(new J1("esc",new H1({color:X.keybind})),new J1(" to cancel",new H1({color:Y.foreground,dim:!0})));let U=new u3({left:2,bottom:0,child:new d1({text:new J1("",void 0,z)})});return new v41({child:new e5({children:[H,U]})})}}class m81 extends a7{}class u81 extends a7{}class X_1 extends a7{}class G_1 extends a7{}class Z_1 extends a7{}class $_1 extends a7{}class q_1 extends a7{}class V_1 extends a7{}var KB8=0;function WB8(J,Q,Y){let G=x6.maybeOf(J)?.colors??d4.of(J).colorScheme,q=Q.trimStart().startsWith("You're absolutely right"),V=new i7(`${Y}-text`),K=[];if(q)K.push(new mS1({key:V,markdown:Q,defaultColor:G.foreground}));else K.push(new x7({key:V,markdown:Q}));if(K.length===1)return K[0];return new s0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:K})}function HB8(J,Q){let X=d4.of(J).colorScheme;if(Q.summary.type!=="message")return new J6;return new s0({crossAxisAlignment:"start",children:[new d1({text:new J1("Summary:",new H1({color:X.foreground,dim:!0,bold:!0,italic:!0})),selectable:!0}),new U0({height:1}),new x7({markdown:Q.summary.summary,styleScheme:{text:new H1({color:X.foreground,dim:!0,italic:!0}),inlineCode:new H1({color:X.foreground,dim:!0,italic:!0}),codeBlock:new H1({color:X.foreground,dim:!0,italic:!0}),tableBorder:X.foreground,link:new H1({color:X.foreground,dim:!0,italic:!0}),syntaxHighlight:{keyword:X.foreground,string:X.foreground,number:X.foreground,comment:X.foreground,function:X.foreground,variable:X.foreground,type:X.foreground,operator:X.foreground}}})]})}class p81 extends G6{items;subagentToolsByParentID;controller;autofocus;onNewMessage;showScrollbar;onCopy;onMessageEditSubmit;onShellCommandSubmit;onMessageRestoreSubmit;onMessageForkSubmit;getAffectedFiles;thread;focusNode;onDismissFocus;isInSelectionMode=!1;get userMessageIndices(){let J=[];for(let Q=0;Q<this.items.length;Q++){let Y=this.items[Q];if(Y?.type==="message"){if(Y.message.role==="user"||sE(Y.message))J.push(Q)}}return J}constructor({key:J,items:Q,subagentToolsByParentID:Y={},controller:X,autofocus:G=!1,onNewMessage:Z,showScrollbar:q=!0,onCopy:V,onMessageEditSubmit:K,onMessageRestoreSubmit:W,onMessageForkSubmit:H,getAffectedFiles:z,thread:U,focusNode:N,onDismissFocus:M,isInSelectionMode:L=!1}){super(J?{key:J}:{});this.items=Q,this.subagentToolsByParentID=Y,this.controller=X,this.autofocus=G,this.onNewMessage=Z,this.showScrollbar=q,this.onCopy=V,this.onMessageEditSubmit=K,this.onMessageRestoreSubmit=W,this.onMessageForkSubmit=H,this.getAffectedFiles=z,this.thread=U,this.focusNode=N,this.onDismissFocus=M,this.isInSelectionMode=L}createState(){return new rJ6}}class rJ6 extends X6{_controller=null;_isDisposed=!1;_thinkingBlockStates=new Map;_globalToggleListener;_streamingIndexes=new Set;_viewportHeight=25;_widgetCache=new Map;_lastCostDisplayState=null;_selectedUserMessageOrdinal=null;_editingMessageOrdinal=null;_isShowingRestoreConfirmation=!1;_isShowingEditConfirmation=!1;_pendingEditText=null;_affectedFiles=[];get controller(){return this._controller}dismiss(){J9.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._selectedUserMessageOrdinal,Q=J!==null?this.getUserMessageIndexFromOrdinal(J):null;this.setState(()=>{if(Q!=null)this._widgetCache.delete(Q);this._selectedUserMessageOrdinal=null})}_selectUserMessageByOrdinal(J){let Q=this._selectedUserMessageOrdinal,Y=J,X=Q!==null?this.getUserMessageIndexFromOrdinal(Q):null,G=this.getUserMessageIndexFromOrdinal(Y);if(X!==null)this._widgetCache.delete(X);if(G!==null)this._widgetCache.delete(G);if(this.setState(()=>{this._selectedUserMessageOrdinal=Y}),G!==null)J9.instance.addPostFrameCallback(()=>{this.scrollToMessage(G,{animated:!0,offset:KB8,edge:"top",duration:200})})}_selectEditingUserMessageByOrdinal(J){let Q=this._editingMessageOrdinal,Y=J,X=Q!==null?this.getUserMessageIndexFromOrdinal(Q):null,G=Y!==null?this.getUserMessageIndexFromOrdinal(Y):null;if(X!==null)this._widgetCache.delete(X);if(G!==null)this._widgetCache.delete(G);this.setState(()=>{this._editingMessageOrdinal=Y})}getUserMessageIndexFromOrdinal(J){return this.widget.userMessageIndices[J]??null}getOrdinalFromUserMessageIndex(J){let Y=this.widget.userMessageIndices.indexOf(J);return Y>=0?Y:null}getLatestUserMessageOrdinal(){let J=this.widget.userMessageIndices;return J.length>0?J.length-1:null}navigateToUserMessage(J){let Q=this._getUserCount(),Y=J==="up"?this._navigateUp(this._selectedUserMessageOrdinal,Q):this._navigateDown(this._selectedUserMessageOrdinal,Q);if(Y===null&&J==="down"){this._controller?.animateToBottom(100),this._clearSelectedUserMessage(),this.dismiss();return}if(Y!==null)this._selectUserMessageByOrdinal(Y)}handleNavigateUserMessageUp=()=>{if(this._editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("up"),"handled"};handleNavigateUserMessageDown=()=>{if(this._editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("down"),"handled"};handleEscape=()=>{if(this._editingMessageOrdinal!==null)return this.setState(()=>{let J=this._ordinalToIndex(this.widget.userMessageIndices,this._editingMessageOrdinal);if(J!=null)this._widgetCache.delete(J);this._editingMessageOrdinal=null}),"handled";else if(this._selectedUserMessageOrdinal!==null)return this._clearSelectedUserMessage(),this.setState(()=>{this._editingMessageOrdinal=null}),this.dismiss(),this._controller?.animateToBottom(100),"handled";return"ignored"};handleScrollDown=()=>{if(this._selectedUserMessageOrdinal!==null)return this._controller?.scrollDown(1),"handled";return"ignored"};handleScrollUp=()=>{if(this._selectedUserMessageOrdinal!==null)return this._controller?.scrollUp(1),"handled";return"ignored"};handleEditMessage=()=>{if(this._selectedUserMessageOrdinal!==null)return this._selectEditingUserMessageByOrdinal(this._selectedUserMessageOrdinal),"handled";return"ignored"};handleRestoreMessage=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(J===0)return"ignored";let Q=this.widget.items[J];if(Q?.type==="message"&&(Q.message.role==="user"||sE(Q.message)))this.showRestoreConfirmation(J)}return"handled"}return"ignored"};async showRestoreConfirmation(J){let Q=[];if(this.widget.getAffectedFiles)try{Q=await this.widget.getAffectedFiles(J)}catch{Q=[]}if(this.setState(()=>{this._widgetCache.clear(),this._isShowingRestoreConfirmation=!0,this._affectedFiles=Q}),this.controller.atBottom)J9.instance.addPostFrameCallback(()=>{this.scrollToMessage(J)})}handleRestoreConfirm=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(J===0)return"ignored";let Q=this.widget.items[J];if(Q?.type==="message"&&(Q.message.role==="user"||Q.message.role==="info"))this.widget.onMessageRestoreSubmit?.(Q.message),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._isShowingRestoreConfirmation=!1,this._affectedFiles=[]}),this.dismiss()}return"handled"}return"ignored"};handleRestoreCancel=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(this.setState(()=>{this._widgetCache.clear(),this._isShowingRestoreConfirmation=!1,this._affectedFiles=[]}),this.controller.atBottom)J9.instance.addPostFrameCallback(()=>{this.scrollToMessage(J)})}}return"handled"};handleForkMessage=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){let Q=this.widget.items[J];if(Q?.type==="message"&&(Q.message.role==="user"||sE(Q.message))){if(J===0)return"ignored";this.widget.onMessageForkSubmit?.(Q.message),this._clearSelectedUserMessage(),this.setState(()=>{}),this.dismiss()}}return"handled"}return"ignored"};handleEditConfirmationRequest=async(J)=>{if(J.trim()==="")return;if(this._editingMessageOrdinal!==null){let Q=this._ordinalToIndex(this.widget.userMessageIndices,this._editingMessageOrdinal);if(Q!=null){let Y=[];if(this.widget.getAffectedFiles)try{Y=await this.widget.getAffectedFiles(Q)}catch{Y=[]}if(this.setState(()=>{this._widgetCache.clear(),this._isShowingEditConfirmation=!0,this._pendingEditText=J,this._affectedFiles=Y,this._editingMessageOrdinal=null}),this.controller.atBottom)J9.instance.addPostFrameCallback(()=>{this.scrollToMessage(Q)})}}};handleEditConfirm=()=>{if(this._selectedUserMessageOrdinal!==null&&this._pendingEditText!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){let Q=this.widget.items[J];if(Q?.type==="message"&&(Q.message.role==="user"||Q.message.role==="info"))this.widget.onMessageEditSubmit?.(Q.message,this._pendingEditText),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._isShowingEditConfirmation=!1,this._pendingEditText=null,this._affectedFiles=[]}),this.dismiss(),this.controller.animateToBottom(100)}}};handleEditCancel=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(this.setState(()=>{this._widgetCache.clear(),this._isShowingEditConfirmation=!1,this._pendingEditText=null,this._affectedFiles=[]}),this.controller.atBottom)J9.instance.addPostFrameCallback(()=>{this.scrollToMessage(J)})}}};_signatureFor(J){if(J.type==="message"){let Q=J.message;if(Q.role==="user"){let Y=f2(Q.content),X=Q.content.filter((G)=>G.type==="image").length;return`${J.id}|user|${Q.interrupted?1:0}|${X}|${Y}`}else if(Q.role==="assistant"){let Y=f2(Q.content),X=Q.state.type==="complete",G=Q.content.filter((K)=>K.type==="thinking"),Z=Q.content.filter((K)=>K.type==="tool_use"),q=Q.usage,V=q?`${q.credits??""}|${q.inputTokens}|${q.outputTokens}|${q.cacheCreationInputTokens??""}|${q.cacheReadInputTokens??""}|${q.model??""}`:"no-usage";return`${J.id}|assistant|${X?1:0}|${G.length}|${Z.length}|${Y}|${V}`}else{let X=Q.content.map((G)=>G.type).join(",");return`${J.id}|info|${X}`}}else{let Y=J.toolResult.run.status,X=this.widget.thread&&Y==="done"?ts(this.widget.thread,J.toolUse.id):void 0;return`${J.id}|tool|${Y}|${J.toolUse.id}|${X??""}`}}getThinkingBlockExpanded(J,Q){let Y=`${J}-${Q}`;return this._thinkingBlockStates.get(Y)??OJ.instance.allExpanded}toggleThinkingBlock=(J,Q)=>{return(Y)=>{let X=`${J}-${Q}`;this.setState(()=>{this._thinkingBlockStates.set(X,Y),this._widgetCache.delete(J)})}};buildThinkingBlock(J,Q,Y,X){let G=Y===X.content.length-1,Z=X.state?.type==="streaming"&&G;return new FO({key:new i7(`thinking-${Q}-${Y}`),thinkingBlock:J,expanded:this.getThinkingBlockExpanded(Q,Y),onToggle:this.toggleThinkingBlock(Q,Y),isStreaming:Z})}buildAssistantMessageWidget(J,Q,Y,X){let G=Q.content.map((U,N)=>({block:U,index:N})).filter((U)=>U.block.type==="thinking"&&_81(U.block.thinking).length>0),Z=G.some(({block:U})=>_81(U.thinking).length>0),q=Q.content.filter((U)=>U.type==="text"),V=[];if(V.push(...G.map(({block:U,index:N})=>this.buildThinkingBlock(U,Y,N,Q))),Z&&q.length>0)V.push(new U0({height:1}));let K=f2(q);if(K.trim())V.push(WB8(J,K,X));let W=Dz(J),H=Q.usage!=null&&(Q.usage.inputTokens>0||Q.usage.outputTokens>0);if(W&&H){let N=x6.maybeOf(J)?.colors??d4.of(J).colorScheme,M=v76(Q.usage);V.push(new c6({padding:f0.only({top:1}),child:new d1({text:new J1(M,new H1({color:N.foreground,dim:!0}))})}))}let z;if(V.length===0)z=new J6;else if(V.length===1)z=V[0];else z=new s0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:V});return z}buildThreadItemWidget(J,Q,Y){let X=new i7(`thread-item-${Q.id}`);if(Q.type==="message"){let G=Q.message;if(G.role==="user"){if(!this.widget.isInSelectionMode)return new jC({message:G,isFirstMessage:Y>0});let Z=this.getOrdinalFromUserMessageIndex(Y);if(Z===null)return new jC({message:G,isFirstMessage:Y>0});if(this._editingMessageOrdinal===Z)return new g81({initialText:f2(G.content),message:G,onSubmitted:(V)=>{this.handleEditConfirmationRequest(V)}});if(this._selectedUserMessageOrdinal===Z)return new b81({message:G,isFirstMessage:Y>0,isShowingRestoreConfirmation:this._isShowingRestoreConfirmation,isShowingEditConfirmation:this._isShowingEditConfirmation,affectedFiles:this._affectedFiles,pendingEditText:this._pendingEditText??void 0,onRestoreConfirm:()=>{this.handleRestoreConfirm()},onRestoreCancel:()=>{this.handleRestoreCancel()},onEditConfirm:()=>{this.handleEditConfirm()},onEditCancel:()=>{this.handleEditCancel()}});else return new jC({message:G,isFirstMessage:Y>0})}else if(G.role==="assistant"){let Z=this.buildAssistantMessageWidget(J,G,Y,Q.id);return new J6({key:X,child:Z})}else{let Z=G,q=[],V=this.getOrdinalFromUserMessageIndex(Y),K=this.widget.isInSelectionMode&&V!==null&&this._selectedUserMessageOrdinal===V;for(let W of Z.content)if(W.type==="manual_bash_invocation")if(this._editingMessageOrdinal===V){let z=`${Q81(W.hidden??!1)}${W.args.cmd}`;q.push(new g81({initialText:z,message:Z,onSubmitted:(U)=>{this.handleEditConfirmationRequest(U)}}))}else if(!this.widget.isInSelectionMode||!K)q.push(new jC({message:Z,isFirstMessage:Y>0}));else q.push(new b81({message:Z,isFirstMessage:Y>0,isShowingRestoreConfirmation:this._isShowingRestoreConfirmation,isShowingEditConfirmation:this._isShowingEditConfirmation,affectedFiles:this._affectedFiles,pendingEditText:this._pendingEditText??void 0,onRestoreConfirm:()=>{this.handleRestoreConfirm()},onRestoreCancel:()=>{this.handleRestoreCancel()},onEditConfirm:()=>{this.handleEditConfirm()},onEditCancel:()=>{this.handleEditCancel()}}));else if(W.type==="summary"&&W.summary.type==="message")q.push(HB8(J,W));if(q.length===0)return new J6;if(q.length===1)return q[0];return new s0({crossAxisAlignment:"stretch",children:q})}}else{let G=new Oz({toolUse:Q.toolUse,toolRun:Q.toolResult.run,subagentTools:this.widget.subagentToolsByParentID[Q.toolUse.id],thread:this.widget.thread});return new J6({key:X,child:G})}return new J6}initState(){if(super.initState(),this._controller=this.widget.controller||new p3,this._globalToggleListener=()=>{this.setState(()=>{this._thinkingBlockStates.clear(),this._widgetCache.clear()})},OJ.instance.addListener(this._globalToggleListener),this.widget.items.length>0)J9.instance.requestFrame()}didUpdateWidget(J){if(super.didUpdateWidget(J),!J.isInSelectionMode&&this.widget.isInSelectionMode){this.widget.focusNode?.requestFocus();let Y=this.getLatestUserMessageOrdinal();if(Y!==null)this._selectUserMessageByOrdinal(Y)}if(J.items===this.widget.items)return;let Q=Math.min(J.items.length,this.widget.items.length);for(let Y=0;Y<Q;Y++){let X=J.items[Y],G=this.widget.items[Y];if(X&&G){if(X.type!==G.type){this._widgetCache.delete(Y);continue}if(X.type==="toolResult"&&G.type==="toolResult"){let Z=X.toolResult.run,q=G.toolResult.run;if(Z.status!==q.status||"result"in Z!=="result"in q||"error"in Z!=="error"in q)this._widgetCache.delete(Y)}if(X.type==="message"&&G.type==="message"){let Z=X.message,q=G.message;if(Z.content!==q.content)this._widgetCache.delete(Y)}}}if(this.widget.items.length<J.items.length)this._cleanupOrphanedCacheEntries();this._updateStreamingIndexes();for(let Y of this._streamingIndexes)if(Y>=this.widget.items.length)this._streamingIndexes.delete(Y)}_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 Y=this._isMessageStreaming(Q);if(Y&&!this._streamingIndexes.has(J))this._streamingIndexes.add(J);else if(!Y&&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._globalToggleListener)OJ.instance.removeListener(this._globalToggleListener);if(!this.widget.controller)this._controller?.dispose();this.widget.focusNode?.dispose(),super.dispose()}build(J){let Q=x6.of(J),Y=Dz(J);if(this._lastCostDisplayState!==null&&this._lastCostDisplayState!==Y)this._widgetCache.clear();this._lastCostDisplayState=Y;let X=this._getTotalItemCount(J),G=[];for(let U=0;U<X;U++)if(G.push(this._buildItemAtIndex(J,U)),U<X-1)G.push(new U0({height:1}));let Z=new O2({controller:this._controller,autofocus:this.widget.autofocus,position:"bottom",child:new s0({key:new i7("message-list-column"),crossAxisAlignment:"start",children:G})}),V=[new c6({padding:f0.only({left:2,right:this.widget.showScrollbar?3:2,bottom:1}),child:Z})];if(this.widget.showScrollbar&&this._controller){let U=new XG({controller:this._controller,getScrollInfo:()=>this._getScrollbarInfo(),thickness:1,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack});V.push(new u3({right:1,top:0,bottom:0,child:new U0({width:1,child:U})}))}let K=new e5({children:V}),W=new tA({key:new i7("message-view-selection-area"),child:K,onCopy:this.widget.onCopy}),H=new Map([[m81,new Q9(this.handleNavigateUserMessageUp)],[u81,new Q9(this.handleNavigateUserMessageDown)],[X_1,new Q9(this.handleEscape)],[G_1,new Q9(this.handleScrollDown)],[Z_1,new Q9(this.handleScrollUp)],[$_1,new Q9(this.handleEditMessage)],[q_1,new Q9(this.handleRestoreMessage)],[V_1,new Q9(this.handleForkMessage)]]),z=new Map([[B4.key("Tab"),new m81],[B4.shift("Tab"),new u81],[B4.key("Escape"),new X_1],[B4.key("j"),new G_1],[B4.key("k"),new Z_1],[B4.key("e"),new $_1],[B4.key("r"),new q_1],[B4.key("f"),new V_1]]);if(!c2())z.set(B4.key("ArrowUp"),new m81),z.set(B4.key("ArrowDown"),new u81);if(this.widget.focusNode)return new Y9({focusNode:this.widget.focusNode,child:new cQ({actions:H,child:new Pq({shortcuts:z,focusNode:this.widget.focusNode,child:W})})});return W}_getTotalItemCount(J){return this.widget.items.length}_shouldDimItem(J){if(this._isShowingRestoreConfirmation||this._isShowingEditConfirmation){let Q=this._selectedUserMessageOrdinal;if(Q===null)return!1;let Y=this.getUserMessageIndexFromOrdinal(Q);if(Y===null)return!1;return J>Y}if(this._editingMessageOrdinal!==null){let Q=this.getUserMessageIndexFromOrdinal(this._editingMessageOrdinal);if(Q===null)return!1;return J>Q}return!1}_buildItemAtIndex(J,Q){let Y=this.widget.items[Q];if(!Y)return new J6;let X=Y.type==="message"&&this._isMessageStreaming(Y),G=Y.type==="toolResult"&&(Y.toolResult.run.status==="queued"||Y.toolResult.run.status==="in-progress")&&!("result"in Y.toolResult.run)&&!("error"in Y.toolResult.run),Z=this._shouldDimItem(Q);if(!X&&!G){let K=`${this._signatureFor(Y)}|dim:${Z?1:0}`,W=this._widgetCache.get(Q);if(W&&W.sig===K)return W.widget;let H=this.buildThreadItemWidget(J,Y,Q),z=Z?new JG({forceDim:!0,child:H}):H;return this._widgetCache.set(Q,{sig:K,widget:z}),z}let V=this.buildThreadItemWidget(J,Y,Q);return Z?new JG({forceDim:!0,child:V}):V}onNewMessage(){if(this._isDisposed)return;this.widget.onNewMessage?.()}scrollToTop(){if(this._isDisposed||!this._controller)return;this._controller.scrollToTop()}scrollToMessage(J,{animated:Q=!1,offset:Y=0,edge:X="top",duration:G}={}){if(this._isDisposed||!this._controller)return!1;let Z=this._getMessageRelativeOffset(J,X);if(Z===null)return!1;let q=Z-Y;if(Q)this._controller.animateTo(q,G);else this._controller.jumpTo(q);return!0}_getColumnElement(){let J=this.context.element;if(!J)return null;let Q=new i7("message-list-column"),Y=(X)=>{if(X.widget.key?.equals(Q))return X;for(let G of X.children){let Z=Y(G);if(Z)return Z}return null};return Y(J)}_getMessageRelativeOffset(J,Q){let Y=this._getColumnElement();if(!Y)return null;let X=J*2,G=Y.children[X];if(!G?.renderObject)return null;let Z=G.renderObject,q=Y.renderObject;if(!q)return null;let V=Z.localToGlobal({x:0,y:0}),K=q.localToGlobal({x:0,y:0}),W=0;if(Q==="bottom")W=Z.size.height;return V.y+W-K.y}_getScrollbarInfo(){let J=this._controller?.maxScrollExtent??0,Q=this._getViewportHeight(),Y=this._controller?.offset??0,X=J+Q;return{totalContentHeight:Math.max(X,0),viewportHeight:Math.max(Q,1),scrollOffset:Math.max(Y,0)}}}class K_1 extends I6{thread;onExecute;onEdit;constructor({thread:J,onExecute:Q,onEdit:Y}){super();this.thread=J,this.onExecute=Q,this.onEdit=Y}build(J){if(this.thread.agentMode!=="plan")return new U0({width:0,height:0});let Q=x6.of(J),Y=Q.colors,X=vU(this.thread);if(!cA(this.thread))return new U0({width:0,height:0});let Z=[];return Z.push(new Q4({mainAxisSize:"max",mainAxisAlignment:"spaceBetween",crossAxisAlignment:"center",children:[new d1({text:new J1("\uD83D\uDCCB Plan",new H1({color:Y.foreground,bold:!0})),textAlign:"left"}),new Q4({mainAxisSize:"min",children:[new _8({onClick:this.onExecute,cursor:"pointer",child:new d1({text:new J1("[Execute]",new H1({color:Y.success})),textAlign:"right"})}),new U0({width:1,height:1}),new _8({onClick:this.onEdit,cursor:"pointer",child:new d1({text:new J1("[Edit]",new H1({color:Y.secondary})),textAlign:"right"})})]})]})),Z.push(l5.vertical(1)),Z.push(new x7({markdown:X,textAlign:"left",styleScheme:{text:new H1({color:Y.mutedForeground,dim:!0}),inlineCode:new H1({color:Y.secondary,bold:!0}),codeBlock:new H1({color:Y.mutedForeground,dim:!0}),tableBorder:Y.border,link:new H1({color:Y.secondary,underline:!0}),syntaxHighlight:Q.app.syntaxHighlight}})),Z.push(l5.vertical(1)),Z.push(new d1({text:new J1("",void 0,[new J1("Ctrl+O ",new H1({color:Y.secondary})),new J1("→ Execute Plan",new H1({color:Y.mutedForeground,dim:!0}))]),textAlign:"left"})),new s0({mainAxisSize:"min",mainAxisAlignment:"start",crossAxisAlignment:"start",children:Z})}}class d81 extends G6{props;constructor(J){super();this.props=J}createState(){return new sJ6}}class sJ6 extends X6{viewportHeight=1;scrollListenerAttached=!1;initState(){if(!this.scrollListenerAttached)this.widget.props.controller.addListener(()=>{this.updateViewportHeight()}),this.scrollListenerAttached=!0}build(J){let{thread:Q,onExecute:Y,onEdit:X,controller:G,appTheme:Z}=this.widget.props;return new Q4({crossAxisAlignment:"stretch",children:[new z4({child:new O2({controller:G,autofocus:!1,child:new K_1({thread:Q,onExecute:Y,onEdit:X})})}),new XG({controller:G,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let{maxScrollExtent:q,offset:V}=G,K=this.viewportHeight,W=q+K;return{totalContentHeight:Math.max(W,0),viewportHeight:Math.max(K,1),scrollOffset:Math.max(V,0)}}})]})}updateViewportHeight(){let J=this.getViewportHeight();if(J!==this.viewportHeight)this.viewportHeight=J}getViewportHeight(){let J=this.context.findRenderObject();if(!J)return this.viewportHeight;let Q=(X,G=0)=>{if(X&&"size"in X&&"children"in X){let Z=X.children||[];for(let q of Z){if(q&&"size"in q){let K=q.size;if(typeof K?.height==="number"&&K.height>0)return K.height}let V=Q(q,G+1);if(V>0)return V}}return 0},Y=Q(J);if(Y>0)return Y;if("size"in J){let X=J.size;if(typeof X?.height==="number"&&X.height>0)return X.height}return this.viewportHeight}}class c81 extends I6{agentMode;constructor(J={}){super(J.key?{key:J.key}:{});this.agentMode=J.agentMode}build(J){let Y=d4.of(J).colorScheme,G=x6.of(J).app,q=U8.of(J).capabilities.animationSupport,K=this.agentMode==="smart"?{type:"news",text:"Smart mode now uses Claude Opus 4.5.",url:"https://ampcode.com/news/opus-4.5"}:{type:"prompt",text:""},W=K.type==="quote"?new H1({color:Y.foreground,dim:!0}):K.type==="hint"?new H1({color:Y.secondary}):new H1({color:K.type==="prompt"||K.type==="note"||K.type==="news"?Y.primary:Y.warning}),H=new H1({color:G.keybind}),z=new H1({color:G.command}),U=new H1({color:Y.secondary}),N=new H1({color:Y.foreground,dim:!0}),M=[];if(K.type==="hint"){let P=K.text.split(/(`[^`]+`)/g);for(let I of P)if(I.startsWith("`")&&I.endsWith("`")){let R=I.slice(1,-1);M.push(new J1(R,z))}else M.push(new J1(I,W))}else M.push(new J1(K.text,W));let L=[new J1("Welcome to Amp",new H1({color:Y.foreground})),new J1(`
|
|
4720
4720
|
|
|
4721
4721
|
|
|
4722
4722
|
`),new J1("Ctrl+O",H),new J1(" to execute ",N),new J1("commands",z),new J1(`
|
|
@@ -4730,7 +4730,7 @@ exit code: ${Z}`,new H1({color:X.foreground,dim:!0,italic:!0})));if(q)V.push(new
|
|
|
4730
4730
|
`,N),...M],A=[new d1({text:new J1("",void 0,L)})];if(K.url){let P=K.url.replace(/^https?:\/\//,"");A.push(new Q4({children:[new d1({text:new J1("See more: ",N)}),new i2({uri:K.url,text:P,style:new H1({color:Y.secondary,underline:!0})})]}))}let E=new s0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:A});return H8.child(new J6({constraints:new r6(40,120,0,1/0),child:new Q4({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[new z4({flex:1,child:new fC1({width:40,height:40,agentMode:this.agentMode,fps:q==="fast"?60:q==="slow"?15:0,...q==="disabled"&&{seed:42,t:3}})}),new U0({width:1}),new z4({flex:2,child:E})]})}))}}L0();N9();A4();b7();N9();o0();function zB8(J,Q){return`${J}:${Q}`}class W_1{threadService;workers=new Map;threadsMap=new Map;subthreadsMap=new Map;mainThreadSubs=new Map;subthreadsSubs=new Map;workerStatusSubs=new Map;subthreadPatchSubs=new Map;mainThreadObservable;subthreadObservable;workerStatusObservable;emitMainThread=null;emitSubthread=null;emitWorkerStatus=null;constructor(J){this.threadService=J;this.mainThreadObservable=new X0((Q)=>{return this.emitMainThread=(Y)=>Q.next(Y),()=>{this.emitMainThread=null}}),this.subthreadObservable=new X0((Q)=>{return this.emitSubthread=(Y)=>Q.next(Y),()=>{this.emitSubthread=null}}),this.workerStatusObservable=new X0((Q)=>{return this.emitWorkerStatus=(Y)=>Q.next(Y),()=>{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.subthreadsMap.set(Q,[]),this.workers.set(Q,{state:"initial"});let Y=this.threadService.observePatches(Q).pipe(UM()).subscribe((Z)=>{this.threadsMap.set(Q,Z);let q=this.subthreadsMap.get(Q)||[],V=this.workers.get(Q)||{state:"initial"};if(this.emitMainThread)this.emitMainThread({threadID:Q,mainThread:Z,subthreads:q,workerStatus:V})});this.mainThreadSubs.set(Q,Y);let X=J.status.subscribe((Z)=>{if(this.workers.set(Q,Z),this.emitWorkerStatus)this.emitWorkerStatus({threadID:Q,status:Z})});this.workerStatusSubs.set(Q,X);let G=J.subthreads.subscribe((Z)=>{this.subthreadsMap.set(Q,Z);for(let q of Z){let V=zB8(Q,q.toolUse.id);if(this.subthreadPatchSubs.has(V))continue;let K=this.threadService.observePatches(q.threadID).pipe(UM()).subscribe((W)=>{if(this.emitSubthread)this.emitSubthread({threadID:Q,thread:W,subthread:q})});this.subthreadPatchSubs.set(V,K)}});this.subthreadsSubs.set(Q,G)}unregisterWorker(J){let Q=this.mainThreadSubs.get(J);if(Q)Q.unsubscribe(),this.mainThreadSubs.delete(J);let Y=this.workerStatusSubs.get(J);if(Y)Y.unsubscribe(),this.workerStatusSubs.delete(J);let X=this.subthreadsSubs.get(J);if(X)X.unsubscribe(),this.subthreadsSubs.delete(J);for(let[G,Z]of this.subthreadPatchSubs.entries())if(G.startsWith(`${J}:`))Z.unsubscribe(),this.subthreadPatchSubs.delete(G);this.workers.delete(J),this.threadsMap.delete(J),this.subthreadsMap.delete(J)}observeThread(J){return{mainThread:new X0((Q)=>{return this.mainThreadObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})}),subthreads:new X0((Q)=>{return this.subthreadObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})}),workerStatus:new X0((Q)=>{return this.workerStatusObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})})}}get threadViewStates(){let J={};for(let[Q,Y]of this.threadsMap){let X=this.workers.get(Q);if(X)J[Q]=VA(Y,X)}return J}dispose(){for(let J of this.mainThreadSubs.values())J.unsubscribe();for(let J of this.subthreadsSubs.values())J.unsubscribe();for(let J of this.workerStatusSubs.values())J.unsubscribe();for(let J of this.subthreadPatchSubs.values())J.unsubscribe();this.mainThreadSubs.clear(),this.subthreadsSubs.clear(),this.workerStatusSubs.clear(),this.subthreadPatchSubs.clear(),this.workers.clear(),this.threadsMap.clear(),this.subthreadsMap.clear()}}function FB8(J,Q){switch(Q.type){case"subthread-patch":{let{thread:Y,subthread:X}=Q,G=J.subagents[X.threadID];if(!G){if(G={subThreadID:Y.id,parentToolID:X.toolUse.id,taskDescription:X.toolUse.input.description||"Task",isCompleted:!1,agentState:{type:"idle"}},J.mainThread){let W=oJ(J.mainThread);G.isCompleted=tJ6(W,X.toolUse.id)}}let Z=UB8(Y,G.agentState),q=G.agentState===Z?G:{...G,agentState:Z},V={...J.tools},K=SC(Y).items.filter((W)=>W.type==="toolResult");for(let W of K)V[W.id]={id:W.id,subthreadID:Y.id,toolRun:W.toolResult.run,toolUse:W.toolUse};return{subagents:{...J.subagents,[X.threadID]:q},tools:V,items:J.items,viewState:J.viewState,todosList:J.todosList,mainThread:J.mainThread}}case"main-thread-patch":{let{thread:Y,subthreads:X,workerStatus:G}=Q,Z=oJ(Y),q={...J.subagents};for(let z of X){let U=q[z.threadID];if(!U)continue;let N=tJ6(Z,z.toolUse.id);q[z.threadID]={...U,isCompleted:N}}let{items:V}=SC(Y),K=VA(Y,G),W=tE({messages:Y.messages}),H=Array.isArray(W)?W:[];return{...J,subagents:q,items:V,viewState:K,todosList:H,mainThread:Y}}case"worker-status-change":{if(!J.mainThread)return J;let Y=VA(J.mainThread,Q.workerStatus);if(Y===J.viewState)return J;return{...J,viewState:Y}}default:return J}}function SC(J){let Q=[],Y=new Map,X=new Set;for(let[G,Z]of J.messages.entries()){let q=`${Z.role}-${G}`;switch(Z.role){case"assistant":{let V=Z.state.type==="streaming";for(let W of Z.content)if(W.type==="tool_use"){if(Y.set(W.id,W),V)X.add(W.id)}if(Z.content.some((W)=>W.type==="text"&&W.text.trim()||W.type==="thinking"))Q.push({type:"message",id:q,message:Z});for(let W of Z.content)if(W.type==="tool_use"){let H=!1;for(let z=G+1;z<J.messages.length;z++){let U=J.messages[z];if(U){for(let N of U.content)if(N.type==="tool_result"&&N.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:V?"in-progress":"queued"}}})}break}case"info":Q.push({type:"message",id:q,message:Z});break;case"user":{let V=Z.content.some((K)=>K.type==="text"&&K.text.trim()||K.type==="image");for(let K of Z.content)if(K.type==="tool_result"){let W=Y.get(K.toolUseID)??NX(J,K.toolUseID);if(!W)throw Error(`(bug) tool use ${K.toolUseID} not found`);Q.push({type:"toolResult",id:K.toolUseID,toolUse:W,toolResult:K})}if(V)Q.push({type:"message",id:q,message:Z});break}}}return{items:Q}}function tJ6(J,Q){let Y=J.get(Q);return(Y&&W2(Y.run))??!1}function UB8(J,Q){let Y=J.messages.at(-1);if(Y?.content.some((G)=>G.type==="tool_result"&&G.run.status==="blocked-on-user"))return f.info("Subagent status: idle (blocked-on-user)",{threadID:J.id}),{type:"idle"};if(SC(J).items.some((G)=>G.type==="toolResult"&&G.toolResult.run.status==="in-progress")){let G=Q?.type==="running-tools"?Q.startTime:Date.now();return f.info("Subagent status: running-tools",{threadID:J.id,startTime:G,hasStartTime:!!G}),{type:"running-tools",startTime:G}}if(Y&&Y.role==="assistant"&&Y.state.type==="streaming")switch(Y.content.at(-1)?.type){case"text":return f.info("Subagent status: streaming-text",{threadID:J.id}),{type:"streaming-text"};case"thinking":return f.info("Subagent status: streaming-thinking",{threadID:J.id}),{type:"streaming-thinking"};case"tool_use":{let Z=Q?.type==="running-tools"?Q.startTime:Date.now();return f.info("Subagent status: running-tools (streaming tool_use)",{threadID:J.id,startTime:Z,hasStartTime:!!Z}),{type:"running-tools",startTime:Z}}default:return f.info("Subagent status: streaming-text (default)",{threadID:J.id}),{type:"streaming-text"}}return f.info("Subagent status: idle (default)",{threadID:J.id}),{type:"idle"}}class H_1 extends G6{props;constructor(J){super();this.props=J}createState(){return new eJ6}}class eJ6 extends X6{state={subagents:{},tools:{},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 W_1(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),Y=Q.mainThread.subscribe((Z)=>{this.dispatch({type:"main-thread-patch",thread:Z.mainThread,subthreads:Z.subthreads,workerStatus:Z.workerStatus})});this.subscriptions.push(Y);let X=Q.subthreads.subscribe((Z)=>{this.dispatch({type:"subthread-patch",thread:Z.thread,subthread:Z.subthread})});this.subscriptions.push(X);let G=Q.workerStatus.subscribe((Z)=>{this.dispatch({type:"worker-status-change",workerStatus:Z.status})});this.subscriptions.push(G)}cleanup(){this.subscriptions.forEach((J)=>J.unsubscribe()),this.subscriptions=[]}switchWorker(J){this.cleanup(),this.setState(()=>{this.currentWorker=J}),this.setState(()=>{this.state={subagents:{},tools:{},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=FB8(this.state,J)})}getThreadData(){let J=Object.values(this.state.tools).map((Z)=>({toolUse:Z.toolUse,toolRun:Z.toolRun,subthreadID:Z.subthreadID})),Q={};for(let Z of Object.values(this.state.subagents)){let q=J.filter((V)=>V.subthreadID===Z.subThreadID);Q[Z.parentToolID]=q}let Y=(Z)=>Z===o5||Z===q9||Z===BX,X=new Map;for(let Z of this.state.items)if(Z.type==="toolResult"&&Y(Z.toolUse.name))X.set(Z.toolUse.id,{toolUseId:Z.toolUse.id,toolName:Z.toolUse.name,toolRun:Z.toolResult.run});let G=Array.from(X.values());for(let{toolUseId:Z,toolRun:q}of G){let V=[],K;if(q.status==="in-progress"||q.status==="done"||q.status==="error"||q.status==="cancelled")K=q.progress;if(K){let W=0;for(let H of K)if(H.tool_uses)for(let z of H.tool_uses){let U=`${Z}:progress:${W++}`;V.push({toolUse:oE(z.tool_name,z.input,U),toolRun:{status:z.status}})}}Q[Z]=V}return{...this.state,subagents:Object.values(this.state.subagents),subagentActiveTools:J,subagentToolsByParentID:Q}}build(J){let Q=this.getThreadData();return this.widget.props.builder(J,Q,this.workerController,(Y)=>this.switchWorker(Y),()=>this.currentWorker,this.recentThreadIDs)}}class z_1 extends G6{props;constructor(J){super({key:J.key});this.props=J}createState(){return new JQ6}}class JQ6 extends X6{build(J){let Y=x6.of(J).colors,{todos:X,title:G="TODOs"}=this.widget.props;if(!Array.isArray(X)||X.length===0)return new U0({width:0,height:0});let Z=X.map((q)=>this.buildTodoItem(q,Y));return new J6({child:new c6({padding:f0.symmetric(1,0),child:new s0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new d1({text:new J1(G,new H1({bold:!0,color:Y.foreground}))}),...Z]})})})}buildTodoItem(J,Q){let Y=this.getStatusIcon(J.status),X=J.status==="completed",G=new H1({bold:J.status==="in-progress",color:Q.foreground,dim:X}),Z=new H1({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Q.foreground,dim:X});return new Q4({crossAxisAlignment:"start",children:[new d1({text:new J1(Y,G)}),new U0({width:1}),new z4({child:new d1({text:new J1(J.content,Z)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class F_1 extends I6{ad;onDismiss;onButtonClick;constructor({key:J,ad:Q,onDismiss:Y,onButtonClick:X}){super({key:J});this.ad=Q,this.onDismiss=Y,this.onButtonClick=X}build(J){let Q=x6.of(J),Y=Q.colors.primary,X=Q.colors.foreground;return new J6({decoration:new O8(void 0,new p4(new P4(Y,1,"rounded"),new P4(Y,1,"rounded"),void 0,new P4(Y,1,"rounded"))),child:new c6({padding:f0.horizontal(1),child:new s0({children:[new Q4({crossAxisAlignment:"start",children:[new z4({child:new d1({text:new J1(this.ad.content,new H1({color:X}))})}),new U0({width:4}),new i2({uri:"https://ampcode.com/free",text:"Ad",style:new H1({color:X,dim:!0}),onError:(G)=>{}})]}),new Q4({crossAxisAlignment:"start",children:[new aC1({text:this.ad.buttonLabel,onPressed:()=>this.onButtonClick?.(),padding:f0.horizontal(1),color:Y,reverse:!0}),new U0({width:2}),new d1({text:new J1(this.ad.destinationUrlHostname,new H1({color:X,dim:!0}))})]})]})})})}}class U_1 extends G6{props;constructor(J){super();this.props=J}createState(){return new QQ6(this.props.autofocus??!0)}}class QQ6 extends X6{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=(V)=>{if(V.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(V.ctrlKey&&V.key==="c"||V.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},Y=U8.sizeOf(J),X=Math.min(60,Y.width-4),G=Y.height-4,Z=[];if(this.widget.props.title)Z.push(new d1({text:new J1(this.widget.props.title,new H1({bold:!0,color:O1.blue}))}),new U0({height:1}));if(this.widget.props.message)Z.push(new d1({text:new J1(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)Z.push(new U0({height:1}));let q=[];if(this.widget.props.showCopyOption)q.push(new d1({text:new J1("Enter to copy",new H1({dim:!0}))}));return q.push(new d1({text:new J1("Escape to close",new H1({dim:!0}))})),Z.push(new Q4({children:q.flatMap((V,K)=>K<q.length-1?[V,new U0({width:1}),new d1({text:new J1("•",new H1({dim:!0}))}),new U0({width:1})]:[V]),mainAxisSize:"min"})),new H8({child:new J6({constraints:new r6(X,X,0,G),decoration:new O8(O1.default(),new p4(new P4(O1.blue,1,"rounded"),new P4(O1.blue,1,"rounded"),new P4(O1.blue,1,"rounded"),new P4(O1.blue,1,"rounded"))),padding:new f0(2,2,2,2),child:new Y9({autofocus:this.autofocus,onKey:Q,child:new s0({children:Z,mainAxisSize:"min"})})})})}}class l81 extends Error{constructor(J="Command timed out"){super(J);this.name="CommandTimeoutError",Object.setPrototypeOf(this,l81.prototype)}}class i81 extends Error{constructor(J){let Q=`${J.noun}: ${J.verb} command cancelled`;super(Q);this.name="CommandCancelledError",Object.setPrototypeOf(this,i81.prototype)}}function B_1(J){let Q=J.match(/"([^"]*)"|'([^']*)'|([^\s"']+)/g);if(!Q)return[];return Q.map((Y)=>{if(Y.startsWith('"')&&Y.endsWith('"')||Y.startsWith("'")&&Y.endsWith("'"))return Y.slice(1,-1);return Y})}qU();L0();import{spawn as BB8}from"node:child_process";import{promises as NB8}from"node:fs";function YQ6(J){return J.kind==="executable"}function XQ6(J){return J.kind==="markdown"}var wz=50000,GQ6=300000;async function N_1(J,Q,Y,X={}){let{timeoutMs:G=GQ6,signal:Z,source:q}=X;try{let V=await Y.getCommand(J,q);if(!V)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Y.isCommandAvailable(J,q))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(f.debug("Executing command",{commandName:J,filePath:V.filePath,args:Q}),XQ6(V))return await DB8(V,Q);else if(YQ6(V))return await MB8(V,Q,G,Z);else return{success:!1,output:"",error:"Unsupported command type"}}catch(V){return f.error("Failed to execute command",{commandName:J,error:V}),{success:!1,output:"",error:V instanceof Error?V.message:"Unknown error occurred"}}}async function DB8(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Y=await NB8.readFile(J.filePath,"utf8");return{success:!0,output:(Y.length>wz?Y.slice(0,wz)+`
|
|
4731
4731
|
... (output truncated at ${wz} characters)`:Y).trim(),exitCode:0}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:"Failed to read markdown file"}}}async function MB8(J,Q,Y=GQ6,X){return new Promise((G)=>{let[Z,q]=LB8(J,Q);f.debug("Spawning command",{spawnCommand:Z,spawnArgs:q.slice(0,10),filePath:J.filePath,timeoutMs:Y});let V=jO0(X),K=!1,W=setTimeout(()=>{K=!0,V.abort(),f.warn("Command execution timed out",{commandName:J.name,timeoutMs:Y})},Y),H=BB8(Z,q,{stdio:["pipe","pipe","pipe"],signal:V.signal,detached:!0}),z=[],U=[],N=0;H.stdout?.on("data",(M)=>{let L=M.toString();if(N+=L.length,N<=wz)z.push(L);else{let A=wz-(N-L.length);if(A>0)z.push(L.slice(0,A))}}),H.stderr?.on("data",(M)=>{let L=M.toString();if(N+=L.length,N<=wz)U.push(L);else{let A=wz-(N-L.length);if(A>0)U.push(L.slice(0,A))}}),H.on("close",(M)=>{if(clearTimeout(W),K){G({success:!1,output:z.join(""),error:`Command timed out after ${Y}ms`,exitCode:void 0});return}if(V.signal.aborted){G({success:!1,output:z.join(""),error:"The command was aborted",exitCode:M??void 0});return}let L=M===0||M===1,A=z.join(""),E=U.join(""),P=A;if(!L&&!A.trim()&&E.trim())P=E;else if(E.trim())P+=A?`
|
|
4732
4732
|
${E}`:E;if(N>wz)P+=`
|
|
4733
|
-
... (output truncated at ${wz} characters)`;G({success:L,output:P.trim(),error:!L?E.trim()||"Command failed":void 0,exitCode:M??void 0})}),H.on("error",(M)=>{clearTimeout(W);let L=M.message;if(K)L=`Command timed out after ${Y}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")L="The command was aborted";G({success:!1,output:z.join(""),error:L})})})}function LB8(J,Q){let{filePath:Y,interpreter:X,extension:G}=J;if(process.platform==="win32")return OB8(Y,X?[...X]:null,G,Q);else return AB8(Y,X?[...X]:null,G,Q)}function AB8(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function OB8(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Y.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}L0();C$();H2();bW();GZ();u$();QH();BH();b7();i_();o0();var UQ6=D6(HP(),1);import{writeFile as HQ6}from"fs/promises";import zQ6 from"path";L0();GZ();class D_1{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,Y])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.
|
|
4733
|
+
... (output truncated at ${wz} characters)`;G({success:L,output:P.trim(),error:!L?E.trim()||"Command failed":void 0,exitCode:M??void 0})}),H.on("error",(M)=>{clearTimeout(W);let L=M.message;if(K)L=`Command timed out after ${Y}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")L="The command was aborted";G({success:!1,output:z.join(""),error:L})})})}function LB8(J,Q){let{filePath:Y,interpreter:X,extension:G}=J;if(process.platform==="win32")return OB8(Y,X?[...X]:null,G,Q);else return AB8(Y,X?[...X]:null,G,Q)}function AB8(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function OB8(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Y.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}L0();C$();H2();bW();GZ();u$();QH();BH();b7();i_();o0();var UQ6=D6(HP(),1);import{writeFile as HQ6}from"fs/promises";import zQ6 from"path";L0();GZ();class D_1{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,Y])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1764248660-g87fd50"},parameters:{metadata:{count:Y}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await to(Q,this.configService)}catch(Q){f.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 M_1 extends G6{props;constructor(J){super();this.props=J}createState(){return new ZQ6}}class ZQ6 extends X6{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Y)=>{this.setState(()=>{this._state=Y(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class $Q6 extends X6{controller=new fZ;focusNode=new c8({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=x6.of(J),{colors:Y,app:X}=Q,G=this.widget.props.isRequiredArg??!0,Z=this.controller.text.trim().length>0,q=!G||Z,V=p4.all(new P4(Y.foreground,1,"solid")),K=new QO({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(N)=>{let M=N.trim();if(G&&M.length===0)return;this.widget.props.onSubmit(M)},autofocus:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new Q4({children:[new J6({decoration:{color:O1.default()},child:new d1({text:new J1(">",new H1({color:Y.foreground}))})}),new z4({child:K})]}),H=new J6({padding:f0.symmetric(1,0),child:new d1({text:new J1("",void 0,[new J1("Command: ",new H1({color:Y.foreground})),new J1(this.widget.props.commandName,new H1({color:O1.yellow,bold:!0}))])})}),z=[];if(q)z.push(new J1("Enter",new H1({color:X.keybind}))),z.push(new J1(" to submit, ",new H1({color:Y.foreground,dim:!0})));z.push(new J1("Esc",new H1({color:X.keybind}))),z.push(new J1(" to cancel",new H1({color:Y.foreground,dim:!0})));let U=new J6({padding:f0.symmetric(1,0),child:new d1({text:new J1("",void 0,z)})});return new J6({decoration:{border:V,color:O1.default()},padding:f0.all(1),child:new s0({children:[H,new U0({height:1}),W,new l5,U]})})}}class n81 extends G6{props;constructor(J){super();this.props=J}createState(){return new $Q6}}QH();class qQ6 extends X6{controller=new fZ;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new c8({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=(J)=>{if(this.imageAttachments.length>=VU)return!1;let Q=FC(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Q=x6.of(J),{colors:Y,app:X}=Q,Z=U8.of(J).size.height,q=Math.max(Math.floor(Z*0.5),10),V=new NO({controller:this.controller,triggers:[new KN],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(N)=>{this.widget.props.onSubmit(N.trim(),this.imageAttachments)},theme:Y,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:E9.instance.tuiInstance.clipboard,showMenuBelow:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),K=new Y9({focusNode:this.focusNode,child:V}),W=new J6({constraints:new r6({maxHeight:q}),padding:f0.symmetric(1,0),child:K}),H=new J6({padding:f0.symmetric(1,0),child:new d1({text:new J1("",void 0,[new J1("Command: ",new H1({color:Y.foreground})),new J1(this.widget.props.commandName,new H1({color:O1.yellow,bold:!0}))])})}),z=new J6({padding:f0.symmetric(1,0),child:new d1({text:this.isConfirmingClearInput?new J1("",void 0,[new J1("Esc",new H1({color:X.keybind})),new J1(" again to clear input",new H1({color:Y.foreground,dim:!0}))]):new J1("",void 0,[new J1("Press ",new H1({color:Y.foreground,dim:!0})),new J1("Enter",new H1({color:X.keybind})),new J1(" to submit, ",new H1({color:Y.foreground,dim:!0})),new J1("Esc",new H1({color:X.keybind})),new J1(" to clear",new H1({color:Y.foreground,dim:!0}))])})}),U=[H,new U0({height:1}),new z4({child:W}),new U0({height:1}),z];return new J6({decoration:{border:p4.all(new P4(Y.foreground,1,"solid")),color:O1.default()},padding:f0.all(1),child:new s0({children:U})})}}class DO extends G6{props;constructor(J){super();this.props=J}createState(){return new qQ6}}function VQ6(J){let Y=new Date().getTime()-J.getTime(),X=Math.floor(Y/60000),G=Math.floor(Y/3600000),Z=Math.floor(Y/86400000);if(X<1)return"just now";if(X<60)return`${X}m ago`;if(G<24)return`${G}h ago`;if(Z<7)return`${Z}d ago`;return J.toLocaleDateString()}class L_1 extends I6{props;debugLabel="ThreadFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((G,Z)=>Z.pubDate.getTime()-G.pubDate.getTime()),Y=Math.max(0,...Q.map((G)=>VQ6(G.pubDate).length));return new xK({items:Q,getLabel:(G)=>G.title,onAccept:(G)=>this.props.onSelect?.(G),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No thread feed entries available",maxRenderItems:100,renderItem:(G,Z,q,V)=>{let K=x6.of(V),{colors:W}=K,H=Z?O1.yellow:void 0,z=Z?O1.black:W.foreground,U=O1.index(8),N=G.authors.map((L)=>L.name).join(", ")||"Community",M=(L,A)=>new U0({width:A,child:Q4.end([new d1({text:new J1(L,new H1({color:U}))})])});return new J6({decoration:H?{color:H}:void 0,padding:f0.symmetric(2,0),child:new Q4({children:[new z4({child:new d1({text:new J1(G.title,new H1({color:z})),overflow:"ellipsis",maxLines:1})}),new U0({width:2}),new d1({text:new J1(N,new H1({color:U})),maxLines:1}),new U0({width:2}),M(VQ6(G.pubDate),Y)]})})}})}}class A_1 extends I6{props;constructor(J){super();this.props=J}build(){return new H8({child:new d1({text:new J1("",void 0,[new J1(`Forked to new thread:
|
|
4734
4734
|
|
|
4735
4735
|
`,new H1({color:O1.white,dim:!0})),new J1(`"${this.props.newThreadTitle||"Untitled"}"`,new H1({color:O1.white}))]),textAlign:"center"})})}}class Ez extends G6{props;constructor(J){super();this.props=J}createState(){return new KQ6}}class KQ6 extends X6{_spinner=new gK;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=x6.of(J),{colors:Y}=Q,X=p4.all(new P4(Y.foreground,1,"solid")),G=this._spinner.toBraille(),Z=new d1({textAlign:"center",text:new J1("",void 0,[new J1(G,new H1({color:O1.yellow})),new J1(" ",void 0),new J1(this.widget.props.message,new H1({color:Y.foreground}))])}),V=[new z4({child:new s0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)V.push(new U0({height:2,child:new J6({padding:f0.symmetric(2,0),child:new d1({text:new J1("",new H1({dim:!0}),[new J1("Press ",new H1({color:Y.foreground})),new J1("Esc",new H1({color:Y.info})),new J1(" to cancel",new H1({color:Y.foreground}))])})})}));let K=new J6({decoration:new O8(O1.default(),X),child:new U0({width:60,height:7,child:new s0({mainAxisAlignment:"start",children:V})})});if(this.widget.props.onAbort)return new Y9({debugLabel:"LoadingDialog",autofocus:!0,onKey:(W)=>{if(W.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:K});return K}}class Iz extends G6{props;constructor(J){super();this.props=J}createState(){return new WQ6}}class WQ6 extends X6{dispose(){super.dispose()}isWidgetMessage(J){return J instanceof vK}build(J){let Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let W=e41(Q);return{title:W.title,type:W.type,description:W.description}})(),X=Y.type==="error"?O1.red:O1.yellow,G=p4.all(new P4(O1.default(),1,"solid")),Z=new J6({padding:f0.symmetric(1,0),child:new d1({text:new J1(Y.title,new H1({color:X,bold:!0}))})}),q=this.isWidgetMessage(Q)?Q.widget:new d1({text:new J1(Y.description,new H1({color:O1.default()})),selectable:!0}),V=new z4({child:new tA({child:new J6({padding:f0.symmetric(1,0),child:q})})}),K=new J6({padding:f0.symmetric(1,0),child:new d1({text:this.widget.props.onRetry?new J1("",void 0,[new J1("Press ",new H1({color:O1.default(),dim:!0})),new J1("R",new H1({color:O1.yellow})),new J1(" to retry, ",new H1({color:O1.default(),dim:!0})),new J1("Esc",new H1({color:O1.yellow})),new J1(" to cancel",new H1({color:O1.default(),dim:!0}))]):new J1("Press any key to close",new H1({color:O1.default(),dim:!0,italic:!0}))})});return new Y9({onKey:(W)=>{if(this.widget.props.onRetry&&W.key==="r")return this.widget.props.onRetry(),"handled";if(W.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!0,child:new J6({decoration:{border:G,color:O1.default()},padding:f0.all(1),child:new s0({mainAxisAlignment:"center",children:[Z,new U0({height:1}),V,K]})})})}}class O_1 extends I6{build(){return new H8({child:new d1({text:new J1("",void 0,[new J1(`✓ Thread Shared
|
|
4736
4736
|
|
|
@@ -4816,7 +4816,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
|
|
|
4816
4816
|
`)?`${V}...`:G,W=new H1({color:O1.index(8)}),H=[new J1(K,W)];if(q>0){let z=new H1({color:Y.success});for(let U=1;U<=q;U++)H.push(new J1(" ")),H.push(new J1(`[${U}]`,z))}return new c6({padding:f0.only({bottom:0}),child:new Q4({crossAxisAlignment:"start",children:[new c6({padding:f0.only({right:1}),child:new d1({text:new J1("•",new H1({color:O1.index(8)}))})}),new z4({child:new d1({text:new J1("",void 0,H)})})]})})}}class s_1 extends G6{createState(){return new $Y6}}class $Y6 extends X6{_animationTimer;_visible=!0;initState(){super.initState(),this._startAnimation()}dispose(){this._stopAnimation(),super.dispose()}_startAnimation(){this._animationTimer=setInterval(()=>{this.setState(()=>{this._visible=!this._visible})},500)}_stopAnimation(){if(this._animationTimer)clearInterval(this._animationTimer),this._animationTimer=void 0}build(J){let Q=new H1({color:O1.red}),Y=new H1({color:this._visible?O1.red:O1.transparent()});return new Q4({children:[new d1({text:new J1("⏺",Y)}),new U0({width:1}),new d1({text:new J1("Replay",Q)})]})}}class t_1 extends I6{entry;constructor({key:J,entry:Q}){super({key:J});this.entry=Q}build(J){let Q=x6.of(J),Y=Q.colors.secondary,X=Q.colors.foreground,G=this.entry.authors.map((Z)=>Z.name).join(", ");return new J6({decoration:new O8(void 0,new p4(new P4(Y,1,"rounded"),new P4(Y,1,"rounded"),void 0,new P4(Y,1,"rounded"))),child:new c6({padding:f0.horizontal(1),child:new s0({children:[new Q4({crossAxisAlignment:"start",children:[new z4({child:new d1({text:new J1(this.entry.title,new H1({color:X,bold:!0}))})}),new U0({width:4}),new d1({text:new J1(G||"Community",new H1({color:X,dim:!0}))})]}),new Q4({crossAxisAlignment:"start",children:[new z4({child:new d1({text:new J1(this.truncateDescription(this.entry.description),new H1({color:X,dim:!0}))})}),new U0({width:2}),new i2({uri:this.entry.link,text:"View Thread",style:new H1({color:Y,underline:!0}),onError:()=>{}})]})]})})})}truncateDescription(J){let Y=J.replace(/\s+/g," ").trim();if(Y.length<=80)return Y;return Y.slice(0,79)+"…"}}o0();function _N8(J){let Y=new Date().getTime()-J.getTime(),X=Math.floor(Y/3600000),G=Math.floor(X/24),Z=Math.floor(G/7),q=Math.floor(G/30);if(X<1)return"Just now";if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;if(Z<=4)return`${Z}w ago`;return`${q}mo ago`}class e_1{threadHistoryService;constructor(J){this.threadHistoryService=J}async fetchThreadSummaries(J=""){try{let Q=await new Promise((Y)=>{let X=this.threadHistoryService.observeThreadList().subscribe((G)=>{X.unsubscribe(),Y(G)})});return{ok:!0,threads:this.formatThreadSummaries(Q,J)}}catch(Q){return{ok:!1,errorMsg:Q instanceof Error?Q.message:"An unexpected error occurred"}}}observeThreadSummaries(J=""){return this.threadHistoryService.observeHistory().pipe(q6((Q)=>this.formatThreadSummaries(Q,J)))}formatThreadSummaries(J,Q){return J.filter((X)=>{if(!Q.trim())return!0;let G=X.title?.toLowerCase()||"untitled",Z=X.id.toLowerCase(),q=Q.toLowerCase();return G.includes(q)||Z.includes(q)}).map((X)=>{let G=new Date(X.userLastInteractedAt),Z=_N8(G),q=X.id.slice(-8),V=X.env?.initial.trees?.[0]?.uri;return{id:X.id,title:X.title||"Untitled",updatedAt:new Date(X.userLastInteractedAt).toISOString(),description:{timeAgo:Z,title:X.title||"Untitled",shortThreadID:q},diffStats:X.summaryStats?.diffStats,workspaceURI:V,parentRelationships:X.parentRelationships}})}}L0();N9();class Jk1{currentId=null;current=null;subscribeTimer=null;subscription=null;listeners=[];threadService=null;scrollController=new p3;constructor(){}setThreadService(J){this.threadService=J}async select(J){if(!this.threadService){f.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId===J)return;this.cancelTimerAndSubscription(),this.currentId=J;let Q=await this.threadService.get(J);if(Q){if(this.currentId===J)this.current=Q,this.notifyListeners()}this.subscribeTimer=setTimeout(()=>{this.subscribeLive(J)},1000)}clear(){this.cancelTimerAndSubscription(),this.currentId=null,this.current=null,this.notifyListeners()}addListener(J){this.listeners.push(J)}removeListener(J){let Q=this.listeners.indexOf(J);if(Q!==-1)this.listeners.splice(Q,1)}dispose(){this.cancelTimerAndSubscription(),this.scrollController.dispose(),this.listeners=[]}subscribeLive(J){if(!this.threadService){f.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId!==J)return;this.subscription=this.threadService.observePatches(J).pipe(UM()).subscribe((Q)=>{if(this.currentId===J)this.current=Q,this.notifyListeners()})}cancelTimerAndSubscription(){if(this.subscribeTimer)clearTimeout(this.subscribeTimer),this.subscribeTimer=null;if(this.subscription)this.subscription.unsubscribe(),this.subscription=null}notifyListeners(){for(let J of this.listeners)J(this.current)}}function qY6(J,Q){switch(J){case"update-available":return[new J1("A newer Amp is available. Run ",new H1({color:Q.foreground,dim:!0})),new J1("amp update",new H1({color:Q.warning}))];case"updated":return null;case"updated-with-warning":return[new J1("Update complete, run ",new H1({color:Q.foreground,dim:!0})),new J1("amp update",new H1({color:Q.warning})),new J1(" to see warnings",new H1({color:Q.foreground,dim:!0}))];case"update-error":return[new J1("Update failed, run ",new H1({color:Q.foreground,dim:!0})),new J1("amp update",new H1({color:Q.warning})),new J1(" to see warnings",new H1({color:Q.foreground,dim:!0}))];case"hidden":return null}}async function fN8(J){return new Promise((Q)=>{yN8("git",["branch","--show-current"],{cwd:J},(Y,X)=>{if(Y){Q(null);return}let G=X.trim();Q(G||null)})})}class HY6 extends G6{dependencies;constructor(J){super();this.dependencies=J}createState(){return new zY6}}class zY6 extends X6{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;connectedClientsStatus=null;connectedClientsStatusExpanded=!1;randomAd=null;adSubscription=null;threadLoadSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();isConfirmingExit=!1;isExiting=!1;isConfirmingClearInput=!1;isConfirmingCancelProcessing=!1;copyMessageTimer=null;isShowingHelp=!1;isShowingConsoleOverlay=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingCostBreakdownOverlay=!1;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;cancelProcessingConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];dismissedEphemeralErrorKey=null;currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;isShowingPalette=!1;paletteInitialCommandId=null;threadsForPicker=[];isLoadingThreads=!1;threadPreviewController=new Jk1;previewThread=null;planScrollController=(()=>{let J=new p3;return J.followMode=!1,J})();todoScrollController=(()=>{let J=new p3;return J.followMode=!1,J})();showingSelectionCopiedHint=!1;isShowingStandaloneThreadPicker=!1;filterThreadPickerByWorkspace=!0;agentModePulseSeq=0;currentGitBranch=null;messageViewFocusNode=new c8({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new c8({debugLabel:"AutocompleteFocus"});isTextfieldAndAutocompleteFocused=!1;submitDisabledHint=null;submitDisabledHintTimer=null;showingCannotToggleMessage=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;adActionModal=null;threadFeedReader=null;currentThreadFeedEntry=null;threadFeedEntries=[];threadFeedSubscription=null;threadFeedRotationTimer=null;threadFeedHidden=!1;threadFeedShownIDs=new Set;threadFeedLatestShownPubDate=null;currentUserInfo=null;bottomGridUserHeight=void 0;bottomGridDragStartY=null;bottomGridDragStartHeight=null;pendingMCPServers=[];mcpTrustSubscription=null;agentModeSubscription=null;currentAgentMode="smart";hasToggledAgentMode=!1;inMemoryAgentModeOverride=null;cachedVisibleModes=mG();freeTierStatus=void 0;updateState="hidden";updateServiceSubscription=null;isMessageViewInSelectionMode=!1;threadBackStack=[];threadForwardStack=[];replayDisplayedMessages=[];replayAbortController=new AbortController;replayTypingTimer=null;async initThreadFeed(){let J=await B6(this.widget.dependencies.configService.config);if(J.settings["feed.enabled"]===!1)this.threadFeedHidden=!0;let Q=J.settings.url,Y=Q.includes("localhost")||Q.includes("127.0.0.1");try{let q=await this.widget.dependencies.internalAPIClient.getUserInfo({},{config:this.widget.dependencies.configService});if(q.ok){let V=q.result,K="user"in V?V.user:V;this.currentUserInfo={username:K.username??void 0,displayName:K.displayName??void 0};let W="ffe10a0c-6c42-41ce-a3a6-38990fd6caf8";if(!Y&&V.team?.id!==W)return}else return}catch(q){f.debug("Failed to fetch user info for thread feed filtering",q);return}let X="/threads.rss",G=async(q,V)=>{let K=q instanceof Request?q.url:q.toString();return RQ(K,V,this.widget.dependencies.configService)},Z=Tc0();Z.get("entries").then((q)=>{if(q){let V=this.filterEntries(q);if(this.threadFeedEntries=V,V.length>0&&!this.currentThreadFeedEntry){let K=this.getNextFeedEntry(V);if(K)this.setState(()=>{this.currentThreadFeedEntry=K})}}}),this.threadFeedReader=new LC1(Z,G,{url:X}),this.threadFeedSubscription=this.threadFeedReader.stream().subscribe({next:(q)=>{try{let V=this.filterEntries(q);if(V.length>0){this.threadFeedEntries=[...V,...this.threadFeedEntries];let K=this.getNextFeedEntry(V);if(K)this.setState(()=>{this.currentThreadFeedEntry=K}),this.resetThreadFeedRotation()}}catch(V){f.error("Thread feed: error in next handler",V)}},error:(q)=>{f.error("Thread feed error:",q)}}),this.resetThreadFeedRotation()}filterEntries(J){if(!this.currentUserInfo)return J;let{username:Q,displayName:Y}=this.currentUserInfo;return J.filter((X)=>{return!X.authors.some((G)=>{let Z=G.name;if(!Z)return!1;return Q&&Z===Q||Y&&Z===Y||Q&&Z.includes(Q)})})}rotateThreadFeed(){if(this.threadFeedRotationTimer)clearInterval(this.threadFeedRotationTimer);this.threadFeedRotationTimer=setInterval(()=>{if(this.threadFeedEntries.length>0){let J=this.getNextFeedEntry(this.threadFeedEntries);if(J)this.setState(()=>{this.currentThreadFeedEntry=J})}},30000)}resetThreadFeedRotation(){this.rotateThreadFeed()}getNextFeedEntry(J){let Q=J.filter((X)=>!this.threadFeedShownIDs.has(X.id));if(this.threadFeedLatestShownPubDate)Q=Q.filter((X)=>X.pubDate.getTime()>=this.threadFeedLatestShownPubDate.getTime());if(Q.length===0&&J.length>0)this.threadFeedShownIDs.clear(),this.threadFeedLatestShownPubDate=null,Q=J;if(Q.length===0)return null;Q.sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime());let Y=Q[0];if(this.threadFeedShownIDs.add(Y.id),!this.threadFeedLatestShownPubDate||Y.pubDate>this.threadFeedLatestShownPubDate)this.threadFeedLatestShownPubDate=Y.pubDate;return Y}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}navigateBack=async()=>{if(this.threadBackStack.length===0)return;let J=this.widget.dependencies.worker.thread.id,Q=this.threadBackStack.pop();this.threadForwardStack.push(J),await this.switchToExistingThread(Q,{recordInNavigationHistory:!1})};navigateForward=async()=>{if(this.threadForwardStack.length===0)return;let J=this.widget.dependencies.worker.thread.id,Q=this.threadForwardStack.pop();this.threadBackStack.push(J),await this.switchToExistingThread(Q,{recordInNavigationHistory:!1})};startAndSwitchToNewThread=async()=>{let J=this.widget.dependencies.worker.thread.id;this.recordNavigation(J);let Q=await this.widget.dependencies.startNewThread();return this.widget.dependencies.worker=Q,this.widget.dependencies.threadID=Q.thread.id,this.widget.dependencies.switchWorker(Q),this.setState(()=>{this.isMessageViewInSelectionMode=!1}),Q};async startReplay(){let J=this.widget.dependencies.replayMode;if(!J)return;let{thread:Q,typingEnabled:Y,baseWpm:X}=J,G=Q.messages;for(let Z=0;Z<G.length;Z++){if(this.replayAbortController.signal.aborted)break;let q=G[Z];if(!q)continue;if(Z>0)await this.replaySleep(J.messageDelayMs);if(q.role==="user"&&Y){let W=q.content.filter((H)=>H.type==="text").map((H)=>H.text).join(`
|
|
4817
4817
|
`);if(W)await this.replayTypeMessage(W,X)}if(q.role==="assistant"){let W=q.content.some((U)=>U.type==="tool_use"),H=G[Z+1],z=H?.role==="user"&&H.content.some((U)=>U.type==="tool_result");if(W&&z){let U={...q,state:{type:"streaming"}};this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,U],this.textController.clear()});let N=J.thread.id;this.getMessageScrollController(N).scrollToBottom(),await this.replaySleep(J.toolProgressDelayMs),this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages.slice(0,-1),q]});continue}}this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,q],this.textController.clear()});let V=J.thread.id;this.getMessageScrollController(V).scrollToBottom()}await this.replaySleep(J.exitDelayMs),E9.instance.stop()}async replayTypeMessage(J,Q){this.textController.clear();let Y=J.split(/(?<=\s)/),X=60000/Q;for(let G of Y){if(this.replayAbortController.signal.aborted)break;let Z=X/G.length;for(let q of G){this.textController.text=this.textController.text+q,this.textController.cursorPosition=this.textController.text.length,this.setState(()=>{});let V=0.8+Math.random()*0.4,K=Z*V;await this.replaySleep(K)}}}replaySleep(J){return new Promise((Q)=>{this.replayTypingTimer=setTimeout(Q,J)})}getEffectiveAgentMode(){return P41(this.widget.dependencies.worker.thread,this.inMemoryAgentModeOverride?{agentMode:this.inMemoryAgentModeOverride}:null,this.freeTierStatus,{"experimental.agentMode":this.currentAgentMode})}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(Boolean(J.viewState.inferenceState==="running"))return!0;let Y=J.items.filter((Z)=>Z.type==="toolResult").filter((Z)=>Z.toolResult.run.status==="in-progress"||Z.toolResult.run.status==="queued"),X=J.subagentActiveTools.filter((Z)=>Z.toolRun.status==="in-progress"||Z.toolRun.status==="queued");return[...Y,...X].length>0}showSubmitDisabledHint(J){if(this.submitDisabledHintTimer)clearTimeout(this.submitDisabledHintTimer);this.setState(()=>{this.submitDisabledHint=J}),this.submitDisabledHintTimer=setTimeout(()=>{this.setState(()=>{this.submitDisabledHint=null}),this.submitDisabledHintTimer=null},3000)}getUIHint(){let J=this.themeColors?.colorScheme;if(!J)return null;let Q=this.themeApp;if(!Q)return null;if(this.submitDisabledHint)return new J1(this.submitDisabledHint,new H1({color:J.foreground,dim:!0}));if(this.isExiting)return new J1("Exiting...",new H1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new J1("",void 0,[new J1("Ctrl+C",new H1({color:Q.keybind})),new J1(" again to exit",new H1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new J1("",void 0,[new J1("Esc",new H1({color:Q.keybind})),new J1(" again to clear input",new H1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new J1("",void 0,[new J1("Escape",new H1({color:Q.keybind})),new J1(" to close help",new H1({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let G=this.getEffectiveAgentMode(),Z=Gk1(G);return new J1("",void 0,[new J1("Images aren't supported in ",new H1({color:J.warning,dim:!1})),new J1(G,new H1({color:Z})),new J1(" mode.",new H1({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0){if(this.isConfirmingCancelProcessing)return new J1("",void 0,[new J1("Esc",new H1({color:Q.keybind})),new J1(" again to cancel",new H1({color:J.foreground,dim:!0}))]);return new J1("",void 0,[new J1("Esc",new H1({color:Q.keybind})),new J1(" to cancel",new H1({color:J.foreground,dim:!0}))])}if(this.showingSelectionCopiedHint)return new J1("Selection copied to clipboard",new H1({color:J.foreground,dim:!0}));if(this.showingCannotToggleMessage)return new J1(this.showingCannotToggleMessage,new H1({color:J.warning,dim:!1}));let Y=qY6(this.updateState,J);if(Y)return new J1("",void 0,Y);let X=this.widget.dependencies.worker.thread;if(X.agentMode==="plan"&&cA(X))return new J1("",void 0,[new J1("Ctrl+O",new H1({color:Q.keybind})),new J1(" → Execute Plan",new H1({color:J.foreground,dim:!0}))]);return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Q,worker:Y}=this.widget.dependencies;if(!Q.mainThread?.id)return;let G=Q.mainThread?.messages.findIndex((Z)=>Z===J);if(G===void 0||G===-1)return;try{this.cancelBashInvocations(),await Y.cancel(),await Y.handle({type:"thread:truncate",fromIndex:G}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(Z){f.error("Failed to edit message:",Z)}};forkMessage=async(J)=>{let{threadState:Q,workerDeps:Y,threadSyncService:X}=this.widget.dependencies,G=Q.mainThread?.id;if(!G)return;let Z=Q.mainThread?.messages.findIndex((q)=>q===J);if(Z===void 0||Z<=0)return;try{let q=await N3.getOrCreateForThread(Y,G),V=await VR(q,X,Z-1);await this.switchToExistingThread(V)}catch(q){f.error("Failed to fork thread:",q),this.showErrorMessage(`Failed to fork thread: ${q}`)}};handleMessageEditSubmit=async(J,Q)=>{let{threadState:Y,worker:X}=this.widget.dependencies,G=Y.mainThread;if(!G)return;let Z=G.messages.findIndex((q)=>q.messageId!==void 0&&q.messageId===J.messageId);if(Z===-1)return;try{this.cancelBashInvocations(),await X.cancel(),this.widget.dependencies.history.add(Q);let q=QN(Q);if(q)await X.handle({type:"thread:truncate",fromIndex:Z}),this.invokeBashCommand(q.cmd,{visibility:q.visibility});else{let V=[{type:"text",text:Q}];if(this.imageAttachments.length>0)V.push(...this.imageAttachments);let K={content:V,agentMode:G.agentMode},W=Z===0;if(G.agentMode&&!W&&K.agentMode!==G.agentMode){f.error(`Cannot edit message: This thread uses ${G.agentMode} mode. To change mode, create a new thread.`);return}await X.handle({type:"user:message",message:K,index:Z})}this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(q){f.error("Failed to edit message:",q)}};getAffectedFiles=async(J)=>{let{worker:Q}=this.widget.dependencies;try{return(await Q.getFilesAffectedByTruncation(J)).map(JJ)}catch(Y){return f.error("Failed to get affected files:",Y),[]}};textController=new fZ;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new p3);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.id;if(!Q)return;this.getMessageScrollController(Q).scrollToBottom()}findElementByKey(J){return this.searchElementTreeByKey(this.context.element,J)}searchElementTreeByKey(J,Q){if(!J)return null;if(J?.widget?.key?.value===Q)return J;if(J?.child){let X=this.searchElementTreeByKey(J.child,Q);if(X)return X}if(J?.children)for(let X of J.children){let G=this.searchElementTreeByKey(X,Q);if(G)return G}return null}setupSelectionListener(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller&&!this.selectionListener)this.selectionListener=()=>{this.setState(()=>{})},Q.controller.addListener(this.selectionListener),Q.controller.onSelectionCopied=()=>{if(this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}}updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.title;if(Q!==this.currentTitle){this.currentTitle=Q;let Y=process.cwd().replace(process.env.HOME||"","~"),X=Q?`amp - ${Q} - ${Y}`:"";process.stdout.write(yR1(X))}}_handleTextCopy(J){if(J&&J.length>0){if(this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}textFieldKey=new i7("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;connectedClientsStatusSubscription=null;paletteCommands=null;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text;if(J==="/"){this.showCommandPalette(),this.textController.clear();return}let Y=QN(J)?.visibility;if(Y!==this.currentShellModeStatus)this.currentShellModeStatus=Y,this.setState(()=>{})};navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!1}),J9.instance.addPostFrameCallback(()=>{this.autocompleteFocusNode.requestFocus()})};handleIdeSelection=async(J,Q)=>{if(this.widget.dependencies.ideClient.getSelectedConfig()?.pid===J.pid){this.dismissIdePicker();return}try{await this.connectToSelectedIde(J,Q)}catch(Y){let X=Y instanceof Error?Y.message:String(Y);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.dismissIdePicker()};async connectToSelectedIde(J,Q){await this.widget.dependencies.ideClient.start(J,!0,Q)}previewControllerListener=(J)=>{this.setState(()=>{this.previewThread=J})};showStandaloneThreadPicker=()=>{this.loadThreadsForPicker(),this.setState(()=>{this.isShowingStandaloneThreadPicker=!0})};dismissStandaloneThreadPicker=()=>{this.exitApplication()};handleStandaloneThreadSelect=async(J)=>{try{await this.switchToExistingThread(J,{recordInNavigationHistory:!1}),this.threadPreviewController.clear(),this.setState(()=>{this.isShowingStandaloneThreadPicker=!1}),J9.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingStandaloneThreadPicker)this.autocompleteFocusNode.requestFocus()})}catch(Q){f.error("Failed to switch thread:",Q),this.showErrorMessage(`Failed to switch thread: ${Q}`)}};toggleThreadPickerWorkspaceFilter=()=>{this.setState(()=>{this.filterThreadPickerByWorkspace=!this.filterThreadPickerByWorkspace})};showCommandPalette(J){if(this.setState(()=>{this.isShowingPalette=!this.isShowingPalette,this.paletteInitialCommandId=J??null}),this.isShowingPalette)this.loadThreadsForPicker()}getPaletteCommands(){if(!this.paletteCommands)this.paletteCommands=new E_1(this.widget.dependencies.configService,this.widget.dependencies.commandRegistry,(J)=>{this.setState(()=>{this.executingCommand=J})},()=>{this.setState(()=>{this.executingCommand=null})},this.widget.dependencies.isDogfooding);return this.paletteCommands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new T_1(this.widget.dependencies.fuzzyServer,this.widget.dependencies.threadFuzzyIndexer);return this.completionBuilder}dismissPalette=()=>{this.setState(()=>{this.isShowingPalette=!1,this.paletteInitialCommandId=null})};getCommandPaletteContext=()=>{let{threadState:J,recentThreadIDs:Q}=this.widget.dependencies;if(!J.mainThread)return null;let Y=n0.file(process.cwd()),X=A6(Y);return{recentThreadIDs:Q,currentThreadID:J.mainThread.id,worker:this.widget.dependencies.worker,editorState:this.textController,isProcessing:this.isProcessing(),thread:J.mainThread,ampURL:this.widget.dependencies.ampURL,threadSyncService:this.widget.dependencies.threadSyncService,configService:this.widget.dependencies.configService,openInEditor:this.openInEditor,takeImageAttachments:()=>{let G=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),G},setImageAttachments:(G)=>{this.setState(()=>{this.imageAttachments=G})},editorDispatch:(G)=>{switch(G.type){case"set-input":this.textController.clear(),this.textController.insertText(G.input);break;case"insert-text":this.textController.insertText(G.text);break;case"clear":this.textController.clear();break}},submitMessage:(G)=>{return this.proceedWithUserMessage(G)},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,connectedClientsService:this.widget.dependencies.connectedClientsService,mcpService:this.widget.dependencies.mcpService,startNewThread:async()=>{await this.startAndSwitchToNewThread()},navigateBack:this.navigateBack,navigateForward:this.navigateForward,canNavigateBack:this.threadBackStack.length>0,canNavigateForward:this.threadForwardStack.length>0,canUseAmpFree:this.widget.dependencies.freeTierStatus?.canUseAmpFree??!1,switchToThread:async(G)=>{return await this.switchToExistingThread(G),this.setState(()=>{this.isMessageViewInSelectionMode=!1}),this.widget.dependencies.worker},generateHandoffPrompt:async(G,Z,q)=>{let V=this.widget.dependencies.threadState.mainThread?.id;if(!V)throw Error("No active thread");let K=setTimeout(()=>{q.throwIfAborted()},60000);try{let W=await this.widget.dependencies.threadService.generateHandoffPrompt(V,G,Z,this.widget.dependencies.configService,q);return clearTimeout(K),W}catch(W){throw clearTimeout(K),W}},handleHandoff:async(G,Z)=>{let{goal:q,generatedPrompt:V,images:K}=Z;if(!q&&!V)return{ok:!1,error:Error("Either goal or generatedPrompt required")};try{let W=this.widget.dependencies.threadState.mainThread?.id;if(!W)return{ok:!1,error:Error("No active thread")};let H=setTimeout(()=>G.abort(new l81("Handoff took too long and was aborted (timeout: 60s)")),60000);try{let z=await this.widget.dependencies.threadService.createHandoffThread(W,{goal:q,generatedPrompt:V,images:K},this.widget.dependencies.configService,G.signal);return clearTimeout(H),await this.switchToExistingThread(z),{ok:!0}}catch(z){if(clearTimeout(H),z instanceof Error&&(z.name==="AbortError"||z.message.includes("aborted")))throw G.signal.reason;throw z}}catch(W){return f.error("Failed to create handoff thread",W),{ok:!1,error:W instanceof Error?W:Error(String(W))}}},getGuidanceFiles:async(G)=>{if(!J.mainThread)return[];return(await bo({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},J.mainThread,G)).map((q)=>({uri:q.uri,type:q.type}))},openIdePicker:()=>{this.openIdePicker()},getInMemoryAgentModeOverride:()=>{return this.inMemoryAgentModeOverride},setInMemoryAgentModeOverride:(G)=>{this.setState(()=>{this.inMemoryAgentModeOverride=G,this.hasToggledAgentMode=!0})},toggleAgentMode:this.toggleAgentMode,getEffectiveAgentMode:()=>this.getEffectiveAgentMode(),getEditorText:()=>this.textController.text,workspace:this.widget.dependencies.workspace??null,handleExecutePlan:async()=>{try{let G=J.mainThread?.id;if(!G){this.setState(()=>{this.displayMessage=Error("No active thread")});return}let Z=await this.widget.dependencies.threadService.createPlanExecutionThread(G,"smart");await this.switchToExistingThread(Z)}catch(G){f.error("Failed to execute plan",G),this.setState(()=>{this.displayMessage=Error(`Failed to execute plan: ${G instanceof Error?G.message:String(G)}`)})}},planFileManager:this.widget.dependencies.planFileManager,completionBuilder:this.getCompletionBuilder(),threads:this.threadsForPicker,previewController:this.threadPreviewController,isLoadingThreads:this.isLoadingThreads,filterByWorkspace:this.filterThreadPickerByWorkspace,currentWorkspace:X,threadViewStates:this.widget.dependencies.workerController.threadViewStates,currentThreadFeedEntry:this.currentThreadFeedEntry,threadFeedEntries:this.threadFeedEntries,threadFeedHidden:this.threadFeedHidden,setThreadFeedHidden:(G)=>{this.setState(()=>{this.threadFeedHidden=G})}}};loadThreadsForPicker(){if(this.threadLoadSubscription)return;this.setState(()=>{this.isLoadingThreads=!0});let J=new e_1(this.widget.dependencies.threadHistoryService);this.threadLoadSubscription=J.observeThreadSummaries("").subscribe({next:(Q)=>{this.setState(()=>{this.threadsForPicker=Q,this.isLoadingThreads=!1})},error:()=>{this.setState(()=>{this.isLoadingThreads=!1})}})}updateGitBranch=async()=>{let J=await fN8(process.cwd());this.setState(()=>{this.currentGitBranch=J})};removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Q)=>Q.id!==J)})};invokeBashCommand=(J,{visibility:Q})=>{let Y=Date.now(),X=`bash-${Y}-${Math.random().toString(36).substring(7)}`,G={cmd:J},Z=new AbortController;this.widget.dependencies.worker.invokeBashTool(G,Z.signal,Q===JN).subscribe({next:(q)=>{this.setState(()=>{if(this.bashInvocations.find((K)=>K.id===X))this.bashInvocations=this.bashInvocations.map((K)=>K.id===X?{...K,toolRun:q}:K);else{let K={id:X,args:G,toolRun:q,startTime:Y,abortController:Z,hidden:Q===JN};this.bashInvocations=[...this.bashInvocations,K]}})},error:()=>this.removeBashInvocation(X),complete:()=>this.removeBashInvocation(X)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Q)=>Q.toolRun.status==="in-progress");if(J)J.abortController.abort()};toggleConnectedClientsStatus=()=>{this.setState(()=>{this.connectedClientsStatusExpanded=!this.connectedClientsStatusExpanded})};toggleAgentMode=()=>{let J=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker;if(_$(J.thread)>0)return;if(this.freeTierStatus?.canUseAmpFree){let X=this.getEffectiveAgentMode(),G=Pk(X,this.cachedVisibleModes);if(G!==X)this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=G,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1});return}let Q=this.getEffectiveAgentMode(),Y=Pk(Q,this.cachedVisibleModes);if(Y===Q)return;if(this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=Y,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1}),E5(Y))this.checkAndShowFreeModeModal()};checkAndShowFreeModeModal=()=>{if(this.freeTierStatus?.canUseAmpFree)return;if(this.freeTierStatus){if(!this.freeTierStatus.eligible){this.setState(()=>{this.showingCannotToggleMessage="Amp Free is unavailable. Switch to another mode."}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}else if(!this.freeTierStatus.workspaceAllowsAmpFree){this.setState(()=>{this.showingCannotToggleMessage="Your workspace does not allow Amp Free. Switch to another mode."}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}}};isInRestrictedFreeMode(){if(this.getEffectiveAgentMode()!=="free")return!1;if(this.freeTierStatus?.canUseAmpFree)return!1;return!0}handleInsertImage=(J)=>{let Q=this.getEffectiveAgentMode();if(!Ik(Q)){if(this.imageUnsupportedHintTimer)clearTimeout(this.imageUnsupportedHintTimer);return this.setState(()=>{this.showImageUnsupportedHint=!0}),this.imageUnsupportedHintTimer=setTimeout(()=>{this.setState(()=>{this.showImageUnsupportedHint=!1}),this.imageUnsupportedHintTimer=null},5000),!1}if(this.imageAttachments.length>=VU)return!1;let Y=FC(J);if(typeof Y==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Y]}),!1;return this.setState(()=>{this.displayMessage=Error(`Failed to attach image: ${Y}`)}),!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};openInEditor=async(J)=>{let{mkdtemp:Q,readFile:Y,unlink:X,rmdir:G,writeFile:Z}=await import("node:fs/promises"),{tmpdir:q}=await import("node:os"),V=await import("node:path");try{let K=await Q(V.join(q(),"amp-edit-")),W=V.join(K,"message.amp.md");await Z(W,J,"utf-8"),await Bz(W);try{let H=await Y(W,"utf-8");this.textController.text=H}catch(H){if(H?.code!=="ENOENT")f.error("Failed to read temporary file",H)}try{await X(W),await G(K)}catch(H){f.warn("Failed to clean up temporary file",H)}}catch(K){f.error("Error opening editor:",K)}};onTextSubmitted=async(J)=>{if(!J.trim())return;let Q=QN(J);if(Q)if(!Q.cmd){this.showSubmitDisabledHint("No command provided");return}else if(this.isProcessing()){this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}else{this.invokeBashCommand(Q.cmd,{visibility:Q.visibility}),this.widget.dependencies.history.add(J),this.textController.clear(),this.resetHistory();return}this.textController.clear(),this.resetHistory(),await this.updateGitBranch(),await this.sendUserMessage(J)};initState(){if(oX.getInstance().interceptConsole(),this.threadPreviewController.setThreadService(this.widget.dependencies.threadService),this.threadPreviewController.addListener(this.previewControllerListener),this.widget.dependencies.openThreadSwitcher)this.showStandaloneThreadPicker();E9.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),E9.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),E9.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()}),this.autocompleteFocusNode.addListener((Y)=>{J9.instance.addPostFrameCallback(()=>{this.setState(()=>{this.isTextfieldAndAutocompleteFocused=Y.hasFocus})})}),this.freeTierStatus=this.widget.dependencies.freeTierStatus,B6(this.widget.dependencies.configService.config).then((Y)=>{let X=P41(this.widget.dependencies.worker.thread,this.widget.dependencies.sessionState??null,this.freeTierStatus,Y.settings);if(f.info(`[initState] Resolved agentMode: ${X}`),this.widget.dependencies.sessionState?.agentMode)this.setState(()=>{this.inMemoryAgentModeOverride=X})}),this.updateGitBranch(),this.adSubscription=eR1(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>{return(this.inMemoryAgentModeOverride&&E5(this.inMemoryAgentModeOverride)||this.randomAd===null)&&tR1(this.lastUserInteractionTime)}).subscribe({next:(Y)=>{if(Y){let X=xN8(16).toString("hex");this.lastAdImpressionId=X,Promise.resolve().then(() => (z91(),H91)).then(({recordAdEvent:G})=>{let Z=this.widget.dependencies.worker.thread,q=Z.messages[Z.messages.length-1];G("viewed",{adId:Y.id,advertiserId:Y.advertiserId,threadId:Z.id,messageId:q?.messageId,impressionId:X,placement:"tui",matchType:Y.metadata?.matchType,matchedPatterns:Y.metadata?.matchedPatterns,candidateAdPoolCount:Y.metadata?.candidateAdPoolCount,clientRegion:Y.metadata?.clientRegion})})}this.setState(()=>{this.randomAd=Y}),J9.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingStandaloneThreadPicker&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})}});let{mcpTrustHandler:J}=this.widget.dependencies;this.mcpTrustSubscription=J.pendingServers$.subscribe((Y)=>{this.setState(()=>{this.pendingMCPServers=Y})}),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((Y)=>{this.setState(()=>{this.ideStatus=Y})}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(Y)=>{let X=this.widget.dependencies.getCurrentWorker();if(!X){f.warn("No active thread worker found to handle IDE message");return}await new Promise((G)=>setTimeout(G,50)),await X.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}}),f.debug("Message sent from IDE to agent",{message:Y.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Y)=>{this.textController.insertText(Y),f.debug("Appended text to CLI prompt from IDE",{text:Y.slice(0,100)})}),this.connectedClientsStatusSubscription=this.widget.dependencies.connectedClientsService.status.subscribe((Y)=>{this.setState(()=>{this.connectedClientsStatus=Y})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((Y)=>{this.setState(()=>{this.updateState=Y})}),this.agentModeSubscription=this.widget.dependencies.configService.config.subscribe((Y)=>{let X=mG(Y.settings,this.freeTierStatus?.canUseAmpFree);this.setState(()=>{this.cachedVisibleModes=X})}),this.textController.addListener(this.textChangeListener),this.updateTerminalTitle();let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q)this.connectToSelectedIde(Q,"auto-startup").catch((Y)=>{let X=Y instanceof Error?Y.message:String(Y);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller();if(this.widget.dependencies.replayMode)setTimeout(()=>this.startReplay(),100);this.initThreadFeed()}didUpdateWidget(J){super.didUpdateWidget(J),this.setupSelectionListener()}dispose(){if(this.replayAbortController.abort(),this.replayTypingTimer)clearTimeout(this.replayTypingTimer);if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.connectedClientsStatusSubscription)this.connectedClientsStatusSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeSubscription)this.agentModeSubscription.unsubscribe();if(this.adSubscription)this.adSubscription.unsubscribe();if(this.mcpTrustSubscription)this.mcpTrustSubscription.unsubscribe();if(this.threadLoadSubscription)this.threadLoadSubscription.unsubscribe();if(this.threadFeedSubscription)this.threadFeedSubscription.unsubscribe();if(this.threadFeedRotationTimer)clearInterval(this.threadFeedRotationTimer);if(this.threadPreviewController.removeListener(this.previewControllerListener),this.threadPreviewController.dispose(),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.textController.removeListener(this.textChangeListener);for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(yR1("")),this.shouldUseProgressBar())process.stdout.write(z96())}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,X=[...J.items.filter((V)=>V.type==="toolResult").map((V)=>({toolUse:V.toolUse,toolRun:V.toolResult.run,subthreadID:void 0})),...J.subagentActiveTools].filter((V)=>V.toolRun.status==="blocked-on-user");if(X.length===0)return null;let G=X[0],Z=G.toolRun.status==="blocked-on-user"?G.toolRun.toAllow??[]:[],q=G.toolRun.status==="blocked-on-user"?G.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:G.toolUse,toAllow:Z}],subthreadID:G.subthreadID,reason:q}}shouldUseProgressBar(){return!1}updateProgressBar(){}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){f.error("No current tool confirmation found");return}let Y=Q.tools[0]?.useBlock;if(!Y){f.error("No tool use block found in confirmation");return}if(J==="allow-all-session")w$("dangerouslyAllowAll",!0);if(J==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0,"global")}catch(G){if(G&&G instanceof Error)this.setState(()=>{this.displayMessage=G});else f.error("Failed to write dangerouslyAllowAll setting:",G);return}if(J==="always-guarded"){let G=Q.tools[0]?.toAllow??[],Z=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],q=[...G,...Z];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",q,"global")}if(J==="connect-github"){let G=new URL("/settings#code-host-connections",this.widget.dependencies.ampURL).toString();try{await j3(G)}catch(Z){f.error("Failed to open settings page:",Z),await this.showErrorMessage(`Cannot open browser. Please go to ${G} to connect to GitHub`)}return}if(J==="disable-librarian"){let G=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!G.includes(BX))await this.widget.dependencies.settingsStorage.set("tools.disable",[...G,BX],"global")}let X=J!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(J);try{let G={type:"user:tool-input",toolUse:Y.id,value:{accepted:X}};if(Q.subthreadID)await(await N3.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(G);else await this.widget.dependencies.worker.handle(G)}catch(G){f.error("Failed to send tool confirmation:",G)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};getErrorKey(J){return`${J.constructor.name}:${J.message}`}getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Q=J.viewState;if(Q.state!=="active"||!Q.ephemeralError)return null;let Y=this.getErrorKey(Q.ephemeralError);if(this.dismissedEphemeralErrorKey===Y)return null;return Q.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let Q=this.getCurrentEphemeralError(),Y=this.widget.dependencies.worker;switch(J){case"retry":this.dismissedEphemeralErrorKey=null,await Y.retry();break;case"dismiss":if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);break;case"new-thread":{this.setState(()=>{this.dismissedEphemeralErrorKey=null}),await this.startAndSwitchToNewThread();break}case"new-smart-thread":{this.setState(()=>{this.inMemoryAgentModeOverride="smart",this.dismissedEphemeralErrorKey=null}),k61({agentMode:"smart"}),await this.startAndSwitchToNewThread();break}case"handoff":{if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);this.showCommandPalette("handoff");break}}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};handleMCPTrustOpenSettings=async()=>{let{mcpTrustHandler:J,settingsStorage:Q}=this.widget.dependencies;await J.deny();try{await Bz(Q.getSettingsFilePath())}catch(Y){let X=Y instanceof Error?Y.message:String(Y);await this.showErrorMessage(`Failed to open settings: ${X}`)}};cancelStreamingMessage=async()=>{await N3.cancel(this.widget.dependencies.threadID)};markLastUserMessageAsInterrupted=async()=>{let J=this.widget.dependencies.threadState.mainThread;if(!J)return;for(let Q=J.messages.length-1;Q>=0;Q--){let Y=J.messages[Q];if(Y?.role==="user"&&!Y.interrupted){await this.widget.dependencies.worker.handle({type:"user:message:interrupt",messageIndex:Q});break}}};switchToExistingThread=async(J,Q={})=>{let{recordInNavigationHistory:Y=!0}=Q;if(Y){let X=this.widget.dependencies.worker.thread.id;if(X!==J)this.recordNavigation(X)}try{f.info(`[switchToExistingThread] Switching to thread: ${J}`);let X=await this.widget.dependencies.switchToThread(J);f.info(`[switchToExistingThread] Got worker for thread ${J}, thread.agentMode: ${X.thread.agentMode}`);let G=await this.widget.dependencies.configService.getLatest(),Z=P41(X.thread,this.widget.dependencies.sessionState??null,this.freeTierStatus,G.settings);if(f.info(`[switchToExistingThread] Thread ${J} resolved agentMode: ${Z}`),this.widget.dependencies.worker=X,this.widget.dependencies.threadID=X.thread.id,this.widget.dependencies.switchWorker(X),this.setState(()=>{f.info("[switchToExistingThread] Clearing inMemoryAgentModeOverride"),this.inMemoryAgentModeOverride=null}),X.thread.draft)if(f.info("[switchToExistingThread] Loading draft content into text controller"),this.textController.clear(),typeof X.thread.draft==="string")this.textController.insertText(X.thread.draft);else{let q=X.thread.draft.filter((W)=>W.type==="text"),V=X.thread.draft.filter((W)=>W.type==="image"),K=q.map((W)=>W.text).join(`
|
|
4818
4818
|
`);if(K)this.textController.insertText(K);if(V.length>0)this.setState(()=>{this.imageAttachments=V})}}catch(X){throw f.error("Failed to switch to thread:",J,X),Error(`Failed to switch to thread: ${J}`)}};sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J)=>{this.cancelBashInvocations(),this.widget.dependencies.history.add(J);let Q=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,Y=_$(Q.thread)===0,X=this.getEffectiveAgentMode();if(Q.thread.agentMode&&!Y&&X!==Q.thread.agentMode){await this.showErrorMessage(`This thread uses ${Q.thread.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let G=[{type:"text",text:J}];if(this.imageAttachments.length>0)G.push(...this.imageAttachments);if(await Q.handle({type:"user:message",message:{content:G,agentMode:X}}),Y)k61({agentMode:X});this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]}),J9.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingStandaloneThreadPicker&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}exitApplication=async()=>{this.setState(()=>{this.isExiting=!0});let J=this.widget.dependencies.threadState.mainThread;if(J?.messages.length===0){if(J.relationships?.find((X)=>X.type==="handoff"&&X.role==="child"))await this.widget.dependencies.threadService.discardHandoffThread(J.id).catch(()=>{})}let Q=this.getEffectiveAgentMode();k61({agentMode:Q}).catch((Y)=>{f.warn("Failed to save session state on exit:",Y)}).finally(()=>{E9.instance.stop()})};onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;this.exitApplication()}else{if(this.setState(()=>{this.isConfirmingExit=!0}),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout);this.exitConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingExit=!1}),this.exitConfirmTimeout=null},1000)}};toHomeRelative(J){let Q=vN8();if(J===Q)return"~";if(J.startsWith(Q+Em.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(Em.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(Em.sep),"…",Q.slice(-2).join(Em.sep)].join(Em.sep)}build(J){let Q=U8.of(J),Y=x6.of(J),X=Y.base;this.themeColors=X;let{colors:G,app:Z}=Y;this.themeApp=Z;let q=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,V=q.thread.agentMode&&E5(q.thread.agentMode),K=V&&this.randomAd!==null,W=!V&&this.currentThreadFeedEntry!==null&&!this.threadFeedHidden,H=K||W,{threadState:z}=this.widget.dependencies;this.updateTerminalTitle(),this.updateProgressBar();let U=this.getCurrentConfirmation(),N=this.widget.dependencies.replayMode,M=Boolean(N),L=z.items,A=z.mainThread||void 0,E=z.subagentToolsByParentID,P=z.todosList;if(M){let d6={...N.thread,messages:this.replayDisplayedMessages};L=SC(d6).items,A=d6,E={};let _4=tE({messages:this.replayDisplayedMessages});P=Array.isArray(_4)?_4:[]}let I=A?.id,R=A,j=M?this.replayDisplayedMessages.length===0:this.isTranscriptEmpty(),y=(d6)=>new p81({key:new i7(`preview-message-view-${d6.id}`),items:SC(d6).items,controller:this.threadPreviewController.scrollController,autofocus:!1,thread:d6,focusNode:new c8({debugLabel:"PreviewFocus"})}),h=this.previewThread,u=h?h.messages.length>2000?new s0({mainAxisSize:"max",children:[new z4({child:new U0}),new c6({padding:f0.all(2),child:new H8({child:new d1({text:new J1("Thread too long for preview",new H1({color:G.mutedForeground,dim:!0}))})})})]}):y(h):j?new c81({agentMode:this.getEffectiveAgentMode()}):new p81({key:I?new i7(`message-view-${I}`):void 0,items:L,subagentToolsByParentID:E,controller:I?this.getMessageScrollController(I):new p3,autofocus:!1,onCopy:M?void 0:this._handleTextCopy.bind(this),thread:R,onMessageEditSubmit:M?void 0:this.handleMessageEditSubmit,onMessageRestoreSubmit:M?void 0:this.handleMessageRestoreSubmit,onMessageForkSubmit:M?void 0:this.forkMessage,getAffectedFiles:M?void 0:this.getAffectedFiles,focusNode:this.messageViewFocusNode,onDismissFocus:()=>{if(this.setState(()=>{this.isMessageViewInSelectionMode=!1}),!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()},isInSelectionMode:this.isMessageViewInSelectionMode}),p=Math.max(Math.floor(Q.size.height*0.4),12),b=this.getCurrentEphemeralError(),l=this.buildBottomWidget(b,U,G,Y,z,P,p,H,M),Q1=Q.size.width<40,a=z.mainThread?kU0(z.mainThread):void 0,g=new G81({threadViewState:z.viewState,threadTokenUsage:a,threadID:I??null,thread:z.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onCostBreakdownClick:()=>{this.setState(()=>{this.isShowingCostBreakdownOverlay=!this.isShowingCostBreakdownOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,connectedClientsStatus:this.connectedClientsStatus,isNarrow:Q1,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!U,showingEphemeralError:Boolean(z.viewState.state==="active"&&z.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),s=new X81({bashInvocations:this.bashInvocations}),q1=[],V1=this.getEffectiveAgentMode(),o=this.currentShellModeStatus,r=Gk1(V1),i=!o?V1.length+1:0,F1=Q.capabilities.animationSupport,y1=F1==="disabled"?0:F1==="slow"?30:60,t=RV(V1)?.uiHints?.fasterAnimation?3:1,f1=y1>0&&this.agentModePulseSeq>0?new e5({children:[l,new u3({top:0,left:1,right:1,height:1,child:new a_1({color:r,trigger:this.agentModePulseSeq,fps:y1,speed:t,leftOffset:i})})]}):l;q1.push(new z4({child:u}),s);let j1=new e5({children:[new s0({mainAxisSize:"min",children:[K?new F_1({ad:this.randomAd,onButtonClick:async()=>{let d6=this.randomAd;if(this.lastAdImpressionId)Promise.resolve().then(() => (z91(),H91)).then(({recordAdEvent:_4})=>{let i4=this.widget.dependencies.worker.thread,u4=i4.messages[i4.messages.length-1];_4("clicked",{adId:d6.id,advertiserId:d6.advertiserId,threadId:i4.id,messageId:u4?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to",matchType:d6.metadata?.matchType,matchedPatterns:d6.metadata?.matchedPatterns,candidateAdPoolCount:d6.metadata?.candidateAdPoolCount,clientRegion:d6.metadata?.clientRegion})});try{await j3(d6.shortDestinationUrl)}catch(_4){let u4=E9.instance.tuiInstance.clipboard.isOsc52Supported();this.setState(()=>{this.adActionModal={showCopyOption:u4,url:d6.shortDestinationUrl}})}}}):W?new t_1({entry:this.currentThreadFeedEntry}):new U0({height:0}),new J6({constraints:new r6(0,Q.size.width,0,p),child:f1})]}),H?new u3({top:0,left:0,right:0,child:new BY6({userHeight:this.bottomGridUserHeight,maxHeight:p,onInitializeHeight:(d6)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(d6,p)})},onDrag:(d6)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(d6.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let _4=Math.floor(d6.localPosition.y)-this.bottomGridDragStartY,i4=Math.max(4,this.bottomGridDragStartHeight-_4),u4=Math.min(i4,p),w4=Math.floor(u4);if(this.bottomGridUserHeight!==w4)this.setState(()=>{this.bottomGridUserHeight=w4})},onRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null}})}):new U0({height:0})]});q1.push(j1,new U0({height:1,child:new c6({padding:f0.horizontal(1),child:g})}));let w0=new s0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:q1}),C1=M?new e5({children:[w0,new u3({top:0,left:0,child:new s_1})]}):w0,s1=new Q9(()=>{if(this.isShowingPalette)return this.dismissPalette(),"handled";if(this.pendingMCPServers.length>0)return this.widget.dependencies.mcpTrustHandler.deny(),"handled";if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingCostBreakdownOverlay)return this.setState(()=>{this.isShowingCostBreakdownOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.textController.hasSelection)return this.textController.clearSelection(),"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.isConfirmingCancelProcessing){if(this.bashInvocations.length>0)this.cancelBashInvocations();if(this.isProcessing())this.markLastUserMessageAsInterrupted().catch((_4)=>{f.error("Failed to mark message as interrupted:",_4)}),this.cancelStreamingMessage().catch((_4)=>{f.error("Failed to cancel streaming message:",_4)});if(this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout),this.cancelProcessingConfirmTimeout=null;return"handled"}if(this.executingCommand)return f.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.bashInvocations.length>0||this.isProcessing()){if(this.setState(()=>{this.isConfirmingCancelProcessing=!0}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout);return this.cancelProcessingConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout=null},1000),"handled"}if(this.textController.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return"ignored"}),U1=new Q9(()=>{return this.onExitPressed(),"handled"}),Y1=new Q9(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),A1=new Q9(()=>{return OJ.instance.toggleAll(),"handled"}),w1=new Q9(()=>{return this.widget.dependencies.configService.getLatest().then((d6)=>{w$("internal.showCost",!(d6.settings["internal.showCost"]??!0))}),"handled"}),I1=new Q9(()=>{return E9.instance.toggleFrameStatsOverlay(),"handled"}),E1=new Q9(()=>{return E9.instance.tuiInstance.getScreen().markForRefresh(),J9.instance.requestFrame(),"handled"}),p1=new Q9(()=>{return this.toggleAgentMode(),"handled"}),h1=new Q9(()=>{let _4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:i4}=this.widget.dependencies,u4=i4.mainThread?.id;return u4?this.getMessageScrollController(u4):null})();if(_4){let i4=Math.max(Math.floor(Q.size.height*0.4),10),u4=Q.size.height-i4;_4.animatePageUp(u4,100)}return"handled"}),r1=new Q9(()=>{let _4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:i4}=this.widget.dependencies,u4=i4.mainThread?.id;return u4?this.getMessageScrollController(u4):null})();if(_4){let i4=Math.max(Math.floor(Q.size.height*0.4),10),u4=Q.size.height-i4;_4.animatePageDown(u4,100)}return"handled"}),$0=new Q9(()=>{let _4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:i4}=this.widget.dependencies,u4=i4.mainThread?.id;return u4?this.getMessageScrollController(u4):null})();if(_4)_4.animateTo(0,100);return"handled"}),G0=new Q9(()=>{let _4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:i4}=this.widget.dependencies,u4=i4.mainThread?.id;return u4?this.getMessageScrollController(u4):null})();if(_4)_4.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),R0=new Q9(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";let{threadState:d6}=this.widget.dependencies;if(!d6.mainThread?.messages.some((i4)=>i4.role==="user"||sE(i4)))return"ignored";return this.setState(()=>{this.isMessageViewInSelectionMode=!0}),"handled"}),F6=new Q9((d6)=>{if(d6.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),M6=new Q9(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return t41().then(async(d6)=>{if(d6)try{this.handleInsertImage(d6)}finally{try{let{unlink:_4}=await import("node:fs/promises");await _4(d6)}catch{}}}),"handled"}),N4=new Map([[B4.ctrl("c"),new sg],[B4.ctrl("l"),new Ym],[B4.ctrl("o"),new p41],[B4.ctrl("v"),new og],[B4.alt("s"),new BC],[B4.ctrl("s"),new BC],[B4.alt("p"),new Qm],[B4.ctrl("r"),new eg],[B4.alt("d"),new Jm],[B4.ctrl("t"),new Xm],[B4.key("PageUp"),new b41],[B4.key("PageDown"),new g41],[B4.key("Home"),new m41],[B4.key("End"),new u41],[B4.key("Escape"),new rg],[B4.ctrl("p"),new NC("previous")],[B4.ctrl("n"),new NC("next")],[B4.key("Tab"),new Gm]]);if(!c2())N4.set(B4.key("ArrowUp"),new Gm);if(!1)N4.set(B4.alt("c"),new tg);let S9=new Q9(()=>{if(this.isShowingStandaloneThreadPicker)return"handled";return this.showCommandPalette(),"handled"}),I0=new Q9(()=>{return this.toggleThreadPickerWorkspaceFilter(),"handled"}),u0=new Map([[rg,s1],[Ym,E1],[BC,p1],[p41,S9],[og,M6],[tg,Y1],[eg,A1],[Jm,w1],[Qm,I1],[Xm,I0],[sg,U1],[b41,h1],[g41,r1],[m41,$0],[u41,G0],[Gm,R0],[NC,F6]]),_6=[C1];if(this.isShowingConsoleOverlay)_6.push(new j_1);if(this.isShowingHelp){let d6=this.getPaletteCommands().getAllCommands();_6.push(new k_1({commands:d6}))}if(this.adActionModal)_6.push(new U_1({title:"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(d6)=>{let _4=this.adActionModal.url;if(d6==="copy")try{await E9.instance.tuiInstance.clipboard.writeText(_4),this.setState(()=>{this.displayMessage=new QG("Link copied to clipboard")})}catch(i4){f.error("Failed to copy to clipboard",{error:i4}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null})}}));if(this.pendingMCPServers.length>0){let{mcpTrustHandler:d6}=this.widget.dependencies;_6.push(new o_1({servers:this.pendingMCPServers,onAlwaysTrust:d6.trustAlways.bind(d6),onTrustOnce:d6.trustOnce.bind(d6),onOpenSettings:this.handleMCPTrustOpenSettings,onDismiss:d6.deny.bind(d6)}))}if(this.isShowingFileChangesOverlay)_6.push(new Bj1({threadData:z}));if(this.isShowingCostBreakdownOverlay&&z.mainThread)_6.push(new S_1({thread:z.mainThread}));if(this.isShowingConfirmationOverlay)_6.push(new R_1({details:this.confirmationOverlayContent}));let Q8=this.getCommandPaletteContext();if(Q8&&this.isShowingPalette)_6.push(new H8({child:new J6({constraints:r6.loose(80,20),child:new P_1({commandContext:Q8,mainThread:z.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette,initialCommandId:this.paletteInitialCommandId??void 0})})}));if(this.isShowingIdePicker)_6.push(new x_1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode}));if(this.isShowingStandaloneThreadPicker){let d6=n0.file(process.cwd()),_4=A6(d6);_6.push(new H8({child:new J6({constraints:r6.loose(80,20),child:new OC({threads:this.threadsForPicker,title:"Continue Thread",onSelect:this.handleStandaloneThreadSelect,onDismiss:this.dismissStandaloneThreadPicker,previewController:this.threadPreviewController,isLoading:this.isLoadingThreads,currentWorkspaceURI:_4,filterByWorkspace:this.filterThreadPickerByWorkspace,threadViewStates:this.widget.dependencies.workerController.threadViewStates,recentThreadIDs:this.widget.dependencies.recentThreadIDs,currentThreadID:this.widget.dependencies.threadState.mainThread?.id})})}))}let k8=new e5({children:_6});if(this.isShowingJetBrainsInstaller)return new JO({child:new cQ({actions:u0,child:new Pq({shortcuts:N4,debugLabel:"jetbrains-installer-shortcuts",child:new n_1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});let B5=new YN({onError:(d6)=>{this.showErrorMessage(d6.message)},child:k8});return new JO({child:new cQ({actions:u0,child:new Pq({shortcuts:N4,debugLabel:"main-app-shortcuts",child:B5})})})}buildScrollableTodoList(J,Q,Y){return new FY6({todos:J,enabled:Q,controller:this.todoScrollController,appTheme:Y})}buildBottomWidget(J,Q,Y,X,G,Z,q,V,K){if(J)return new __1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new C_1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new r_1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let W=X.app,H=Y81(X),z=this.isInRestrictedFreeMode(),U=new NO({key:this.textFieldKey,controller:this.textController,triggers:K?[]:[new KN],completionBuilder:K?void 0:this.getCompletionBuilder(),ampURL:this.widget.dependencies.ampURL,onSubmitted:K?void 0:this.onTextSubmitted,theme:Y,placeholder:K?"Press Ctrl+C to exit":z?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,enabled:this.isTextfieldAndAutocompleteFocused&&!z&&!this.isShowingStandaloneThreadPicker,shellPromptRules:H,focusNode:this.autocompleteFocusNode,autofocus:!this.isMessageViewInSelectionMode&&!this.isShowingStandaloneThreadPicker&&!this.isShowingIdePicker,clipboard:E9.instance.tuiInstance.clipboard,onCopy:this._handleTextCopy.bind(this),onInsertImage:this.handleInsertImage,imageAttachments:this.imageAttachments,popImage:this.handlePopImage}),N=G.mainThread?.queuedMessages??[],M=Array.isArray(Z)&&Z.length>0,L=Array.isArray(N)&&N.length>0,A=G.mainThread?.agentMode==="plan"&&cA(G.mainThread),E,P;if(A){if(E=new bC1(new d81({thread:G.mainThread,onExecute:async()=>{let b=this.getCommandPaletteContext();if(b)await this.getPaletteCommands().execute("execute-plan",b,void 0,new AbortController)},onEdit:async()=>{try{let b=process.env.EDITOR||process.env.VISUAL||"nano",{filePath:l}=await this.widget.dependencies.planFileManager.ensureSync(G.mainThread.id);E9.instance.tuiInstance.suspend();let{execSync:Q1}=await import("child_process");Q1(`${b} "${l}"`,{stdio:"inherit"}),E9.instance.tuiInstance.resume()}catch(b){f.error("Failed to edit plan",b),this.setState(()=>{this.displayMessage=Error("Failed to edit plan")})}},controller:this.planScrollController,appTheme:X}),{clipBehavior:"antiAlias"}),L)P=new W91({queuedMessages:N});else if(M)P=this.buildScrollableTodoList(Z,this.isTextfieldAndAutocompleteFocused&&!z,X)}else E=L?new W91({queuedMessages:N}):void 0,P=M?this.buildScrollableTodoList(Z,this.isTextfieldAndAutocompleteFocused&&!z,X):void 0;let I=[],R=this.currentShellModeStatus;if(R)I.push({text:new J1(R==="hidden"?"shell mode (incognito)":"shell mode",new H1({color:R==="hidden"?X.app.shellModeHidden:X.app.shellMode})),position:"top-left"});if(!R&&this.cachedVisibleModes.length>1){let b=this.previewThread,l=b?b.agentMode??this.getEffectiveAgentMode():this.getEffectiveAgentMode(),Q1=Gk1(l);if(b)I.push({text:new J1(l,new H1({color:Q1})),position:"top-left",offsetY:0});else{let g=Pk(l,this.cachedVisibleModes)!==l,s=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,q1=_$(s.thread)===0,o=z||!this.hasToggledAgentMode&&g&&q1?new J1("",void 0,[new J1(l,new H1({color:Q1})),new J1(" (click or ",new H1({color:Y.foreground,dim:!0})),new J1("Ctrl+S",new H1({color:W.keybind})),new J1(" to switch)",new H1({color:Y.foreground,dim:!0}))]):new J1(l,new H1({color:Q1}));I.push({text:o,position:"top-left",offsetY:0,onClick:q1?this.toggleAgentMode:void 0})}}if(this.connectedClientsStatus&&this.connectedClientsStatus.enabled){let b=this.connectedClientsStatus,l=b.mode||"disconnected",Q1=!!b.errorMessage,a=b.clientID||"unknown",g,s;if(Q1)g="●",s=O1.red;else if(l==="presence")g="○",s=O1.yellow;else if(l==="connected"&&b.connected)g="●",s=O1.green;else g="○",s=O1.yellow;let q1=this.connectedClientsStatusExpanded?`${a} ${g}`:g;I.push({text:new J1(q1,new H1({color:s})),position:"top-right",offsetX:-2,offsetY:0,onClick:this.toggleConnectedClientsStatus})}let j=K?this.widget.dependencies.replayMode.thread.env?.initial.trees?.[0]?.uri:G.mainThread?.env?.initial.trees?.[0]?.uri,y;if(j)y=n0.parse(j).fsPath;else y=process.cwd();let h=this.toHomeRelative(y),u=this.shorten(h),p=!K&&this.currentGitBranch?`${u} (${this.currentGitBranch})`:u;return I.push({text:new J1(p,new H1({color:Y.foreground,dim:!0})),position:"bottom-right"}),new $j1({leftChild:new z4({child:U}),rightChild1:E,rightChild2:P,maxHeight:q,overlayTexts:I,borderColor:z||!this.isTextfieldAndAutocompleteFocused?O1.index(8):void 0,hasBanner:V,userHeight:this.bottomGridUserHeight,onInitializeHeight:(b)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(b,q)})},onDrag:(b)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(b.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let l=Math.floor(b.localPosition.y)-this.bottomGridDragStartY,Q1=Math.max(4,this.bottomGridDragStartHeight-l),a=Math.min(Q1,q),g=Math.floor(a);if(this.bottomGridUserHeight!==g)this.setState(()=>{this.bottomGridUserHeight=g})},onDragRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null},enableResize:!V})}}async function Zk1(J){if((await J.configService.getLatest()).settings["terminal.animation"]===!1)E9.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:!0}});let X=()=>null,Z=!1,q=new Vz(Z,1000,J.inspectorPort),V=J.features?.find((A)=>A.name==="amp-connect")?.enabled??!1,K=new H_1({threadService:J.threadService,worker:J.worker,builder:(A,E,P,I,R,j)=>{if(X=R,J.threadDependencies&&V)EC1(J.threadDependencies,J.configService,R,I,J.connectedClientsService,J.startNewThread,J.switchToThread,J.clientId).catch((u)=>{f.error("Failed to start automatic presence:",u)});let y=R(),h={...J,worker:y,threadID:y.thread.id};return new HY6({...h,threadState:E,workerController:P,switchWorker:I,getCurrentWorker:R,recentThreadIDs:j})}}),W=new Hj1({configService:J.configService,child:K}),H=new Vj1({configService:J.configService,child:W}),z=new oC1(H),U=new x6({data:MC.fromBaseTheme(vZ.default()),child:z});try{await aR1(U,{onRootElementMounted:(A)=>{if(f.info("TUI input ready for user interaction"),Z)q.start(A)}})}finally{if(Z)q.stop();if(J.threadDependencies&&V){let{stopGlobalSession:A}=await Promise.resolve().then(() => (IC1(),H76));A()}}let M=X()?.thread.id||J.threadID,L=await J.threadService.get(M);if(L&&L.messages.length>0){let A=`${J.ampURL.replace(/\/$/,"")}/threads/${M}`;y76(L,A,J.stdout)}}function Gk1(J){let Y=RV(J)?.uiHints?.secondaryColor;if(Y)return O1.rgb(Y.r,Y.g,Y.b);return hN8(J)}class FY6 extends G6{props;constructor(J){super();this.props=J}createState(){return new UY6}}class UY6 extends X6{viewportHeight=1;scrollListenerAttached=!1;initState(){if(!this.scrollListenerAttached)this.widget.props.controller.addListener(()=>{this.updateViewportHeight()}),this.scrollListenerAttached=!0}build(J){let{todos:Q,controller:Y,appTheme:X}=this.widget.props;return new Q4({crossAxisAlignment:"stretch",children:[new z4({child:new O2({controller:Y,autofocus:!1,child:new z_1({todos:Q})})}),new XG({controller:Y,thumbColor:X.app.scrollbarThumb,trackColor:X.app.scrollbarTrack,getScrollInfo:()=>{let{maxScrollExtent:G,offset:Z}=Y,q=this.viewportHeight,V=G+q;return{totalContentHeight:Math.max(V,0),viewportHeight:Math.max(q,1),scrollOffset:Math.max(Z,0)}}})]})}updateViewportHeight(){let J=this.getViewportHeight();if(J!==this.viewportHeight)this.viewportHeight=J}getViewportHeight(){let J=this.context.findRenderObject();if(!J)return this.viewportHeight;let Q=(X,G=0)=>{if(X&&"size"in X&&"children"in X){let Z=X.children||[];for(let q of Z){if(q&&"size"in q){let K=q.size;if(typeof K?.height==="number"&&K.height>0)return K.height}let V=Q(q,G+1);if(V>0)return V}}return 0},Y=Q(J);if(Y>0)return Y;if("size"in J){let X=J.size;if(typeof X?.height==="number"&&X.height>0)return X.height}return this.viewportHeight}}class BY6 extends I6{props;constructor(J){super();this.props=J}build(J){return new _8({child:new U0({height:1}),cursor:l9.NS_RESIZE,onDrag:(Q)=>{if(this.props.userHeight===void 0){let X=J.findRenderObject()?.size.height??0;if(X>0){this.props.onInitializeHeight(X);return}}this.props.onDrag(Q)},onRelease:this.props.onRelease})}}function hN8(J){let Q=0;for(let G=0;G<J.length;G++){let Z=J.charCodeAt(G);Q=(Q<<5)-Q+Z,Q=Q&Q}let Y=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],X=Math.abs(Q)%Y.length;return O1.index(Y[X])}nR1();try{if(process.platform==="win32")await Promise.resolve().then(() => D6(oC(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){lZ.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
4819
|
-
`)}var xy1=yy1.join(Wz0||yy1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function GO8(J){process.emitWarning=function(Q,Y,X,G){let Z=typeof Q==="string"?Q:Q.message||String(Q),q=Y||"Warning",V=!1;J.warn(Z,{name:q,code:X})}}function kq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")w$("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")w$("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")w$("model.sonnet",Q.useSonnet)}async function fy1(J){try{await QO8(yy1.dirname(xy1),{recursive:!0}),await YO8(xy1,J,"utf-8")}catch(Q){f.debug("Failed to save last thread ID",Q)}}async function ZO8(){try{return(await uZ6(xy1,"utf-8")).trim()}catch(J){return null}}var bZ6=[{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)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??jZ,description:`Custom settings file path (overrides the default location ${jZ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(f).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${tT1})`},{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:c2(),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 Gemini 3":"Use default model (Gemini 3)"},{name:"tryOpus",long:"try-opus",type:"switch",default:!1,description:"(deprecated) Opus 4.5 is now the default in smart mode",hidden:!0,deprecated:!0},{name:"mode",long:"mode",short:"m",type:"option",default:lE.SMART.key,description:`Set the agent mode (${mG().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:mG().map((J)=>J.mode)}],gZ6=(J)=>("deprecated"in J)&&J.deprecated===!0,$O8=(J)=>("hidden"in J)&&J.hidden===!0,qO8=(J)=>("default"in J),VO8=(J)=>("default"in J)?J.default:void 0;function KO8(J,Q){let Y=Q.args[0],X=Q.commands.map((Z)=>Z.name());if(Y&&!Y.includes(" ")&&Y.length<30&&!/[./\\]/.test(Y)){let Z=X.filter((V)=>Y.includes(V)||V.includes(Y)),q="Run amp --help for a list of available commands.";if(Z.length>0)q=`Did you mean: ${Z.join(", ")}? Or run amp --help for all commands.`;throw new j8(CZ.unknownCommand(Y),1,q)}}var pZ6=null;function az5(){return pZ6}function im(J){return{...J,getThreadEnvironment:q61,vfs:Mj0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new fv(J.fileSystem),generateThreadTitle:xc0,deleteThread:(Q)=>J.threadService.delete(Q)}}var hy1=n0.file(XO8.homedir()),dZ6=process.env.XDG_CONFIG_HOME?n0.file(process.env.XDG_CONFIG_HOME):Z6.joinPath(hy1,".config");async function yq(J,Q){cU0("0.0.
|
|
4819
|
+
`)}var xy1=yy1.join(Wz0||yy1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function GO8(J){process.emitWarning=function(Q,Y,X,G){let Z=typeof Q==="string"?Q:Q.message||String(Q),q=Y||"Warning",V=!1;J.warn(Z,{name:q,code:X})}}function kq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")w$("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")w$("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")w$("model.sonnet",Q.useSonnet)}async function fy1(J){try{await QO8(yy1.dirname(xy1),{recursive:!0}),await YO8(xy1,J,"utf-8")}catch(Q){f.debug("Failed to save last thread ID",Q)}}async function ZO8(){try{return(await uZ6(xy1,"utf-8")).trim()}catch(J){return null}}var bZ6=[{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)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??jZ,description:`Custom settings file path (overrides the default location ${jZ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(f).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${tT1})`},{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:c2(),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 Gemini 3":"Use default model (Gemini 3)"},{name:"tryOpus",long:"try-opus",type:"switch",default:!1,description:"(deprecated) Opus 4.5 is now the default in smart mode",hidden:!0,deprecated:!0},{name:"mode",long:"mode",short:"m",type:"option",default:lE.SMART.key,description:`Set the agent mode (${mG().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:mG().map((J)=>J.mode)}],gZ6=(J)=>("deprecated"in J)&&J.deprecated===!0,$O8=(J)=>("hidden"in J)&&J.hidden===!0,qO8=(J)=>("default"in J),VO8=(J)=>("default"in J)?J.default:void 0;function KO8(J,Q){let Y=Q.args[0],X=Q.commands.map((Z)=>Z.name());if(Y&&!Y.includes(" ")&&Y.length<30&&!/[./\\]/.test(Y)){let Z=X.filter((V)=>Y.includes(V)||V.includes(Y)),q="Run amp --help for a list of available commands.";if(Z.length>0)q=`Did you mean: ${Z.join(", ")}? Or run amp --help for all commands.`;throw new j8(CZ.unknownCommand(Y),1,q)}}var pZ6=null;function az5(){return pZ6}function im(J){return{...J,getThreadEnvironment:q61,vfs:Mj0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new fv(J.fileSystem),generateThreadTitle:xc0,deleteThread:(Q)=>J.threadService.delete(Q)}}var hy1=n0.file(XO8.homedir()),dZ6=process.env.XDG_CONFIG_HOME?n0.file(process.env.XDG_CONFIG_HOME):Z6.joinPath(hy1,".config");async function yq(J,Q){cU0("0.0.1764248660-g87fd50");let Y=U$1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:X0.of([n0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:hy1,userConfigDir:dZ6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (z91(),H91));X(Y);let G=await Y.getLatest();f.debug("Global configuration initialized",{settingsKeys:Object.keys(G.settings)});let{toolService:Z,dispose:q}=Xt0({configService:Y}),V=new Map,K=()=>V.clear(),W=new FN1(Y,J.settings.getWorkspaceRootPath()),H=CC0({configService:Y,trustStore:W,createOAuthProvider:async(a)=>{let g=V.get(a);if(g)return f.debug("Reusing existing OAuth provider for server",{serverName:a}),g;f.debug("Creating OAuth provider for server",{serverName:a});let s=(async()=>{let q1=new kM(J.secrets),V1=await q1.getClientInfo(a),o=new hz1({storage:q1,serverName:a,clientId:V1?.clientId,clientSecret:V1?.clientSecret,scopes:V1?.scopes});return f.debug("OAuth provider created",{serverName:a,hasManualClientId:!!V1?.clientId,willUseDCR:!V1?.clientId}),o})();return V.set(a,s),s}}),z=D01({configService:Y,filesystem:F5,spawn:wA}),{initializeToolProviders:U}=await Promise.resolve().then(() => (hZ6(),fZ6)),{registrations:N,initErrors:M}=await U({toolService:Z,providers:[H,z],initialTimeout:J.executeMode?15000:5000});for(let[a,g]of M)f.warn(`${a} provider initialization slow or failed:`,g);if(Q.jetbrains)JI("JetBrains");else if(Q.ide&&$86())JI("VS Code");else if(Q.ide&&q86())JI("Neovim");if(J.executeMode)lU0(!0);let L,A=z2.status.pipe(q6((a)=>Boolean(a.connected&&a.authenticated)),x4()).subscribe((a)=>{if(a){if(!L)L=Z.registerTool(ur0)}else L?.dispose(),L=void 0}),E;if(!J.executeMode)E=new M61(process.cwd(),{},!0);else E=new class extends M61{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(v5.write(`No API key found. Starting login flow...
|
|
4820
4820
|
`),!await WO8(J))await gA(),process.exit(1)}let P=await Ij0({isDevelopment:!1}),I=new ME1(P,Y),R=new FE1(P,{lazy:!0}),j=new EN1(I,(a,g)=>{let s=N3.get(a);if(s)s.handle(g).catch((q1)=>{f.error("Failed to apply artifact delta",q1)})}),y=Q.notifications!==void 0?Q.notifications:!J.executeMode,h=Zt0({playNotificationSound:async(a)=>{if(y){Gt0(a);let g=lR1(),s=iR1();if((!g||s)&&G.settings["notifications.system.enabled"]!==!1){if(a==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(a==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:I,configService:Y});f.info("Starting Amp background services");let u=fc0({threadService:I,threadHistoryService:R,configService:Y,isExtensionDevelopment:!1}),p;z2.status.subscribe((a)=>{p=a});let b=new JZ1({workspaceRoots:[n0.file(process.cwd())],getCurrentFile:()=>{if(!p?.openFile)return;try{return n0.parse(p.openFile)}catch(a){f.warn("Failed to parse current file URI",{uri:p.openFile,error:a});return}},getOpenFiles:()=>{if(!p?.visibleFiles?.length)return[];let a=p.openFile;return p.visibleFiles.filter((g)=>g!==a).map((g)=>{try{return n0.parse(g)}catch(s){return f.warn("Failed to parse visible file URI",{uri:g,error:s}),null}}).filter((g)=>g!==null)}}),l=new oR1,Q1={codebaseContextService:b,configService:Y,toolService:Z,mcpService:H,trustStore:W,threadService:I,threadHistoryService:R,threadSyncService:u,planFileManager:j,threadStorage:P,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:E,notificationService:h,fileSystem:Q.jetbrains||Q.ide?Bj0:F5,terminal:l};return{...Q1,async asyncDispose(){if(Q1.mcpService.hasAuthenticatingClients())f.info("Waiting for OAuth authentication to complete before exit..."),await Q1.mcpService.waitForAuthentication();for(let a of N.values())a.dispose();await Q1.mcpService.dispose(),K(),await Q1.threadService.asyncDispose(),Q1.configService.unsubscribe(),q(),Q1.fuzzyServer.dispose(),Q1.threadSyncService.dispose(),Q1.settingsStorage[Symbol.dispose](),A.unsubscribe(),L?.dispose()}}}async function WO8(J){if(!J.executeMode){if(!await ER1("Would you like to log in to Amp? [(y)es, (n)o]: "))return v5.write(`Login cancelled. Run the command again to retry.
|
|
4821
4821
|
`),!1}return await cZ6(J)}async function cZ6(J){let Q=JO8(32).toString("hex"),Y=await wR1(J.ampURL,Q),X=new AbortController;try{await j3(Y,X.signal)}catch(Z){f.error("Error opening browser",{error:Z})}let G=await wR1(J.ampURL,Q,!1);v5.write(`If your browser does not open automatically, visit:
|
|
4822
4822
|
|
|
@@ -4826,7 +4826,7 @@ ${v4.blue.bold(G)}
|
|
|
4826
4826
|
Login successful! You can now use the Amp CLI.
|
|
4827
4827
|
`),!0}catch(Z){return f.error("Login failed",{error:Z}),lZ.write(`
|
|
4828
4828
|
Login failed: ${Z instanceof Error?Z.message:String(Z)}
|
|
4829
|
-
`),!1}}function HO8(){let J=new RA().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)bR(),process.exit(0);let z=H.originalError??H;Q46(z)}),J.option("-V, --version","Print the version number and exit",()=>{v5.write(`0.0.
|
|
4829
|
+
`),!1}}function HO8(){let J=new RA().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)bR(),process.exit(0);let z=H.originalError??H;Q46(z)}),J.option("-V, --version","Print the version number and exit",()=>{v5.write(`0.0.1764248660-g87fd50 (released 2025-11-27T13:09:46.800Z)
|
|
4830
4830
|
`),process.exit(0)}),J.addHelpText("after",X86()),J.configureHelp({formatHelp:G86}),J.command("logout").description("Log out by removing stored API key").action(async(H,z)=>{let U=z.optsWithGlobals(),N=await tQ(U);await BO8(N)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(H,z)=>{let U=z.optsWithGlobals(),N=await tQ(U);await UO8(N,await HR1(U,N.settings))});let Q=async(H,z,U)=>{U$1({storage:z.settings,secretStorage:z.secrets,workspaceRoots:X0.of([n0.file(process.cwd())]),defaultAmpURL:z.ampURL,homeDir:hy1,userConfigDir:dZ6});let N={...z,executeMode:!1};await vy1(N,{...H,openThreadSwitcher:!0},U)},Y=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(H,z)=>{let U=z.optsWithGlobals(),N=await tQ(U);await mZ6(U,N,z)});Y.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(H,z)=>{let U=z.optsWithGlobals(),N=await tQ(U);await wO8(U,N,z)}),Y.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(H,z,U)=>{let N=U.optsWithGlobals(),M=await tQ(N);if(z.pick)lZ.write(`${v4.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
|
|
4831
4831
|
`);if(z.last||H||M.executeMode)await OO8(N,M,H,U);else await Q(N,M,U)}),Y.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(H,z,U)=>{let N=U.optsWithGlobals(),M=await tQ(N);await AO8(N,M,H,U)}),Y.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(H,z)=>{let U=z.optsWithGlobals(),N=await tQ(U);await mZ6(U,N,z)}),Y.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, unlisted, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, unlisted, workspace, group)").option("--support [message]","Share thread with Amp support for debugging").action(async(H,z,U)=>{let N=U.optsWithGlobals(),M=await tQ(N);await LO8(N,M,H,U,z.support)}),Y.command("rename <threadId> <newName>").alias("r").summary("Rename a thread").description('Change the title of a thread. Quote names with spaces: amp threads rename T-123 "New thread name"').action(async(H,z,U,N)=>{let M=N.optsWithGlobals(),L=await tQ(M);await NO8(M,L,H,z,N)}),Y.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(H,z,U)=>{let N=U.optsWithGlobals(),M=await tQ(N);await DO8(N,M,H,U)}),Y.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(H,z,U)=>{let N=U.optsWithGlobals(),M=await tQ(N);await MO8(N,M,H,z,U)}),e96(J,async(H,z)=>{let U=await tQ(z);kq(H,z);let N=await yq(U,z);return{context:U,mcpService:N.mcpService,toolService:N.toolService,toolServices:N.toolService,configService:N.configService,cleanupTerminal:bR,asyncDispose:N.asyncDispose.bind(N)}}),u86(J,async(H)=>{let z=H.optsWithGlobals();return await tQ(z)}),_86(J,async(H)=>{let z=await tQ(H);return{settings:z.settings,secretStorage:z.secrets,getThreadDeps:async(U)=>{kq(U,H);let N=await yq(z,H);return{mcpService:N.mcpService,settings:z.settings,asyncDispose:N.asyncDispose.bind(N)}}}});function G(H,z,U){let M=typeof H.description==="string"?H.description:U===void 0?H.description(!0):H.description(U),L=new fB(z,M),A=VO8(H);if(A)L.default(A);if(L.hidden=$O8(H)||gZ6(H),"choices"in H)L.choices([...H.choices]);return L}for(let H of bZ6)switch(H.type){case"flag":{J.addOption(G(H,`--${H.long}`)),J.addOption(G(H,`--no-${H.long}`,!1));break}case"switch":{J.addOption(G(H,`--${H.long}`,!0));break}default:{J.addOption(G(H,`${"short"in H?`-${H.short}, `:""}--${H.long} <value>`));break}}let Z=new fB("-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(Z);let q=new fB("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(q);let V=new fB("--stream-json","When used with --execute, output in Claude Code-compatible stream JSON format instead of plain text.").default(!1);J.addOption(V);let K=new fB("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(K);let W=new fB("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(W),process.env.AMP_CONNECT==="1"){let H=new fB("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(H)}return J.action(async(H,z)=>{let U=H,N=await tQ(U);if(z.getOptionValueSourceWithGlobals("tryOpus")==="cli")v5.write(v4.yellow(`Opus 4.5 is now the default in Amp's smart mode. Rerun without --try-opus.
|
|
4832
4832
|
`)),process.exit(0);if(Object.keys(U).forEach((M)=>{let L=bZ6.find((A)=>A.name===M);if(L&&gZ6(L)&&!qO8(L))lZ.write(v4.yellow(`Warning: '--${M}' flag is deprecated
|
|
@@ -4834,8 +4834,8 @@ Login failed: ${Z instanceof Error?Z.message:String(Z)}
|
|
|
4834
4834
|
Or pipe via stdin: echo "your message" | amp --execute`);kq(Y,Q);let q=await yq(J,Q);pZ6=q;let V=im(q),K=async(l)=>{let Q1=await uZ6(l,"utf-8"),a=JSON.parse(Q1);if(!S$(a.id))throw new j8(CZ.invalidThreadId);return J51(q,{visibility:X,agentMode:Q.mode,thread:a})},W=async(l)=>{if(!S$(l))throw new j8(CZ.invalidThreadId);try{let[a,g]=await Promise.all([I5.getThreadLinkInfo({thread:l},{config:q.configService}),I5.getUserInfo({},{config:q.configService})]);if(a.ok&&g.ok){let s=a.result.creatorUserID,q1=g.result.id;if(s&&s!==q1&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new j8(`Cannot resume thread created by another user.
|
|
4835
4835
|
|
|
4836
4836
|
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.`)}}catch(a){if(a instanceof j8)throw a;f.warn("Failed to validate thread ownership in CLI, allowing to open",{error:a})}let Q1=await q.threadService.get(l)??void 0;return f.info(`[fetchAndStartThread] Loaded thread ${l}, agentMode: ${Q1?.agentMode??"undefined"}`),J51(q,{visibility:X,agentMode:Q1?void 0:Q.mode,thread:Q1})},H=async()=>{try{if(Q.threadId)return W(Q.threadId);else return J51(q,{visibility:X})}catch(l){if(l instanceof j8)throw l;throw await Ug(l,Q.threadId),Error("handleError should have called process.exit()")}},z=async()=>{return J51(q,{visibility:X})};if(Q.format==="jsonl")lZ.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
4837
|
-
`),await gA(),process.exit(1);if(J.executeMode&&Q.remote)await p86(G,Z,q.configService),await q.asyncDispose(),process.exit(0);let U=await H();if(J.executeMode)x86(q.mcpService,J.settings),await B46(U,U.threadID,G,Z,q,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await q.asyncDispose(),process.exit(0);let N=!1,M=!1;if(Q.jetbrains||Q.ide){await VD0();let l=NI({jetbrainsOnly:Q.jetbrains});if(l.length===0){if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall")}else if(l.length===1){let Q1=l[0];if(Q1)z2.selectConfig(Q1)}else N=!0}let L=R61("0.0.
|
|
4838
|
-
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Y=process.stdout.isTTY&&process.stderr.isTTY,X=await u46({...J,workspaceTrust:{current:!0,changes:a_},getHook:process.env.AMP_URL?(Z,q)=>{if(Z==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let Z=await k86(J.mcpConfig);X=y86(X,Z)}let G=await X.get("url","global");if(!G)G=zY;if(!vF(G))f.info("Targeting custom Amp server",{ampURL:G});return X=VF0(X),{executeMode:Q,isTTY:Y,ampURL:G,settings:X,secrets:d86(await HR1(J,X))}}function zO8(J){let Q={};for(let Y=0;Y<J.length;Y++){let X=J[Y];if(X?.startsWith("--")){let Z=X.slice(2).replace(/-([a-z])/g,(V,K)=>K.toUpperCase()),q=J[Y+1];if(q&&!q.startsWith("--"))Q[Z]=q,Y++}}return Q}async function FO8(){let J=zO8(process.argv);if(i66({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),GO8(f),f.info("Starting Amp CLI.",{version:"0.0.
|
|
4837
|
+
`),await gA(),process.exit(1);if(J.executeMode&&Q.remote)await p86(G,Z,q.configService),await q.asyncDispose(),process.exit(0);let U=await H();if(J.executeMode)x86(q.mcpService,J.settings),await B46(U,U.threadID,G,Z,q,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await q.asyncDispose(),process.exit(0);let N=!1,M=!1;if(Q.jetbrains||Q.ide){await VD0();let l=NI({jetbrainsOnly:Q.jetbrains});if(l.length===0){if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall")}else if(l.length===1){let Q1=l[0];if(Q1)z2.selectConfig(Q1)}else N=!0}let L=R61("0.0.1764248660-g87fd50",q.settingsStorage),A=new W11(q.threadStorage),E=X0.of([n0.file(process.cwd())]),P=HZ1(void 0,E),I=new C61(q.mcpService,J.settings.getWorkspaceRootPath());if(G)U.handle({type:"user:message",message:{content:[{type:"text",text:G}]}});let R=(async()=>{try{let l=await I5.getUserFreeTierStatus({},{config:q.configService,signal:AbortSignal.timeout(5000)});if(l.ok)return f.info("User free tier status:",l),l.result}catch(l){f.error("Failed to fetch free tier status:",l)}})(),j=(async()=>{try{let l=await I5.getUserInfo({},{config:q.configService});if(l.ok)return l.result}catch(l){f.debug("Failed to fetch user workspace info:",l)}})(),[y,h]=await Promise.all([R,j]),u=h?.email,p=u&&(u.endsWith("@sourcegraph.com")||u.endsWith("@ampcode.com")||u==="auth-bypass-user@example.com");if(p)q.toolService.registerTool(cr0);let b=await i86();f.info("Loaded session state:",b),await Zk1({codebaseContextService:q.codebaseContextService,stdout:process.stdout,history:new H61,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadHistoryService:q.threadHistoryService,threadSyncService:q.threadSyncService,planFileManager:q.planFileManager,threadID:U.threadID,threadFuzzyIndexer:A,worker:U,workerDeps:V,configService:q.configService,internalAPIClient:I5,ampURL:J.ampURL,startNewThread:z,switchToThread:W,ideClient:z2,connectedClientsService:new Gi,commandRegistry:P,mcpService:q.mcpService,mcpTrustHandler:I,showJetBrainsInstaller:M,showIdePicker:N,openThreadSwitcher:Q.openThreadSwitcher,updateService:L,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:b,freeTierStatus:y,workspace:h?.team??null,features:h?.features??[],isDogfooding:p||!1,threadDependencies:q}),await q.asyncDispose(),process.exit(0)}async function tQ(J){if(J.interactive)lZ.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
4838
|
+
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Y=process.stdout.isTTY&&process.stderr.isTTY,X=await u46({...J,workspaceTrust:{current:!0,changes:a_},getHook:process.env.AMP_URL?(Z,q)=>{if(Z==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let Z=await k86(J.mcpConfig);X=y86(X,Z)}let G=await X.get("url","global");if(!G)G=zY;if(!vF(G))f.info("Targeting custom Amp server",{ampURL:G});return X=VF0(X),{executeMode:Q,isTTY:Y,ampURL:G,settings:X,secrets:d86(await HR1(J,X))}}function zO8(J){let Q={};for(let Y=0;Y<J.length;Y++){let X=J[Y];if(X?.startsWith("--")){let Z=X.slice(2).replace(/-([a-z])/g,(V,K)=>K.toUpperCase()),q=J[Y+1];if(q&&!q.startsWith("--"))Q[Z]=q,Y++}}return Q}async function FO8(){let J=zO8(process.argv);if(i66({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),GO8(f),f.info("Starting Amp CLI.",{version:"0.0.1764248660-g87fd50",buildTimestamp:"2025-11-27T13:09:46.800Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new j8(CZ.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await HO8().parseAsync(process.argv)}VE1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await FO8().catch(Ug)});async function UO8(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),v5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
4839
4839
|
`);else if(!vF(J.ampURL))v5.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
4840
4840
|
`);let Y=process.env.AMP_API_KEY;if(Y)v5.write(`API key found in environment variable, storing...
|
|
4841
4841
|
`),await Q.set("apiKey",Y,J.ampURL),v5.write(`API key successfully stored.
|
|
@@ -4848,7 +4848,7 @@ This thread belongs to a different user and cannot be continued for security rea
|
|
|
4848
4848
|
`);else v5.write(`Successfully logged out from ${new URL(J.ampURL).hostname}.
|
|
4849
4849
|
`);process.exit(0)}async function NO8(J,Q,Y,X,G){kq(G,J);let Z=await yq(Q,J);try{let q=Q51(Y);if(!q)Y51(Y);let V=q,K=X.trim();if(K.length===0)cZ("Thread name cannot be empty");if(K.length>256)cZ("Thread name cannot exceed 256 characters");if(!(await rC(V,Z)).messages.length)cZ("Cannot rename an empty thread.");let H=im(Z);await(await N3.getOrCreateForThread(H,V)).handle({type:"title",value:K}),f.info("GOT HERE"),await Z.threadSyncService.sync(),f.info("GOT THERE"),v5.write(v4.green(`✓ Thread ${V} renamed to "${K}"
|
|
4850
4850
|
`)),await Z.asyncDispose(),process.exit(0)}catch(q){await Z.asyncDispose();let V=`Failed to rename thread: ${q instanceof Error?q.message:String(q)}`;cZ(V)}}async function DO8(J,Q,Y,X){kq(X,J);let G=await yq(Q,J);try{let Z=Q51(Y);if(!Z)Y51(Y);let V=await rC(Z,G),K=qR(V);v5.write(K+`
|
|
4851
|
-
`),await G.asyncDispose(),process.exit(0)}catch(Z){await G.asyncDispose();let q=`Failed to render thread as markdown: ${Z instanceof Error?Z.message:String(Z)}`;cZ(q)}}async function MO8(J,Q,Y,X,G){kq(G,J);let Z=await yq(Q,J);try{let q=await by1(Y),V=await rC(q,Z),K=X.typing!==!1,W=parseInt(X.wpm||"120",10),H=parseInt(X.messageDelay||"1000",10),z=parseInt(X.toolProgressDelay||"800",10),U=parseInt(X.exitDelay||"3",10)*1000,N=X.indicator!==!1,M=im(Z),L=V.id;await Z.threadStorage.set(L,V);let A=await N3.getOrCreateForThread(M,L);await A.resume();let E=K11.fromWorker(A),P=new W11(Z.threadStorage),I=X0.of([n0.file(process.cwd())]),R=HZ1(void 0,I),j=new C61(Z.mcpService,Q.settings.getWorkspaceRootPath()),y=R61("0.0.
|
|
4851
|
+
`),await G.asyncDispose(),process.exit(0)}catch(Z){await G.asyncDispose();let q=`Failed to render thread as markdown: ${Z instanceof Error?Z.message:String(Z)}`;cZ(q)}}async function MO8(J,Q,Y,X,G){kq(G,J);let Z=await yq(Q,J);try{let q=await by1(Y),V=await rC(q,Z),K=X.typing!==!1,W=parseInt(X.wpm||"120",10),H=parseInt(X.messageDelay||"1000",10),z=parseInt(X.toolProgressDelay||"800",10),U=parseInt(X.exitDelay||"3",10)*1000,N=X.indicator!==!1,M=im(Z),L=V.id;await Z.threadStorage.set(L,V);let A=await N3.getOrCreateForThread(M,L);await A.resume();let E=K11.fromWorker(A),P=new W11(Z.threadStorage),I=X0.of([n0.file(process.cwd())]),R=HZ1(void 0,I),j=new C61(Z.mcpService,Q.settings.getWorkspaceRootPath()),y=R61("0.0.1764248660-g87fd50",Z.settingsStorage);await Zk1({codebaseContextService:Z.codebaseContextService,stdout:process.stdout,history:new H61,fuzzyServer:Z.fuzzyServer,settingsStorage:Z.settingsStorage,threadService:Z.threadService,threadHistoryService:Z.threadHistoryService,threadSyncService:Z.threadSyncService,planFileManager:Z.planFileManager,threadID:L,threadFuzzyIndexer:P,worker:E,workerDeps:M,configService:Z.configService,internalAPIClient:I5,ampURL:Q.ampURL,startNewThread:async()=>E,switchToThread:async()=>E,ideClient:z2,connectedClientsService:new Gi,commandRegistry:R,mcpService:Z.mcpService,mcpTrustHandler:j,showJetBrainsInstaller:!1,updateService:y,isDogfooding:!1,replayMode:{thread:V,typingEnabled:K,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:z,exitDelayMs:U,showIndicator:N}}),await Z.asyncDispose(),process.exit(0)}catch(q){await Z.asyncDispose(),await Ug(q,Y)}}async function LO8(J,Q,Y,X,G){kq(X,J);let Z=await yq(Q,J);try{let q=Q51(Y);if(!q)Y51(Y);let V=q,K=await I5.getUserInfo({},{config:Z.configService}),W=K.ok?K.result:null,H=j61(J,W);if(!H&&!G)cZ("Must specify either --visibility or --support");if(H&&G)cZ("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)cZ(H.message);if(H)await Z.threadSyncService.updateThreadMeta(V,S61(H)),v5.write(v4.green("✓ ")+`Thread ${V} visibility changed to ${H}.
|
|
4852
4852
|
`);if(G){await rC(V,Z);let z=typeof G==="string"?G:void 0;await vT0(Z.threadService,V,Z.configService,z),v5.write(v4.green("✓ ")+`Thread ${V} has been shared with Amp support. These thread reports will be aggregated and analysed.
|
|
4853
4853
|
`)}await Z.asyncDispose(),process.exit(0)}catch(q){await Z.asyncDispose(),cZ(`Failed to update thread: ${q instanceof Error?q.message:String(q)}`)}}async function AO8(J,Q,Y,X){kq(X,J);let G=await yq(Q,J),Z=im(G);try{let q=await by1(Y),K=(await rC(q,G)).messages.length-1,W=await N3.getOrCreateForThread(Z,q),H=await VR(W,G.threadSyncService,K);await Promise.all([G.threadSyncService.uploadThread(q),G.threadSyncService.uploadThread(H)]),await fy1(H),v5.write(`${H}
|
|
4854
4854
|
`),await G.asyncDispose(),process.exit(0)}catch(q){lZ.write(`Error forking thread: ${q instanceof Error?q.message:String(q)}
|