@sourcegraph/amp 0.0.1780773165-gd9c390 → 0.0.1780774659-gd08a06
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 +13 -13
- package/package.json +2 -2
package/dist/main.js
CHANGED
|
@@ -2771,16 +2771,16 @@ ${B}`}async function F46(A,Q){if(!Q?.forceExternal&&Q?.onShowImagePreview&&ZW4(A
|
|
|
2771
2771
|
`,U.text),selectable:!0}));F.push(...this.processBlock(A,V,$,B,E)),G=V}break}case I4.Paragraph:{let G=this.processInline(A,Q,$),V=G.length===1&&G[0]?G[0]:new g(void 0,U.text,G),K=B?new ZB(`${B}p-${X++}`):void 0;F.push(new D0({key:K,text:V,selectable:!0}));break}case I4.Heading:{let G=Z.data1[Q]??1,K={1:Y.primary,2:Y.secondary,3:Y.primary,4:Y.secondary,5:U.text.color??Y.foreground,6:U.text.color??Y.foreground}[G],z=G<=2,W=U.text.copyWith({color:K,bold:z}),C=this.processInline(A,Q,$,W),H=C.length===1&&C[0]?C[0]:new g(void 0,W,C),w=(G<=2?$.headingKeys?.[$.nextHeadingIndex++]:void 0)??(B?new ZB(`${B}h${G}-${X++}`):void 0);F.push(new D0({key:w,text:H,selectable:!0}));break}case I4.BlockQuote:{let G=[];for(let V of J.children(Q))G.push(...this.processBlock(A,V,$,B,E));F.push(new GA({padding:c0.only({left:2,right:4}),child:new GA({padding:c0.only({left:1}),decoration:new v1(void 0,new U1(void 0,void 0,void 0,new Y1(Y.border,1))),child:new UA({crossAxisAlignment:"start",children:G})})}));break}case I4.ThematicBreak:{F.push(new D0({text:new g("---",U.text),selectable:!0}));break}case I4.HtmlBlock:case I4.HtmlInline:{let G=J.nodeText(Q);F.push(...this.processHtmlNode(A,G,$));break}case I4.List:{let V=((Z.flags[Q]??0)&OE.Ordered)!==0,K=Z.data1[Q]??0,z=K>0?K:1,W=[],C=0;for(let N of J.children(Q)){let w={ordered:V,itemIndex:z+C};W.push(...this.processBlock(A,N,$,B,E,w)),C++}let H=new UA({crossAxisAlignment:"start",children:W});if(E>0){let N=E*2;F.push(new GA({padding:c0.only({left:N}),child:H}))}else F.push(H);break}case I4.ListItem:{let G=Z.flags[Q]??0,K=(G&OE.Task)!==0?(G&OE.Checked)!==0:null,z;if(typeof K==="boolean")z=K?"- [x] ":"- [ ] ";else if(D?.ordered)z=`${D.itemIndex}. `;else z="- ";let W=[],C=0,H=0;for(let N of J.children(Q)){if(H!==0&&this.hasBlankLineBetween($,H,N))W.push(new D0({text:new g(`
|
|
2772
2772
|
`,U.text),selectable:!0}));let w=Z.kind[N];if(w===I4.Paragraph){let u=this.processInline(A,N,$);if(C===0)u.unshift(new g(z,U.text));let L=u.length===1&&u[0]?u[0]:new g(void 0,U.text,u);W.push(new D0({text:L,selectable:!0}))}else if(C===0)if(W.push(new D0({text:new g(z,U.text),selectable:!0})),w===I4.List)W.push(...this.processBlock(A,N,$,B,E+1));else W.push(...this.processBlock(A,N,$,B,E));else if(w===I4.List)W.push(...this.processBlock(A,N,$,B,E+1));else W.push(...this.processBlock(A,N,$,B,E));H=N,C++}F.push(new OA({crossAxisAlignment:"start",mainAxisAlignment:"start",children:[new P4({child:new UA({crossAxisAlignment:"start",children:W})})]}));break}case I4.CodeBlock:{let G=J.info(Q)||"",V=J.nodeText(Q);if(V.trim()){let K=GB6(V,G,U.syntaxHighlight,U.codeBlock.color??Y.foreground,U.codeBlock),z=new g(void 0,U.codeBlock,K),W=G==="diagram"||G==="nowrap";F.push(new GA({padding:c0.only({left:4,right:4}),child:W?new CN4({textSpan:z}):new D0({text:z,selectable:!0})}))}break}case I4.Table:{let G=[],V=J.tableAlignments(Q),K=V.length,z=Array.from({length:K},(C,H)=>{let N=V[H]??null,w=N==="center"?"center":N==="right"?"right":"left";return Og0(w,"proportional")}),W=!0;for(let C of J.children(Q)){let H=Z.kind[C];if(H===I4.TableHead||H===I4.TableBody){for(let N of J.children(C))if(Z.kind[N]===I4.TableRow){let w=[],u=0;for(let L of J.children(N))if(Z.kind[L]===I4.TableCell){let R=this.processInline(A,L,$),_=R.length===1&&R[0]?R[0]:new g(void 0,U.text,R),P=z[u],f=P?.alignment==="center"?"center":P?.alignment==="right"?"right":"left";w.push(ug0(new D0({text:_,selectable:!0,textAlign:f}))),u++}G.push(Mg0(w,W)),W=!1}}}F.push(new C80({rows:G,columnConfigs:z,borderColor:U.tableBorder,showBorders:!0}));break}case I4.Image:{let G=H80(J,Q)||"Image";F.push(new D0({text:new g(`[Image: ${G}]`,U.link.copyWith({italic:!0})),selectable:!0}));break}default:{for(let G of J.children(Q))F.push(...this.processBlock(A,G,$,B,E));break}}return F}processInline(A,Q,$,B){let{doc:E,styleScheme:D,onLinkClick:J,fallbackColor:U}=$,Y=E.arena,Z=[],F=B??D.text;for(let X of E.children(Q))switch(Y.kind[X]){case I4.Text:{let G=Y.start[X],V=this.applyColorTransform(F,G,U);Z.push(new g(E.nodeText(X),V));break}case I4.Strong:{let G=F.copyWith({bold:!0});Z.push(...this.processInline(A,X,$,G));break}case I4.Emphasis:{let G=F.copyWith({italic:!0});Z.push(...this.processInline(A,X,$,G));break}case I4.Strikethrough:{let G=F.copyWith({strikethrough:!0});Z.push(...this.processInline(A,X,$,G));break}case I4.CodeSpan:{let G=Y.start[X],V=E.nodeText(X),K=this.applyColorTransform(F.merge(D.inlineCode),G,U),z=XB6(V);if(z){let W=K.merge(D.link),C={uri:z.url,id:zN4(z.url,$.nextHyperlinkIndex++)};Z.push(new g(z.text,W,void 0,C,()=>{J(z.url)}));break}Z.push(new g(V,K));break}case I4.Link:{let G=E.destination(X),V=F.merge(D.link),K={uri:G,id:zN4(G,$.nextHyperlinkIndex++)},z=this.processInline(A,X,$,V);for(let W of z)Z.push(new g(W.text,W.style,W.children,K,()=>{J(G)}));break}case I4.HardBreak:{Z.push(new g(`
|
|
2773
2773
|
`,F));break}case I4.SoftBreak:{Z.push(new g(`
|
|
2774
|
-
`,F));break}case I4.HtmlInline:{Z.push(new g(E.nodeText(X),F));break}case I4.Image:{let G=H80(E,X)||"Image";Z.push(new g(`[Image: ${G}]`,D.link.copyWith({italic:!0})));break}default:{if((Y.firstChild[X]??0)!==0)Z.push(...this.processInline(A,X,$,B));break}}return Z}processHtmlNode(A,Q,$){try{let B=wg0(Q,{fragment:!0});return this.processHastNode(A,B,$)}catch{let B=new g(Q,$.styleScheme.text);return[new D0({text:B,selectable:!0})]}}processHastNode(A,Q,$){let{styleScheme:B}=$,E=[];if(Q.type==="root"){for(let J of Q.children)E.push(...this.processHastNode(A,J,$));return E}if(Q.type==="doctype")return E;if(Q.type==="text"){let J=Q;if(J.value.trim())E.push(new D0({text:new g(J.value,B.text),selectable:!0}));return E}if(Q.type!=="element")return E;let D=Q;if(D.tagName==="table"){let J=this.processHtmlTable(A,D,B);if(J)E.push(J);return E}for(let J of D.children||[])E.push(...this.processHastNode(A,J,$));return E}processHtmlTable(A,Q,$){let B=[],E=0,D=(U,Y)=>{let Z=[];for(let F of U.children||[]){if(F.type!=="element")continue;let X=F;if(X.tagName!=="td"&&X.tagName!=="th")continue;let I=this.extractTextFromHast(X);Z.push(ug0(new D0({text:new g(I,$.text),selectable:!0})))}if(Z.length===0)return null;return E=Math.max(E,Z.length),Mg0(Z,Y)};for(let U of Q.children||[]){if(U.type!=="element")continue;let Y=U;if(Y.tagName==="tr"){let Z=D(Y,B.length===0);if(Z)B.push(Z)}else if(Y.tagName==="thead"||Y.tagName==="tbody"){let Z=Y.tagName==="thead";for(let F of Y.children||[]){if(F.type!=="element")continue;let X=F;if(X.tagName==="tr"){let I=D(X,Z&&B.length===0);if(I)B.push(I)}}}}if(B.length===0)return null;let J=Array.from({length:E},()=>Og0("left","proportional"));return new C80({rows:B,columnConfigs:J,borderColor:$.tableBorder,showBorders:!0})}extractTextFromHast(A){if(A.type==="text")return A.value;if(A.type==="element")return(A.children||[]).map(($)=>this.extractTextFromHast($)).join("");return""}}function H80(A,Q){let $=A.arena,B="";for(let E of A.children(Q)){let D=$.kind[E];if(D===I4.Text||D===I4.CodeSpan)B+=A.nodeText(E);else B+=H80(A,E)}return B}function Lg0(A){let Q=xh0(A.trimEnd(),WN4),$=[];for(let B of Q.children(Q.root)){if(Q.arena.kind[B]!==I4.Heading)continue;let E=Q.arena.data1[B];if(E!==1&&E!==2)continue;$.push({level:E,text:H80(Q,B).trim()})}return $}function GB6(A,Q,$,B,E){let D=tY.default.languages[Q]||tY.default.languages.clike,J=E?.copyWith({color:B})??new A0({color:B});if(!D)return[new g(A,J)];try{let U=mP(A,$,`file.${Q}`),Y=[];for(let Z of U){let F=Z.color??B,X=E?.copyWith({color:F})??new A0({color:F});Y.push(new g(Z.content,X))}return Y.length>0?Y:[new g(A,J)]}catch{return[new g(A,J)]}}class CN4 extends d0{textSpan;constructor({textSpan:A}){super({});this.textSpan=A}createState(){return new HN4}}class HN4 extends m0{_controller=new a6;_scrollViewKey=new c3("no-wrap-code-scroll-view");_scrollListener=null;initState(){super.initState(),this._scrollListener=()=>{if(this.mounted)this.setState()},this._controller.addListener(this._scrollListener)}dispose(){if(this._scrollListener)this._controller.removeListener(this._scrollListener),this._scrollListener=null;this._controller.dispose(),super.dispose()}_getViewportWidth(){return this._scrollViewKey.currentElement?.renderObject?.size.width??0}_getScrollbarInfo(){let A=this._getViewportWidth();return{totalContent:(this._controller.maxScrollExtent??0)+A,viewportSize:A,scrollOffset:this._controller.offset}}build(A){let Q=e0.of(A);return new UA({crossAxisAlignment:"start",children:[new O5({key:this._scrollViewKey,scrollDirection:"horizontal",controller:this._controller,autofocus:!1,keyboardScrolling:!1,child:new D0({text:this.widget.textSpan,selectable:!0})}),new y0({height:1,child:new Ml({controller:this._controller,getScrollInfo:()=>this._getScrollbarInfo(),axis:"horizontal",thickness:1,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack})})]})}}var VB6=54,KB6=24,zB6=2,WB6=c0.symmetric(2,1);class Ol extends d0{props;constructor(A){super();this.props=A}createState(){return new NN4}}class NN4 extends m0{hovered=!1;actionHovered=!1;build(){let A=new qN4({...this.widget.props,hovered:this.hovered,actionHovered:this.actionHovered,onActionEnter:()=>{this.setState(()=>{this.actionHovered=!0})},onActionExit:()=>{this.setState(()=>{this.actionHovered=!1})}});if(this.widget.props.mouseBehavior==="click-action")return A;return new iA({cursor:o1.POINTER,opaque:!1,onClick:this.widget.props.action.onAction,onEnter:()=>{this.hovered=!0,this.requestClickAnywherePointerCursor(),this.setState(()=>{this.hovered=!0})},onHover:()=>{this.requestClickAnywherePointerCursor()},onExit:()=>{this.hovered=!1,I6.instance.requestCursorChange(o1.DEFAULT),this.setState(()=>{this.hovered=!1})},child:A})}requestClickAnywherePointerCursor(){I6.instance.requestCursorChange(o1.POINTER),queueMicrotask(()=>{if(this.hovered)I6.instance.requestCursorChange(o1.POINTER)})}}class qN4 extends eA{props;constructor(A){super();this.props=A}build(A){let Q=S4.of(A),$=e0.of(A),B=X4.of(A),E=this.props.width??VB6,D=Math.max(this.props.minWidth??KB6,B.size.width-zB6),J=Math.min(E,D),U=this.props.padding??WB6,Y=Math.max(1,J-U.horizontal-2),F=this.props.mouseBehavior==="click-anywhere"&&this.props.hovered?Q.colorScheme.foreground:CB6(this.props.variant,$.app),X=this.buildOverlays(Q,$,F),I=new GA({width:Math.max(1,J-2),padding:U,child:new y0({width:Y,child:this.buildMessage(Q)})});return new h$({width:J,decoration:new v1(Q.colorScheme.background,U1.all(new Y1(F,1,"rounded"))),overlays:X,child:I})}buildMessage(A){if(this.props.renderMarkdown)return new yq({markdown:this.props.message});return new D0({text:new g(this.props.message,new A0({color:A.colorScheme.foreground})),overflow:"ellipsis",maxLines:3,selectable:!0})}buildOverlays(A,Q,$){let B=A.colorScheme.background,E=[];if(this.props.title)E.push({position:"top",alignment:"left",child:new D0({text:new g(` ${this.props.title} `,new A0({color:$,backgroundColor:B,bold:!0})),overflow:"ellipsis",maxLines:1,selectable:!0})});return E.push({position:"bottom",alignment:"right",child:this.buildAction(A,Q)}),E}buildAction(A,Q){let $=A.colorScheme.background,B=this.props.mouseBehavior==="click-anywhere"?this.props.hovered:this.props.actionHovered,E=new D0({text:new g("",void 0,this.buildActionSpans(A,Q,$,B)),textAlign:"right",overflow:"ellipsis",maxLines:1});if(this.props.mouseBehavior==="click-anywhere")return E;return new iA({cursor:o1.POINTER,opaque:!1,onClick:this.props.action.onAction,onEnter:this.props.onActionEnter,onExit:this.props.onActionExit,child:E})}buildActionSpans(A,Q,$,B){let E=new A0({color:Q.app.keybind,backgroundColor:$}),D=new A0({color:A.colorScheme.foreground,backgroundColor:$,dim:!0});if(this.props.action.command){let J=[new g(` ${this.props.action.keyboardShortcut}`,E),new g(", ",D),new g(this.props.action.command,new A0({color:Q.app.command,backgroundColor:$,bold:B}))];if(this.props.action.confirmShortcut)J.push(new g(", ",D),new g(this.props.action.confirmShortcut,E));return J.push(new g(" ",D)),J}return[new g(` ${this.props.action.keyboardShortcut} `,new A0({color:Q.app.keybind,backgroundColor:$})),new g(`${this.props.action.label} `,new A0({color:A.colorScheme.foreground,backgroundColor:$,dim:!B,bold:B}))]}}function CB6(A,Q){switch(A){case"danger":return Q.toolError;case"success":return Q.toolSuccess;case"info":return Q.diffContext}}var HB6=54;class Ll extends eA{props;constructor(A){super();this.props=A}build(){let A=this.props.notice,Q={width:this.props.width??HB6,message:A.message,renderMarkdown:!0,variant:A.variant==="danger"?"danger":"info",mouseBehavior:"click-action",action:{keyboardShortcut:"Ctrl+.",label:"dismiss",onAction:this.props.onDismiss}};if(A.title)Q.title=A.title;return new Ol(Q)}}class jg0{configService;setState;notices=[];displayedNoticeKey=null;reloadInterval=null;listeners=new Set;constructor(A,Q){this.configService=A;this.setState=Q}get current(){return this.notices[0]??null}addListener(A){this.listeners.add(A)}removeListener(A){this.listeners.delete(A)}buildComplexToast(){let A=this.current;if(!A)return null;return new Ll({notice:A,onDismiss:()=>this.dismiss(A.key)})}async load(){try{let A=await j4.notices({},{config:this.configService});if(!A.ok)return;this.setState(()=>{this.notices=A.result}),this.notifyListeners(),this.logCurrentView()}catch(A){S.debug("Failed to load notices",{error:A})}}startPolling(){this.load(),this.reloadInterval=setInterval(()=>void this.load(),60000)}dispose(){if(this.reloadInterval)clearInterval(this.reloadInterval),this.reloadInterval=null}dismiss(A){this.logAction(A,"dismiss"),this.setState(()=>{this.notices=this.notices.filter((Q)=>Q.key!==A)}),this.notifyListeners(),this.logCurrentView()}dismissCurrent(){let A=this.current;if(!A)return!1;return this.dismiss(A.key),!0}logAction(A,Q){j4.logNoticeAction({key:A,action:Q},{config:this.configService}).catch(($)=>{S.debug("Failed to log notice action",{error:$,key:A,action:Q})})}logCurrentView(){let A=this.current;if(!A){this.displayedNoticeKey=null;return}if(this.displayedNoticeKey===A.key)return;this.displayedNoticeKey=A.key,this.logAction(A.key,"view")}notifyListeners(){for(let A of this.listeners)A()}}Kg();var wN4=process.platform==="win32"?" ":"█",uN4=process.platform==="win32"?"░":"█";class Rg0 extends d0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:A,controller:Q,getScrollInfo:$,thickness:B=1,trackChar:E=wN4,thumbChar:D=uN4,showTrack:J=!0,thumbColor:U,trackColor:Y}){super(A?{key:A}:{});this.controller=Q,this.getScrollInfo=$,this.thickness=B,this.trackChar=E,this.thumbChar=D,this.showTrack=J,this.thumbColor=U,this.trackColor=Y}createState(){return new MN4}}class MN4 extends m0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(A){let{totalContentHeight:Q,viewportHeight:$}=this.widget.getScrollInfo(),E=this.context.findRenderObject()?.size.height??0;if(E===0||Q<=$)return!1;let D=this.widget.getScrollInfo(),J=Math.min(1,$/Q),U=Math.max(1,E*J),Y=Math.max(0,Math.min(1,D.scrollOffset/(Q-$))),Z=E-U,F=Math.max(0,Z*Y),X=F+U;return A>=F&&A<=X}_handleHover=(A)=>{let Q=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(A.localPosition.y),Q!==this._isOverThumb)this.setState()};_handleDrag=(A)=>{let{totalContentHeight:Q,viewportHeight:$,scrollOffset:B}=this.widget.getScrollInfo(),D=this.context.findRenderObject()?.size.height??0;if(D===0||Q<=$)return;if(this._dragStartY===null)this._dragStartY=A.localPosition.y,this._dragStartOffset=B;let J=A.localPosition.y-this._dragStartY,U=Math.min(1,$/Q),Y=Math.max(1,D*U),Z=D-Y;if(Z<=0)return;let F=Q-$,X=Z/F,I=J/X,G=Math.max(0,Math.min(F,this._dragStartOffset+I));this.widget.controller.jumpTo(G)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(A)=>{if(A.button!=="left")return;let Q=A.localPosition.y,{totalContentHeight:$,viewportHeight:B,scrollOffset:E}=this.widget.getScrollInfo(),J=this.context.findRenderObject()?.size.height??0;if(J===0||$<=B)return;let U=Math.min(1,B/$),Y=Math.max(1,J*U),Z=$-B,F=J-Y,X=Math.max(0,Math.min(1,E/($-B))),I=Math.max(0,F*X),G=I+Y;if(Q>=I&&Q<=G)return;if(Q<I)this.widget.controller.animateTo(Math.max(0,E-B));else this.widget.controller.animateTo(Math.min(Z,E+B))};build(A){return new iA({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?o1.POINTER:o1.DEFAULT,child:new ON4({controller:this.widget.controller,getScrollInfo:this.widget.getScrollInfo,thickness:this.widget.thickness,trackChar:this.widget.trackChar,thumbChar:this.widget.thumbChar,showTrack:this.widget.showTrack,thumbColor:this.widget.thumbColor,trackColor:this.widget.trackColor})})}}class ON4 extends QZ{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:A,controller:Q,getScrollInfo:$,thickness:B=1,trackChar:E=wN4,thumbChar:D=uN4,showTrack:J=!0,thumbColor:U,trackColor:Y}){super(A?{key:A}:{});this.controller=Q,this.getScrollInfo=$,this.thickness=B,this.trackChar=E,this.thumbChar=D,this.showTrack=J,this.thumbColor=U,this.trackColor=Y}createRenderObject(){return new LN4(this)}updateRenderObject(A){A.updateWidget(this)}}class LN4 extends bA{_widget;constructor(A){super();this._widget=A}updateWidget(A){this._widget=A,this.markNeedsLayout()}performLayout(){let A=this._lastConstraints;oA(!!A,"performLayout called without constraints");let Q=Math.min(A.maxWidth,this._widget.thickness),$=A.maxHeight;this.setSize(Q,$),super.performLayout()}getMinIntrinsicWidth(A){return this._widget.thickness}getMaxIntrinsicWidth(A){return this._widget.thickness}getMinIntrinsicHeight(A){return 0}getMaxIntrinsicHeight(A){return 0}paint(A,Q,$){let{thumbStartFloat:B,thumbSizeFloat:E,showScrollbar:D}=this._calculateScrollbarMetrics();if(!D)return;let J=this._widget.trackColor,U=this._widget.thumbColor,Y=process.platform==="win32",Z=B,F=B+E;if(!Y){let X=["▁","▂","▃","▄","▅","▆","▇","█"];for(let I=0;I<this.size.height;I++){let G="█",V=!0;if(I===Math.floor(Z)){let K=1-(Z-I),z=Math.floor(K*8);G=X[z]||"█",V=!1}else if(I===Math.floor(F)){let K=1-(F-I),z=Math.floor(K*8);G=X[z]||"█"}else if(I>Z&&I<F)V=!1;A.setChar(Q,$+I,G,{fg:U,bg:J,reverse:V},1)}return}for(let X=0;X<this.size.height;X++){let I=X+0.5,G=I>=Z&&I<F,V=G?this._widget.thumbChar:this._widget.trackChar;A.setChar(Q,$+X,V,{fg:G?U:J,bg:J,reverse:!1},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:A,viewportHeight:Q,scrollOffset:$}=this._widget.getScrollInfo(),B=this.size.height;if(A<=Q||B<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let E=Math.max(0,Math.min(1,$/(A-Q))),D=Math.min(1,Q/A),J=Math.max(1,B*D),U=B-J;return{thumbStartFloat:Math.max(0,U*E),thumbSizeFloat:J,showScrollbar:!0}}}var jN4=1;class jl extends d0{props;constructor(A){super();this.props=A}createState(){return new RN4}}class RN4 extends m0{ownership;viewportHeight=0;initState(){let A=this.widget.props.controller;if(A)this.ownership={controller:A,owned:!1};else{let Q=new a6;Q.followMode=!1,Q.jumpTo(0),this.ownership={controller:Q,owned:!0}}}didUpdateWidget(A){oA(A.props.controller===this.widget.props.controller,"ScrollArea.controller identity must be stable across rebuilds")}dispose(){if(this.ownership.owned)this.ownership.controller.dispose()}getScrollInfo=()=>{let{controller:A}=this.ownership,Q=this.viewportHeight;return{totalContentHeight:Math.max(A.maxScrollExtent+Q,0),viewportHeight:Q,scrollOffset:Math.max(A.offset,0)}};setMeasuredHeight=(A)=>{this.viewportHeight=A};build(A){let Q=e0.of(A),{controller:$}=this.ownership;return new PN4({thickness:jN4,onMeasured:this.setMeasuredHeight,scrollable:new O5({controller:$,autofocus:this.widget.props.autofocus??!0,keyboardScrolling:this.widget.props.keyboardScrolling??!0,child:this.widget.props.child}),scrollbar:new Rg0({controller:$,thickness:jN4,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:this.getScrollInfo})})}__testing={isOwned:()=>this.ownership.owned,controller:()=>this.ownership.controller}}class PN4 extends r7{thickness;onMeasured;constructor({scrollable:A,scrollbar:Q,thickness:$,onMeasured:B}){super({children:[A,Q]});this.thickness=$,this.onMeasured=B}createRenderObject(){return new TN4(this.thickness,this.onMeasured)}}class TN4 extends bA{thickness;onMeasured;constructor(A,Q){super();this.thickness=A;this.onMeasured=Q}performLayout(){let A=this._lastConstraints;oA(!!A,"ScrollAreaLayoutRenderObject.performLayout called without constraints");let Q=A.maxWidth,$=Math.max(0,Math.min(this.thickness,Q)),B=Q-$,[E,D]=this.children;oA(E!==void 0&&D!==void 0,"ScrollAreaLayout requires scrollable and scrollbar children"),E.layout(new A4(B,B,0,A.maxHeight)),E.setOffset(0,0);let J=E.size.height;this.onMeasured(J),D.layout(new A4($,$,J,J)),D.setOffset(B,0),this.setSize(Q,J)}}class vB extends jl{props;constructor(A){super(A);this.props=A}}class Pg0 extends d0{pluginService;onDismiss;constructor(A){super();this.pluginService=A.pluginService,this.onDismiss=A.onDismiss}createState(){return new vN4}}class vN4 extends m0{entries=[];subscription=null;initState(){this.subscribe()}didUpdateWidget(A){if(A.pluginService===this.widget.pluginService)return;this.subscription?.unsubscribe(),this.subscribe()}dispose(){this.subscription?.unsubscribe(),super.dispose()}subscribe(){this.subscription=this.widget.pluginService.activity.subscribe((A)=>{this.setState(()=>{this.entries=A})})}rows(A){let Q=e0.of(A),{app:$,colors:B}=Q,E=new A0({color:B.foreground,dim:!0}),D=new A0({color:B.foreground,bold:!0}),J=new A0({color:$.link});if(this.entries.length===0)return[new mA({padding:c0.symmetric(1,1),child:new D0({text:new g("No plugin activity recorded yet.",E)})})];let U=this.entries.map((Y)=>new mA({padding:c0.only({left:1,right:1}),child:new D0({text:new g(`${MV(Y.timestamp).padStart(5," ")} ago `,E,[new g(Y.pluginName,D),new g(" ",E),new g(Y.label,J)]),maxLines:1,overflow:"ellipsis"})}));if(this.entries.length>=Zj)U.push(new mA({padding:c0.only({left:1,right:1,top:1}),child:new D0({text:new g(`Showing the most recent ${Zj} invocations. Earlier activity is not retained.`,E),maxLines:2,overflow:"ellipsis"})}));return U}build(A){let Q=e0.of(A),$=new A0({color:Q.colors.foreground,dim:!0});return new E1({header:"Plugin Activity",autofocus:!1,maxWidth:90,maxHeight:30,footer:[{keys:["Esc"],label:"close"},{keys:["↑↓","j/k"],label:"scroll"}],onDismiss:this.widget.onDismiss,child:new UA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new mA({padding:c0.only({left:1,right:1,bottom:1}),child:new D0({text:new g(`Last ${Zj} plugin invocations from hooks in the current CLI session.`,$),maxLines:3,overflow:"ellipsis"})}),new n6({fit:"loose",child:new vB({child:new UA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:this.rows(A)})})})]})})}}E3();E4();var _N4=10;class Tg0 extends d0{pluginService;workspaceRoot;logFilePath;onDismiss;constructor(A){super();this.pluginService=A.pluginService,this.workspaceRoot=A.workspaceRoot,this.logFilePath=A.logFilePath,this.onDismiss=A.onDismiss}createState(){return new SN4}}class SN4 extends m0{plugins=[];subscription=null;initState(){this.subscription=this.widget.pluginService.plugins.subscribe((A)=>{this.setState(()=>{this.plugins=A})})}didUpdateWidget(A){if(A.pluginService===this.widget.pluginService)return;this.subscription?.unsubscribe(),this.subscription=this.widget.pluginService.plugins.subscribe((Q)=>{this.setState(()=>{this.plugins=Q})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}relativePath(A){let Q=g0.file(this.widget.workspaceRoot),$=BA.relativePath(Q,C6(A));if($!==null&&$!==""&&$!==".."&&!$.startsWith("../"))return $;return v7(A)}detailPrefix(A){if(A.length===0)return` ${" ".repeat(_N4)}`;return` ${`${A}:`.padEnd(_N4," ")}`}bunNotFoundExplanation(A,Q){let $=e0.of(A),{app:B,colors:E}=$,D=new A0({color:E.foreground}),J=new A0({color:B.toolError}),U=new A0({color:B.link,underline:!0}),Y=`${Q} ${z1(Q,"plugin")} could not start because Bun is not installed.`,Z="https://ampcode.com/install",F="https://bun.sh",X=(I,G)=>new g(G,U,void 0,Bq(I),()=>{z$(A,I)});return new mA({padding:c0.only({left:1,right:1,bottom:1}),child:new UA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new D0({text:new g(Y,J),maxLines:2,overflow:"ellipsis"}),new D0({text:new g(" ",D)}),new D0({text:new g("To run plugins, either ",D,[X("https://ampcode.com/install","install the Amp binary"),new g(" or ",D),X("https://bun.sh","install bun"),new g(".",D)])})]})})}pluginRows(A){let Q=e0.of(A),{app:$,colors:B}=Q,E=new A0({color:B.foreground,dim:!0}),D=new A0({color:$.link}),J=new A0({color:$.link,underline:!0});if(this.plugins.length===0)return[new mA({padding:c0.symmetric(1,1),child:new D0({text:new g("No plugins found.",E)})})];let U=this.plugins.filter((X)=>X.errorMessage!==null),Y=U.length>0&&U.every((X)=>jh(X.errorMessage)),F=(Y?this.plugins.filter((X)=>!jh(X.errorMessage)):this.plugins).map((X)=>{let I=X.uri.toString(),G=I.startsWith("file://"),V=()=>{z$(A,I)},K=X.status==="active"?new A0({color:$.toolSuccess}):X.status==="error"?new A0({color:$.toolError}):new A0({color:B.warning}),z=new D0({text:new g(this.relativePath(X.uri),G?J:new A0({color:$.command}),void 0,G?Bq(I):void 0,G?V:void 0),maxLines:1,overflow:"ellipsis"}),W=G?new iA({cursor:"pointer",onClick:V,child:z}):z,C=[new OA({children:[new D0({text:new g(X.status,K,[new g(" ",E)]),maxLines:1,overflow:"clip"}),new n6({fit:"loose",child:W})]})];if(X.errorMessage)C.push(new D0({text:new g(this.detailPrefix("Error"),E,[new g(X.errorMessage,new A0({color:$.toolError}))]),maxLines:1,overflow:"ellipsis"}),new D0({text:new g(this.detailPrefix(""),E,[new g(`see logs: ${this.widget.logFilePath}`,E)]),maxLines:1,overflow:"ellipsis"}));if(X.registeredEvents.length>0)C.push(new D0({text:new g(this.detailPrefix("Events"),E,[new g(X.registeredEvents.join(", "),D)]),maxLines:1,overflow:"ellipsis"}));for(let[H,N]of X.registeredCommands.entries())C.push(new D0({text:new g(H===0?this.detailPrefix("Commands"):this.detailPrefix(""),E,[new g(`${N.category}: ${N.title}`,D)]),maxLines:1,overflow:"ellipsis"}));for(let[H,N]of X.registeredTools.entries())C.push(new D0({text:new g(H===0?this.detailPrefix("Tools"):this.detailPrefix(""),E,[new g(N.name,D)]),maxLines:1,overflow:"ellipsis"}));return new mA({padding:c0.only({left:1,right:1,bottom:1}),child:new UA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:C})})});if(Y)F.push(this.bunNotFoundExplanation(A,U.length));return F}build(A){let Q=this.plugins.filter((D)=>D.status==="active").length,$=this.plugins.reduce((D,J)=>D+J.registeredCommands.length,0),B=this.plugins.reduce((D,J)=>D+J.registeredTools.length,0),E=`${Q}/${this.plugins.length} ${z1(this.plugins.length,"plugin")} active (${$} ${z1($,"command")}, ${B} ${z1(B,"tool")})`;return new E1({header:"Plugins",autofocus:!1,maxWidth:90,maxHeight:30,footer:[{keys:["Esc"],label:"close"},{keys:["↑↓","j/k"],label:"scroll"}],onDismiss:this.widget.onDismiss,child:new UA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new mA({padding:c0.only({left:1,right:1,bottom:1}),child:new D0({text:new g(E,new A0({bold:!0}))})}),new n6({fit:"loose",child:new vB({child:new UA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:this.pluginRows(A)})})})]})})}}var NB6=O4("plugins.list",{noun:"plugins",verb:"list",description:"List all loaded plugins",status:{type:"enabled"}},(A,{controller:Q,dismiss:$})=>{Q.push(new Tg0({pluginService:A.pluginService,workspaceRoot:A.workspaceRoot,logFilePath:A.logFilePath,onDismiss:$}))}),qB6=O4("plugins.activity",{noun:"plugins",verb:"activity",description:"Show recent plugin activity triggered by hooks",status:{type:"enabled"}},(A,{controller:Q,dismiss:$})=>{Q.push(new Pg0({pluginService:A.pluginService,onDismiss:$}))}),wB6=O4("plugins.reload",{noun:"plugins",verb:"reload",description:"Reload all plugins",status:{type:"enabled"}},(A,{dismiss:Q})=>{A.pluginService.reload(),A.toastController.show("Reloading plugins..."),Q()});function kN4(A){return[NB6.bind(A),qB6.bind(A),wB6.bind(A)]}ub();i0();class vg0 extends G4{}class N80 extends G4{}var uB6=8;class _g0 extends d0{props;constructor(A){super(A.key===void 0?{}:{key:A.key});this.props=A}createState(){return new fN4}}class fN4 extends m0{build(A){let{options:Q,onConfirm:$,onCancel:B}=this.widget.props,{colors:E}=e0.of(A),D=Q.message?new D0({text:new g(Q.message,new A0({color:E.foreground}))}):new y0({height:1}),J=MB6(Q.message),U=[{keys:["Alt+Y"],label:Q.confirmButtonText??"yes"},{keys:["Alt+N","Esc"],label:"cancel"}];if(J)U.push({keys:["↑↓","j/k"],label:"scroll"});return new E1({header:Q.title,minWidth:64,maxWidth:80,footer:U,autofocus:!1,onDismiss:B,child:new N4({actions:new Map([[vg0,new cA(()=>$())],[N80,new cA(()=>B())]]),child:new rQ({debugLabel:"ConfirmDialogShortcuts",shortcuts:OB6(),child:new vB({child:D})})})})}}function MB6(A){if(A===void 0)return!1;return A.split(`
|
|
2774
|
+
`,F));break}case I4.HtmlInline:{Z.push(new g(E.nodeText(X),F));break}case I4.Image:{let G=H80(E,X)||"Image";Z.push(new g(`[Image: ${G}]`,D.link.copyWith({italic:!0})));break}default:{if((Y.firstChild[X]??0)!==0)Z.push(...this.processInline(A,X,$,B));break}}return Z}processHtmlNode(A,Q,$){try{let B=wg0(Q,{fragment:!0});return this.processHastNode(A,B,$)}catch{let B=new g(Q,$.styleScheme.text);return[new D0({text:B,selectable:!0})]}}processHastNode(A,Q,$){let{styleScheme:B}=$,E=[];if(Q.type==="root"){for(let J of Q.children)E.push(...this.processHastNode(A,J,$));return E}if(Q.type==="doctype")return E;if(Q.type==="text"){let J=Q;if(J.value.trim())E.push(new D0({text:new g(J.value,B.text),selectable:!0}));return E}if(Q.type!=="element")return E;let D=Q;if(D.tagName==="table"){let J=this.processHtmlTable(A,D,B);if(J)E.push(J);return E}for(let J of D.children||[])E.push(...this.processHastNode(A,J,$));return E}processHtmlTable(A,Q,$){let B=[],E=0,D=(U,Y)=>{let Z=[];for(let F of U.children||[]){if(F.type!=="element")continue;let X=F;if(X.tagName!=="td"&&X.tagName!=="th")continue;let I=this.extractTextFromHast(X);Z.push(ug0(new D0({text:new g(I,$.text),selectable:!0})))}if(Z.length===0)return null;return E=Math.max(E,Z.length),Mg0(Z,Y)};for(let U of Q.children||[]){if(U.type!=="element")continue;let Y=U;if(Y.tagName==="tr"){let Z=D(Y,B.length===0);if(Z)B.push(Z)}else if(Y.tagName==="thead"||Y.tagName==="tbody"){let Z=Y.tagName==="thead";for(let F of Y.children||[]){if(F.type!=="element")continue;let X=F;if(X.tagName==="tr"){let I=D(X,Z&&B.length===0);if(I)B.push(I)}}}}if(B.length===0)return null;let J=Array.from({length:E},()=>Og0("left","proportional"));return new C80({rows:B,columnConfigs:J,borderColor:$.tableBorder,showBorders:!0})}extractTextFromHast(A){if(A.type==="text")return A.value;if(A.type==="element")return(A.children||[]).map(($)=>this.extractTextFromHast($)).join("");return""}}function H80(A,Q){let $=A.arena,B="";for(let E of A.children(Q)){let D=$.kind[E];if(D===I4.Text||D===I4.CodeSpan)B+=A.nodeText(E);else B+=H80(A,E)}return B}function Lg0(A){let Q=xh0(A.trimEnd(),WN4),$=[];for(let B of Q.children(Q.root)){if(Q.arena.kind[B]!==I4.Heading)continue;let E=Q.arena.data1[B];if(E!==1&&E!==2)continue;$.push({level:E,text:H80(Q,B).trim()})}return $}function GB6(A,Q,$,B,E){let D=tY.default.languages[Q]||tY.default.languages.clike,J=E?.copyWith({color:B})??new A0({color:B});if(!D)return[new g(A,J)];try{let U=mP(A,$,`file.${Q}`),Y=[];for(let Z of U){let F=Z.color??B,X=E?.copyWith({color:F})??new A0({color:F});Y.push(new g(Z.content,X))}return Y.length>0?Y:[new g(A,J)]}catch{return[new g(A,J)]}}class CN4 extends d0{textSpan;constructor({textSpan:A}){super({});this.textSpan=A}createState(){return new HN4}}class HN4 extends m0{_controller=new a6;_scrollViewKey=new c3("no-wrap-code-scroll-view");_scrollListener=null;initState(){super.initState(),this._scrollListener=()=>{if(this.mounted)this.setState()},this._controller.addListener(this._scrollListener)}dispose(){if(this._scrollListener)this._controller.removeListener(this._scrollListener),this._scrollListener=null;this._controller.dispose(),super.dispose()}_getViewportWidth(){return this._scrollViewKey.currentElement?.renderObject?.size.width??0}_getScrollbarInfo(){let A=this._getViewportWidth();return{totalContent:(this._controller.maxScrollExtent??0)+A,viewportSize:A,scrollOffset:this._controller.offset}}build(A){let Q=e0.of(A);return new UA({crossAxisAlignment:"start",children:[new O5({key:this._scrollViewKey,scrollDirection:"horizontal",controller:this._controller,autofocus:!1,keyboardScrolling:!1,child:new D0({text:this.widget.textSpan,selectable:!0})}),new y0({height:1,child:new Ml({controller:this._controller,getScrollInfo:()=>this._getScrollbarInfo(),axis:"horizontal",thickness:1,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack})})]})}}var VB6=54,KB6=24,zB6=2,WB6=c0.symmetric(2,1);class Ol extends d0{props;constructor(A){super();this.props=A}createState(){return new NN4}}class NN4 extends m0{hovered=!1;actionHovered=!1;build(){let A=new qN4({...this.widget.props,hovered:this.hovered,actionHovered:this.actionHovered,onActionEnter:()=>{this.setState(()=>{this.actionHovered=!0})},onActionExit:()=>{this.setState(()=>{this.actionHovered=!1})}});if(this.widget.props.mouseBehavior==="click-action")return A;return new iA({cursor:o1.POINTER,opaque:!1,onClick:this.widget.props.action.onAction,onEnter:()=>{this.hovered=!0,this.requestClickAnywherePointerCursor(),this.setState(()=>{this.hovered=!0})},onHover:()=>{this.requestClickAnywherePointerCursor()},onExit:()=>{this.hovered=!1,I6.instance.requestCursorChange(o1.DEFAULT),this.setState(()=>{this.hovered=!1})},child:A})}requestClickAnywherePointerCursor(){I6.instance.requestCursorChange(o1.POINTER),queueMicrotask(()=>{if(this.hovered)I6.instance.requestCursorChange(o1.POINTER)})}}class qN4 extends eA{props;constructor(A){super();this.props=A}build(A){let Q=S4.of(A),$=e0.of(A),B=X4.of(A),E=this.props.width??VB6,D=Math.max(this.props.minWidth??KB6,B.size.width-zB6),J=Math.min(E,D),U=this.props.padding??WB6,Y=Math.max(1,J-U.horizontal-2),F=this.props.mouseBehavior==="click-anywhere"&&this.props.hovered?Q.colorScheme.foreground:CB6(this.props.variant,$.app),X=this.buildOverlays(Q,$,F),I=new GA({width:Math.max(1,J-2),padding:U,child:new y0({width:Y,child:this.buildMessage(Q)})});return new h$({width:J,decoration:new v1(Q.colorScheme.background,U1.all(new Y1(F,1,"rounded"))),overlays:X,child:I})}buildMessage(A){if(this.props.renderMarkdown)return new yq({markdown:this.props.message});return new D0({text:new g(this.props.message,new A0({color:A.colorScheme.foreground})),overflow:"ellipsis",maxLines:3,selectable:!0})}buildOverlays(A,Q,$){let B=A.colorScheme.background,E=[];if(this.props.title)E.push({position:"top",alignment:"left",child:new D0({text:new g(` ${this.props.title} `,new A0({color:$,backgroundColor:B,bold:!0})),overflow:"ellipsis",maxLines:1,selectable:!0})});return E.push({position:"bottom",alignment:"right",child:this.buildAction(A,Q)}),E}buildAction(A,Q){let $=A.colorScheme.background,B=this.props.mouseBehavior==="click-anywhere"?this.props.hovered:this.props.actionHovered,E=new D0({text:new g("",void 0,this.buildActionSpans(A,Q,$,B)),textAlign:"right",overflow:"ellipsis",maxLines:1});if(this.props.mouseBehavior==="click-anywhere")return E;return new iA({cursor:o1.POINTER,opaque:!1,onClick:this.props.action.onAction,onEnter:this.props.onActionEnter,onExit:this.props.onActionExit,child:E})}buildActionSpans(A,Q,$,B){let E=new A0({color:Q.app.keybind,backgroundColor:$}),D=new A0({color:A.colorScheme.foreground,backgroundColor:$,dim:!0});if(this.props.action.command){let J=[new g(` ${this.props.action.keymapKey}`,E),new g(", ",D),new g(this.props.action.command,new A0({color:Q.app.command,backgroundColor:$,bold:B}))];if(this.props.action.confirmShortcut)J.push(new g(", ",D),new g(this.props.action.confirmShortcut,E));return J.push(new g(" ",D)),J}return[new g(` ${this.props.action.keymapKey} `,new A0({color:Q.app.keybind,backgroundColor:$})),new g(`${this.props.action.label} `,new A0({color:A.colorScheme.foreground,backgroundColor:$,dim:!B,bold:B}))]}}function CB6(A,Q){switch(A){case"danger":return Q.toolError;case"success":return Q.toolSuccess;case"info":return Q.diffContext}}var HB6=54;class Ll extends eA{props;constructor(A){super();this.props=A}build(){let A=this.props.notice,Q={width:this.props.width??HB6,message:A.message,renderMarkdown:!0,variant:A.variant==="danger"?"danger":"info",mouseBehavior:"click-action",action:{keymapKey:"Ctrl+.",label:"dismiss",onAction:this.props.onDismiss}};if(A.title)Q.title=A.title;return new Ol(Q)}}class jg0{configService;setState;notices=[];displayedNoticeKey=null;reloadInterval=null;listeners=new Set;constructor(A,Q){this.configService=A;this.setState=Q}get current(){return this.notices[0]??null}addListener(A){this.listeners.add(A)}removeListener(A){this.listeners.delete(A)}buildComplexToast(){let A=this.current;if(!A)return null;return new Ll({notice:A,onDismiss:()=>this.dismiss(A.key)})}async load(){try{let A=await j4.notices({},{config:this.configService});if(!A.ok)return;this.setState(()=>{this.notices=A.result}),this.notifyListeners(),this.logCurrentView()}catch(A){S.debug("Failed to load notices",{error:A})}}startPolling(){this.load(),this.reloadInterval=setInterval(()=>void this.load(),60000)}dispose(){if(this.reloadInterval)clearInterval(this.reloadInterval),this.reloadInterval=null}dismiss(A){this.logAction(A,"dismiss"),this.setState(()=>{this.notices=this.notices.filter((Q)=>Q.key!==A)}),this.notifyListeners(),this.logCurrentView()}dismissCurrent(){let A=this.current;if(!A)return!1;return this.dismiss(A.key),!0}logAction(A,Q){j4.logNoticeAction({key:A,action:Q},{config:this.configService}).catch(($)=>{S.debug("Failed to log notice action",{error:$,key:A,action:Q})})}logCurrentView(){let A=this.current;if(!A){this.displayedNoticeKey=null;return}if(this.displayedNoticeKey===A.key)return;this.displayedNoticeKey=A.key,this.logAction(A.key,"view")}notifyListeners(){for(let A of this.listeners)A()}}Kg();var wN4=process.platform==="win32"?" ":"█",uN4=process.platform==="win32"?"░":"█";class Rg0 extends d0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:A,controller:Q,getScrollInfo:$,thickness:B=1,trackChar:E=wN4,thumbChar:D=uN4,showTrack:J=!0,thumbColor:U,trackColor:Y}){super(A?{key:A}:{});this.controller=Q,this.getScrollInfo=$,this.thickness=B,this.trackChar=E,this.thumbChar=D,this.showTrack=J,this.thumbColor=U,this.trackColor=Y}createState(){return new MN4}}class MN4 extends m0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(A){let{totalContentHeight:Q,viewportHeight:$}=this.widget.getScrollInfo(),E=this.context.findRenderObject()?.size.height??0;if(E===0||Q<=$)return!1;let D=this.widget.getScrollInfo(),J=Math.min(1,$/Q),U=Math.max(1,E*J),Y=Math.max(0,Math.min(1,D.scrollOffset/(Q-$))),Z=E-U,F=Math.max(0,Z*Y),X=F+U;return A>=F&&A<=X}_handleHover=(A)=>{let Q=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(A.localPosition.y),Q!==this._isOverThumb)this.setState()};_handleDrag=(A)=>{let{totalContentHeight:Q,viewportHeight:$,scrollOffset:B}=this.widget.getScrollInfo(),D=this.context.findRenderObject()?.size.height??0;if(D===0||Q<=$)return;if(this._dragStartY===null)this._dragStartY=A.localPosition.y,this._dragStartOffset=B;let J=A.localPosition.y-this._dragStartY,U=Math.min(1,$/Q),Y=Math.max(1,D*U),Z=D-Y;if(Z<=0)return;let F=Q-$,X=Z/F,I=J/X,G=Math.max(0,Math.min(F,this._dragStartOffset+I));this.widget.controller.jumpTo(G)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(A)=>{if(A.button!=="left")return;let Q=A.localPosition.y,{totalContentHeight:$,viewportHeight:B,scrollOffset:E}=this.widget.getScrollInfo(),J=this.context.findRenderObject()?.size.height??0;if(J===0||$<=B)return;let U=Math.min(1,B/$),Y=Math.max(1,J*U),Z=$-B,F=J-Y,X=Math.max(0,Math.min(1,E/($-B))),I=Math.max(0,F*X),G=I+Y;if(Q>=I&&Q<=G)return;if(Q<I)this.widget.controller.animateTo(Math.max(0,E-B));else this.widget.controller.animateTo(Math.min(Z,E+B))};build(A){return new iA({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?o1.POINTER:o1.DEFAULT,child:new ON4({controller:this.widget.controller,getScrollInfo:this.widget.getScrollInfo,thickness:this.widget.thickness,trackChar:this.widget.trackChar,thumbChar:this.widget.thumbChar,showTrack:this.widget.showTrack,thumbColor:this.widget.thumbColor,trackColor:this.widget.trackColor})})}}class ON4 extends QZ{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:A,controller:Q,getScrollInfo:$,thickness:B=1,trackChar:E=wN4,thumbChar:D=uN4,showTrack:J=!0,thumbColor:U,trackColor:Y}){super(A?{key:A}:{});this.controller=Q,this.getScrollInfo=$,this.thickness=B,this.trackChar=E,this.thumbChar=D,this.showTrack=J,this.thumbColor=U,this.trackColor=Y}createRenderObject(){return new LN4(this)}updateRenderObject(A){A.updateWidget(this)}}class LN4 extends bA{_widget;constructor(A){super();this._widget=A}updateWidget(A){this._widget=A,this.markNeedsLayout()}performLayout(){let A=this._lastConstraints;oA(!!A,"performLayout called without constraints");let Q=Math.min(A.maxWidth,this._widget.thickness),$=A.maxHeight;this.setSize(Q,$),super.performLayout()}getMinIntrinsicWidth(A){return this._widget.thickness}getMaxIntrinsicWidth(A){return this._widget.thickness}getMinIntrinsicHeight(A){return 0}getMaxIntrinsicHeight(A){return 0}paint(A,Q,$){let{thumbStartFloat:B,thumbSizeFloat:E,showScrollbar:D}=this._calculateScrollbarMetrics();if(!D)return;let J=this._widget.trackColor,U=this._widget.thumbColor,Y=process.platform==="win32",Z=B,F=B+E;if(!Y){let X=["▁","▂","▃","▄","▅","▆","▇","█"];for(let I=0;I<this.size.height;I++){let G="█",V=!0;if(I===Math.floor(Z)){let K=1-(Z-I),z=Math.floor(K*8);G=X[z]||"█",V=!1}else if(I===Math.floor(F)){let K=1-(F-I),z=Math.floor(K*8);G=X[z]||"█"}else if(I>Z&&I<F)V=!1;A.setChar(Q,$+I,G,{fg:U,bg:J,reverse:V},1)}return}for(let X=0;X<this.size.height;X++){let I=X+0.5,G=I>=Z&&I<F,V=G?this._widget.thumbChar:this._widget.trackChar;A.setChar(Q,$+X,V,{fg:G?U:J,bg:J,reverse:!1},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:A,viewportHeight:Q,scrollOffset:$}=this._widget.getScrollInfo(),B=this.size.height;if(A<=Q||B<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let E=Math.max(0,Math.min(1,$/(A-Q))),D=Math.min(1,Q/A),J=Math.max(1,B*D),U=B-J;return{thumbStartFloat:Math.max(0,U*E),thumbSizeFloat:J,showScrollbar:!0}}}var jN4=1;class jl extends d0{props;constructor(A){super();this.props=A}createState(){return new RN4}}class RN4 extends m0{ownership;viewportHeight=0;initState(){let A=this.widget.props.controller;if(A)this.ownership={controller:A,owned:!1};else{let Q=new a6;Q.followMode=!1,Q.jumpTo(0),this.ownership={controller:Q,owned:!0}}}didUpdateWidget(A){oA(A.props.controller===this.widget.props.controller,"ScrollArea.controller identity must be stable across rebuilds")}dispose(){if(this.ownership.owned)this.ownership.controller.dispose()}getScrollInfo=()=>{let{controller:A}=this.ownership,Q=this.viewportHeight;return{totalContentHeight:Math.max(A.maxScrollExtent+Q,0),viewportHeight:Q,scrollOffset:Math.max(A.offset,0)}};setMeasuredHeight=(A)=>{this.viewportHeight=A};build(A){let Q=e0.of(A),{controller:$}=this.ownership;return new PN4({thickness:jN4,onMeasured:this.setMeasuredHeight,scrollable:new O5({controller:$,autofocus:this.widget.props.autofocus??!0,keyboardScrolling:this.widget.props.keyboardScrolling??!0,child:this.widget.props.child}),scrollbar:new Rg0({controller:$,thickness:jN4,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:this.getScrollInfo})})}__testing={isOwned:()=>this.ownership.owned,controller:()=>this.ownership.controller}}class PN4 extends r7{thickness;onMeasured;constructor({scrollable:A,scrollbar:Q,thickness:$,onMeasured:B}){super({children:[A,Q]});this.thickness=$,this.onMeasured=B}createRenderObject(){return new TN4(this.thickness,this.onMeasured)}}class TN4 extends bA{thickness;onMeasured;constructor(A,Q){super();this.thickness=A;this.onMeasured=Q}performLayout(){let A=this._lastConstraints;oA(!!A,"ScrollAreaLayoutRenderObject.performLayout called without constraints");let Q=A.maxWidth,$=Math.max(0,Math.min(this.thickness,Q)),B=Q-$,[E,D]=this.children;oA(E!==void 0&&D!==void 0,"ScrollAreaLayout requires scrollable and scrollbar children"),E.layout(new A4(B,B,0,A.maxHeight)),E.setOffset(0,0);let J=E.size.height;this.onMeasured(J),D.layout(new A4($,$,J,J)),D.setOffset(B,0),this.setSize(Q,J)}}class vB extends jl{props;constructor(A){super(A);this.props=A}}class Pg0 extends d0{pluginService;onDismiss;constructor(A){super();this.pluginService=A.pluginService,this.onDismiss=A.onDismiss}createState(){return new vN4}}class vN4 extends m0{entries=[];subscription=null;initState(){this.subscribe()}didUpdateWidget(A){if(A.pluginService===this.widget.pluginService)return;this.subscription?.unsubscribe(),this.subscribe()}dispose(){this.subscription?.unsubscribe(),super.dispose()}subscribe(){this.subscription=this.widget.pluginService.activity.subscribe((A)=>{this.setState(()=>{this.entries=A})})}rows(A){let Q=e0.of(A),{app:$,colors:B}=Q,E=new A0({color:B.foreground,dim:!0}),D=new A0({color:B.foreground,bold:!0}),J=new A0({color:$.link});if(this.entries.length===0)return[new mA({padding:c0.symmetric(1,1),child:new D0({text:new g("No plugin activity recorded yet.",E)})})];let U=this.entries.map((Y)=>new mA({padding:c0.only({left:1,right:1}),child:new D0({text:new g(`${MV(Y.timestamp).padStart(5," ")} ago `,E,[new g(Y.pluginName,D),new g(" ",E),new g(Y.label,J)]),maxLines:1,overflow:"ellipsis"})}));if(this.entries.length>=Zj)U.push(new mA({padding:c0.only({left:1,right:1,top:1}),child:new D0({text:new g(`Showing the most recent ${Zj} invocations. Earlier activity is not retained.`,E),maxLines:2,overflow:"ellipsis"})}));return U}build(A){let Q=e0.of(A),$=new A0({color:Q.colors.foreground,dim:!0});return new E1({header:"Plugin Activity",autofocus:!1,maxWidth:90,maxHeight:30,footer:[{keys:["Esc"],label:"close"},{keys:["↑↓","j/k"],label:"scroll"}],onDismiss:this.widget.onDismiss,child:new UA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new mA({padding:c0.only({left:1,right:1,bottom:1}),child:new D0({text:new g(`Last ${Zj} plugin invocations from hooks in the current CLI session.`,$),maxLines:3,overflow:"ellipsis"})}),new n6({fit:"loose",child:new vB({child:new UA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:this.rows(A)})})})]})})}}E3();E4();var _N4=10;class Tg0 extends d0{pluginService;workspaceRoot;logFilePath;onDismiss;constructor(A){super();this.pluginService=A.pluginService,this.workspaceRoot=A.workspaceRoot,this.logFilePath=A.logFilePath,this.onDismiss=A.onDismiss}createState(){return new SN4}}class SN4 extends m0{plugins=[];subscription=null;initState(){this.subscription=this.widget.pluginService.plugins.subscribe((A)=>{this.setState(()=>{this.plugins=A})})}didUpdateWidget(A){if(A.pluginService===this.widget.pluginService)return;this.subscription?.unsubscribe(),this.subscription=this.widget.pluginService.plugins.subscribe((Q)=>{this.setState(()=>{this.plugins=Q})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}relativePath(A){let Q=g0.file(this.widget.workspaceRoot),$=BA.relativePath(Q,C6(A));if($!==null&&$!==""&&$!==".."&&!$.startsWith("../"))return $;return v7(A)}detailPrefix(A){if(A.length===0)return` ${" ".repeat(_N4)}`;return` ${`${A}:`.padEnd(_N4," ")}`}bunNotFoundExplanation(A,Q){let $=e0.of(A),{app:B,colors:E}=$,D=new A0({color:E.foreground}),J=new A0({color:B.toolError}),U=new A0({color:B.link,underline:!0}),Y=`${Q} ${z1(Q,"plugin")} could not start because Bun is not installed.`,Z="https://ampcode.com/install",F="https://bun.sh",X=(I,G)=>new g(G,U,void 0,Bq(I),()=>{z$(A,I)});return new mA({padding:c0.only({left:1,right:1,bottom:1}),child:new UA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new D0({text:new g(Y,J),maxLines:2,overflow:"ellipsis"}),new D0({text:new g(" ",D)}),new D0({text:new g("To run plugins, either ",D,[X("https://ampcode.com/install","install the Amp binary"),new g(" or ",D),X("https://bun.sh","install bun"),new g(".",D)])})]})})}pluginRows(A){let Q=e0.of(A),{app:$,colors:B}=Q,E=new A0({color:B.foreground,dim:!0}),D=new A0({color:$.link}),J=new A0({color:$.link,underline:!0});if(this.plugins.length===0)return[new mA({padding:c0.symmetric(1,1),child:new D0({text:new g("No plugins found.",E)})})];let U=this.plugins.filter((X)=>X.errorMessage!==null),Y=U.length>0&&U.every((X)=>jh(X.errorMessage)),F=(Y?this.plugins.filter((X)=>!jh(X.errorMessage)):this.plugins).map((X)=>{let I=X.uri.toString(),G=I.startsWith("file://"),V=()=>{z$(A,I)},K=X.status==="active"?new A0({color:$.toolSuccess}):X.status==="error"?new A0({color:$.toolError}):new A0({color:B.warning}),z=new D0({text:new g(this.relativePath(X.uri),G?J:new A0({color:$.command}),void 0,G?Bq(I):void 0,G?V:void 0),maxLines:1,overflow:"ellipsis"}),W=G?new iA({cursor:"pointer",onClick:V,child:z}):z,C=[new OA({children:[new D0({text:new g(X.status,K,[new g(" ",E)]),maxLines:1,overflow:"clip"}),new n6({fit:"loose",child:W})]})];if(X.errorMessage)C.push(new D0({text:new g(this.detailPrefix("Error"),E,[new g(X.errorMessage,new A0({color:$.toolError}))]),maxLines:1,overflow:"ellipsis"}),new D0({text:new g(this.detailPrefix(""),E,[new g(`see logs: ${this.widget.logFilePath}`,E)]),maxLines:1,overflow:"ellipsis"}));if(X.registeredEvents.length>0)C.push(new D0({text:new g(this.detailPrefix("Events"),E,[new g(X.registeredEvents.join(", "),D)]),maxLines:1,overflow:"ellipsis"}));for(let[H,N]of X.registeredCommands.entries())C.push(new D0({text:new g(H===0?this.detailPrefix("Commands"):this.detailPrefix(""),E,[new g(`${N.category}: ${N.title}`,D)]),maxLines:1,overflow:"ellipsis"}));for(let[H,N]of X.registeredTools.entries())C.push(new D0({text:new g(H===0?this.detailPrefix("Tools"):this.detailPrefix(""),E,[new g(N.name,D)]),maxLines:1,overflow:"ellipsis"}));return new mA({padding:c0.only({left:1,right:1,bottom:1}),child:new UA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:C})})});if(Y)F.push(this.bunNotFoundExplanation(A,U.length));return F}build(A){let Q=this.plugins.filter((D)=>D.status==="active").length,$=this.plugins.reduce((D,J)=>D+J.registeredCommands.length,0),B=this.plugins.reduce((D,J)=>D+J.registeredTools.length,0),E=`${Q}/${this.plugins.length} ${z1(this.plugins.length,"plugin")} active (${$} ${z1($,"command")}, ${B} ${z1(B,"tool")})`;return new E1({header:"Plugins",autofocus:!1,maxWidth:90,maxHeight:30,footer:[{keys:["Esc"],label:"close"},{keys:["↑↓","j/k"],label:"scroll"}],onDismiss:this.widget.onDismiss,child:new UA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new mA({padding:c0.only({left:1,right:1,bottom:1}),child:new D0({text:new g(E,new A0({bold:!0}))})}),new n6({fit:"loose",child:new vB({child:new UA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:this.pluginRows(A)})})})]})})}}var NB6=O4("plugins.list",{noun:"plugins",verb:"list",description:"List all loaded plugins",status:{type:"enabled"}},(A,{controller:Q,dismiss:$})=>{Q.push(new Tg0({pluginService:A.pluginService,workspaceRoot:A.workspaceRoot,logFilePath:A.logFilePath,onDismiss:$}))}),qB6=O4("plugins.activity",{noun:"plugins",verb:"activity",description:"Show recent plugin activity triggered by hooks",status:{type:"enabled"}},(A,{controller:Q,dismiss:$})=>{Q.push(new Pg0({pluginService:A.pluginService,onDismiss:$}))}),wB6=O4("plugins.reload",{noun:"plugins",verb:"reload",description:"Reload all plugins",status:{type:"enabled"}},(A,{dismiss:Q})=>{A.pluginService.reload(),A.toastController.show("Reloading plugins..."),Q()});function kN4(A){return[NB6.bind(A),qB6.bind(A),wB6.bind(A)]}ub();i0();class vg0 extends G4{}class N80 extends G4{}var uB6=8;class _g0 extends d0{props;constructor(A){super(A.key===void 0?{}:{key:A.key});this.props=A}createState(){return new fN4}}class fN4 extends m0{build(A){let{options:Q,onConfirm:$,onCancel:B}=this.widget.props,{colors:E}=e0.of(A),D=Q.message?new D0({text:new g(Q.message,new A0({color:E.foreground}))}):new y0({height:1}),J=MB6(Q.message),U=[{keys:["Alt+Y"],label:Q.confirmButtonText??"yes"},{keys:["Alt+N","Esc"],label:"cancel"}];if(J)U.push({keys:["↑↓","j/k"],label:"scroll"});return new E1({header:Q.title,minWidth:64,maxWidth:80,footer:U,autofocus:!1,onDismiss:B,child:new N4({actions:new Map([[vg0,new cA(()=>$())],[N80,new cA(()=>B())]]),child:new rQ({debugLabel:"ConfirmDialogShortcuts",shortcuts:OB6(),child:new vB({child:D})})})})}}function MB6(A){if(A===void 0)return!1;return A.split(`
|
|
2775
2775
|
`).length>uB6}function OB6(){return new Map([[wA.alt("y"),new vg0],[wA.alt("n"),new N80],[wA.key("Escape"),new N80]])}var q80=8,xN4=q80-1;class w80 extends G4{}class Sg0 extends G4{}class kg0 extends G4{}class fg0 extends G4{}class Rl extends d0{props;constructor(A){super(A.key===void 0?{}:{key:A.key});this.props=A}createState(){return new yN4}}class yN4 extends m0{controller=new EZ;helpScroll=new a6;onTextChanged=()=>{this.setState()};initState(){this.controller.text=this.widget.props.initialValue??"",this.controller.addListener(this.onTextChanged),this.helpScroll.followMode=!1,this.helpScroll.jumpTo(0)}dispose(){this.controller.removeListener(this.onTextChanged),this.controller.dispose(),this.helpScroll.dispose(),super.dispose()}handleSubmit(){let A=this.controller.text.trim();if((this.widget.props.isRequired??!0)&&A.length===0)return;this.widget.props.onSubmit(A)}build(A){let{colors:Q,app:$}=e0.of(A),E=!(this.widget.props.isRequired??!0)||this.controller.text.trim().length>0,D=LB6(this.widget.props.helpText),J=[];if(E)J.push({keys:["Enter"],label:"submit"});if(D)J.push({keys:["PgUp","PgDn"],label:"scroll"});J.push({keys:["Esc"],label:"cancel"});let U=[];if(this.widget.props.helpText)U.push(jB6(this.widget.props.helpText,this.helpScroll,Q.foreground)),U.push(new y0({height:1}));U.push(new OA({children:[new D0({text:new g("> ",new A0({color:$.command}))}),new P4({child:new Yq({controller:this.controller,placeholder:this.widget.props.placeholder??"",autofocus:!0,maxLines:1,style:{textColor:Q.foreground,border:null},onSubmitted:()=>this.handleSubmit()})})]}));let Y=new UA({crossAxisAlignment:"stretch",mainAxisSize:"min",children:U}),Z=D?new N4({actions:this.buildScrollActions(),child:new rQ({debugLabel:"InputDialogScrollShortcuts",shortcuts:RB6(),child:Y})}):Y;return new E1({header:this.widget.props.header,minWidth:80,maxWidth:80,footer:J,autofocus:!1,bodyFit:this.widget.props.bodyFit,onDismiss:this.widget.props.onDismiss,child:Z})}buildScrollActions(){let A=(Q)=>{let $=PB6(this.helpScroll.offset+Q,0,this.helpScroll.maxScrollExtent);this.helpScroll.jumpTo($)};return new Map([[w80,new cA(()=>A(-xN4))],[Sg0,new cA(()=>A(xN4))],[kg0,new cA(()=>this.helpScroll.jumpTo(0))],[fg0,new cA(()=>this.helpScroll.jumpTo(this.helpScroll.maxScrollExtent))]])}}function LB6(A){if(A===void 0)return!1;return A.split(`
|
|
2776
2776
|
`).length>q80}function jB6(A,Q,$){let B=A.split(`
|
|
2777
2777
|
`).length,E=new D0({text:new g(A,new A0({color:$}))});if(B<=q80)return E;return new y0({width:1/0,height:q80,child:new vB({autofocus:!1,controller:Q,child:E})})}function RB6(){return new Map([[wA.key("PageUp"),new w80],[wA.key("PageDown"),new Sg0],[wA.ctrl("u"),new w80],[wA.shift("Home"),new kg0],[wA.shift("End"),new fg0]])}function PB6(A,Q,$){return Math.max(Q,Math.min(A,$))}var xg0=8,bN4=1,hN4=xg0-1;class yg0 extends G4{}class bg0 extends G4{}class u80 extends G4{}class M80 extends G4{}class hg0 extends G4{}class gg0 extends G4{}class mg0 extends d0{props;constructor(A){super(A.key===void 0?{}:{key:A.key});this.props=A}createState(){return new gN4}}class gN4 extends m0{messageScroll=new a6;initState(){super.initState(),this.messageScroll.followMode=!1,this.messageScroll.jumpTo(0)}dispose(){this.messageScroll.dispose(),super.dispose()}build(A){let Q=this.widget.props,$=TB6(Q,this.messageScroll),B=vB6(Q.options.message),E=B?new N4({actions:this.buildScrollActions(),child:new rQ({debugLabel:"SelectDialogScrollShortcuts",shortcuts:SB6(),child:$})}):$,D=[{keys:["↑/↓","j/k"],label:"move"},{keys:["Enter"],label:"select"}];if(B)D.push({keys:["Ctrl+E","Ctrl+Y"],label:"scroll"});return D.push({keys:["Esc"],label:"cancel"}),new E1({header:Q.options.title,minWidth:64,maxWidth:80,footer:D,autofocus:!1,onDismiss:Q.onCancel,child:E})}buildScrollActions(){let A=(Q)=>{let $=kB6(this.messageScroll.offset+Q,0,this.messageScroll.maxScrollExtent);this.messageScroll.jumpTo($)};return new Map([[yg0,new cA(()=>A(-bN4))],[bg0,new cA(()=>A(bN4))],[u80,new cA(()=>A(-hN4))],[M80,new cA(()=>A(hN4))],[hg0,new cA(()=>this.messageScroll.jumpTo(0))],[gg0,new cA(()=>this.messageScroll.jumpTo(this.messageScroll.maxScrollExtent))]])}}function TB6(A,Q){let $=A.options.options.map((E)=>({value:E,label:E})),B=Math.max(0,$.findIndex((E)=>E.value===A.options.initialValue));return new xX({options:$,selectedIndex:B,body:_B6(A.options.message,Q),onSelect:(E)=>{if(E===null){A.onCancel();return}A.onSelect(E)},padding:c0.all(0),showBorder:!1,showDismissalMessage:!1,enableMouseInteraction:!0,wrapOptions:!0})}function vB6(A){if(A===void 0)return!1;return A.split(`
|
|
2778
2778
|
`).length>xg0}function _B6(A,Q){if(A===void 0)return;let $=A.split(`
|
|
2779
2779
|
`).length,B=Math.min($,xg0);return new y0({width:1/0,height:B,child:new vB({autofocus:!1,controller:Q,child:new D0({text:new g(A)})})})}function SB6(){return new Map([[wA.key("PageUp"),new u80],[wA.key("PageDown"),new M80],[wA.ctrl("u"),new u80],[wA.ctrl("d"),new M80],[wA.ctrl("y"),new yg0],[wA.ctrl("e"),new bg0],[wA.shift("Home"),new hg0],[wA.shift("End"),new gg0]])}function kB6(A,Q,$){return Math.max(Q,Math.min(A,$))}var fB6=3,xB6=2097152,yB6=new ZB("PluginDialogOverlay");function O80(A,Q,$){if($!==void 0)return{type:"response",id:A,error:$};if(Q===void 0)return{type:"response",id:A};return{type:"response",id:A,result:Q}}function bB6(A){let Q=new TextEncoder().encode(JSON.stringify(A)).byteLength;if(Q<=xB6)return;throw Error(`thread.messages response is too large (${Q} bytes). Request fewer messages.`)}class dg0{options;unregisterPluginCommands=null;pluginCommandSubscriptions=[];pluginErrorToastKeys=new Set;activeDialog=null;queuedDialogs=[];resolvingDialog=null;pendingOwnerUIRequests=new Map;pendingActorUIRequests=new Map;stateBackedRequestIDs=new Set;pluginUIRespondRequestCounter=0;statusItems=new Map;blockingConfirmDialog=!1;disposed=!1;constructor(A){this.options=A}init(){this.disposed=!1,this.configurePluginPlatform(),this.subscribePluginCommands()}dispose(){this.disposed=!0,this.unregisterPluginCommands?.(),this.unregisterPluginCommands=null;for(let A of this.pluginCommandSubscriptions)A.unsubscribe();this.pluginCommandSubscriptions=[],this.cancelOwnerUIRequests(),this.cancelPendingDialogs(),this.statusItems.clear(),this.clearPluginPlatformStatusHandlers()}handlePluginMessage(A,Q){let $=A.message;if($.type==="response"){this.cancelOwnerUIRequest($.id),this.cancelActorUIRequest($.id);return}if($.type==="event"){if(this.handlePluginUIStateEvent($,Q))return;this.handlePluginEvent($);return}if(this.stateBackedRequestIDs.has($.id))return;if(!O30($.method)){if($.method==="thread.messages")this.handleThreadMessagesRequest($,Q);return}this.handleOwnerUIRequest($,Q)}cancelOwnerUIRequests(){let A=[...this.pendingOwnerUIRequests.values(),...this.pendingActorUIRequests.values()];this.pendingOwnerUIRequests.clear(),this.pendingActorUIRequests.clear(),this.stateBackedRequestIDs.clear();for(let Q of A)Q.abort()}hasBlockingDialog(){return this.activeDialog!==null}hasBlockingConfirmDialog(){return this.activeDialog?.kind==="confirm"}buildDialogLayers(){let A=this.activeDialog;if(!A)return[];return[new E6({key:yB6,debugLabel:"PluginDialogOverlay",autofocus:!1,canRequestFocus:!0,child:this.buildActiveDialog(A)})]}buildActiveDialog(A){switch(A.kind){case"input":return new Rl({key:new CK(A),header:A.options.title??"Input",helpText:A.options.helpText,initialValue:A.options.initialValue,isRequired:!1,onSubmit:(Q)=>this.resolveInputDialog(A,Q),onDismiss:()=>this.resolveInputDialog(A,void 0)});case"confirm":return new _g0({key:new CK(A),options:A.options,onConfirm:()=>this.resolveConfirmDialog(A,!0),onCancel:()=>this.resolveConfirmDialog(A,!1)});case"select":return new mg0({key:new CK(A),options:A.options,onSelect:(Q)=>this.resolveSelectDialog(A,Q),onCancel:()=>this.resolveSelectDialog(A,void 0)})}}getStatusItems(){return[...this.statusItems.values()].flatMap((A)=>A.value===void 0?[]:[{pluginURI:A.pluginURI,id:A.id,value:A.value}])}configurePluginPlatform(){let A=this.options.context.pluginPlatform;if(!A)return;if(A.showToast=(Q)=>this.options.toastController.show(Q,"success"),A.showOpenedURLToast=(Q)=>{this.options.toastController.show(`Opened URL: ${Q}`,"success",8000)},A.appendToThreadHandler=this.options.context.observerOnly?async()=>{throw Error("thread.append is only available from an executor-owned plugin runtime")}:this.options.appendToThread,this.options.readThreadMessages)A.readThreadMessagesHandler=this.readThreadMessages;if(this.options.readThreadTitle)A.readThreadTitleHandler=this.readThreadTitle;if(this.options.subscribeThreadTitle)A.subscribeThreadTitleHandler=this.subscribeThreadTitle;A.runAgentHandler=this.options.context.observerOnly?async()=>{throw Error("agent.run is only available from an executor-owned plugin runtime")}:this.options.runAgent??(async()=>{throw Error("agent.run is not available in this context")}),A.showInputDialog=this.showInputDialog,A.showConfirmDialog=this.showConfirmDialog,A.showSelectDialog=this.showSelectDialog,A.createStatusItemHandler=this.createStatusItem,A.updateStatusItemHandler=this.updateStatusItem,A.removeStatusItemHandler=this.removeStatusItem}handlePluginEvent(A){if(A.event!=="ui.notify")return;let Q=A.data;if(typeof Q.message==="string")this.options.toastController.show(Q.message,"success")}async handleThreadMessagesRequest(A,Q){try{let{options:$,threadID:B}=this.parseThreadMessagesRequestParams(A.params),E=await this.readThreadMessages($,B);bB6(E),Q(O80(A.id,E))}catch($){Q(O80(A.id,void 0,$ instanceof Error?$.message:String($)))}}parseThreadMessagesRequestParams(A){if(!A||typeof A!=="object")return{options:void 0,threadID:void 0};let Q=A;return{options:Q.options,threadID:typeof Q.threadID==="string"?Q.threadID:void 0}}async handleOwnerUIRequest(A,Q){let $=new AbortController;this.pendingOwnerUIRequests.set(A.id,$);try{let B=await this.dispatchOwnerUIRequest(A,$.signal);if(this.pendingOwnerUIRequests.get(A.id)!==$)return;this.pendingOwnerUIRequests.delete(A.id),Q(O80(A.id,B))}catch(B){if(this.pendingOwnerUIRequests.get(A.id)!==$)return;this.pendingOwnerUIRequests.delete(A.id),Q(O80(A.id,void 0,B instanceof Error?B.message:String(B)))}}dispatchOwnerUIRequest(A,Q){switch(A.method){case"ui.input":return this.showInputDialog(A.params.options,Q);case"ui.confirm":return this.showConfirmDialog(A.params.options,Q);case"ui.select":return this.showSelectDialog(A.params.options,Q);default:throw Error(`Unknown owner UI request method: ${A.method}`)}}cancelOwnerUIRequest(A){let Q=this.pendingOwnerUIRequests.get(A);if(!Q)return;this.pendingOwnerUIRequests.delete(A),Q.abort()}cancelActorUIRequest(A){let Q=this.pendingActorUIRequests.get(A);if(!Q)return;this.pendingActorUIRequests.delete(A),Q.abort()}buildPluginUIRespondRequest(A,Q,$){this.pluginUIRespondRequestCounter+=1;let B={requestId:A};if($!==void 0)B.error=$;else if(Q!==void 0)B.result=Q;return{type:"request",id:`plugin-ui-respond-${A}-${this.pluginUIRespondRequestCounter}`,method:"plugin.ui.respond",params:B}}async handleActorUIRequest(A,Q){let $=new AbortController;this.pendingActorUIRequests.set(A.requestId,$);let B={type:"request",id:A.requestId,method:A.method,params:A.params};try{let E=await this.dispatchOwnerUIRequest(B,$.signal);if(this.pendingActorUIRequests.get(A.requestId)!==$)return;this.pendingActorUIRequests.delete(A.requestId),Q(this.buildPluginUIRespondRequest(A.requestId,E))}catch(E){if(this.pendingActorUIRequests.get(A.requestId)!==$)return;this.pendingActorUIRequests.delete(A.requestId),Q(this.buildPluginUIRespondRequest(A.requestId,void 0,E instanceof Error?E.message:String(E)))}}upsertActorUIState(A,Q){if(this.stateBackedRequestIDs.add(A.requestId),A.status!=="pending"){this.cancelActorUIRequest(A.requestId);return}if(this.pendingActorUIRequests.has(A.requestId))return;this.handleActorUIRequest(A,Q)}handlePluginUISnapshot(A,Q){let $=new Set(A.requests.map((B)=>B.requestId));for(let B of this.pendingActorUIRequests.keys())if(!$.has(B))this.cancelActorUIRequest(B);for(let B of this.stateBackedRequestIDs)if(!$.has(B))this.stateBackedRequestIDs.delete(B);for(let B of A.requests)this.upsertActorUIState(B,Q)}handlePluginUIRequestAdded(A,Q){this.upsertActorUIState(A.request,Q)}handlePluginUIRequestSettled(A,Q){this.upsertActorUIState(A.request,Q)}handlePluginUIRequestRemoved(A){this.cancelActorUIRequest(A.requestId),this.stateBackedRequestIDs.delete(A.requestId)}handlePluginUIStateEvent(A,Q){if(A.event==="plugin.ui.snapshot"){let $=VF4.safeParse(A.data);if($.success)this.handlePluginUISnapshot($.data,Q);return!0}if(A.event==="plugin.ui.request_added"){let $=KF4.safeParse(A.data);if($.success)this.handlePluginUIRequestAdded($.data,Q);return!0}if(A.event==="plugin.ui.request_settled"){let $=zF4.safeParse(A.data);if($.success)this.handlePluginUIRequestSettled($.data,Q);return!0}if(A.event==="plugin.ui.request_removed"){let $=WF4.safeParse(A.data);if($.success)this.handlePluginUIRequestRemoved($.data);return!0}return!1}clearPluginPlatformStatusHandlers(){let A=this.options.context.pluginPlatform;if(!A)return;if(A.readThreadMessagesHandler===this.readThreadMessages)A.readThreadMessagesHandler=null;if(A.readThreadTitleHandler===this.readThreadTitle)A.readThreadTitleHandler=null;if(A.subscribeThreadTitleHandler===this.subscribeThreadTitle)A.subscribeThreadTitleHandler=null;if(A.createStatusItemHandler===this.createStatusItem)A.createStatusItemHandler=null;if(A.updateStatusItemHandler===this.updateStatusItem)A.updateStatusItemHandler=null;if(A.removeStatusItemHandler===this.removeStatusItem)A.removeStatusItemHandler=null;if(A.runAgentHandler===this.options.runAgent)A.runAgentHandler=null}subscribePluginCommands(){let A=this.options.context.pluginService;if(!A)return;this.refreshPluginCommands(A.commands.list()),this.pluginCommandSubscriptions=[A.plugins.subscribe((Q)=>{this.removeInactivePluginStatusItems(Q),this.showNewPluginErrorToasts(Q),this.refreshPluginCommands(A.commands.list())}),A.commands.changed.subscribe(()=>{this.refreshPluginCommands(A.commands.list())})]}refreshPluginCommands(A){this.unregisterPluginCommands?.();let $=A.map((B)=>this.createPluginCommand(B)).map((B)=>this.options.commandRegistry.register(B));this.unregisterPluginCommands=()=>{for(let B of $)B()}}showNewPluginErrorToasts(A){let Q=new Set;for(let $ of A){if($.status!=="error")continue;if(jh($.errorMessage))continue;let B=`${$.uri.toString()}
|
|
2780
|
-
${$.errorMessage??""}`;if(Q.add(B),this.pluginErrorToastKeys.has(B))continue;this.options.toastController.show(this.formatPluginErrorToast($),"error",8000)}this.pluginErrorToastKeys=Q}removeInactivePluginStatusItems(A){let Q=new Set(A.filter((B)=>B.status==="active").map((B)=>B.uri.toString())),$=[];for(let[B,E]of this.statusItems){if(Q.has(E.pluginURI))continue;$.push(B)}if($.length===0)return;this.updateStatusItemState(()=>{for(let B of $)this.statusItems.delete(B)})}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.context.logFilePath}`}createPluginCommand(A){return{id:A.id,noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,status:A.availability,run:async(Q,$,B)=>{B();try{await this.options.context.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(E){S.error("Neo plugin command failed",{error:E,command:A}),this.options.toastController.show(E instanceof Error?E.message:String(E),"error",5000)}}}}showInputDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"input",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=iG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showConfirmDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(!1);return}let B={kind:"confirm",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=iG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showSelectDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"select",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=iG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};createStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let B=this.statusItemKey(A,Q),E={pluginURI:A,id:Q};if($!==void 0)E.value=$;this.statusItems.set(B,E)})};updateStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.set(this.statusItemKey(A,Q),{pluginURI:A,id:Q,value:$})})};removeStatusItem=(A,Q)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.delete(this.statusItemKey(A,Q))})};readThreadMessages=(A,Q)=>{let $=this.options.readThreadMessages;if(!$)return Promise.reject(Error("thread.messages is not available - no active thread"));return $(A,Q)};readThreadTitle=(A)=>{let Q=this.options.readThreadTitle;if(!Q)return Promise.reject(Error("thread.title is not available - no active thread"));return Q(A)};subscribeThreadTitle=(A,Q)=>{let $=this.options.subscribeThreadTitle;if(!$)throw Error("thread.title.subscribe is not available - no active thread");return $(A,Q)};updateStatusItemState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}statusItemKey(A,Q){return`${A}\x00${Q}`}cancelPendingDialogs(){let A=[];if(this.activeDialog)A.push(this.activeDialog);A.push(...this.queuedDialogs),this.activeDialog=null,this.queuedDialogs=[],this.resolvingDialog=null,this.emitBlockingConfirmDialogChange();for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.abortUnsubscribe(),A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}abortDialog(A){if(this.activeDialog===A){this.advanceDialog(),this.cancelDialog(A);return}let Q=this.queuedDialogs.indexOf(A);if(Q===-1)return;this.updateDialogState(()=>{this.queuedDialogs.splice(Q,1)}),this.cancelDialog(A)}enqueueDialog(A){if(this.activeDialog){if(this.queuedDialogs.push(A),this.resolvingDialog===this.activeDialog)this.advanceResolvingDialog(this.activeDialog);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A}),this.emitBlockingConfirmDialogChange()}resolveInputDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveConfirmDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveSelectDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveDialog(A,Q){if(this.activeDialog!==A||this.resolvingDialog===A)return;this.resolvingDialog=A,A.abortUnsubscribe(),Q(),this.scheduleResolvingDialogAdvance(A,fB6)}scheduleResolvingDialogAdvance(A,Q){cQ.instance.addPostFrameCallback(()=>{if(this.activeDialog!==A)return;if(this.queuedDialogs.length>0||Q<=1){this.advanceResolvingDialog(A);return}this.scheduleResolvingDialogAdvance(A,Q-1)},"PluginIntegration.advanceDialog")}advanceResolvingDialog(A){if(this.resolvingDialog===A)this.resolvingDialog=null;if(this.activeDialog!==A)return;this.advanceDialog()}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A();this.emitBlockingConfirmDialogChange()}emitBlockingConfirmDialogChange(){let A=this.hasBlockingConfirmDialog();if(A===this.blockingConfirmDialog)return;this.blockingConfirmDialog=A,this.options.onBlockingConfirmDialogChange?.(A)}}i0();import{spawnSync as hB6}from"node:child_process";import I9 from"node:process";var mN4={options:new Set(["settings-file","log-level","log-file","mcp-config"]),booleans:new Set(["color","dangerously-allow-all","ide","jetbrains","neo-orb","notifications"])};function Pl(A){let Q=A.getRelaunchThreadIDs();if(A.onRelaunchRequested?.(Q),A.stop)A.stop();else G1.instance.stop()}var gB6=O4("amp.relaunch",{noun:"amp",verb:"Relaunch (Quit & Reopen)",description:"Quit, reopen Amp, and resume active threads",keywords:["restart","update"],defaultKey:I9.env.NODE_ENV==="development"&&I9.platform==="darwin"?"meta+r":void 0,status:{type:"enabled"},sortBoost:90},(A,{dismiss:Q})=>{Q(),Pl(A)});function dN4(A){return gB6.bind(A)}function mB6(A,Q){let{command:$,args:B}=dB6(A),E=I9.execve,D=I9.platform==="win32"||!E,J=D?"spawnSync":"execve";if(S.info("Relaunching Amp; threads will be resumed",{threadIDs:A,relaunchMethod:J}),D){let U=hB6($,B,{cwd:Q,env:I9.env,stdio:"inherit"});if(U.error)return S.error("Failed to relaunch Amp",{error:U.error}),1;return U.status??1}try{if(I9.chdir(Q),$.includes("/"))return E($,[$,...B],I9.env);return E("/usr/bin/env",["env",$,...B],I9.env)}catch(U){return S.error("Failed to relaunch Amp",{error:U}),1}}class cg0{relaunchRequested=!1;requestedThreadIDs=[];request=(A)=>{S.info("Relaunch requested; threads will be resumed",{threadIDs:A}),this.relaunchRequested=!0,this.requestedThreadIDs=A};get shouldShowExitSummary(){return!this.relaunchRequested}relaunchIfRequested(A){if(!this.relaunchRequested)return;return mB6(this.requestedThreadIDs,A)}}function dB6(A){let Q=A.length>0?["threads","continue",...A]:[],$=cB6(I9.argv),B=lB6();if(B)return{command:B.command,args:[...B.args,...$,...Q]};let E=I9.argv[1],D=E&&pB6(E)?[E]:[];return{command:I9.execPath,args:[...D,...$,...Q]}}function cB6(A){let Q=[],$=A.slice(2);for(let B=0;B<$.length;B+=1){let E=$[B];if(!E?.startsWith("--"))continue;let[D,J]=E.split("=",2);if(!D)continue;let U=D.slice(2),Y=U.startsWith("no-")?U.slice(3):U;if(mN4.booleans.has(Y)){Q.push(E);continue}if(!mN4.options.has(U))continue;if(J!==void 0){Q.push(E);continue}let Z=$[B+1];if(Z===void 0||Z.startsWith("--"))continue;Q.push(E,Z),B+=1}return Q}function pB6(A){return A!==I9.execPath&&!A.startsWith("/$bunfs/")}function lB6(){if(I9.env.NODE_ENV!=="development")return null;let A=I9.env.AMP_DEV_RELAUNCH_COMMAND?.trim();if(!A)return null;let Q=iB6(A),$=Q[0];if(!$)return null;return{command:$,args:Q.slice(1)}}function iB6(A){if(A.startsWith("["))try{let Q=JSON.parse(A);if(Array.isArray(Q)&&Q.every(($)=>typeof $==="string"))return Q}catch{return[]}return A.split(/\s+/).filter(Boolean)}var nB6=48;class pg0{visible=!1;onClick=void 0;listeners=new Set;show(A){this.visible=!0,this.onClick=A,this.notifyListeners()}activate(){this.onClick?.()}get isVisible(){return this.visible}dismiss(){this.visible=!1,this.onClick=void 0,this.notifyListeners()}addListener(A){this.listeners.add(A)}removeListener(A){this.listeners.delete(A)}buildComplexToast(){if(!this.visible||!this.onClick)return null;return new Ol({width:nB6,title:"Relaunch to Update Amp",message:"Your threads will resume.",variant:"success",mouseBehavior:"click-anywhere",action:{keyboardShortcut:"Ctrl+O",command:"amp: relaunch",confirmShortcut:"Enter",label:"relaunch",onAction:()=>this.activate()}})}notifyListeners(){for(let A of this.listeners)A()}}import{readFile as sB6}from"node:fs/promises";import ig0 from"node:os";var aB6=["command","args","url","transport","_target"];function lg0(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}function oB6(A){if(typeof A!=="string")return A;let Q=A.indexOf("?");return Q===-1?A:A.slice(0,Q)}function rB6(A){if(!lg0(A))return A;let Q={};for(let[$,B]of Object.entries(A)){if(!lg0(B)){Q[$]=B;continue}let E={};for(let D of aB6){if(!(D in B))continue;E[D]=D==="url"?oB6(B[D]):B[D]}Q[$]=E}return Q}function cN4(A){let Q=PO(A,[],{allowTrailingComma:!0});if(!lg0(Q))return uP(A);let $={...Q};for(let B of Object.keys($))if(B==="mcpServers"||B==="amp.mcpServers")$[B]=rB6($[B]);return uP(JSON.stringify($,null,2))}F$();function tB6(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function pN4(A,Q,$=uP){try{return{path:Q,contents:$(await sB6(A,"utf8"))}}catch{return null}}async function L80(A,Q){let $=[],B=tB6(),E=await j4.getThread({thread:Q},{config:A.configService}),D=E.ok?E.result.thread.data:null;$.push({path:`${B}/thread.json`,contents:JSON.stringify(nD(D),null,2)});let J=await pN4(fP(Q),`${B}/logs/${Q}.log`);if(J)$.push(J);let U=await pN4(A.settingsFilePath,`${B}/settings/global.json`,cN4);if(U)$.push(U);let Y=await sY()??"unknown",Z=await j4.sendReport({threadID:Q,files:$,metadata:{clientVersion:"0.0.1780773165-gd9c390",clientOS:`${ig0.platform()} ${ig0.release()} ${ig0.arch()}`,installMethod:Y}},{config:A.configService});if(!Z.ok)throw Error(`Failed to submit report: ${Z.error.message}`);return Z.result.reportID}class ng0{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.backStack.pop();this.forwardStack.push(Q)}}}}var eB6=86400000;class ag0{options;subscription=null;relaunchNotificationShown=!1;relaunchNotificationPending=!1;relaunchNotificationTimer=null;openedAt=Date.now();constructor(A){this.options=A}init(){if(this.subscription=this.options.updateService?.state.subscribe((A)=>{this.handleUpdateState(A)})??null,process.env.DEV_SHOW_RELAUNCH_NOTIF_ON_STARTUP==="1")this.showUpdateRelaunchNotification(!0)}dispose(){if(this.subscription?.unsubscribe(),this.subscription=null,this.relaunchNotificationTimer)clearTimeout(this.relaunchNotificationTimer),this.relaunchNotificationTimer=null}handleUpdateState(A){if(A!=="updated")return;this.showUpdateRelaunchNotification()}showUpdateRelaunchNotification(A=!1){if(this.relaunchNotificationShown)return;let $=(this.options.minimumOpenDurationMs??eB6)-(Date.now()-this.openedAt);if($>0&&!A){if(this.relaunchNotificationPending=!0,!this.relaunchNotificationTimer)this.relaunchNotificationTimer=setTimeout(()=>{if(this.relaunchNotificationTimer=null,!this.relaunchNotificationPending)return;this.relaunchNotificationPending=!1,this.showUpdateRelaunchNotification()},$),this.relaunchNotificationTimer.unref();return}this.relaunchNotificationPending=!1,this.relaunchNotificationShown=!0,this.options.relaunchNotificationController.show(()=>Pl(this.options))}}class rg0 extends eA{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter((E)=>E.status.type!=="hidden"),$=Q36(Q),B="";return new E1({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:c0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new j5({items:Q,showBorder:!1,getLabel:(E)=>{let D=og0(E);return E.keywords&&E.keywords.length>0?`${D} ${E.keywords.join(" ").toLowerCase()}`:D},onQueryChange:(E)=>{B=E},sortItems:(E,D,J)=>{B=J;let U=J.trim().toLowerCase();if(U===""){let V=E.item.status.type==="disabled"?1:0,K=D.item.status.type==="disabled"?1:0;if(V!==K)return V-K;let z=E.item.sortBoost??0,W=D.item.sortBoost??0;if(z!==W)return W-z;let C=E.item.noun?.toLowerCase()??"",H=D.item.noun?.toLowerCase()??"";if(C!==H)return C<H?-1:1;return 0}let Y=lN4(E.item,U),Z=lN4(D.item,U);if(Y!==Z)return Y?-1:1;let F=uq(E.item.verb.toLowerCase(),J),X=uq(D.item.verb.toLowerCase(),J);if(F!==X)return X-F;let I=uq(og0(E.item),J),G=uq(og0(D.item),J);if(I!==G)return G-I;return D.score-E.score},isItemDisabled:(E)=>E.status.type==="disabled",buildDisabledReasonWidget:(E,D)=>{if(E.status.type!=="disabled")return;let{colors:J}=e0.of(D);return new D0({text:new g(E.status.reason,new A0({color:J.mutedForeground,dim:!0})),textAlign:"center",maxLines:1,overflow:"ellipsis"})},renderItem:(E,D,J,U)=>new iN4({command:E,shortcuts:j80(E,this.props.keymapShortcuts),isSelected:D,isDisabled:J,categoryWidth:$,query:B,buildContext:U}),onAccept:(E)=>{this.props.onAccept(E)},onDismiss:this.props.onDismiss})})}}class iN4 extends eA{props;constructor(A){super();this.props=A}build(A){let{command:Q,shortcuts:$,isSelected:B,isDisabled:E,categoryWidth:D,query:J,buildContext:U}=this.props,Y=e0.of(U),{colors:Z,app:F}=Y,X=B?F.selectionBackground:void 0,I=B?F.selectionForeground:Z.foreground,G=B?I:Z.mutedForeground,V=new D0({text:new g(Q.noun?.toLowerCase()??"",new A0({color:G,dim:E||!B})),textAlign:"right",maxLines:1,overflow:"ellipsis"}),K=Q.verb.toLowerCase();if(E)K+=" (unavailable)";let z=A36(Q,J);if(z)K+=` (alias: ${z})`;let W=new D0({text:new g(K,new A0({color:I,bold:!0,dim:E})),maxLines:1,overflow:"ellipsis"}),C=[{child:V,fixedWidth:D},{child:W,expanded:!0}];if($.length>0)C.push({child:$36($,Y,E)});return new nN4({columns:C,padding:c0.horizontal(1),backgroundColor:X})}}function og0(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function lN4(A,Q){return A.keywords?.some(($)=>$.trim().toLowerCase()===Q)??!1}function A36(A,Q){let $=Q.trim().toLowerCase();if($==="")return;return A.keywords?.find((B)=>B.trim().toLowerCase()===$)}function Q36(A){return A.reduce((Q,$)=>{return $.noun?Math.max(Q,RA($.noun)):Q},0)}function $36(A,Q,$){let{app:B}=Q,E=new A0({color:B.keybind,bold:!0,dim:$}),D=[];for(let J=0;J<A.length;J++){if(J>0)D.push(new g(", ",E));D.push(new g(aN(A[J]),E))}return D0.spans(D)}class nN4 extends eA{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:$=2,padding:B,backgroundColor:E}=this.props,D=[];for(let U=0;U<Q.length;U++){let Y=Q[U];if(U>0&&$>0)D.push(new y0({width:$}));if(Y.fixedWidth!==void 0)D.push(new y0({width:Y.fixedWidth,child:Y.child}));else if(Y.expanded)D.push(new P4({child:Y.child}));else D.push(Y.child)}let J=new OA({crossAxisAlignment:"start",children:D});if(!B&&!E)return J;return new GA({decoration:E?{color:E}:void 0,padding:B,child:J})}}class sg0{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#$(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#$()}}findByID(A){return this.#A.find((Q)=>Q.id===A)}runByID(A,Q,$=new Rq,B=()=>{}){let E=this.findByID(A);if(!E||E.status.type!=="enabled")return!1;return E.run($,Q,B),!0}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#$(){for(let A of this.#Q)A()}}class sB extends sQ{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=sB.maybeOf(A);if(!Q)throw Error("No CommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(sB)?.commandRegistry??null}}function j80(A,Q){let $=A.id?Q.get(A.id)??[]:[];if(!A.shortcut)return $;return new Set(Array.from(Q.values()).flatMap((E)=>E.map((D)=>ec(D).toString()))).has(A.shortcut.toString())?$:[...$,A.shortcut]}class tg0 extends d0{keymapShortcuts;onDismiss;constructor(A){super();this.keymapShortcuts=A.keymapShortcuts??new Map,this.onDismiss=A.onDismiss}createState(){return new aN4}}class aN4 extends m0{modalStack=new Rq;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=sB.of(this.context);this.commandRegistry=A,A.addListener(this.onCommandsChanged)})}dispose(){this.commandRegistry?.removeListener(this.onCommandsChanged),this.commandRegistry=null,super.dispose()}onCommandsChanged=()=>{this.setState()};build(A){let Q=sB.of(A).commands,$=new rg0({commands:Q,keymapShortcuts:this.widget.keymapShortcuts,onAccept:(B)=>{B.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new $l({root:$,controller:this.modalStack})}}var oN4=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Move cursor left/right",methods:[{keys:["←"]},{keys:["→"]},{input:"B",keys:["Ctrl"]},{input:"F",keys:["Ctrl"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!0},{description:"Insert newline",methods:[{keys:["Enter"]},{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!1},{description:"Submit message",methods:[{keys:["Enter"]}],submitOnEnterOnly:!0},{description:"Submit message",methods:[{keys:["Ctrl/Cmd","Enter"]}],submitOnEnterOnly:!1},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]},{keys:["Ctrl","←"]},{input:"B",keys:["Alt"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]},{keys:["Ctrl","→"]},{input:"F",keys:["Alt"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]},{input:"H",keys:["Ctrl"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]},{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]}]},{description:"Toggle reasoning effort",methods:[{input:"D",keys:["Alt"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]},{description:"Mention threads",methods:[{keys:["@@"]}]},{description:"Show prompt history",methods:[{input:"R",keys:["Ctrl"]}]},{description:"Toggle inline shortcuts help",methods:[{keys:["?"]}]},{description:"Toggle thinking/dense view",methods:[{input:"T",keys:["Alt"]}]}],rN4=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Half-page scroll",methods:[{input:"K",keys:["Alt"]},{input:"J",keys:["Alt"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class R80 extends eA{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let $=X4.of(A).size.width<50,B=[];for(let E of this.items){let[D,J]=this.renderRow(E),U;if($)U=new UA({crossAxisAlignment:"start",mainAxisSize:"min",children:[D,new mA({padding:c0.only({left:4}),child:J})]});else U=new OA({crossAxisAlignment:"start",children:[new P4({flex:1,child:D}),new y0({width:1}),new P4({flex:1,child:J})]});B.push(new mA({padding:c0.horizontal(6),child:U}))}return new UA({crossAxisAlignment:"start",mainAxisSize:"min",children:B})}}function sN4(A){let Q=[...A.keys];if(A.input)Q.push(A.input);return RX(Q.join("+"))}function P80(A){return A.replaceAll("Opt","Alt").replaceAll("Cmd","Meta").replaceAll("←","ArrowLeft").replaceAll("→","ArrowRight").replaceAll("↑","ArrowUp").replaceAll("↓","ArrowDown").replaceAll("Pg Up","PageUp").replaceAll("Pg Down","PageDown")}function B36(A){let Q=sN4(A);return Q.includes("Ctrl/Cmd")?[P80(Q.replace("Ctrl/Cmd","Ctrl")),P80(Q.replace("Ctrl/Cmd","Cmd"))]:[P80(Q)]}class eg0 extends eA{commands;keymapShortcuts;onDismiss;constructor(A){super();this.commands=A.commands,this.keymapShortcuts=A.keymapShortcuts,this.onDismiss=A.onDismiss}build(A){let Q=e0.of(A),{colors:$,app:B}=Q,E=X4.of(A),D=new A0({color:$.secondary,bold:!0}),J=new A0({color:B.keybind}),U=new A0({color:B.command}),Y=new A0({color:$.foreground}),Z=Math.max(40,Math.min(80,E.size.width-4)),X=[...this.commands.filter((z)=>{let W=z.noun?.toLowerCase();return W!=="dev"&&W!=="debug"&&z.status.type!=="hidden"})].sort((z,W)=>{let C=(z.noun??"").toLowerCase(),H=(W.noun??"").toLowerCase(),N=C.localeCompare(H);if(N!==0)return N;return z.verb.toLowerCase().localeCompare(W.verb.toLowerCase())}),I=(z)=>{let W=z.methods.map((C)=>sN4(C)).join(", ");return[new D0({text:new g(W,J)}),new D0({text:new g(z.description,Y)})]},G=new Set(Array.from(this.keymapShortcuts.values()).flatMap((z)=>z.map((W)=>P80(aN(ec(W)))))),V=(z)=>z.flatMap((W)=>{let C=W.methods.filter((H)=>B36(H).every((N)=>!G.has(N)));return C.length>0?[{...W,methods:C}]:[]}),K=new vB({autofocus:!0,child:new GA({constraints:new A4(Z,Z,0,Number.POSITIVE_INFINITY),child:new UA({crossAxisAlignment:"start",mainAxisSize:"min",children:[new mA({padding:c0.horizontal(2),child:new D0({text:new g(`Editor Shortcuts
|
|
2780
|
+
${$.errorMessage??""}`;if(Q.add(B),this.pluginErrorToastKeys.has(B))continue;this.options.toastController.show(this.formatPluginErrorToast($),"error",8000)}this.pluginErrorToastKeys=Q}removeInactivePluginStatusItems(A){let Q=new Set(A.filter((B)=>B.status==="active").map((B)=>B.uri.toString())),$=[];for(let[B,E]of this.statusItems){if(Q.has(E.pluginURI))continue;$.push(B)}if($.length===0)return;this.updateStatusItemState(()=>{for(let B of $)this.statusItems.delete(B)})}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.context.logFilePath}`}createPluginCommand(A){return{id:A.id,noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,status:A.availability,run:async(Q,$,B)=>{B();try{await this.options.context.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(E){S.error("Neo plugin command failed",{error:E,command:A}),this.options.toastController.show(E instanceof Error?E.message:String(E),"error",5000)}}}}showInputDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"input",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=iG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showConfirmDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(!1);return}let B={kind:"confirm",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=iG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showSelectDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"select",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=iG(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};createStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let B=this.statusItemKey(A,Q),E={pluginURI:A,id:Q};if($!==void 0)E.value=$;this.statusItems.set(B,E)})};updateStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.set(this.statusItemKey(A,Q),{pluginURI:A,id:Q,value:$})})};removeStatusItem=(A,Q)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.delete(this.statusItemKey(A,Q))})};readThreadMessages=(A,Q)=>{let $=this.options.readThreadMessages;if(!$)return Promise.reject(Error("thread.messages is not available - no active thread"));return $(A,Q)};readThreadTitle=(A)=>{let Q=this.options.readThreadTitle;if(!Q)return Promise.reject(Error("thread.title is not available - no active thread"));return Q(A)};subscribeThreadTitle=(A,Q)=>{let $=this.options.subscribeThreadTitle;if(!$)throw Error("thread.title.subscribe is not available - no active thread");return $(A,Q)};updateStatusItemState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}statusItemKey(A,Q){return`${A}\x00${Q}`}cancelPendingDialogs(){let A=[];if(this.activeDialog)A.push(this.activeDialog);A.push(...this.queuedDialogs),this.activeDialog=null,this.queuedDialogs=[],this.resolvingDialog=null,this.emitBlockingConfirmDialogChange();for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.abortUnsubscribe(),A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}abortDialog(A){if(this.activeDialog===A){this.advanceDialog(),this.cancelDialog(A);return}let Q=this.queuedDialogs.indexOf(A);if(Q===-1)return;this.updateDialogState(()=>{this.queuedDialogs.splice(Q,1)}),this.cancelDialog(A)}enqueueDialog(A){if(this.activeDialog){if(this.queuedDialogs.push(A),this.resolvingDialog===this.activeDialog)this.advanceResolvingDialog(this.activeDialog);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A}),this.emitBlockingConfirmDialogChange()}resolveInputDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveConfirmDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveSelectDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveDialog(A,Q){if(this.activeDialog!==A||this.resolvingDialog===A)return;this.resolvingDialog=A,A.abortUnsubscribe(),Q(),this.scheduleResolvingDialogAdvance(A,fB6)}scheduleResolvingDialogAdvance(A,Q){cQ.instance.addPostFrameCallback(()=>{if(this.activeDialog!==A)return;if(this.queuedDialogs.length>0||Q<=1){this.advanceResolvingDialog(A);return}this.scheduleResolvingDialogAdvance(A,Q-1)},"PluginIntegration.advanceDialog")}advanceResolvingDialog(A){if(this.resolvingDialog===A)this.resolvingDialog=null;if(this.activeDialog!==A)return;this.advanceDialog()}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A();this.emitBlockingConfirmDialogChange()}emitBlockingConfirmDialogChange(){let A=this.hasBlockingConfirmDialog();if(A===this.blockingConfirmDialog)return;this.blockingConfirmDialog=A,this.options.onBlockingConfirmDialogChange?.(A)}}i0();import{spawnSync as hB6}from"node:child_process";import I9 from"node:process";var mN4={options:new Set(["settings-file","log-level","log-file","mcp-config"]),booleans:new Set(["color","dangerously-allow-all","ide","jetbrains","neo-orb","notifications"])};function Pl(A){let Q=A.getRelaunchThreadIDs();if(A.onRelaunchRequested?.(Q),A.stop)A.stop();else G1.instance.stop()}var gB6=O4("amp.relaunch",{noun:"amp",verb:"Relaunch (Quit & Reopen)",description:"Quit, reopen Amp, and resume active threads",keywords:["restart","update"],defaultKey:I9.env.NODE_ENV==="development"&&I9.platform==="darwin"?"meta+r":void 0,status:{type:"enabled"},sortBoost:90},(A,{dismiss:Q})=>{Q(),Pl(A)});function dN4(A){return gB6.bind(A)}function mB6(A,Q){let{command:$,args:B}=dB6(A),E=I9.execve,D=I9.platform==="win32"||!E,J=D?"spawnSync":"execve";if(S.info("Relaunching Amp; threads will be resumed",{threadIDs:A,relaunchMethod:J}),D){let U=hB6($,B,{cwd:Q,env:I9.env,stdio:"inherit"});if(U.error)return S.error("Failed to relaunch Amp",{error:U.error}),1;return U.status??1}try{if(I9.chdir(Q),$.includes("/"))return E($,[$,...B],I9.env);return E("/usr/bin/env",["env",$,...B],I9.env)}catch(U){return S.error("Failed to relaunch Amp",{error:U}),1}}class cg0{relaunchRequested=!1;requestedThreadIDs=[];request=(A)=>{S.info("Relaunch requested; threads will be resumed",{threadIDs:A}),this.relaunchRequested=!0,this.requestedThreadIDs=A};get shouldShowExitSummary(){return!this.relaunchRequested}relaunchIfRequested(A){if(!this.relaunchRequested)return;return mB6(this.requestedThreadIDs,A)}}function dB6(A){let Q=A.length>0?["threads","continue",...A]:[],$=cB6(I9.argv),B=lB6();if(B)return{command:B.command,args:[...B.args,...$,...Q]};let E=I9.argv[1],D=E&&pB6(E)?[E]:[];return{command:I9.execPath,args:[...D,...$,...Q]}}function cB6(A){let Q=[],$=A.slice(2);for(let B=0;B<$.length;B+=1){let E=$[B];if(!E?.startsWith("--"))continue;let[D,J]=E.split("=",2);if(!D)continue;let U=D.slice(2),Y=U.startsWith("no-")?U.slice(3):U;if(mN4.booleans.has(Y)){Q.push(E);continue}if(!mN4.options.has(U))continue;if(J!==void 0){Q.push(E);continue}let Z=$[B+1];if(Z===void 0||Z.startsWith("--"))continue;Q.push(E,Z),B+=1}return Q}function pB6(A){return A!==I9.execPath&&!A.startsWith("/$bunfs/")}function lB6(){if(I9.env.NODE_ENV!=="development")return null;let A=I9.env.AMP_DEV_RELAUNCH_COMMAND?.trim();if(!A)return null;let Q=iB6(A),$=Q[0];if(!$)return null;return{command:$,args:Q.slice(1)}}function iB6(A){if(A.startsWith("["))try{let Q=JSON.parse(A);if(Array.isArray(Q)&&Q.every(($)=>typeof $==="string"))return Q}catch{return[]}return A.split(/\s+/).filter(Boolean)}var nB6=48;class pg0{visible=!1;onClick=void 0;listeners=new Set;show(A){this.visible=!0,this.onClick=A,this.notifyListeners()}activate(){this.onClick?.()}get isVisible(){return this.visible}dismiss(){this.visible=!1,this.onClick=void 0,this.notifyListeners()}addListener(A){this.listeners.add(A)}removeListener(A){this.listeners.delete(A)}buildComplexToast(){if(!this.visible||!this.onClick)return null;return new Ol({width:nB6,title:"Relaunch to Update Amp",message:"Your threads will resume.",variant:"success",mouseBehavior:"click-anywhere",action:{keymapKey:"Ctrl+O",command:"amp: relaunch",confirmShortcut:"Enter",label:"relaunch",onAction:()=>this.activate()}})}notifyListeners(){for(let A of this.listeners)A()}}import{readFile as sB6}from"node:fs/promises";import ig0 from"node:os";var aB6=["command","args","url","transport","_target"];function lg0(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}function oB6(A){if(typeof A!=="string")return A;let Q=A.indexOf("?");return Q===-1?A:A.slice(0,Q)}function rB6(A){if(!lg0(A))return A;let Q={};for(let[$,B]of Object.entries(A)){if(!lg0(B)){Q[$]=B;continue}let E={};for(let D of aB6){if(!(D in B))continue;E[D]=D==="url"?oB6(B[D]):B[D]}Q[$]=E}return Q}function cN4(A){let Q=PO(A,[],{allowTrailingComma:!0});if(!lg0(Q))return uP(A);let $={...Q};for(let B of Object.keys($))if(B==="mcpServers"||B==="amp.mcpServers")$[B]=rB6($[B]);return uP(JSON.stringify($,null,2))}F$();function tB6(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function pN4(A,Q,$=uP){try{return{path:Q,contents:$(await sB6(A,"utf8"))}}catch{return null}}async function L80(A,Q){let $=[],B=tB6(),E=await j4.getThread({thread:Q},{config:A.configService}),D=E.ok?E.result.thread.data:null;$.push({path:`${B}/thread.json`,contents:JSON.stringify(nD(D),null,2)});let J=await pN4(fP(Q),`${B}/logs/${Q}.log`);if(J)$.push(J);let U=await pN4(A.settingsFilePath,`${B}/settings/global.json`,cN4);if(U)$.push(U);let Y=await sY()??"unknown",Z=await j4.sendReport({threadID:Q,files:$,metadata:{clientVersion:"0.0.1780774659-gd08a06",clientOS:`${ig0.platform()} ${ig0.release()} ${ig0.arch()}`,installMethod:Y}},{config:A.configService});if(!Z.ok)throw Error(`Failed to submit report: ${Z.error.message}`);return Z.result.reportID}class ng0{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.backStack.pop();this.forwardStack.push(Q)}}}}var eB6=86400000;class ag0{options;subscription=null;relaunchNotificationShown=!1;relaunchNotificationPending=!1;relaunchNotificationTimer=null;openedAt=Date.now();constructor(A){this.options=A}init(){if(this.subscription=this.options.updateService?.state.subscribe((A)=>{this.handleUpdateState(A)})??null,process.env.DEV_SHOW_RELAUNCH_NOTIF_ON_STARTUP==="1")this.showUpdateRelaunchNotification(!0)}dispose(){if(this.subscription?.unsubscribe(),this.subscription=null,this.relaunchNotificationTimer)clearTimeout(this.relaunchNotificationTimer),this.relaunchNotificationTimer=null}handleUpdateState(A){if(A!=="updated")return;this.showUpdateRelaunchNotification()}showUpdateRelaunchNotification(A=!1){if(this.relaunchNotificationShown)return;let $=(this.options.minimumOpenDurationMs??eB6)-(Date.now()-this.openedAt);if($>0&&!A){if(this.relaunchNotificationPending=!0,!this.relaunchNotificationTimer)this.relaunchNotificationTimer=setTimeout(()=>{if(this.relaunchNotificationTimer=null,!this.relaunchNotificationPending)return;this.relaunchNotificationPending=!1,this.showUpdateRelaunchNotification()},$),this.relaunchNotificationTimer.unref();return}this.relaunchNotificationPending=!1,this.relaunchNotificationShown=!0,this.options.relaunchNotificationController.show(()=>Pl(this.options))}}class rg0 extends eA{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter((E)=>E.status.type!=="hidden"),$=Q36(Q),B="";return new E1({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:c0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new j5({items:Q,showBorder:!1,getLabel:(E)=>{let D=og0(E);return E.keywords&&E.keywords.length>0?`${D} ${E.keywords.join(" ").toLowerCase()}`:D},onQueryChange:(E)=>{B=E},sortItems:(E,D,J)=>{B=J;let U=J.trim().toLowerCase();if(U===""){let V=E.item.status.type==="disabled"?1:0,K=D.item.status.type==="disabled"?1:0;if(V!==K)return V-K;let z=E.item.sortBoost??0,W=D.item.sortBoost??0;if(z!==W)return W-z;let C=E.item.noun?.toLowerCase()??"",H=D.item.noun?.toLowerCase()??"";if(C!==H)return C<H?-1:1;return 0}let Y=lN4(E.item,U),Z=lN4(D.item,U);if(Y!==Z)return Y?-1:1;let F=uq(E.item.verb.toLowerCase(),J),X=uq(D.item.verb.toLowerCase(),J);if(F!==X)return X-F;let I=uq(og0(E.item),J),G=uq(og0(D.item),J);if(I!==G)return G-I;return D.score-E.score},isItemDisabled:(E)=>E.status.type==="disabled",buildDisabledReasonWidget:(E,D)=>{if(E.status.type!=="disabled")return;let{colors:J}=e0.of(D);return new D0({text:new g(E.status.reason,new A0({color:J.mutedForeground,dim:!0})),textAlign:"center",maxLines:1,overflow:"ellipsis"})},renderItem:(E,D,J,U)=>new iN4({command:E,shortcuts:j80(E,this.props.keymapShortcuts),isSelected:D,isDisabled:J,categoryWidth:$,query:B,buildContext:U}),onAccept:(E)=>{this.props.onAccept(E)},onDismiss:this.props.onDismiss})})}}class iN4 extends eA{props;constructor(A){super();this.props=A}build(A){let{command:Q,shortcuts:$,isSelected:B,isDisabled:E,categoryWidth:D,query:J,buildContext:U}=this.props,Y=e0.of(U),{colors:Z,app:F}=Y,X=B?F.selectionBackground:void 0,I=B?F.selectionForeground:Z.foreground,G=B?I:Z.mutedForeground,V=new D0({text:new g(Q.noun?.toLowerCase()??"",new A0({color:G,dim:E||!B})),textAlign:"right",maxLines:1,overflow:"ellipsis"}),K=Q.verb.toLowerCase();if(E)K+=" (unavailable)";let z=A36(Q,J);if(z)K+=` (alias: ${z})`;let W=new D0({text:new g(K,new A0({color:I,bold:!0,dim:E})),maxLines:1,overflow:"ellipsis"}),C=[{child:V,fixedWidth:D},{child:W,expanded:!0}];if($.length>0)C.push({child:$36($,Y,E)});return new nN4({columns:C,padding:c0.horizontal(1),backgroundColor:X})}}function og0(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function lN4(A,Q){return A.keywords?.some(($)=>$.trim().toLowerCase()===Q)??!1}function A36(A,Q){let $=Q.trim().toLowerCase();if($==="")return;return A.keywords?.find((B)=>B.trim().toLowerCase()===$)}function Q36(A){return A.reduce((Q,$)=>{return $.noun?Math.max(Q,RA($.noun)):Q},0)}function $36(A,Q,$){let{app:B}=Q,E=new A0({color:B.keybind,bold:!0,dim:$}),D=[];for(let J=0;J<A.length;J++){if(J>0)D.push(new g(", ",E));D.push(new g(aN(A[J]),E))}return D0.spans(D)}class nN4 extends eA{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:$=2,padding:B,backgroundColor:E}=this.props,D=[];for(let U=0;U<Q.length;U++){let Y=Q[U];if(U>0&&$>0)D.push(new y0({width:$}));if(Y.fixedWidth!==void 0)D.push(new y0({width:Y.fixedWidth,child:Y.child}));else if(Y.expanded)D.push(new P4({child:Y.child}));else D.push(Y.child)}let J=new OA({crossAxisAlignment:"start",children:D});if(!B&&!E)return J;return new GA({decoration:E?{color:E}:void 0,padding:B,child:J})}}class sg0{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#$(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#$()}}findByID(A){return this.#A.find((Q)=>Q.id===A)}runByID(A,Q,$=new Rq,B=()=>{}){let E=this.findByID(A);if(!E||E.status.type!=="enabled")return!1;return E.run($,Q,B),!0}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#$(){for(let A of this.#Q)A()}}class sB extends sQ{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=sB.maybeOf(A);if(!Q)throw Error("No CommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(sB)?.commandRegistry??null}}function j80(A,Q){let $=A.id?Q.get(A.id)??[]:[];if(!A.shortcut)return $;return new Set(Array.from(Q.values()).flatMap((E)=>E.map((D)=>ec(D).toString()))).has(A.shortcut.toString())?$:[...$,A.shortcut]}class tg0 extends d0{keymapShortcuts;onDismiss;constructor(A){super();this.keymapShortcuts=A.keymapShortcuts??new Map,this.onDismiss=A.onDismiss}createState(){return new aN4}}class aN4 extends m0{modalStack=new Rq;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=sB.of(this.context);this.commandRegistry=A,A.addListener(this.onCommandsChanged)})}dispose(){this.commandRegistry?.removeListener(this.onCommandsChanged),this.commandRegistry=null,super.dispose()}onCommandsChanged=()=>{this.setState()};build(A){let Q=sB.of(A).commands,$=new rg0({commands:Q,keymapShortcuts:this.widget.keymapShortcuts,onAccept:(B)=>{B.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new $l({root:$,controller:this.modalStack})}}var oN4=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Move cursor left/right",methods:[{keys:["←"]},{keys:["→"]},{input:"B",keys:["Ctrl"]},{input:"F",keys:["Ctrl"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!0},{description:"Insert newline",methods:[{keys:["Enter"]},{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!1},{description:"Submit message",methods:[{keys:["Enter"]}],submitOnEnterOnly:!0},{description:"Submit message",methods:[{keys:["Ctrl/Cmd","Enter"]}],submitOnEnterOnly:!1},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]},{keys:["Ctrl","←"]},{input:"B",keys:["Alt"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]},{keys:["Ctrl","→"]},{input:"F",keys:["Alt"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]},{input:"H",keys:["Ctrl"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]},{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]}]},{description:"Toggle reasoning effort",methods:[{input:"D",keys:["Alt"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]},{description:"Mention threads",methods:[{keys:["@@"]}]},{description:"Show prompt history",methods:[{input:"R",keys:["Ctrl"]}]},{description:"Toggle inline shortcuts help",methods:[{keys:["?"]}]},{description:"Toggle thinking/dense view",methods:[{input:"T",keys:["Alt"]}]}],rN4=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Half-page scroll",methods:[{input:"K",keys:["Alt"]},{input:"J",keys:["Alt"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class R80 extends eA{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let $=X4.of(A).size.width<50,B=[];for(let E of this.items){let[D,J]=this.renderRow(E),U;if($)U=new UA({crossAxisAlignment:"start",mainAxisSize:"min",children:[D,new mA({padding:c0.only({left:4}),child:J})]});else U=new OA({crossAxisAlignment:"start",children:[new P4({flex:1,child:D}),new y0({width:1}),new P4({flex:1,child:J})]});B.push(new mA({padding:c0.horizontal(6),child:U}))}return new UA({crossAxisAlignment:"start",mainAxisSize:"min",children:B})}}function sN4(A){let Q=[...A.keys];if(A.input)Q.push(A.input);return RX(Q.join("+"))}function P80(A){return A.replaceAll("Opt","Alt").replaceAll("Cmd","Meta").replaceAll("←","ArrowLeft").replaceAll("→","ArrowRight").replaceAll("↑","ArrowUp").replaceAll("↓","ArrowDown").replaceAll("Pg Up","PageUp").replaceAll("Pg Down","PageDown")}function B36(A){let Q=sN4(A);return Q.includes("Ctrl/Cmd")?[P80(Q.replace("Ctrl/Cmd","Ctrl")),P80(Q.replace("Ctrl/Cmd","Cmd"))]:[P80(Q)]}class eg0 extends eA{commands;keymapShortcuts;onDismiss;constructor(A){super();this.commands=A.commands,this.keymapShortcuts=A.keymapShortcuts,this.onDismiss=A.onDismiss}build(A){let Q=e0.of(A),{colors:$,app:B}=Q,E=X4.of(A),D=new A0({color:$.secondary,bold:!0}),J=new A0({color:B.keybind}),U=new A0({color:B.command}),Y=new A0({color:$.foreground}),Z=Math.max(40,Math.min(80,E.size.width-4)),X=[...this.commands.filter((z)=>{let W=z.noun?.toLowerCase();return W!=="dev"&&W!=="debug"&&z.status.type!=="hidden"})].sort((z,W)=>{let C=(z.noun??"").toLowerCase(),H=(W.noun??"").toLowerCase(),N=C.localeCompare(H);if(N!==0)return N;return z.verb.toLowerCase().localeCompare(W.verb.toLowerCase())}),I=(z)=>{let W=z.methods.map((C)=>sN4(C)).join(", ");return[new D0({text:new g(W,J)}),new D0({text:new g(z.description,Y)})]},G=new Set(Array.from(this.keymapShortcuts.values()).flatMap((z)=>z.map((W)=>P80(aN(ec(W)))))),V=(z)=>z.flatMap((W)=>{let C=W.methods.filter((H)=>B36(H).every((N)=>!G.has(N)));return C.length>0?[{...W,methods:C}]:[]}),K=new vB({autofocus:!0,child:new GA({constraints:new A4(Z,Z,0,Number.POSITIVE_INFINITY),child:new UA({crossAxisAlignment:"start",mainAxisSize:"min",children:[new mA({padding:c0.horizontal(2),child:new D0({text:new g(`Editor Shortcuts
|
|
2781
2781
|
`,D)})}),new R80({items:V(oN4).filter((z)=>z.submitOnEnterOnly===void 0||z.submitOnEnterOnly===!0),renderRow:I}),new y0({height:1}),new mA({padding:c0.horizontal(2),child:new D0({text:new g(`Scrolling & Navigation
|
|
2782
2782
|
`,D)})}),new R80({items:V(rN4),renderRow:I}),new y0({height:1}),new mA({padding:c0.horizontal(2),child:new D0({text:new g(`Command Palette Commands
|
|
2783
|
-
`,D)})}),new R80({items:X,renderRow:(z)=>{let W=z.noun?`${z.noun}: ${z.verb}`:z.verb,H=j80(z,this.keymapShortcuts).map(aN).join(", ");return[new D0({text:H?new g("",void 0,[new g(W,U),new g(` ${H}`,J)]):new g(W,U)}),new D0({text:new g(z.description,Y)})]}}),new y0({height:1})]})})});return new E1({header:"Amp CLI — Help &
|
|
2783
|
+
`,D)})}),new R80({items:X,renderRow:(z)=>{let W=z.noun?`${z.noun}: ${z.verb}`:z.verb,H=j80(z,this.keymapShortcuts).map(aN).join(", ");return[new D0({text:H?new g("",void 0,[new g(W,U),new g(` ${H}`,J)]):new g(W,U)}),new D0({text:new g(z.description,Y)})]}}),new y0({height:1})]})})});return new E1({header:"Amp CLI — Help & Keymap",minWidth:Z,maxWidth:Z,maxHeight:E.size.height,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["↑↓","j/k"],label:"scroll"}],onDismiss:this.onDismiss,child:K})}}class zT extends sQ{completionBuilder;constructor({completionBuilder:A,child:Q}){super({child:Q});this.completionBuilder=A}updateShouldNotify(A){return!1}static of(A){let Q=A.dependOnInheritedWidgetOfExactType(zT);if(!Q)throw Error("No CompletionBuilderProvider found in widget tree");return Q.completionBuilder}}var E36=250,D36=2000;class Am0 extends d0{configReloadEvents;toastController;child;constructor(A){super();this.configReloadEvents=A.configReloadEvents,this.toastController=A.toastController,this.child=A.child}createState(){return new tN4}}class tN4 extends m0{subscription=null;toastTimer=null;pendingToastType=null;lastToast=null;initState(){this.subscribeToConfigReloadEvents()}didUpdateWidget(A){if(A.configReloadEvents===this.widget.configReloadEvents)return;this.clearPendingToast(),this.subscribeToConfigReloadEvents()}dispose(){this.subscription?.unsubscribe(),this.subscription=null,this.clearPendingToast(),super.dispose()}build(A){return this.widget.child}subscribeToConfigReloadEvents(){this.subscription?.unsubscribe(),this.subscription=this.widget.configReloadEvents.subscribe((A)=>{this.scheduleToast(A)})}scheduleToast(A){if(this.pendingToastType=J36(this.pendingToastType,A),this.toastTimer)clearTimeout(this.toastTimer);this.toastTimer=setTimeout(()=>{if(!this.mounted)return;this.flushToast()},E36),this.toastTimer.unref()}flushToast(){let A=this.pendingToastType;if(this.clearPendingToast(),!A)return;let Q=Date.now();if(U36(this.lastToast,A,Q))return;this.lastToast={type:A,shownAt:Q},Y36(this.widget.toastController,A)}clearPendingToast(){if(this.toastTimer)clearTimeout(this.toastTimer),this.toastTimer=null;this.pendingToastType=null}}function J36(A,Q){return A==="failed"||Q.type==="failed"?"failed":"succeeded"}function U36(A,Q,$){return A?.type===Q&&$-A.shownAt<D36}function Y36(A,Q){switch(Q){case"succeeded":A.show("Config reloaded","success",1500);break;case"failed":A.show("Config reload failed","error",5000);break}}class MQ extends sQ{context;constructor({context:A,child:Q}){super({child:Q});this.context=A}updateShouldNotify(A){return!1}static of(A){let Q=A.dependOnInheritedWidgetOfExactType(MQ);if(!Q)throw Error("No ContextProvider found in widget tree");return Q.context}}i0();f8();var v80=80,Z36=15,F36=1,eN4=-v80,X36=16,I36=Ub0(v80,v80);function Aq4({ampURL:A,threadID:Q,logPath:$}){return[`Debug thread ${hG(new URL(A),Q).toString()} (cli log: ${$}). Start with the CLI log, actor logs, and Rivet DB/inspector as sources of truth. Read thread-actors/docs/debugging-actors.md and thread-actors/scripts/README.md. For dev, actor logs are in .amp/in/thread-actors.json.log; for staging/prod, logs are in gcloud.`,"","Problem: "].join(`
|
|
2784
2784
|
`)}function Qq4({getActiveThreadID:A,context:Q,toastController:$,startNewDraftThread:B,sendFeedbackReport:E}){let D=(Z,F,X)=>{$.show(Z,F,X)},J=new cA(()=>{let Z=A();if(!Z)return D("No active thread","error",2000),"handled";let F=fP(Z);return G1.instance.tuiInstance.clipboard.writeText(F).then(()=>{D("Copied log path to clipboard","success",2000)}).catch((X)=>{S.error("Failed to copy thread log path",{error:X,threadID:Z,logPath:F}),D("Failed to copy log path","error",2000)}),"handled"}),U=new cA(()=>{if(!Q.isInternalUser)return"ignored";let Z=A();if(!Z)return"handled";try{B({prompt:Aq4({ampURL:Q.ampURL,threadID:Z,logPath:fP(Z)}),hideDebugOverlay:!0})}catch(F){S.error("Failed to prepare thread issue investigation",{error:F,threadID:Z})}return"handled"}),Y=new cA(()=>{let Z=A();if(!Z)return D("No active thread","error",2000),"handled";return D("Sending report...","success",2000),E(Z).then(async(F)=>{try{await G1.instance.tuiInstance.clipboard.writeText(F),D("Sent report and copied report ID","success",3000)}catch(X){S.warn("Failed to copy report ID to clipboard",{error:X,reportID:F}),D(`Sent report ${F}`,"success",3000)}}).catch((F)=>{S.error("Failed to send report from debug overlay",{error:F,threadID:Z}),D("Failed to send report","error",3000)}),"handled"});return[[v70,J],[S70,U],[k70,Y]]}class Qm0 extends d0{top;visible;pid;activeThreadID;observerSnapshot$;constructor(A){super();this.top=A.top,this.visible=A.visible,this.pid=A.pid,this.activeThreadID=A.activeThreadID,this.observerSnapshot$=A.observerSnapshot$}createState(){return new $q4}}class $q4 extends m0{observerSnapshot=new p3(this,null);animationProgress=1;animationFrom=1;animationTo=1;animationStartTime=0;animationTimer=null;initState(){super.initState(),this.animationProgress=this.widget.visible?1:0,this.animationFrom=this.animationProgress,this.animationTo=this.animationProgress,this.subscribeObserverSnapshot(this.widget.observerSnapshot$)}didUpdateWidget(A){if(super.didUpdateWidget(A),A.observerSnapshot$!==this.widget.observerSnapshot$)this.subscribeObserverSnapshot(this.widget.observerSnapshot$);if(A.visible!==this.widget.visible)this.animateTo(this.widget.visible?1:0)}dispose(){this.stopAnimation(),super.dispose()}build(A){let Q=e0.of(A),$=G36(Q),B=U1.all(new Y1(Q.app.command,1,"rounded")),E=Math.round(eN4+(F36-eN4)*this.animationProgress);return new m1({top:this.widget.top,right:E,width:v80,height:Z36,child:new GA({decoration:new v1(Q.colors.background,B),child:new mA({padding:c0.only({left:2,right:1}),child:new UA({crossAxisAlignment:"stretch",children:[OA.spaceBetween([new D0({text:new g("Debug",$.heading)}),new OA({children:[new D0({text:new g("alt+i toggle ",$.meta)}),new iA({cursor:"pointer",onClick:()=>{N4.invoke(A,new v70)},child:new D0({text:new g("[copy log]",$.button)})}),new D0({text:new g(" ",$.meta)}),new iA({cursor:"pointer",onClick:()=>{N4.invoke(A,new k70)},child:new D0({text:new g("[send report]",$.button)})}),new D0({text:new g(" ",$.meta)}),new iA({cursor:"pointer",onClick:()=>{N4.invoke(A,new S70)},child:new D0({text:new g("[investigate]",$.button)})})]})]),new y0({height:1}),...V36({context:A,activeThreadID:this.widget.activeThreadID,snapshot:this.observerSnapshot.getValue(),pid:this.widget.pid,styles:$})]})})})})}subscribeObserverSnapshot(A){if(!A){this.observerSnapshot.dispose(null);return}this.observerSnapshot.subscribe(A)}animateTo(A){if(this.stopAnimation(),this.animationProgress===A)return;this.animationFrom=this.animationProgress,this.animationTo=A,this.animationStartTime=Date.now(),this.animationTimer=setInterval(()=>{let Q=Date.now()-this.animationStartTime,$=Math.min(Q/g50,1),B=I36($);if(this.mounted)this.setState(()=>{this.animationProgress=this.animationFrom+(this.animationTo-this.animationFrom)*B});if($>=1)this.stopAnimation()},X36),this.animationTimer.unref()}stopAnimation(){if(!this.animationTimer)return;clearInterval(this.animationTimer),this.animationTimer=null}}function G36(A){let{app:Q,colors:$}=A;return{heading:new A0({color:Q.keybind,bold:!0}),meta:new A0({color:Q.fileReference,dim:!0}),button:new A0({color:Q.keybind,underline:!0}),label:new A0({color:$.foreground}),value:new A0({color:$.foreground,bold:!0}),success:new A0({color:Q.toolSuccess,bold:!0}),warning:new A0({color:$.warning,bold:!0}),error:new A0({color:Q.toolError,bold:!0}),dim:new A0({color:$.foreground,dim:!0})}}function V36(A){let{context:Q,activeThreadID:$,snapshot:B,pid:E,styles:D}=A,J=B?.session??null,U=J?.transport??null;return[T80(Q,"Thread",$,D.value,D),yK(Q,"State",U?.state??null,w36(J,D),D),yK(Q,"Role",C36(J),H36(J,D),D),yK(Q,"Ready",N36(J),q36(J,D),D),yK(Q,"Resume",J?.resume.state??null,D.value,D),yK(Q,"Resume version",J===null?null:String(J.resume.version),D.value,D),yK(Q,"Attempt",K36(J),D.value,D),yK(Q,"Next retry",z36(J),D.value,D),yK(Q,"Cause",W36(J),D.value,D),T80(Q,"PID",String(E),D.value,D),T80(Q,"Client",J?.identity.clientId??null,D.value,D)]}function K36(A){let Q=A?.transport.reconnectAttempt;return Q===void 0?null:String(Q)}function z36(A){let Q=A?.transport.nextRetryAt;if(Q===void 0)return null;return`${Math.max(1,Math.ceil((Q-Date.now())/1000))}s`}function W36(A){let Q=A?.transport.reconnectCause;if(!Q)return null;let $=[Q.type];if(Q.code!==void 0)$.push(`code=${Q.code}`);if(Q.reason!==void 0)$.push(`reason=${Q.reason}`);if(Q.error!==void 0)$.push(`error=${Q.error}`);return $.join(" ")}function C36(A){if(!A)return null;if(!A.identity.role)return A.identity.requiredRole?`none (requires ${A.identity.requiredRole})`:null;if(A.identity.requiredRole&&A.identity.role!==A.identity.requiredRole)return`${A.identity.role} (requires ${A.identity.requiredRole})`;return A.identity.role}function H36(A,Q){let $=A?.identity.role??null,B=A?.identity.requiredRole??null;if($===null&&B===null)return Q.dim;if($===B)return Q.success;return Q.error}function N36(A){if(!A)return null;return A.ready?"yes":"no"}function q36(A,Q){if(!A)return Q.dim;return A.ready?Q.success:Q.error}function yK(A,Q,$,B,E){return T80(A,Q,$,B,E,{copyable:!1})}function T80(A,Q,$,B,E,D={}){let J=[new D0({text:new g(void 0,void 0,[new g(`${Q}: `,E.label),new g($??"-",$?B:E.dim)])})];if($&&D.copyable!==!1)J.push(new D0({text:new g(" ",E.meta)}),new iA({cursor:"pointer",onClick:()=>{N4.invoke(A,new IB($,`${Q} copied to clipboard`,`Failed to copy ${Q}`))},child:new D0({text:new g("[copy]",E.button)})}));return new OA({children:J})}function w36(A,Q){switch(A?.transport.state){case"connected":return Q.success;case"connecting":case"authenticating":case"reconnecting":return Q.warning;case"disconnected":return Q.error;default:return Q.dim}}i0();import y80 from"node:process";var u36={dotField:[" ",".","·","·",":",":","•","•","●","●"],ascii:[" ",".",":","-","=","+","*","#","%","@"]},Bq4=" ",pX=64,S80=0.5,Jq4=0.055,$m0=1.06,M36=$m0-1,O36=(1+Jq4)*$m0,_80=0.82,Eq4=0.96,Dq4=0.34,i2=1,Bm0=30,Tl=3;class bK extends d0{width;height;minWidth;minHeight;maxWidth;maxHeight;agentMode;colorMode;glyphSet;primaryColor;secondaryColor;backgroundColor;t;effectTime;clickCharge;sizeScale;onFrame;fps;seed;glow;shockwaves;onShockwave;onClick;constructor({key:A,width:Q=40,height:$=40,minWidth:B,minHeight:E,maxWidth:D,maxHeight:J,agentMode:U,colorMode:Y="intensity",glyphSet:Z="dotField",primaryColor:F,secondaryColor:X,backgroundColor:I,t:G,effectTime:V,clickCharge:K=0,sizeScale:z=1,onFrame:W,fps:C=30,seed:H,glow:N,shockwaves:w,onShockwave:u,onClick:L}){super(A?{key:A}:{});this.width=Q,this.height=$,this.minWidth=B??8,this.minHeight=E??8,this.maxWidth=D??40,this.maxHeight=J??40,this.agentMode=U,this.colorMode=Y,this.glyphSet=Z,this.primaryColor=F,this.secondaryColor=X,this.backgroundColor=I,this.t=G,this.effectTime=V,this.clickCharge=Math.max(0,Math.min(1,K)),this.sizeScale=Math.max(0.08,Math.min(1,z)),this.onFrame=W,this.fps=C,this.seed=H,this.glow=N,this.shockwaves=w,this.onShockwave=u,this.onClick=L}createState(){return new Uq4}}class Uq4 extends m0{_t=0;_effectTime=0;_timer=null;_internalShockwaves=[];_glow;_renderedSize=null;_sizeRef={set:(A)=>{this._renderedSize=A}};initState(){if(super.initState(),this._glow=this.widget.glow??new P5(this.widget.seed),this.widget.t!==void 0||this.widget.fps===0){this._t=this.widget.t??0,this._effectTime=this.widget.effectTime??this._t;return}this._timer=setInterval(()=>{if(this._t+=1/this.widget.fps,this._effectTime+=1/this.widget.fps,this.widget.onFrame){let A=this._t;setImmediate(()=>this.widget.onFrame?.(A))}this._internalShockwaves=this._internalShockwaves.filter((A)=>this._effectTime-A.startTime<i2),this.setState(()=>{})},1000/this.widget.fps)}didUpdateWidget(A){if(super.didUpdateWidget(A),this.widget.glow!==A.glow)this._glow=this.widget.glow??new P5(this.widget.seed);if(this.widget.t!==void 0&&this.widget.t!==A.t)this._t=this.widget.t,this.setState(()=>{});if(this.widget.effectTime!==void 0&&this.widget.effectTime!==A.effectTime)this._effectTime=this.widget.effectTime,this.setState(()=>{})}dispose(){if(this._timer)clearInterval(this._timer),this._timer=null;super.dispose()}isClickInsideOrb(A,Q){let $=this._renderedSize;if(!$)return!0;let B=$.width/2,E=$.height/2,D=Math.max(1,$.width/2-1),J=Math.max(1,$.height/(2*S80)-1),U=Math.min(D,J),Y=A-B,Z=(Q-E)/S80;return Y*Y+Z*Z<U*U}handleClick=(A)=>{if(!this.isClickInsideOrb(A.localPosition.x,A.localPosition.y))return;let Q=this.widget.effectTime??this._effectTime;this.widget.onClick?.({x:A.position.x,y:A.position.y,localX:A.localPosition.x,localY:A.localPosition.y,time:Q});let $={x:A.localPosition.x,y:A.localPosition.y,startTime:Q};if(this.widget.onShockwave)this.widget.onShockwave($);else this._internalShockwaves.push($);this.setState(()=>{})};build(A){let Q=S4.of(A),$=this.widget.backgroundColor??Q.colorScheme.background,B=new Yq4({width:this.widget.width,height:this.widget.height,minWidth:this.widget.minWidth,minHeight:this.widget.minHeight,maxWidth:this.widget.maxWidth,maxHeight:this.widget.maxHeight,time:this._t,agentMode:this.widget.agentMode,colorMode:this.widget.colorMode,glyphSet:this.widget.glyphSet,primaryColor:this.widget.primaryColor,secondaryColor:this.widget.secondaryColor,backgroundColor:$,glow:this._glow,shockwaves:this.widget.shockwaves??this._internalShockwaves,effectTime:this.widget.effectTime??this._effectTime,clickCharge:this.widget.clickCharge,sizeScale:this.widget.sizeScale,sizeRef:this._sizeRef}),E=!!(this.widget.onClick||this.widget.onShockwave);return new iA({opaque:E,onClick:E?this.handleClick:void 0,child:B})}}class Yq4 extends XB{props;constructor(A,Q){super(Q?{key:Q}:{});this.props=A}createElement(){return new $J(this)}createRenderObject(){return new WT(this.props.width,this.props.height,this.props.minWidth,this.props.minHeight,this.props.maxWidth,this.props.maxHeight,this.props.time,this.props.agentMode,this.props.colorMode,this.props.glyphSet,this.props.primaryColor,this.props.secondaryColor,this.props.backgroundColor,this.props.glow,this.props.shockwaves,this.props.effectTime,this.props.clickCharge,this.props.sizeScale,this.props.sizeRef)}updateRenderObject(A){let Q=A;Q.setSizeRef(this.props.sizeRef),Q.update(this.props.width,this.props.height,this.props.minWidth,this.props.minHeight,this.props.maxWidth,this.props.maxHeight,this.props.time,this.props.agentMode,this.props.colorMode,this.props.glyphSet,this.props.primaryColor,this.props.secondaryColor,this.props.backgroundColor,this.props.glow,this.props.shockwaves,this.props.effectTime,this.props.clickCharge,this.props.sizeScale)}}class WT extends bA{_width;_height;_minWidth;_minHeight;_maxWidth;_maxHeight;_time;_agentMode;_colorMode;_GlyphSet;_primaryColor;_secondaryColor;_backgroundColor;_glow;_shockwaves;_effectTime;_ClickCharge;_SizeScale;_sizeRef;_palette=[];_paletteSignature="";constructor(A,Q,$,B,E,D,J,U,Y,Z,F,X,I,G,V=[],K=J,z=0,W=1,C){super();this._width=A;this._height=Q;this._minWidth=$;this._minHeight=B;this._maxWidth=E;this._maxHeight=D;this._time=J;this._agentMode=U;this._colorMode=Y;this._GlyphSet=Z;this._primaryColor=F;this._secondaryColor=X;this._backgroundColor=I;this._glow=G;this._shockwaves=V;this._effectTime=K;this._ClickCharge=z;this._SizeScale=W;this._sizeRef=C;this._ClickCharge=Math.max(0,Math.min(1,this._ClickCharge)),this._SizeScale=Math.max(0.08,Math.min(1,this._SizeScale)),this.rebuildPalette(this._agentMode,this._primaryColor,this._secondaryColor)}getPaletteSignature(A,Q,$){if(Q&&$)return`${Q.r},${Q.g},${Q.b}|${$.r},${$.g},${$.b}`;return`mode:${A??"smart"}`}rebuildPalette(A,Q,$){let B=Q&&$?{primary:Q,secondary:$}:void 0;this._palette=Array.from({length:pX},(E,D)=>{let J=D/(pX-1);return e7(J,A,B)}),this._paletteSignature=this.getPaletteSignature(A,Q,$)}get glyphs(){return u36[this._GlyphSet]}getMinIntrinsicWidth(A){return this._minWidth}getMaxIntrinsicWidth(A){return this._maxWidth}getMinIntrinsicHeight(A){return this._minHeight}getMaxIntrinsicHeight(A){return this._maxHeight}update(A,Q,$,B,E,D,J,U,Y,Z,F,X,I,G,V=[],K=J,z=0,W=1){let C=!1;if(A!==this._width||Q!==this._height||$!==this._minWidth||B!==this._minHeight||E!==this._maxWidth||D!==this._maxHeight)this._width=A,this._height=Q,this._minWidth=$,this._minHeight=B,this._maxWidth=E,this._maxHeight=D,C=!0;if(this._time=J,this._agentMode=U,this._colorMode=Y,this._GlyphSet=Z,this._primaryColor=F,this._secondaryColor=X,this._backgroundColor=I,this._glow=G,this._shockwaves=V,this._effectTime=K,this._ClickCharge=Math.max(0,Math.min(1,z)),this._SizeScale=Math.max(0.08,Math.min(1,W)),this.getPaletteSignature(U,F,X)!==this._paletteSignature)this.rebuildPalette(U,F,X);if(C)this.markNeedsLayout();this.markNeedsPaint()}setSizeRef(A){this._sizeRef=A}performLayout(){let A=this._lastConstraints;oA(!!A,"performLayout called without constraints");let Q=A.constrain(this._width,this._height);this.setSize(Q.width,Q.height),this._sizeRef?.set({width:Q.width,height:Q.height}),super.performLayout()}getPaletteIndex(A,Q,$){if(this._colorMode==="vertical"){let B=Math.max(0,Math.min(1,0.5-Q/(2*$)));return Math.min(pX-1,Math.floor(B*pX))}return Math.min(pX-1,Math.floor(A*pX))}getShockwaveIntensity(A,Q,$,B){let E=0,D=0,J=0;for(let U of this._shockwaves){let Y=this._effectTime-U.startTime;if(Y<0||Y>i2)continue;let Z=A-U.x,F=(Q-U.y)*B,X=Math.sqrt(Z*Z+F*F),I=Y*Bm0,G=Math.abs(X-I);if(G>=Tl)continue;let V=1-Y/i2,K=(1-G/Tl)**1.35,z=Math.max(0.35,1-$*0.25),W=K*V*z;E=Math.max(E,W),D+=W,J++}if(J<=1)return E;return Math.min(1,E+Math.max(0,D-E)*0.42)}getClickImpulse(){let A=0;for(let Q of this._shockwaves){let $=this._effectTime-Q.startTime;if($<0||$>_80)continue;let B=$/_80,E=Math.exp(-B*4.2),D=Math.sin(B*Math.PI*3.1)*Math.exp(-B*2.4);A=Math.max(A,Math.max(0,E*0.95+D*0.35))}return A}getClickDent(A,Q,$,B){let E=0;for(let D of this._shockwaves){let J=this._effectTime-D.startTime;if(J<0||J>_80)continue;let U=J/_80,Y=A-D.x,Z=(Q-D.y)*B,F=Math.sqrt(Y*Y+Z*Z),X=Math.exp(-(F*F)/34),I=Math.max(0.25,$)**0.55,G=Math.sin(Math.min(1,U*1.45)*Math.PI);E=Math.max(E,X*I*G*(1-U)**0.65)}return E}getClickBloom(A,Q,$,B){let E=0;for(let D of this._shockwaves){let J=this._effectTime-D.startTime;if(J<0||J>Eq4)continue;let U=J/Eq4,Y=A-D.x,Z=(Q-D.y)*B,F=Y*Y+Z*Z,X=Math.exp(-F/18),I=Math.max(0.22,1-$*0.18),G=Math.sin(Math.min(1,U*1.65)*Math.PI),V=X*I*(0.25+G*0.75)*(1-U)**0.78,K=Math.min(1,J/Dq4),z=Math.max(0,Math.sin(A*2.7+Q*4.4+this._effectTime*58))**4,W=J<Dq4?X*I*z*(1-K)**1.25:0;E=Math.max(E,Math.min(1,V+W*0.55))}return E}paint(A,Q=0,$=0){this.paintNeo(A,Q,$)}paintNeo(A,Q=0,$=0){let B=Q+this.offset.x,E=$+this.offset.y,D=Math.floor(this.size.width),J=Math.floor(this.size.height),U=A.getSize(),Y=U.width,Z=U.height,F=this._backgroundColor,X=this._palette,I=this.glyphs,G=D/2,V=J/2,K=Math.max(1,D/2-1),z=Math.max(1,J/(2*S80)-1),W=Math.max(1,Math.min(K,z)/O36*this._SizeScale),C=this._agentMode==="rush"?3.4:this._agentMode==="deep"?0.9:1.45,H=this._shockwaves.length>0,N=H?this.getClickImpulse():0,w=this._ClickCharge,u=w>0?(Math.sin(this._effectTime*31)*0.5+0.5)*w:0,L=w*(0.7+u*0.3),R=Math.sin(this._time*1.35*C),_=(R*0.5+0.5)**2,P=W*(1+R*Jq4+N*0.038+w*0.018),h=1/(P*P),x=1/S80,v=0.96+_*0.16+N*0.18+L*0.18,k=(this._time+N*0.22+u*0.12)*0.45*C,c=-0.56+Math.sin(k)*0.16,d=-0.66+Math.cos(k*0.7)*0.1,b=0.6,p=Math.cos(this._time*1.55*C)*0.38-0.18,n=Math.sin(this._time*1.15*C)*0.25-0.26,a=P*$m0,X0=a*a;for(let t=0;t<J;t++){let Z0=E+t;if(Z0<0||Z0>=Z)continue;let K0=(t-V)*x,R0=K0*K0;if(R0>=X0)continue;let B0=Math.sqrt(X0-R0),C0=Math.max(0,Math.floor(G-B0)),l=Math.min(D-1,Math.ceil(G+B0));for(let i=C0;i<=l;i++){let $0=i-G,s=$0*$0+R0;if(s>=X0)continue;let E0=B+i;if(E0<0||E0>=Y)continue;let Q0=Math.sqrt(s*h),G0=Q0>1,V0=H?this.getShockwaveIntensity(i,t,Q0,x):0,w0=H?this.getClickDent(i,t,Q0,x):0,I0=H?this.getClickBloom(i,t,Q0,x):0,u0=w>0.45?Math.max(0,Math.sin(i*1.7+t*2.9+this._effectTime*38))**10*w:0;if(G0){let eB=this._glow.sample(i*1.35+Math.sin(this._time*1.3*C+N)*8,t*1.1-this._time*7*C,this._time*1.6,C),Q5=Math.max(0,1-(Q0-1)/M36),F8=Math.max(0,0.25+$0/P*0.85-K0/P*0.18+w0*0.45),NJ=Q5*Q5*(0.045+eB*0.04+F8*0.12)*v+V0*(0.1+Q5*0.14)+w0*Q5*0.08+I0*Q5*0.12+L*Q5*Q5*(0.045+u0*0.18);if(NJ<0.055)continue;let DI=Math.min(pX-1,Math.floor((NJ+V0*0.45+L*0.18+u0*0.4)*pX*1.8)),Mz=X[DI]||X[0],RZ=L>0.35?Math.max(0,Math.sin(Math.atan2(K0,$0)*5-this._effectTime*7))**8*Q5*L:0,Oz=L>0.62&&Q5>0.76;A.setCell(E0,Z0,{char:I[V0>0.35||u0>0.32||I0>0.62?I.length-1:NJ>0.14||Oz||RZ>0.18?2:1]??Bq4,width:1,style:{fg:Mz,bg:F,bold:V0>0.25||u0>0.18||I0>0.35}});continue}let k0=$0/P,o0=K0/P,IA=Math.sqrt(Math.max(0,1-Q0*Q0)),DA=L*Math.max(0,Q0-0.35),xA=w0*(0.6+Q0*0.45)+DA*0.12+I0*0.16,rA=(this._time+N*0.18)*1.35*C+IA*3.2+Math.sin(o0*4.4+this._time*0.85*C+xA*2.4)*0.7+xA*0.9+L*0.35,$4=Math.sin(rA),dA=Math.cos(rA),ZA=k0*dA-o0*$4,nA=k0*$4+o0*dA,JA=this._glow.sample(ZA*P*1.35+IA*7+Math.sin(this._time*1.3*C)*8,nA*P*1.1-this._time*7*C-xA*3,this._time*1.6,C),r1=this._glow.sample(ZA*P*0.58-this._time*9*C,nA*P*1.65+Math.cos(this._time*1.05*C)*6,this._time*1.1,C*0.7),b4=Math.sin(ZA*3.8+nA*2.6+this._time*1.4*C)*0.15+Math.sin(nA*6.2-this._time*0.9*C)*0.055,K1=k0*c+o0*d+IA*0.6+b4+w0*0.18,Z1=Math.max(0,Math.min(1,(K1+0.08)/1.06)),z4=Z1*Z1*(3-Z1*2),q4=z4**0.82,L0=Math.max(0,1-z4)**1.45,O0=Math.max(0,1-IA)**2.45,t0=Math.max(0,0.32+k0*1.05-o0*0.18)**1.25,jA=O0*t0,PA=L>0.35?Math.max(0,Math.sin(Math.atan2(o0,k0)*5-this._effectTime*7))**8*Math.max(0,Q0-0.34)*L:0,T4=u0*Math.max(0,Q0-0.48)**0.65,F1=Math.exp(-((k0-0.74)*(k0-0.74)*34+(o0+0.02)*(o0+0.02)*2.8))*jA,f1=Math.exp(-((k0-p)*(k0-p)*58+(o0-n)*(o0-n)*130)),u6=JA*0.64+r1*0.36,e3=Math.max(0,(u6-0.58)/0.42)**1.7,N7=Math.sin(nA*11+ZA*3.5+IA*5+this._time*4.6*C),U6=Math.sin(ZA*8.5-nA*4.5+IA*7-this._time*3.6*C),A5=Math.max(0,N7*0.5+0.5)**4*0.12,SB=Math.max(0,U6*0.5+0.5)**5*0.14,EI=(u6-0.5)*0.12+e3*0.09+A5+SB,wz=0.105+(1-Q0)*0.035+JA*0.012,r6=(0.045+q4*0.72+IA*0.055-L0*0.105)*(0.88+EI)+jA*0.26+F1*0.95+f1*(0.38+q4)*1.28;if(r6*=v,r6=Math.max(r6,wz),V0>0){let eB=Math.max(0,Q0-0.58)*0.55;r6=Math.min(1,r6+V0*(0.46+eB))}if(w0>0){let eB=Math.max(0,Q0-0.42)*0.5;r6=Math.min(1,r6+w0*(0.12+eB)-xA*0.045)}if(L>0)r6=Math.min(1,r6+L*(jA*0.2+e3*0.045)+T4*0.35+PA*0.22);if(I0>0)r6=Math.min(1,r6+I0*(0.22+IA*0.1));r6=Math.max(0,Math.min(1,r6));let uz=Math.max(1,Math.min(I.length-1,Math.floor(r6*I.length)+Math.floor(V0*3)+Math.floor(T4*3)+Math.floor(PA*2)+Math.floor(I0*2))),zw=I[uz]||Bq4,Ww=Math.max(0,Math.min(1,r6*0.58+q4*0.3+jA*0.12+V0*0.32+L*0.12+T4*0.3+PA*0.18+I0*0.28)),q9=this.getPaletteIndex(Ww,K0,P),Z8=X[q9]||X[pX-1];A.setCell(E0,Z0,{char:zw,width:1,style:{fg:Z8,bg:F,bold:V0>0.24||T4>0.18||I0>0.32}})}}}}var Em0="https://static.ampcode.com";function Zq4(A,Q="https://static.ampcode.com"){let $=new URL(A.path,Q).toString();return{type:"image",source:{type:"url",url:$},sourcePath:$}}var Dm0=[{id:"photo-4389",title:"DSCF4389",sourceName:"DSCF4389.jpg",rotationDegrees:-8,path:"/neo/end-credits/photos/dscf4389-d697433521.png"},{id:"photo-4384",title:"DSCF4384",sourceName:"DSCF4384.jpg",rotationDegrees:7,path:"/neo/end-credits/photos/dscf4384-4a94547253.png"},{id:"photo-4332",title:"DSCF4332",sourceName:"DSCF4332.jpg",rotationDegrees:-5,path:"/neo/end-credits/photos/dscf4332-990ad9c680.png"},{id:"photo-4272",title:"DSCF4272",sourceName:"DSCF4272.jpg",rotationDegrees:8,path:"/neo/end-credits/photos/dscf4272-473ca6bcd3.png"},{id:"photo-2225",title:"DSCF2225",sourceName:"DSCF2225 Edited.jpg",rotationDegrees:-6,path:"/neo/end-credits/photos/dscf2225-c43159d980.png"},{id:"photo-l1000650",title:"L1000650",sourceName:"L1000650.jpg",rotationDegrees:-4,path:"/neo/end-credits/photos/l1000650-43249c8236.png"},{id:"photo-r0007603",title:"R0007603",sourceName:"R0007603.JPG",rotationDegrees:7,path:"/neo/end-credits/photos/r0007603-511aa562e1.png"},{id:"photo-r0007803",title:"R0007803",sourceName:"R0007803.jpg",rotationDegrees:-8,path:"/neo/end-credits/photos/r0007803-700a2ac7b7.png"},{id:"photo-4241",title:"DSCF4241",sourceName:"DSCF4241.jpg",rotationDegrees:8,path:"/neo/end-credits/photos/dscf4241-c1240d483d.png"},{id:"photo-4366",title:"DSCF4366",sourceName:"DSCF4366.jpg",rotationDegrees:7,path:"/neo/end-credits/photos/dscf4366-24756ce180.png"},{id:"photo-4387",title:"DSCF4387",sourceName:"DSCF4387.jpg",rotationDegrees:-7,path:"/neo/end-credits/photos/dscf4387-11dab5d857.png"},{id:"photo-e7681b82",title:"E7681B82",sourceName:"E7681B82-2C76-44E8-8F63-2442FE69D663_1_102_o.jpeg",rotationDegrees:-5,path:"/neo/end-credits/photos/e7681b82-4ea9a6e03f.png"}];var L36=33,j36=220,Tq4=850,vq4=820,_q4=Tq4+vq4+220,Sq4=520,Nm0=_q4+Sq4+1100,kq4=1900,fq4=900,$QB=kq4+fq4,R36=3000,Zm0=1800,P36=1800,vl=360,T36=150,v36=330,_36=8,S36=0.88,xq4=620,k36=3000,yq4=620,Fq4=xq4+k36+yq4,Xq4=0.5,f36=5,Fm0=2,bq4=2,k80=6,HT=2,NT=5,qm0=2,x36=1,y36=3,Iq4=42,Jm0=135,b36=46,h36=360,g36=10,Gq4=520,Vq4=420,m36=980,wm0=1350,d36=480,Xm0=1200,c36=3,hq4=280,Im0=7,p36=2,Kq4=92,l36=11000,i36=50,gq4="↯",n36="◉",bq=[[VZ(["....#..#....",".....##.....","....####....","...######...","..##.##.##..","..########..","..#.#..#.#..",".....##....."]),VZ(["....#..#....","..#.####.#..","..########..",".##########.","...######...","....#..#....","...#....#...","..#......#.."])],[VZ(["...#....#...","....#..#....","...######...","..##.##.##..",".##########.",".#.######.#.",".#.#....#.#.","....##.##..."]),VZ(["...#....#...",".#..#..#..#.",".#.######.#.",".##########.","..########..","...######...","..#......#..",".#........#."])],[VZ(["....####....",".##########.","############","###..##..###","############","..###..###..",".##..##..##.","..##....##.."]),VZ(["....####....",".##########.","############","###..##..###","############","...##..##...","..##.##.##..","##........##"])]],Gm0=VZ(["....##....","....##....","...####...","...####...",".########.","##########","##..##..##","#........#"]),a36=VZ(["....####......","..##########..",".############.","##.########.##","##############","..###....###..",".##........##.",".............."]),_l=VZ(["....########....","..############..",".##############.","################","################","######....######","#####......#####","####........####","####........####","####........####","####........####","................"]),o36=VZ(["..#..#..#...","#..#..#..#..",".#.#..#.#...","...######...","...######...",".#.#..#.#...","#..#..#..#..","..#..#..#..."]),zq4=["·","˙","∙","⠂","⠄"],n2=mq(255,225,102),gq=mq(255,125,34),gK=mq(103,255,168),r36=mq(245,244,238),Vm0=mq(104,169,255),Sl=mq(170,116,255),s36=mq(255,84,94),Wq4=["✦","✧","✶","⋆","*","·"],Cq4=[n2,gK,Vm0,Sl,gq],Hq4=32000,Km0={r:103,g:255,b:168},f80=[{r:103,g:255,b:168},{r:104,g:169,b:255},{r:170,g:116,b:255},{r:255,g:125,b:34},{r:255,g:225,b:102}],t36="by Amp Frontier Corp.",e36=[" ⢀⣴⣾⠿⠿⢿⣶⣄⣰⣶ ⣶⣶⢀⣶⡆⢰⣶ ⣰⣶⣴⣾⠿⠿⣿⣶⣄","⣰⣿⠏ ⠈⢿⣿⡏ ⣿⡇⢸⣿⠁⣿⡿ ⣿⣿⠋ ⠙⣿⣧","⣿⡏ ⢸⣿⡇⢸⣿⠇⣼⣿⢀⣿⡇⢠⣿⡇ ⢸⣿","⢿⣷ ⣼⣿ ⢸⣿ ⣿⡏⢸⣿⠃⢸⣿⣇ ⢀⣾⡿","⠈⢿⣷⣤⣄⣠⣤⣾⣿⣿ ⣿⡟⢰⣿⡇⣸⣿ ⣼⣿⢻⣷⣤⣄⣤⣴⣾⠟⠁"," ⠈⠉⠛⠛⠉⠁⠉⠁ ⠉⠁⠈⠉ ⠉⠉ ⣿⡇ ⠈⠉⠛⠛⠉⠁ "," ⢰⣿⡇ ",""," Neo"],A56=["Thorsten Ball","Hamish Bultitude","Harry Charlesworth","Camden Cheek","Karl Clement","Tim Culverhouse","Will Dollman","Jesse Edelstein","Isuru Fonseka","Nicolay Gerold","Dario Hamidi","Brady Jeong","Brett Jones","Alex Kemper","Beyang Liu","Tim Lucas","Lewis Metcalf","Connor O'Brien","Hitesh Sagtani","Quinn Slack"],a2=[{kind:"logo",lines:e36},...A56.map((A)=>({kind:"name",lines:[A]})),{kind:"message",lines:["Special thanks","to all our early testers"]},{kind:"message",lines:["THE END","for now"]}],Q56=[{photoIndex:8,startOffsetMs:2800,xRatio:0.06,yRatio:0.76,widthRatio:0.23,maxWidth:30},{photoIndex:3,startOffsetMs:7400,xRatio:0.94,yRatio:0.12,widthRatio:0.23,maxWidth:30},{photoIndex:10,startOffsetMs:12000,xRatio:0.08,yRatio:0.44,widthRatio:0.23,maxWidth:30},{photoIndex:5,startOffsetMs:16700,xRatio:0.94,yRatio:0.1,widthRatio:0.23,maxWidth:30},{photoIndex:1,startOffsetMs:21400,xRatio:0.08,yRatio:0.12,widthRatio:0.23,maxWidth:30},{photoIndex:11,startOffsetMs:26100,xRatio:0.94,yRatio:0.72,widthRatio:0.24,maxWidth:31},{photoIndex:6,startOffsetMs:30800,xRatio:0.07,yRatio:0.78,widthRatio:0.24,maxWidth:31},{photoIndex:0,startOffsetMs:35500,xRatio:0.1,yRatio:0.16,widthRatio:0.23,maxWidth:30},{photoIndex:4,startOffsetMs:40200,xRatio:0.12,yRatio:0.34,widthRatio:0.23,maxWidth:30},{photoIndex:9,startOffsetMs:44900,xRatio:0.93,yRatio:0.18,widthRatio:0.23,maxWidth:30},{photoIndex:2,startOffsetMs:49600,xRatio:0.92,yRatio:0.8,widthRatio:0.25,maxWidth:32},{photoIndex:7,startOffsetMs:54300,xRatio:0.9,yRatio:0.45,widthRatio:0.24,maxWidth:31}];class um0 extends d0{onComplete;highScore;onHighScoreChange;elapsedMs;viewportSize;constructor(A){super();this.onComplete=A.onComplete,this.highScore=A.highScore??0,this.onHighScoreChange=A.onHighScoreChange,this.elapsedMs=A.elapsedMs,this.viewportSize=A.viewportSize}createState(){return new mq4}}class mq4 extends m0{focusScopeNode=new a7({debugLabel:"EndCreditsTakeover"});lastTickAt=performance.now();elapsedMs=0;timer=null;completed=!1;manualPaused=!1;clickedOrbID=null;hoveredOrbID=null;orbClickCount=0;orbShockwaves=[];spaceInvaders=null;unregisterKeyInterceptor=null;prefetchedPhotoBaseURL=null;endCreditsPhotoImages=new Map;initState(){super.initState(),this.startTimerIfNeeded(),q76(),this.unregisterKeyInterceptor=d80()?null:G1.instance.addKeyInterceptor((A)=>{if(!this.mounted)return!1;return this.handleKeyEvent(A)==="handled"},{position:"front"}),queueMicrotask(()=>{if(this.mounted)this.focusScopeNode.requestFocus()})}didUpdateWidget(A){if(super.didUpdateWidget(A),A.elapsedMs!==this.widget.elapsedMs)this.startTimerIfNeeded()}dispose(){this.stopTimer(),w76(),this.unregisterKeyInterceptor?.(),this.unregisterKeyInterceptor=null,this.focusScopeNode.dispose(),super.dispose()}startTimerIfNeeded(){if(this.stopTimer(),this.completed=!1,this.manualPaused=!1,this.clickedOrbID=null,this.hoveredOrbID=null,this.orbClickCount=0,this.orbShockwaves=[],this.spaceInvaders=null,this.widget.elapsedMs!==void 0){this.elapsedMs=W1(this.widget.elapsedMs,0,hK());return}this.lastTickAt=performance.now(),this.elapsedMs=0,this.timer=setInterval(()=>{let A=performance.now(),Q=Math.max(0,A-this.lastTickAt);this.lastTickAt=A,this.advanceElapsed(Q)},L36)}advanceElapsed(A){if(this.spaceInvaders){this.advanceSpaceInvaders(A);return}if(this.widget.elapsedMs!==void 0)return;if(this.manualPaused&&this.elapsedMs<hK())return;this.setState(()=>{let Q=Math.max(0,this.elapsedMs+A);if(this.elapsedMs<hK()&&Q>=hK())this.clickedOrbID=null,this.hoveredOrbID=null,this.orbClickCount=0,this.orbShockwaves=[];this.elapsedMs=Q})}advanceSpaceInvaders(A){let Q=this.spaceInvaders;if(!Q)return;let $=Q;if(this.setState(()=>{$=Q76(Q,A),this.spaceInvaders=$}),$.highScore>Q.highScore)this.widget.onHighScoreChange?.($.highScore)}stopTimer(){if(!this.timer)return;clearInterval(this.timer),this.timer=null}completeOnce(){if(this.completed)return;this.completed=!0,this.stopTimer(),this.widget.onComplete()}handleKeyEvent=(A)=>{if(Pq4(A))return"ignored";if(this.spaceInvaders)return this.handleSpaceInvadersKeyEvent(A);if(A.eventType==="release")return"handled";if(s$(A,"Escape")){if(this.isWaitingForContinue())this.completeOnce();else this.skipToEnd();return"handled"}if(C76(A))return this.stepScene(-1),"handled";if(W76(A))return this.stepScene(1),"handled";if(this.isWaitingForContinue())return"handled";if(this.manualPaused){if(s$(A,"Enter"))this.resumePlayback();return"handled"}if(z76(A))this.advanceElapsed(j36);return"handled"};handleSpaceInvadersKeyEvent(A){if(Pq4(A))return"ignored";if(s$(A,"Escape"))return this.completeOnce(),"handled";let Q=this.spaceInvaders;if(!Q)return"handled";let $=kl(Q),B=I76(A);if(A.eventType==="release"){if(B!==0)this.setState(()=>{this.spaceInvaders=Lq4(Q,B,!1)});else if(Rq4(A))this.setState(()=>{this.spaceInvaders=jq4(Q,!1)});return"handled"}if(Q.gameOver){if(s$(A,"Enter"))this.setState(()=>{this.spaceInvaders=Cm0(eq4(Q),{highScore:Q.highScore})});return"handled"}if(!$)return"handled";if(B!==0)return this.setState(()=>{this.spaceInvaders=A.eventType===void 0?G76(Q,B):Lq4(Q,B,!0)}),"handled";if(Rq4(A))this.setState(()=>{if(A.eventType===void 0){this.spaceInvaders=Hm0(Q);return}let E=jq4(Q,!0);this.spaceInvaders=A.eventType==="repeat"?E:Hm0(E)});return"handled"}stepScene(A){let Q=s56(this.getVisibleElapsedMs()),$=W1(Q+A,0,a2.length-1);this.lastTickAt=performance.now(),this.setState(()=>{if(this.elapsedMs=t56($),this.manualPaused=!0,$>=a2.length-1)this.clickedOrbID=null,this.hoveredOrbID=null,this.orbClickCount=0,this.orbShockwaves=[]})}resumePlayback(){this.lastTickAt=performance.now(),this.setState(()=>{this.manualPaused=!1})}skipToEnd(){this.lastTickAt=performance.now(),this.setState(()=>{this.elapsedMs=hK(),this.manualPaused=!1,this.clickedOrbID=null,this.hoveredOrbID=null,this.orbClickCount=0,this.orbShockwaves=[]})}handleOrbClick(A,Q,$){this.lastTickAt=performance.now();let B=this.clickedOrbID===A?this.orbClickCount+1:1,E=this.getVisibleElapsedMs(),D=c80({size:Q,elapsedMs:E}).find((U)=>U.clickableID===A);if(B>=f36){let U=e56(Q),Y=D?Math.round(D.left+D.width/2):Math.floor(Q.width/2),Z=D?Math.round(D.top+D.height/2):Math.floor(Q.height/2);this.setState(()=>{this.clickedOrbID=A,this.hoveredOrbID=null,this.orbClickCount=0,this.orbShockwaves=[],this.manualPaused=!1,this.spaceInvaders=Cm0(U,{highScore:this.widget.highScore,introElapsedMs:0,revealX:Y,revealY:Z})});return}let J=D?{orbID:A,x:W1($.x,0,Math.max(0,D.width-1)),y:W1($.y,0,Math.max(0,D.height-1)),startTime:cq4({elapsedMs:E,orb:D,clickEnergy:B,hovered:this.hoveredOrbID===A})}:null;this.setState(()=>{if(this.clickedOrbID=A,this.orbClickCount=B,J)this.orbShockwaves=E56(this.orbShockwaves,J)})}handleOrbHoverChange=(A)=>{if(this.hoveredOrbID===A)return;this.setState(()=>{this.hoveredOrbID=A})};isWaitingForContinue(){return this.getVisibleElapsedMs()>=hK()}getVisibleElapsedMs(){return this.widget.elapsedMs??this.elapsedMs}startPhotoPrefetch(){if(d80())return;let A=Em0;if(this.prefetchedPhotoBaseURL===A)return;this.prefetchedPhotoBaseURL=A,X56(A).then((Q)=>{if(!this.mounted||this.prefetchedPhotoBaseURL!==A)return;this.setState(()=>{this.endCreditsPhotoImages=Q})})}build(A){let Q=S4.of(A).colorScheme,$=e0.of(A),B=X4.of(A).size,E=this.widget.viewportSize??B,D=this.getVisibleElapsedMs();this.startPhotoPrefetch();let J=this.spaceInvaders,U=!J&&this.isWaitingForContinue(),Y=!J&&this.manualPaused&&!U;return new E6({focusScopeNode:this.focusScopeNode,canRequestFocus:!0,debugLabel:"EndCreditsTakeover",onKey:this.handleKeyEvent,onPaste:()=>"handled",child:new y0({width:E.width,height:E.height,child:new t1({fit:"expand",children:[new zm0({layer:"background",elapsedMs:D,background:Q.background,foreground:Q.foreground,mutedForeground:Q.mutedForeground,warning:Q.warning,keybind:$.app.keybind,waitingForContinue:U,manualPaused:Y,spaceInvaders:J}),new zm0({layer:"foreground",elapsedMs:D,background:Q.background,foreground:Q.foreground,mutedForeground:Q.mutedForeground,warning:Q.warning,keybind:$.app.keybind,waitingForContinue:U,manualPaused:Y,spaceInvaders:J}),...!J?[...$56({size:E,elapsedMs:D,background:Q.background,clickedOrbID:this.clickedOrbID,hoveredOrbID:this.hoveredOrbID,orbClickCount:this.orbClickCount,orbShockwaves:this.orbShockwaves,onOrbClick:(Z,F)=>this.handleOrbClick(Z,E,F),onOrbHoverChange:this.handleOrbHoverChange}),...F56({size:E,elapsedMs:D,background:Q.background,photoImages:this.endCreditsPhotoImages})]:[]]})})})}}class zm0 extends XB{layer;elapsedMs;background;foreground;mutedForeground;warning;keybind;waitingForContinue;manualPaused;spaceInvaders;constructor({layer:A,elapsedMs:Q,background:$,foreground:B,mutedForeground:E,warning:D,keybind:J,waitingForContinue:U,manualPaused:Y,spaceInvaders:Z}){super();this.layer=A,this.elapsedMs=Q,this.background=$,this.foreground=B,this.mutedForeground=E,this.warning=D,this.keybind=J,this.waitingForContinue=U,this.manualPaused=Y,this.spaceInvaders=Z}createRenderObject(){return new dq4({layer:this.layer,elapsedMs:this.elapsedMs,background:this.background,foreground:this.foreground,mutedForeground:this.mutedForeground,warning:this.warning,keybind:this.keybind,waitingForContinue:this.waitingForContinue,manualPaused:this.manualPaused,spaceInvaders:this.spaceInvaders})}updateRenderObject(A){A.update({layer:this.layer,elapsedMs:this.elapsedMs,background:this.background,foreground:this.foreground,mutedForeground:this.mutedForeground,warning:this.warning,keybind:this.keybind,waitingForContinue:this.waitingForContinue,manualPaused:this.manualPaused,spaceInvaders:this.spaceInvaders})}}class dq4 extends bA{props;constructor(A){super();this.props=A}update(A){this.props=A,this.markNeedsPaint()}performLayout(){let A=this._lastConstraints;oA(!!A,"performLayout called without constraints");let Q=A.constrain(A.biggest.width,A.biggest.height);this.setSize(Q.width,Q.height),super.performLayout()}paint(A,Q=0,$=0){let B=Math.floor(Q+this.offset.x),E=Math.floor($+this.offset.y),D=Math.floor(this.size.width),J=Math.floor(this.size.height);if(D<=0||J<=0)return;if(this.props.layer==="background"){if(A.fill(B,E,D,J," ",{bg:this.props.background}),!this.props.spaceInvaders)U56({screen:A,absoluteX:B,absoluteY:E,width:D,height:J,elapsedMs:this.props.elapsedMs});return}if(this.props.spaceInvaders){H56({screen:A,absoluteX:B,absoluteY:E,width:D,height:J,game:this.props.spaceInvaders,background:this.props.background,mutedForeground:this.props.mutedForeground,warning:this.props.warning,keybind:this.props.keybind});return}if(K56({screen:A,absoluteX:B,absoluteY:E,width:D,height:J,elapsedMs:this.props.elapsedMs,foreground:this.props.foreground,mutedForeground:this.props.mutedForeground}),k56(A,B,E,D,J,this.props.background),z56({screen:A,absoluteX:B,absoluteY:E,width:D,height:J,elapsedMs:this.props.elapsedMs,foreground:this.props.foreground}),this.props.waitingForContinue)f56({screen:A,absoluteX:B,absoluteY:E,width:D,height:J,mutedForeground:this.props.mutedForeground,keybind:this.props.keybind});else if(this.props.manualPaused)x56({screen:A,absoluteX:B,absoluteY:E,width:D,height:J,keybind:this.props.keybind,mutedForeground:this.props.mutedForeground})}}function $56({size:A,elapsedMs:Q,background:$,clickedOrbID:B,hoveredOrbID:E,orbClickCount:D,orbShockwaves:J,onOrbClick:U,onOrbHoverChange:Y}){let Z=Q/1000,F=iq4({size:A,elapsedMs:Q}).map((X)=>X.rect);return c80({size:A,elapsedMs:Q}).filter((X)=>{if(X.clickableID)return!0;return!F.some((I)=>aq4(oq4(X,1),I))}).map((X)=>{let I=X.clickableID,G=I!==void 0&&B===I,V=I!==void 0&&E===I,K=G?D:0,z=cq4({elapsedMs:Q,orb:X,clickEnergy:K,hovered:V}),W=new bK({width:X.width,height:X.height,agentMode:X.agentMode,glyphSet:X.glyphSet,primaryColor:X.primaryColor,secondaryColor:X.secondaryColor,backgroundColor:$,t:Z+X.timeOffset+K*0.7+(V?0.2:0),effectTime:z,clickCharge:V?0.34:0,sizeScale:V?1.08:1,shockwaves:B56(J,I),seed:X.seed+K*17,fps:0}),C=I?D56({orb:X,orbWidget:W,clickableID:I,onOrbClick:U,onOrbHoverChange:Y}):W;return new m1({left:X.left,top:X.top,width:X.width,height:X.height,child:C})})}function cq4({elapsedMs:A,orb:Q,clickEnergy:$,hovered:B}){return A/1000+Q.timeOffset+$*3+(B?0.8:0)}function B56(A,Q){if(Q===void 0)return[];return A.filter(($)=>$.orbID===Q).map(({x:$,y:B,startTime:E})=>({x:$,y:B,startTime:E}))}function E56(A,Q){return[...A.filter(($)=>{if($.orbID!==Q.orbID)return!0;return Q.startTime-$.startTime<=i2}),Q]}function D56({orb:A,orbWidget:Q,clickableID:$,onOrbClick:B,onOrbHoverChange:E}){return new t1({fit:"expand",children:[Q,...J56(A).map((D)=>new m1({left:D.left,top:D.top,width:D.width,height:D.height,child:new iA({onClick:(J)=>{if(J.button==="left")B($,{x:D.left+J.localPosition.x,y:D.top+J.localPosition.y})},onEnter:()=>E($),onHover:()=>E($),onExit:()=>E(null),cursor:"pointer",child:new y0({width:D.width,height:D.height})})}))]})}function J56(A){let Q=A.width/2,$=A.height/2,B=Math.max(1,Math.min(A.width/2-1,A.height/(2*Xq4)-1)),E=[];for(let D=0;D<A.height;D++){let J=(D+0.5-$)/Xq4,U=J*J;if(U>=B*B)continue;let Y=Math.sqrt(B*B-U),Z=W1(Math.floor(Q-Y),0,A.width-1),F=W1(Math.ceil(Q+Y),Z+1,A.width);E.push({left:Z,top:D,width:F-Z,height:1})}return E}function U56({screen:A,absoluteX:Q,absoluteY:$,width:B,height:E,elapsedMs:D}){if(B<40||E<12)return;let J=l80(D),U=W1(Math.floor(B*E/180),12,34),Y=[1,0.42,0.2],Z=[0.14,0.34,0.58],F=[0.34,0.26,0.2];for(let[X,I]of Y.entries()){let G=Math.max(1,Math.floor(U*I)),V=Z[X]??0.2,K=J*E*V+D/(5800-X*900);for(let z=0;z<G;z++){let W=z+X*211,C=G9(W,17)%B,H=G9(W,41)%E,N=Math.sin(D/(3700+X*680)+W*0.47)*1.6,w=Q+W1(Math.round(C+N),0,B-1),u=$+Rm0(Math.round(H-K),E),L=Wq4[G9(W,83)%Wq4.length]??"·",R=Cq4[G9(W,109)%Cq4.length]??n2,_=0.5+Math.sin(D/(460+X*130)+W*1.31)*0.5,P=(F[X]??0.12)*(0.42+_*0.58);K7(A,w,u,L,{fg:L$(R,P),bold:L!=="·"&&_>0.68})}}}function c80({size:A,elapsedMs:Q}){if(A.width<50||A.height<18)return[];let $=Q>=hK(),B=Z56(Q),E=W1(Math.floor(A.width*0.2),16,30),D=W1(Math.round(E*0.55),8,16),J=W1(Math.floor(A.width*0.28),22,38),U=W1(Math.round(J*0.55),11,20),Y=-Math.floor(E*0.42),Z=A.width-Math.ceil(J*0.58),F=W1(Math.floor(A.width*0.5),34,50),X=W1(Math.round(F*0.8),24,40),I=-X-2,G=-Math.floor(X/2),V=Um0({id:"small",left:Math.round(Y+(-E-2-Y)*B),top:-Math.floor(D*0.22),width:E,height:D,seed:13,agentMode:"smart",glyphSet:"ascii",primaryColor:{r:103,g:255,b:168},secondaryColor:{r:104,g:169,b:255},timeOffset:0},Q),K=Um0({id:"large",left:Math.round(Z+(A.width+2-Z)*B),top:A.height-Math.ceil(U*0.72),width:J,height:U,seed:42,agentMode:"deep",glyphSet:"dotField",primaryColor:{r:255,g:225,b:102},secondaryColor:{r:255,g:125,b:34},timeOffset:8},Q),z=Um0({id:"top",left:Math.round((A.width-F)/2),top:Math.round(I+(G-I)*B),width:F,height:X,seed:42,agentMode:"rush",glyphSet:"dotField",primaryColor:{r:140,g:38,b:0},secondaryColor:{r:255,g:225,b:102},timeOffset:12},Q),W=[Ym0(V,null),Ym0(K,null)];if(B>0||$)W.push(Ym0(z,$?"top":null));return W.filter((C)=>aq4(C,{left:0,top:0,width:A.width,height:A.height}))}function Um0(A,Q){let $=Rm0(A.seed*0.013+A.timeOffset*0.071,1);return{...A,primaryColor:Nq4(A.primaryColor,Q,$),secondaryColor:Nq4(A.secondaryColor,Q,$+0.34)}}function Nq4(A,Q,$){let B=Y56(Q/Hq4+$),E=0.5+Math.sin((Q/Hq4+$)*Math.PI*2)*0.5;return jm0(A,B,0.16+E*0.08)}function Y56(A){let Q=Rm0(A,1)*f80.length,$=Math.floor(Q),B=($+1)%f80.length,E=f80[$]??Km0,D=f80[B]??Km0;return jm0(E,D,V9(Q-$))}function Z56(A){let Q=a2.length-1,$=i80(Q)-Zm0;return a80(W1((A-$)/Zm0,0,1))}function Ym0(A,Q){if(Q===null)return A;return{...A,clickableID:Q}}function F56({size:A,elapsedMs:Q,background:$,photoImages:B}){if(A.width<72||A.height<22)return[];return iq4({size:A,elapsedMs:Q}).map(({asset:E,focus:D,rect:J})=>{let U=B.get(E.id),Y=[];if(U)Y.push(new gX({image:U,width:J.width,height:J.height}));return Y.push(new pq4({progress:D,background:$})),new m1({left:J.left,top:J.top,width:J.width,height:J.height,child:new t1({fit:"expand",children:Y})})})}async function X56(A=Em0){let Q=new Map;return await Promise.all(Dm0.map(async($)=>{try{let B=await uK(Zq4($,A));Q.set($.id,B.image)}catch(B){S.debug("Failed to prefetch end-credit photo",{path:$.path,error:B})}})),Q}class pq4 extends XB{props;constructor(A){super();this.props=A}createRenderObject(){return new lq4(this.props)}updateRenderObject(A){A.update(this.props)}}class lq4 extends bA{props;constructor(A){super();this.props=A}update(A){this.props=A,this.markNeedsPaint()}performLayout(){let A=this._lastConstraints;oA(!!A,"performLayout called without constraints");let Q=A.constrain(A.biggest.width,A.biggest.height);this.setSize(Q.width,Q.height),super.performLayout()}paint(A,Q=0,$=0){let B=W1(this.props.progress,0,1);if(B>=0.999)return;let E=Math.floor(Q+this.offset.x),D=Math.floor($+this.offset.y),J=Math.floor(this.size.width),U=Math.floor(this.size.height);if(J<=0||U<=0)return;let Y=B*1.35-0.18;for(let Z=0;Z<U;Z++)for(let F=0;F<J;F++){if((F/Math.max(1,J-1)+Z/Math.max(1,U-1))/2<=Y)continue;A.setChar(E+F,D+Z," ",{bg:this.props.background},1)}}}function I56(A){let Q=[];for(let $ of Q56){let B=Dm0[$.photoIndex];if(!B)continue;let E=A-V56($);if(E<0||E>=Fq4)continue;let D=W1(E/xq4,0,1),J=W1((Fq4-E)/yq4,0,1);Q.push({cue:$,asset:B,focus:a80(Math.min(D,J))})}return Q}function iq4({size:A,elapsedMs:Q}){let $=c80({size:A,elapsedMs:Q}).map((B)=>oq4(B,1));return I56(Q).map((B)=>{let{cue:E,focus:D}=B,J=W1(Math.floor(A.width*E.widthRatio),20,E.maxWidth),U=W1(Math.round(J*0.61),10,18),Y=E.xRatio<0.5?-1:1,Z=Math.round((1-D)*4*Y),F=W1(Math.floor((A.width-J)*E.xRatio)+Z,1,Math.max(1,A.width-J-1)),X=W1(Math.floor((A.height-U)*E.yRatio),1,Math.max(1,A.height-U-2));return{...B,rect:G56({preferredLeft:F,preferredTop:X,imageWidth:J,imageHeight:U,cue:E,size:A,orbRects:$})}})}function G56({preferredLeft:A,preferredTop:Q,imageWidth:$,imageHeight:B,cue:E,size:D,orbRects:J}){let U=Math.max(1,D.width-$-1),Y=Math.max(1,D.height-B-2),Z=W1(Math.floor(D.width*0.5)-$-2,1,U),F=W1(Math.ceil(D.width*0.5)+2,1,U),X=W1(Math.floor((D.width-$)*(1-E.xRatio)),1,U),I=wq4([A,E.xRatio<0.5?Z:F,X,E.xRatio<0.5?F:Z,E.xRatio<0.5?1:U]),G=wq4([Q,W1(Q-B-2,1,Y),W1(Q+B+2,1,Y),W1(Math.floor(D.height*0.18),1,Y),W1(Math.floor(D.height*0.52),1,Y),W1(Math.floor(D.height*0.78)-B,1,Y)]),V={left:A,top:Q,width:$,height:B},K=qq4(V,J,A,Q);for(let z of I)for(let W of G){let C={left:z,top:W,width:$,height:B},H=qq4(C,J,A,Q);if(H>=K)continue;if(V=C,K=H,H===0)return V}return V}function qq4(A,Q,$,B){let E=Q.reduce((J,U)=>J+nq4(A,U)*100,0),D=Math.abs(A.left-$)+Math.abs(A.top-B);return E+D}function nq4(A,Q){let $=Math.max(0,Math.min(A.left+A.width,Q.left+Q.width)-Math.max(A.left,Q.left)),B=Math.max(0,Math.min(A.top+A.height,Q.top+Q.height)-Math.max(A.top,Q.top));return $*B}function aq4(A,Q){return nq4(A,Q)>0}function oq4(A,Q){return{left:A.left-Q,top:A.top-Q,width:A.width+Q*2,height:A.height+Q*2}}function wq4(A){return[...new Set(A)]}function V56(A){return Nm0+A.startOffsetMs}function K56({screen:A,absoluteX:Q,absoluteY:$,width:B,height:E,elapsedMs:D,foreground:J,mutedForeground:U}){let Y=l80(D),Z=tq4(E);for(let[F,X]of a2.entries()){let I=E/2+(F-Y)*Z;if(I<-Z||I>E+Z)continue;W56({screen:A,absoluteX:Q,absoluteY:$,width:B,height:E,elapsedMs:D,sceneIndex:F,scene:X,centerY:I,foreground:J,mutedForeground:U})}}function z56({screen:A,absoluteX:Q,absoluteY:$,width:B,height:E,elapsedMs:D,foreground:J}){if(E<5)return;let U=l80(D),Y=tq4(E),Z=E/2-U*Y,F=o56(t36,V9(W1(U/0.5,0,1)));if(F.trim()==="")return;let X=Math.round(E-2+(Z-E/2)*E/Y);if(X<0||X>=E)return;p80({screen:A,x:Q,y:$+X,width:B,text:F,maxTextWidth:B-2,style:{fg:J,dim:!0}})}function W56({screen:A,absoluteX:Q,absoluteY:$,width:B,height:E,elapsedMs:D,sceneIndex:J,scene:U,centerY:Y,foreground:Z,mutedForeground:F}){let X=Math.round(Y-(U.lines.length-1)/2),I=g56(Y,E),G=Math.max(8,B-(U.kind==="logo"?2:4)),V=U.kind==="logo"?Math.min(G,Math.max(...U.lines.map((K)=>RA(K)))):void 0;for(let[K,z]of U.lines.entries()){let W=U.kind==="logo"?d56({line:z,lineIndex:K,lineCount:U.lines.length,elapsedMs:D}):z,C=U.kind==="logo"?c56(K,U.lines.length,D):1;if(C<=0)continue;let H=X+K;if(H<0||H>=E)continue;let N=C56({scene:U,lineIndex:K,focusAlpha:I*C,foreground:Z,mutedForeground:F,elapsedMs:D});if(U.kind==="name"){y56({screen:A,x:Q,y:$+H,width:B,height:E,text:W,maxTextWidth:G,style:N,focusAlpha:I*C,sceneIndex:J,elapsedMs:D});continue}p80({screen:A,x:Q,y:$+H,width:B,text:W,maxTextWidth:G,blockWidth:V,style:N})}}function C56({scene:A,lineIndex:Q,focusAlpha:$,foreground:B,mutedForeground:E,elapsedMs:D}){switch(A.kind){case"logo":return{fg:L$(Q===A.lines.length-1?n56(D):n2,$),bold:!0};case"name":return{fg:L$(B,$),bold:!0};case"message":return Q===0?{fg:L$(gq,$),bold:!0}:{fg:L$(E,$)}}}function H56({screen:A,absoluteX:Q,absoluteY:$,width:B,height:E,game:D,background:J,mutedForeground:U,warning:Y,keybind:Z}){let F=Math.min(D.arenaWidth,Math.max(1,B-2)),X=Math.min(D.arenaHeight,Math.max(1,E-Fm0-bq4)),I=Q+Math.max(0,Math.floor((B-F)/2)),G=$+Fm0,V=m80(D);N56({screen:A,x:Q+2,y:$+1,score:D.score,highScore:D.highScore,keybind:Z,mutedForeground:U});let K=bq[0].length,z=Math.floor(D.elapsedMs/420)%K;if(D.introElapsedMs>=Vq4){if(D.saucer)b80(A,I+Math.round(D.saucer.x),G+D.saucer.y,a36,{fg:L$(s36,1),bold:!0});for(let W of D.invaders)w56({screen:A,x:I+Math.round(W.x),y:G+W.y,playTop:G,playHeight:X,frame:z,kind:W.kind,color:u56({game:D,invader:W,playerY:V})})}if(D.introElapsedMs>=Vq4+220)P56({screen:A,left:I,top:G,playWidth:F,playerY:V,barrierDamage:D.barrierDamage});for(let W of D.playerBullets){if(W.y<0||W.y>=X)continue;K7(A,I+W.x,G+W.y,"│",{fg:L$(gK,1),bold:!0})}for(let W of D.enemyBullets){if(W.y<0||W.y>=X)continue;K7(A,I+W.x,G+W.y,gq4,{fg:L$(Y,0.92),bold:!0})}if(O56({screen:A,left:I,top:G,playHeight:X,warning:Y,effects:D.effects}),D.playerExplosionElapsedMs!==null)v56({screen:A,centerX:I+Math.round(D.playerX)+Math.floor(NT/2),topY:G+V,elapsedMs:D.playerExplosionElapsedMs});else if(!D.gameOver&&D.introElapsedMs>=m36)b80(A,I+Math.round(D.playerX),G+V,Gm0,{fg:L$(gK,1),bold:!0});if(T56({screen:A,absoluteX:Q,absoluteY:$,width:B,height:E,game:D,mutedForeground:U,keybind:Z}),q56({screen:A,absoluteX:Q,absoluteY:$,width:B,height:E,game:D,background:J}),!D.gameOver||D.gameOverElapsedMs<d36)return;p80({screen:A,x:Q,y:$+Math.floor(E/2),width:B,text:"GAME OVER",maxTextWidth:B,style:{fg:L$(gq,1),bold:!0}})}function N56({screen:A,x:Q,y:$,score:B,highScore:E,keybind:D,mutedForeground:J}){Mm0({screen:A,x:Q,y:$,hints:[{key:"score",label:` ${B.toString().padStart(4,"0")}`},{key:"high",label:` ${E.toString().padStart(4,"0")}`}],keybind:D,mutedForeground:J})}function q56({screen:A,absoluteX:Q,absoluteY:$,width:B,height:E,game:D,background:J}){if(D.introElapsedMs>=Gq4)return;let U=o80(W1(D.introElapsedMs/Gq4,0,1)),Y=U*Math.hypot(B,E)*0.72,Z=Q+D.revealX,F=$+D.revealY;for(let I=0;I<E;I++)for(let G=0;G<B;G++){if(Math.hypot(Q+G-Z,($+I-F)*1.7)<=Y)continue;A.setChar(Q+G,$+I," ",{bg:J},1)}if(U<=0.04)return;let X=18;for(let I=0;I<X;I++){let G=Math.PI*2*I/X+U*1.4,V=(G9(I,D.revealX+D.revealY)%100/100-0.5)*4,K=Math.round(Z+Math.cos(G)*(Y+V)),z=Math.round(F+Math.sin(G)*(Y+V)/1.7),W=I%3===0?"✦":I%3===1?"·":"*",C=I%3===0?n2:I%3===1?gK:gq;K7(A,K,z,W,{fg:L$(C,1-U*0.35),bold:!0})}}function w56({screen:A,x:Q,y:$,playTop:B,playHeight:E,frame:D,kind:J,color:U}){let Y=bq[0],F=bq[J%bq.length]??Y,X=F[D%F.length]??F[0];for(let[I,G]of X.entries()){let V=$+I;if(V<B||V>=B+E)continue;K7(A,Q,V,G,{fg:L$(U,1),bold:!0})}}function u56({game:A,invader:Q,playerY:$}){let B=V9((840-Aw4(A))/680),E=W1((Q.y-1)/Math.max(1,$-7),0,1),D=V9((E-0.18)/0.58),J=W1(B*0.34+D*0.86,0,1),U=M56(Q.kind);if(J<0.34)return hq(U,Sl,V9(J/0.34));if(J<0.66)return hq(Sl,n2,V9((J-0.34)/0.32));return hq(n2,gq,V9((J-0.66)/0.34))}function M56(A){if(A===0)return Vm0;if(A===1)return hq(Vm0,Sl,0.45);return Sl}function O56({screen:A,left:Q,top:$,playHeight:B,warning:E,effects:D}){for(let J of D){if(J.y<0||J.y>=B)continue;let U=W1(J.elapsedMs/hq4,0,1);if(J.kind==="alienExplosion"){L56({screen:A,x:Q+J.x,y:$+J.y,progress:U});continue}let Y=j56(J.kind,U,E),Z=R56(J.kind,U);K7(A,Q+J.x,$+J.y,Z,Y)}}function L56({screen:A,x:Q,y:$,progress:B}){let E=1-B*0.72,D=B<0.5?n2:gq;b80(A,Q,$,o36,{fg:L$(D,E),bold:B<0.82})}function j56(A,Q,$){let B=1-Q*0.72;return{fg:L$(A==="enemyShot"?$:A==="playerImpact"?n2:gq,B),bold:Q<0.65}}function R56(A,Q){if(A==="enemyShot")return gq4;return Q<0.38?"✹":Q<0.72?"✦":"·"}function P56({screen:A,left:Q,top:$,playWidth:B,playerY:E,barrierDamage:D}){for(let J of Lm0({width:B,playerY:E}))for(let[U,Y]of _l.entries()){let Z=0;for(let F of Q4(Y)){if(F!==" "&&!n80(D,J.x+Z,J.y+U))K7(A,Q+J.x+Z,$+J.y+U,F,{fg:L$(r36,1),bold:!0});Z+=UQ(F)}}}function T56({screen:A,absoluteX:Q,absoluteY:$,width:B,height:E,game:D,mutedForeground:J,keybind:U}){if(E<2)return;let Y=$+E-2;for(let X=1;X<D.livesRemaining;X++)K7(A,Q+2+(X-1)*2,Y,n36,{fg:L$(gK,1),bold:!0});let Z=D.gameOver?[{key:"enter",label:" retry"},{key:"esc",label:" to go back to work"}]:[{key:"←/→",label:" move"},{key:"enter",label:" fire"},{key:"esc",label:" to go back to work"}],F=Z.reduce((X,I,G)=>X+RA(I.key)+RA(I.label)+(G>0?3:0),0);Mm0({screen:A,x:Q+Math.max(2,B-F-2),y:Y,hints:Z,keybind:U,mutedForeground:J})}function Mm0({screen:A,x:Q,y:$,hints:B,keybind:E,mutedForeground:D}){let J=Q;for(let[U,Y]of B.entries()){if(U>0)K7(A,J,$," · ",{fg:L$(D,0.58)}),J+=3;K7(A,J,$,Y.key,{fg:L$(E,1),bold:!0}),J+=RA(Y.key),K7(A,J,$,Y.label,{fg:L$(D,0.82)}),J+=RA(Y.label)}}function v56({screen:A,centerX:Q,topY:$,elapsedMs:B}){let E=W1(B/Xm0,0,1);if(E>=1)return;let D=RA(Gm0[0]??""),J=Q-Math.floor(D/2),U=(1-V9(E/0.34))*(B%132<66?1:0.42);if(U>0.05)b80(A,J,$,Gm0,{fg:L$(hq(gK,n2,V9(E/0.24)),U),bold:!0});let Y=14;for(let Z=0;Z<Y;Z++){let F=G9(Z,503)%24/100,X=W1((E-F)/Math.max(0.1,1-F),0,1);if(X<=0||X>=1)continue;if(G9(Z,Math.floor(B/74))%5===0)continue;let I=J+G9(Z,617)%Math.max(1,D),G=$+G9(Z,739)%qm0,V=Math.round((G9(Z,853)%3-1)*X*1.4),K=Math.round((G9(Z,977)%3-1)*0.5-X*1.2),z=I+V,W=G+K,C=zq4[G9(Z,Math.floor(B/90))%zq4.length]??"·",H=(1-V9(X))*(0.32+G9(Z,877)%22/100),N=hq(gK,n2,0.18+V9(X)*0.34);K7(A,z,W,C,{fg:L$(N,H),bold:!1})}}function _56(A,Q){if(A===0)return[1,2,4,64][Q]??0;return[8,16,32,128][Q]??0}function S56(A){return String.fromCharCode(10240+A)}function VZ(A){let Q=Math.max(0,...A.map((D)=>D.length)),$=Q+Q%2,B=A.length+(A.length%4===0?0:4-A.length%4),E=[];for(let D=0;D<B;D+=4){let J="";for(let U=0;U<$;U+=2){let Y=0;for(let Z=0;Z<4;Z++){let F=A[D+Z]??"";for(let X=0;X<2;X++){if(F[U+X]!=="#")continue;Y|=_56(X,Z)}}J+=Y===0?" ":S56(Y)}E.push(J)}return E}function k56(A,Q,$,B,E,D){let J=Math.min(3,Math.floor(E/5));for(let U=0;U<J;U++){let Y=0.32-U*0.09;A.fill(Q,$+U,B,1," ",{bg:L$(D,Y)}),A.fill(Q,$+E-U-1,B,1," ",{bg:L$(D,Y)})}}function f56({screen:A,absoluteX:Q,absoluteY:$,width:B,height:E,mutedForeground:D,keybind:J}){if(E<3)return;let U=[{key:"esc",label:" to go back to work"}],Y=RA(U[0]?.key??"")+RA(U[0]?.label??""),Z=Q+Math.max(0,Math.floor((B-Y)/2)),F=$+E-2;Mm0({screen:A,x:Z,y:F,hints:U,keybind:J,mutedForeground:D})}function x56({screen:A,absoluteX:Q,absoluteY:$,width:B,height:E,keybind:D,mutedForeground:J}){if(E<3)return;let U=$+E-2,Y="Paused — j/k or ↑/↓ to step, ",Z="Enter",F=" to continue",X=RA(Y)+RA(Z)+RA(F),I=Q+Math.max(0,Math.floor((B-X)/2)),G=[{text:"Paused — ",color:J,alpha:0.92,bold:!0},{text:"j/k",color:D,alpha:1,bold:!0},{text:" or ",color:J,alpha:0.92,bold:!0},{text:"↑/↓",color:D,alpha:1,bold:!0},{text:" to step, ",color:J,alpha:0.92,bold:!0},{text:Z,color:D,alpha:1,bold:!0},{text:F,color:J,alpha:0.92,bold:!0}];for(let V of G)K7(A,I,U,V.text,{fg:L$(V.color,V.alpha),bold:V.bold}),I+=RA(V.text)}function y56({screen:A,x:Q,y:$,width:B,height:E,text:D,maxTextWidth:J,style:U,focusAlpha:Y,sceneIndex:Z,elapsedMs:F}){let X=h56({text:D,sceneIndex:Z,elapsedMs:F,width:B,height:E});if(!X){p80({screen:A,x:Q,y:$,width:B,text:D,maxTextWidth:J,style:U});return}let I=o7(D,J),G=Q4(I),V=RA(I),K=Q+Math.max(0,Math.floor((B-V)/2));for(let[z,W]of G.entries()){let C=UQ(W);if(C<=0)continue;let H=b56({index:z,pulseRange:X,baseStyle:U,focusAlpha:Y});K7(A,K,$,W,H),K+=C}}function b56({index:A,pulseRange:Q,baseStyle:$,focusAlpha:B}){let E=uq4({pulseRange:Q,focusAlpha:B,bold:$.bold===!0,highlight:!1}),D=uq4({pulseRange:Q,focusAlpha:B,bold:!0,highlight:!0});if(Q.kind==="entrance"){if(A<Q.start)return $;if(A<Q.end)return D;return E}if(A<Q.start)return E;if(A<Q.end)return D;return $}function uq4({pulseRange:A,focusAlpha:Q,bold:$,highlight:B}){let E=B?Math.max(Q,0.72):Q;return{fg:L$({type:"rgb",value:A.color},E),bold:$}}function h56({text:A,sceneIndex:Q,elapsedMs:$,width:B,height:E}){let D=i80(Q),J=D-T36-vl;if(Q>0){let V=D-g80(Q-1);if($>=V&&$<J)return{kind:"entrance",start:Number.NEGATIVE_INFINITY,end:Number.NEGATIVE_INFINITY,color:x80({width:B,height:E,elapsedMs:$,position:"bottom"})}}let U=$-J,Y=Mq4({text:A,localElapsedMs:U});if(Y)return{...Y,kind:"entrance",color:x80({width:B,height:E,elapsedMs:$,position:"bottom"})};if(Q>=a2.length-1)return null;let Z=Math.max(0,g80(Q)-v36-vl),F=$-(D+h80(Q)+Z),X=Mq4({text:A,localElapsedMs:F});if(X)return{...X,kind:"exit",color:x80({width:B,height:E,elapsedMs:$,position:"top"})};let I=D+h80(Q)+Z+vl,G=D+Om0(Q);if($>=I&&$<G)return{kind:"exit",start:Number.POSITIVE_INFINITY,end:Number.POSITIVE_INFINITY,color:x80({width:B,height:E,elapsedMs:$,position:"top"})};return null}function Mq4({text:A,localElapsedMs:Q}){if(Q<0||Q>=vl)return null;let $=Q4(A).length,B=Math.max(7,Math.ceil($*0.7)),E=a80(Q/vl),D=Math.floor(E*($+B))-Math.floor(B/2);return{start:D,end:D+B}}function x80({width:A,height:Q,elapsedMs:$,position:B}){let E=B==="bottom"?"large":"small",D=c80({size:{width:A,height:Q},elapsedMs:$}).find((J)=>J.id===E);if(!D)return Km0;return B==="bottom"?D.primaryColor:D.secondaryColor}function p80({screen:A,x:Q,y:$,width:B,text:E,maxTextWidth:D,blockWidth:J,style:U}){let Y=o7(E,D),Z=RA(Y),X=Q+Math.max(0,Math.floor((B-(J??Z))/2));K7(A,X,$,Y,U)}function b80(A,Q,$,B,E){for(let[D,J]of B.entries())K7(A,Q,$+D,J,E)}function K7(A,Q,$,B,E){let D=Q;for(let J of Q4(B)){let U=UQ(J);if(U<=0)continue;A.setChar(D,$,J,E,U),D+=U}}function g56(A,Q){let $=Math.abs(A-Q/2),B=Math.max(1,Q*0.42);return W1(1-$/B,0.08,1)}function m56(A){return o80(W1((A-Tq4)/vq4,0,1))}function rq4(A){return o80(W1((A-_q4)/Sq4,0,1))}function d56({line:A,lineIndex:Q,lineCount:$,elapsedMs:B}){let E=sq4(Q,$,B);if(Q===$-1)return l56(A,E,B);return p56(A,E,Q)}function c56(A,Q,$){return V9(sq4(A,Q,$))}function sq4(A,Q,$){if(A===Q-1)return rq4($);let B=m56($),E=A/Math.max(1,Q-2)*0.2;return o80(W1((B-E)/0.72,0,1))}function p56(A,Q,$){let B=Q4(A);if(Q>=0.999)return A;return B.map((E,D)=>{let J=UQ(E);if(J<=0)return"";let U=D/Math.max(1,B.length-1)*0.86+$%3*0.018;if(Q>=U)return E;if(Q>=U-0.055&&E.trim()!=="")return"▒".repeat(J);return" ".repeat(J)}).join("")}function l56(A,Q,$){let B=Q4(A),E=B.findIndex((U)=>U.trim()!=="");if(E===-1)return a56(A);let D=B.slice(0,E).join(""),J=B.slice(E).join("");return`${D}${i56(J,Q,$)}`}function i56(A,Q,$){let B=Q4(A);if(Q>=0.999)return A;let E=V9(Q),D=Math.min(B.length,Math.floor(E*B.length)),J=B.slice(0,D).join(""),U=B.slice(D);if(Q<=0.04||U.length===0)return`${J}${Wm0(U)}`;let Y=["▌","▐","▖","▘"],Z=Y[Math.floor($/120)%Y.length]??"▌";return`${J}${Z}${Wm0(U.slice(1))}`}function n56(A){let Q=rq4(A),$=0.5+Math.sin(A/145)*0.5;return hq(gK,n2,W1(V9(Q)*0.24+$*0.16,0,0.46))}function a56(A){return Wm0(Q4(A))}function Wm0(A){return A.map((Q)=>" ".repeat(Math.max(0,UQ(Q)))).join("")}function o56(A,Q){if(Q<=0)return A;return Q4(A).map(($,B)=>{if($.trim()==="")return $;if(r56(B)>=Q)return $;return" ".repeat(Math.max(1,UQ($)))}).join("")}function r56(A){return G9(A+1,919)%1000/1000}function l80(A){let Q=Math.max(0,A-Nm0),$=0;for(let B=0;B<a2.length-1;B++){let E=Om0(B);if(Q<$+E){let D=Q-$,J=W1((D-h80(B))/g80(B),0,1);return B+a80(J)}$+=E}return a2.length-1}function tq4(A){return Math.max(_36,Math.floor(A*S36))}function hK(){return i80(a2.length-1)+P36}function s56(A){return Math.round(l80(A))}function t56(A){if(A>=a2.length-1)return hK();return i80(A)}function i80(A){let Q=Nm0;for(let $=0;$<A;$++)Q+=Om0($);return Q}function Om0(A){return h80(A)+g80(A)}function h80(A){return A===a2.length-2?R36:kq4}function g80(A){return A===a2.length-2?Zm0:fq4}function e56(A){return{width:Math.max(1,A.width-2),height:Math.max(1,A.height-Fm0-bq4)}}function eq4(A){return{width:A.arenaWidth,height:A.arenaHeight}}function Cm0(A={width:78,height:28},Q={}){let $=Q.wave??1,B=Q.score??0,E=Math.max(Q.highScore??0,B);return{arenaWidth:A.width,arenaHeight:A.height,playerX:Qw4(A.width),heldLeft:!1,heldRight:!1,heldFire:!1,lastMoveDirection:0,legacyMoveHoldMs:0,introElapsedMs:Q.introElapsedMs??wm0,revealX:Q.revealX??Math.floor(A.width/2),revealY:Q.revealY??Math.floor(A.height/2),marchStepCount:0,fireElapsedMs:0,playerBullets:[],enemyBullets:[],barrierDamage:[],effects:[],invaders:A76(A,$),saucer:null,saucerElapsedMs:0,direction:1,stepElapsedMs:0,enemyShotElapsedMs:0,elapsedMs:Q.elapsedMs??0,score:B,highScore:E,wave:$,livesRemaining:Q.livesRemaining??c36,playerExplosionElapsedMs:null,gameOver:!1,gameOverElapsedMs:0}}function A76(A,Q){let $=[],B=W1(Math.floor((A.height-14)/3)+Math.floor((Q-1)/4),3,5),E=W1(Math.floor((A.width-8)/(k80+2)),6,11),D=Math.max(k80+2,Math.floor((A.width-8)/Math.max(1,E))),J=(E-1)*D+k80,U=Math.max(2,Math.floor((A.width-J)/2));for(let Y=0;Y<B;Y++)for(let Z=0;Z<E;Z++)$.push({x:U+Z*D,y:3+Y*(HT+1),kind:Y===0?0:Y<=2?1:2,width:k80});return $}function Q76(A,Q){let $=[...A.invaders],B=[...A.playerBullets],E=[...A.enemyBullets],D=[...A.barrierDamage],J=Z76(A.effects,Q),U=A.score,Y=A.highScore,Z=A.livesRemaining,F=A.saucer,X=A.saucerElapsedMs,I=A.playerExplosionElapsedMs===null?null:A.playerExplosionElapsedMs+Q,G=A.gameOver,V=A.gameOver?A.gameOverElapsedMs+Q:0,K=A.introElapsedMs+Q,z=K>=wm0,W=z&&!G&&I===null,C=W?V76(A):0,H=$76(A,Q,C),N=!1,w=m80(A),u=W&&(A.heldLeft||A.heldRight)?A.legacyMoveHoldMs:Math.max(0,A.legacyMoveHoldMs-Q),L=Math.min(4,Math.floor((A.elapsedMs+Q)/Iq4)-Math.floor(A.elapsedMs/Iq4));for(let b=0;b<L;b++){let p=[];for(let a of B){let X0={...a,y:a.y-1};if(X0.y<0)continue;let t=Oq4({arenaWidth:A.arenaWidth,playerY:w,barrierDamage:D,bullet:X0});if(t){D=t,J=CT(J,{x:X0.x,y:X0.y,kind:"playerImpact"});continue}if(F&&E76(X0,F)){F=null,X=0,J=CT(J,{x:X0.x,y:X0.y,kind:"playerImpact"}),U+=i36;continue}let Z0=$.findIndex((R0)=>B76(X0,R0));if(Z0===-1){p.push(X0);continue}let K0=$[Z0];if(!K0)continue;$=$.filter((R0,B0)=>B0!==Z0),J=CT(J,{x:Math.round(K0.x),y:K0.y,kind:"alienExplosion"}),U+=10}B=p;let n=[];for(let a of E){let X0={...a,y:a.y+1};if(X0.y>=A.arenaHeight)continue;let t=Oq4({arenaWidth:A.arenaWidth,playerY:w,barrierDamage:D,bullet:X0});if(t){D=t,J=CT(J,{x:X0.x,y:X0.y,kind:"enemyImpact"});continue}if(W&&J76(X0,H,w)){N=!0,J=CT(J,{x:X0.x,y:X0.y,kind:"enemyImpact"});continue}n.push(X0)}E=n}let R=W&&A.heldFire?A.fireElapsedMs+Q:0;while(R>=Jm0&&W&&!N){let b=B.length,p=Hm0({...A,playerX:H,playerBullets:B,effects:J});if(B=[...p.playerBullets],J=[...p.effects],R-=Jm0,B.length===b){R=Math.min(R,Jm0);break}}let _=A.elapsedMs+Q,P=A.direction,f=z?A.stepElapsedMs+Q:A.stepElapsedMs,h=A.marchStepCount,x=Aw4({...A,elapsedMs:_,score:U});if(z&&!G&&f>=x&&$.length>0){f%=x,h++;let b=Math.min(...$.map((X0)=>X0.x)),p=Math.max(...$.map((X0)=>X0.x+X0.width-1)),n=P>0&&p>=A.arenaWidth-2||P<0&&b<=1,a=h%g36===0;if(n||a)P=P===1?-1:1,$=$.map((X0)=>({...X0,y:X0.y+1}));else $=$.map((X0)=>({...X0,x:X0.x+P}))}if(D=U76({arenaWidth:A.arenaWidth,playerY:w,barrierDamage:D,invaders:$}),$.length===0){let b=U+100;return Cm0(eq4(A),{score:b,highScore:Math.max(Y,b),wave:A.wave+1,elapsedMs:_,livesRemaining:Z})}let v=z?A.enemyShotElapsedMs+Q:A.enemyShotElapsedMs,k=F76({...A,elapsedMs:_,score:U});while(z&&!G&&I===null&&v>=k&&E.length<y36&&$.length>0){v-=k;let b=X76($,H);E=[...E,b],J=CT(J,{...b,kind:"enemyShot"})}if(z&&!G){let b=D76({game:A,saucer:F,saucerElapsedMs:X,deltaMs:Q});F=b.saucer,X=b.saucerElapsedMs}let c=$.some((b)=>b.y+HT>=w-1);if(z&&!G&&I===null&&(N||c))Z=Math.max(0,Z-1),I=0,R=0;if(I!==null&&I>=Xm0)if(Z>0&&!G)I=null,H=Qw4(A.arenaWidth),E=[];else G=!0,V=Math.max(V,I-Xm0);Y=Math.max(Y,U);let d=G||I!==null;return{...A,playerX:H,heldLeft:d?!1:A.heldLeft,heldRight:d?!1:A.heldRight,heldFire:d?!1:A.heldFire,lastMoveDirection:d||!A.heldLeft&&!A.heldRight&&u<=0?0:A.lastMoveDirection,legacyMoveHoldMs:d?0:u,introElapsedMs:K,marchStepCount:G?0:h,fireElapsedMs:d?0:R,playerBullets:B,enemyBullets:E,barrierDamage:D,effects:J,invaders:$,saucer:F,saucerElapsedMs:X,direction:P,stepElapsedMs:f,enemyShotElapsedMs:v,elapsedMs:_,score:U,highScore:Y,livesRemaining:Z,playerExplosionElapsedMs:I,gameOver:G,gameOverElapsedMs:V}}function $76(A,Q,$){if($===0)return A.playerX;let B=Q/b36*$;return K76(A,A.playerX+B)}function B76(A,Q){return A.y>=Q.y&&A.y<Q.y+HT&&A.x>=Q.x&&A.x<Q.x+Q.width}function E76(A,Q){return A.y>=Q.y&&A.y<Q.y+p36&&A.x>=Q.x&&A.x<Q.x+Im0}function D76({game:A,saucer:Q,saucerElapsedMs:$,deltaMs:B}){if(!Q){let Z=$+B;if(Z<l36)return{saucer:null,saucerElapsedMs:Z};let F=A.wave%2===0?-1:1;return{saucer:{x:F===1?-Im0:A.arenaWidth,y:0,direction:F},saucerElapsedMs:0}}let E=$+B,D=Math.min(6,Math.floor(E/Kq4));E%=Kq4;let J={...Q,x:Q.x+Q.direction*D},U=-Im0-1,Y=A.arenaWidth+1;if(J.x<U||J.x>Y)return{saucer:null,saucerElapsedMs:0};return{saucer:J,saucerElapsedMs:E}}function J76(A,Q,$){let B=Math.round(Q);return A.y>=$&&A.y<$+qm0&&A.x>=B&&A.x<B+NT}function Lm0({width:A,playerY:Q}){let $=RA(_l[0]??""),B=_l.length,E=A>=64?4:3,D=Math.max(HT+6,Q-7);return Array.from({length:E},(J,U)=>({x:Math.round((U+0.5)*A/E-$/2),y:D,width:$,height:B}))}function Oq4({arenaWidth:A,playerY:Q,barrierDamage:$,bullet:B}){for(let E of Lm0({width:A,playerY:Q})){if(B.x<E.x||B.x>=E.x+E.width||B.y<E.y||B.y>=E.y+E.height)continue;let D=_l[B.y-E.y],J=D?Q4(D)[B.x-E.x]:void 0;if(!J||J===" ")continue;if(n80($,B.x,B.y))continue;return Y76($,B.x,B.y)}return null}function U76({arenaWidth:A,playerY:Q,barrierDamage:$,invaders:B}){let E=[...$];for(let D of Lm0({width:A,playerY:Q}))for(let J of B){let U=Math.round(J.x),Y=Math.max(D.x,U),Z=Math.min(D.x+D.width,U+J.width),F=Math.max(D.y,J.y),X=Math.min(D.y+D.height,J.y+HT);if(Y>=Z||F>=X)continue;let I=bq[J.kind%bq.length]?.[0]??bq[0][0];for(let G=F;G<X;G++){let V=Q4(_l[G-D.y]??""),K=Q4(I[G-J.y]??"");for(let z=Y;z<Z;z++){let W=V[z-D.x],C=K[z-U];if(!W||W===" "||!C||C===" ")continue;if(!n80(E,z,G))E.push({x:z,y:G})}}}return E}function Y76(A,Q,$){let B=[...A];for(let[E,D]of[[0,0],[-1,0],[1,0],[0,1]]){let J=Q+E,U=$+D;if(!n80(B,J,U))B.push({x:J,y:U})}return B}function Z76(A,Q){return A.map(($)=>({...$,elapsedMs:$.elapsedMs+Q})).filter(($)=>$.elapsedMs<hq4)}function CT(A,Q){return[...A,{...Q,elapsedMs:0}]}function n80(A,Q,$){return A.some((B)=>B.x===Q&&B.y===$)}function Aw4(A){return Math.max(150,850-A.wave*38-A.score*0.52-A.elapsedMs/260)}function F76(A){return Math.max(220,820-A.wave*38-A.score*0.42-A.elapsedMs/240)}function X76(A,Q){let $=Math.round(Q)+Math.floor(NT/2),B=A.reduce((E,D)=>{let J=Math.abs(E.x+Math.floor(E.width/2)-$),U=Math.abs(D.x+Math.floor(D.width/2)-$);if(U<J)return D;if(U===J&&D.y>E.y)return D;return E});return{x:B.x+Math.floor(B.width/2),y:B.y+HT}}function I76(A){if(H76(A))return-1;if(N76(A))return 1;return 0}function Lq4(A,Q,$){if(!kl(A))return A;let B=Q===-1?$:A.heldLeft,E=Q===1?$:A.heldRight,D=A.lastMoveDirection;if($)D=Q;else if(D===Q)D=B?-1:E?1:0;return{...A,heldLeft:B,heldRight:E,lastMoveDirection:D,legacyMoveHoldMs:$?A.legacyMoveHoldMs:0}}function jq4(A,Q){if(!kl(A))return A;return{...A,heldFire:Q,fireElapsedMs:Q?A.fireElapsedMs:0}}function G76(A,Q){if(!kl(A))return A;return{...A,lastMoveDirection:Q,legacyMoveHoldMs:h36}}function kl(A){return A.introElapsedMs>=wm0&&!A.gameOver&&A.playerExplosionElapsedMs===null}function V76(A){if(A.heldLeft&&A.heldRight)return A.lastMoveDirection;if(A.heldLeft)return-1;if(A.heldRight)return 1;return A.legacyMoveHoldMs>0?A.lastMoveDirection:0}function Hm0(A){if(!kl(A))return A;if(A.playerBullets.length>=x36)return A;let Q=Math.round(A.playerX)+Math.floor(NT/2),$=A.playerBullets.filter((B)=>B.x===Q&&B.y>=m80(A)-5).length;return{...A,playerBullets:[...A.playerBullets,{x:Q,y:m80(A)-1-Math.min(4,$)}]}}function K76(A,Q){return W1(Q,1,Math.max(1,A.arenaWidth-NT-1))}function Qw4(A){return Math.floor((A-NT)/2)}function m80(A){return Math.max(1,A.arenaHeight-qm0-2)}function a80(A){return A<0.5?4*A*A*A:1-(-2*A+2)**3/2}function o80(A){return 1-(1-A)**3}function z76(A){return s$(A,"Enter")||s$(A," ")||s$(A,"Space")}function W76(A){return s$(A,"j")||s$(A,"ArrowDown")||s$(A,"Down")}function C76(A){return s$(A,"k")||s$(A,"ArrowUp")||s$(A,"Up")}function H76(A){return s$(A,"a")||s$(A,"w")||s$(A,"ArrowLeft")||s$(A,"Left")}function N76(A){return s$(A,"d")||s$(A,"ArrowRight")||s$(A,"Right")}function Rq4(A){return s$(A,"Enter")||s$(A," ")||s$(A,"Space")}function s$(A,Q){return!A.shiftKey&&!A.ctrlKey&&!A.altKey&&!A.metaKey&&A.key===Q}function Pq4(A){return!A.altKey&&!A.metaKey&&A.ctrlKey&&A.key.toLowerCase()==="c"}function mq(A,Q,$){return{type:"rgb",value:{r:A,g:Q,b:$}}}function hq(A,Q,$){let B=W1($,0,1);if(A.type!=="rgb"||Q.type!=="rgb")return B<0.5?A:Q;return{type:"rgb",value:jm0(A.value,Q.value,B)}}function jm0(A,Q,$){let B=W1($,0,1);return{r:Math.round(A.r+(Q.r-A.r)*B),g:Math.round(A.g+(Q.g-A.g)*B),b:Math.round(A.b+(Q.b-A.b)*B)}}function L$(A,Q){let $=W1(Q,0,1);switch(A.type){case"default":return{type:"default",alpha:$};case"index":return{type:"index",value:A.value,alpha:$};case"rgb":return{type:"rgb",value:A.value,alpha:$};case"none":return A}}function W1(A,Q,$){return Math.min($,Math.max(Q,A))}function Rm0(A,Q){return(A%Q+Q)%Q}function V9(A){let Q=W1(A,0,1);return Q*Q*(3-2*Q)}function G9(A,Q){let $=A*374761393+Q*668265263;return $=($^$>>13)*1274126177,($^$>>16)>>>0}function q76(){if(d80()||!y80.stdout.isTTY)return;G1.instance.tuiInstance.enableKittyKeyboard({reportEventTypes:!0,reportAllKeys:!0})}function w76(){if(d80()||!y80.stdout.isTTY)return;G1.instance.tuiInstance.disableKittyKeyboard()}function d80(){return y80.env.NODE_ENV==="test"||!!y80.env.VITEST}var u76=[{keys:["Enter","Esc"],label:"continue"}];class Pm0 extends eA{props;constructor(A){super(A.key===void 0?{}:{key:A.key});this.props=A}build(A){let{existingExecutorPid:Q,onChoice:$}=this.props;return new E1({header:"Thread Already Running",tone:"warning",minWidth:64,maxWidth:80,footer:u76,autofocus:!1,onDismiss:()=>$("watch"),child:new VQ({autofocus:!0,debugLabel:"ExecutorAlreadyConnectedDialogContinue",onKey:(B)=>{if(B.key!=="Enter")return"ignored";return $("watch"),"handled"},child:new D0({text:new g(M76(Q))})})})}}function M76(A){return[A===null?"This thread is already open and active in another Amp.":`This thread is already open and active in another Amp (PID: ${A})`,"","You can watch and control the thread here, but the other Amp will run the commands and tools."].join(`
|
|
2785
2785
|
`)}class Tm0 extends d0{createState(){return new $w4}}class $w4 extends m0{timer=null;initState(){super.initState(),this.timer=setInterval(()=>{if(this.mounted)this.setState()},250)}dispose(){if(this.timer)clearInterval(this.timer);this.timer=null,super.dispose()}build(A){let Q=e0.of(A),{app:$,colors:B}=Q,E=b$.instance.debugDumpFocusTree(),D=b$.getRecentKeystrokes(),J={dim:new A0({color:B.foreground,dim:!0}),label:new A0({color:B.foreground}),scope:new A0({color:$.command,bold:!0}),primary:new A0({color:$.keybind,bold:!0}),focusChain:new A0({color:$.toolSuccess}),error:new A0({color:$.toolError}),heading:new A0({color:$.keybind,bold:!0}),meta:new A0({color:$.fileReference,dim:!0})},U=[];U.push(new g("Focus Inspector",J.heading)),U.push(new g(` ctrl+t to toggle
|
|
2786
2786
|
`,J.dim)),U.push(new g("▶",J.primary)),U.push(new g(" primary ",J.dim)),U.push(new g("●",J.focusChain)),U.push(new g(" in chain ",J.dim)),U.push(new g("◇",J.scope)),U.push(new g(" scope",J.dim)),U.push(new g(`
|
|
@@ -2876,7 +2876,7 @@ ${nK(Q.diff)}`:Q.diff??A.diff}}function P96(A){let Q=[],$=new Set,B=A.split(`
|
|
|
2876
2876
|
|
|
2877
2877
|
`),new g(O90.join("/"),new A0({color:$.app.keybind})),new g(` ${L90(Q)}`,new A0({color:$.colors.foreground,dim:!0}))])})}class yd0 extends d0{props;debugLabel="ThreadContinuationPicker";constructor(A){super();this.props=A}createState(){return new xM4}}class xM4 extends m0{spinner=new _5;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(A){if(this.isSwitchingThread===A)return;this.setState(()=>{this.isSwitchingThread=A})}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(A){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(A){let{props:Q}=this.widget,$=this.isBusy,B=`${this.spinner.toBraille()} Loading threads...`,E=Q.filterByWorkspace&&Q.currentWorkspaceURI?Q.threads.filter((C)=>!C.workspaceURI||C.workspaceURI===Q.currentWorkspaceURI):Q.threads;if(Q.excludeCurrentThread&&Q.currentThreadID)E=E.filter((C)=>C.id!==Q.currentThreadID);let D=Q.recentThreadIDs||[],J=new Set(D),U=Q.currentThreadID,Y=[...E].sort((C,H)=>{if(U){if(C.id===U)return-1;if(H.id===U)return 1}let N=D.indexOf(C.id),w=D.indexOf(H.id);if(N!==-1&&w!==-1)return N-w;if(N!==-1)return-1;if(w!==-1)return 1;return 0}),Z=mD6(Y),F=Math.max(0,...Z.map((C)=>C.description.timeAgo.length)),X=Z.some((C)=>C.usesThreadActors)?3:0,I=e0.of(A),G=new mA({padding:c0.symmetric(0,1),child:new pQ({child:new D0({text:new g("",new A0({color:I.colors.foreground,dim:!0}),[new g(O90.join("/"),new A0({color:I.colors.primary,dim:!0})),new g(` ${Q.filterByWorkspace?"for":"to"} ${L90(Q.filterByWorkspace===!0)}`,new A0({color:I.colors.foreground,dim:!0}))])})})}),V="",K=null,z=(C)=>{if(C!==V)V=C,K=D3(C);return K};return new j5({items:Z,getLabel:(C)=>`${C.title} ${C.id}`,acceptOnClick:!0,filterItem:(C,H)=>{let N=z(H);if(N)return C.id.toLowerCase()===N.toLowerCase();return!0},normalizeQuery:(C)=>z(C)?"":C,onAccept:async(C,H)=>{if(!Q.onSelect||this.isSwitchingThread)return;let N=Q.onSelect(C.id,H);if(!cD6(N))return;this.setSwitchingThread(!0);try{await N}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Q.onDismiss,onSelectionChange:(C)=>{if(Q.onSelectionChange?.(C),Q.previewController){if(C)Q.previewController.select(C.id)}},title:Q.title,showBorder:Q.showBorder,enabled:!$,isLoading:$,hidePromptWhenLoading:!0,loadingText:B,emptyStateText:Q.hasError?"Failed to load threads":void 0,emptyStateWidget:Q.hasError?void 0:(C)=>xd0(C,Q.filterByWorkspace===!0),maxRenderItems:200,footer:$||Q.hasError||Q.showInlineWorkspaceFilterHint===!1?void 0:G,renderItem:(C,H,N,w)=>{let u=e0.of(w),{app:L,colors:R}=u,_=H?L.selectionBackground:void 0,P=H?L.selectionForeground:R.foreground,f=R.mutedForeground,h=(a,X0,t=f)=>new y0({width:X0,child:OA.end([new D0({text:new g(a,new A0({color:t}))})])}),x=Q.threadViewStates[C.id],v=[],k=C.relationshipType==="handoff",c=new cl({connectorColor:R.mutedForeground});if(C.depth>0){let a=[],X0=C.ancestorsAreLast.slice(1);for(let K0 of X0)a.push(new g(c.getAncestorPrefix(K0),new A0({color:c.connectorColor,dim:c.connectorDim})));let t=C.isLast?c.elbow:c.tee,Z0=c.getConnectorText(t);a.push(new g(Z0,new A0({color:c.connectorColor,dim:c.connectorDim}))),v.push(new D0({text:new g("",void 0,a)}))}let d=[],b=U===C.id?new g("(current) ",new A0({color:R.success})):J.has(C.id)?new g("(visited) ",new A0({color:R.foreground,dim:!0})):null;if(b)d.push(new D0({text:b}));if(kM4(x))d.push(new kd0),d.push(new y0({width:1}));let p=C.title;if(C.relationshipType==="fork"){let a=p.match(/^Forked\((\d+)\): /);if(a)p=p.slice(a[0].length);else while(p.startsWith("Forked: "))p=p.slice(8);d.push(new D0({text:new g("[fork] ",new A0({color:R.primary}))}))}else if(k)d.push(new D0({text:new g("[handoff] ",new A0({color:R.accent}))}));if(d.push(new P4({child:new D0({text:new g(p,new A0({color:P})),overflow:"ellipsis",maxLines:1})})),d.push(new y0({width:2})),C.diffStats&&(C.diffStats.added>0||C.diffStats.changed>0||C.diffStats.deleted>0)){let a=H?{success:f,warning:f,destructive:f}:R;d.push(...dD6(C.diffStats.added,C.diffStats.changed,C.diffStats.deleted,a)),d.push(new y0({width:2}))}if(d.push(h(C.description.timeAgo,F)),X>0)d.push(new y0({width:2})),d.push(h(C.usesThreadActors?"neo":"",X,C.usesThreadActors&&!H?L.command:f));return new GA({decoration:_?{color:_}:void 0,padding:c0.symmetric(2,0),child:new OA({children:[...v,...d]})})}})}}function pD6(A,Q=Date.now()){return Q-A>86400000}function yM4(A,Q,$=Date.now()){let B=[],E=[];for(let J of A){let U=Q(J);if(pD6(U.lastActivityAt,$))E.push(J);else B.push(J)}let D=(J)=>J.toSorted((U,Y)=>{let Z=Q(U),F=Q(Y),X=F.createdAt-Z.createdAt;if(X!==0)return X;return Z.id.localeCompare(F.id)});return[D(B),D(E)].filter((J)=>J.length>0)}function vT(A){let $=new Date().getTime()-A.getTime(),B=Math.floor($/60000),E=Math.floor(B/60),D=Math.floor(E/24),J=Math.floor(D/7),U=Math.floor(D/30);if(B<1)return"Just now";if(B<60)return`${B}m ago`;if(E<24)return`${E}h ago`;if(D<7)return`${D}d ago`;if(J<=4)return`${J}w ago`;return`${U}mo ago`}function _T(A){if(A==="Just now")return"1m";return A.replace(/ ago$/,"")}function j90(A){return A!==void 0&&A!=="idle"&&A!=="error"}function bM4(A){return A.updatedAt?Date.parse(A.updatedAt)||0:0}function lD6(A){return A.createdAt??bM4(A)}function rK(A,Q=Date.now()){return yM4(A,($)=>({id:$.id,createdAt:lD6($),lastActivityAt:bM4($)}),Q)}var iD6=150,nD6=120;class hM4 extends d0{thread;activeThreadID;constructor(A,Q){super();this.thread=A;this.activeThreadID=Q}createState(){return new gM4}}class gM4 extends m0{threadController=null;initState(){this.threadController=this.createThreadController(this.widget.thread)}didUpdateWidget(A){if(A.thread!==this.widget.thread)this.threadController?.dispose(),this.threadController=this.createThreadController(this.widget.thread)}dispose(){this.threadController?.dispose(),this.threadController=null,super.dispose()}build(){let A=this.threadController;if(!A)return new y0;return new el({threadController:A,copyOnSelectEnabled:!1,activeThreadID:this.widget.activeThreadID,editingMessageId:null,editingController:null,onSubmitEdit:()=>{},autofocus:!1})}createThreadController(A){let Q=A.agentMode??i9.SMART.key,$=Z90(A.messages,{threadID:A.id,...Y90(Q),isWorking:!1});return new gl(SM4(...$))}}function tl(A){return rK(A.filter((Q)=>!Q.parentThreadID&&!Q.archived).map((Q)=>{let $=Q.title||"Untitled",B=new Date(Q.userLastInteractedAt),E=Q.env?.initial.trees?.[0]?.uri;return{id:Q.id,title:$,createdAt:Q.created,updatedAt:B.toISOString(),description:{timeAgo:vT(B),title:$,shortThreadID:Q.id.slice(-8)},diffStats:Q.summaryStats?.diffStats,workspaceURI:E,relationships:Q.relationships,agentMode:Q.agentMode,details:{messageCount:Q.summaryStats?.messageCount},archived:Q.archived}})).flat()}class mM4 extends d0{props;constructor(A){super();this.props=A}createState(){return new dM4}}class dM4 extends m0{threadViewStates={};currentWorkspaceURI=U4(g0.file(process.cwd()));threads=[];isLoading=!0;hasError=!1;filterByWorkspace=!0;tailLoadState={status:"idle",threadID:null,thread:null};tailLoadToken=0;tailLoadLimit=0;tailLoadDebounceTimer=null;handleKeyEvent=(A)=>{if(A.ctrlKey&&A.key.toLowerCase()==="t"||A.altKey&&A.key.toLowerCase()==="w")return this.setState(()=>{this.filterByWorkspace=!this.filterByWorkspace}),"handled";return"ignored"};initState(){super.initState(),this.loadThreadSummaries()}dispose(){this.clearTailLoadDebounceTimer(),this.tailLoadToken++,super.dispose()}async loadThreadSummaries(){try{let A=await this.widget.props.loadThreads(),Q=tl(A);if(!this.mounted)return;this.setState(()=>{this.threads=Q,this.isLoading=!1,this.hasError=!1})}catch(A){if(S.error("Failed to load threads for Neo command palette",{error:A}),!this.mounted)return;this.setState(()=>{this.isLoading=!1,this.hasError=!0})}}scheduleThreadTailLoad(A,Q){this.clearTailLoadDebounceTimer(),this.tailLoadToken++,this.tailLoadDebounceTimer=setTimeout(()=>{if(this.tailLoadDebounceTimer=null,this.mounted)this.loadThreadTail(A,Q)},iD6)}clearTailLoadDebounceTimer(){if(this.tailLoadDebounceTimer)clearTimeout(this.tailLoadDebounceTimer),this.tailLoadDebounceTimer=null}loadThreadTail(A,Q){let $=this.widget.props.loadThreadTail;if(!$)return;if(this.tailLoadState.threadID===A&&this.tailLoadLimit===Q&&this.tailLoadState.status!=="error")return;let B=++this.tailLoadToken;this.tailLoadLimit=Q;let E=this.tailLoadState.threadID===A?this.tailLoadState.thread:null;this.setState(()=>{this.tailLoadState={status:"loading",threadID:A,thread:E}}),$(A,Q).then((D)=>{if(!this.mounted||B!==this.tailLoadToken)return;this.setState(()=>{this.tailLoadState={status:"loaded",threadID:A,thread:D}})}).catch((D)=>{if(S.error("Failed to load thread tail for Neo thread picker",{error:D,threadID:A}),!this.mounted||B!==this.tailLoadToken)return;this.setState(()=>{this.tailLoadState={status:"error",threadID:A,thread:E}})})}buildTailPreview(A){let Q=e0.of(A),{colors:$}=Q,B=this.tailLoadState.thread,E=this.tailLoadState.status==="loading"?"Loading Preview…":this.tailLoadState.status==="error"?"Preview Unavailable":"Thread Preview",D=[new D0({text:new g(E,new A0({color:$.mutedForeground})),maxLines:1}),new y0({height:1})];if(!B||B.messages.length===0)D.push(new D0({text:new g("No messages to preview",new A0({color:$.mutedForeground})),maxLines:1}));else D.push(new P4({child:new hM4(B,this.widget.props.activeThreadID)}));return new GA({padding:c0.symmetric(1,1),child:new UA({children:D})})}build(A){let Q=X4.of(A),$=Q.size.width<nD6,B=Math.max(1,Math.floor(Q.size.height)),E=[{keys:O90,label:L90(this.filterByWorkspace)},{keys:["Esc"],label:"close"}];return new E1({header:this.widget.props.title,autofocus:!1,bodyFit:{kind:"fill",modalRows:Math.max(12,Math.floor(Q.size.height)-4)},footer:E,maxWidth:140,minWidth:Math.min(100,Math.max(0,Math.floor(Q.size.width)-4)),onDismiss:this.widget.props.onDismiss,child:new VQ({onKey:this.handleKeyEvent,debugLabel:"ThreadSwitchPicker",child:new DZ({direction:$?"vertical":"horizontal",children:[new P4({child:new yd0({threads:this.threads,showBorder:!1,showInlineWorkspaceFilterHint:!1,onSelect:this.widget.props.onSelect,onDismiss:this.widget.props.onDismiss,onSelectionChange:(D)=>{if(D)cQ.instance.addPostFrameCallback(()=>{if(this.mounted)this.scheduleThreadTailLoad(D.id,B)})},isLoading:this.isLoading,hasError:this.hasError,currentWorkspaceURI:this.currentWorkspaceURI,filterByWorkspace:this.filterByWorkspace,threadViewStates:this.threadViewStates,currentThreadID:this.widget.props.activeThreadID??void 0,excludeCurrentThread:this.widget.props.excludeCurrentThread})}),new y0({width:$?void 0:1,height:$?1:void 0}),new P4({child:new GA({decoration:new v1(void 0,U1.all(new Y1(e0.of(A).colors.border,1,"rounded"))),child:this.buildTailPreview(A)})})]})})})}}function cM4(A,Q){return new mM4({title:Q.title,activeThreadID:A.activeThreadID,loadThreads:A.loadThreads,loadThreadTail:A.loadThreadTail,excludeCurrentThread:Q.excludeCurrentThread,onSelect:async($)=>{try{await A.onSelectThread($),A.onThreadSelected()}catch(B){Q.logFailure($,B)}},onDismiss:A.onDismiss})}function bd0(A){return cM4(A,{title:"Switch Thread",excludeCurrentThread:!1,logFailure:(Q,$)=>{S.error("Failed to switch thread",{error:$,threadID:Q})}})}function hd0(A){return cM4(A,{title:"Mention Thread",excludeCurrentThread:!0,logFailure:(Q,$)=>{S.error("Failed to mention thread",{error:$,threadID:Q})}})}function pM4(A,Q){let{graphemes:$,cursorPosition:B}=A,E=-1;for(let D=B-2;D>=0;D--)if($[D]==="@"&&$[D+1]==="@"){E=D;break}if(E!==-1){let D=$.slice(0,E).join(""),J=$.slice(B).join(""),U=B===$.length,Y=`@${Q}${U?" ":""}`;A.text=D+Y+J,A.cursorPosition=E+Q4(Y).length;return}A.insertText(`@${Q} `)}var aD6=O4("prompt.history",{noun:"prompt",verb:"history",description:"Restore a previous prompt",defaultKey:"ctrl+r",status:(A)=>A.isHistoryAvailable()&&A.isEffectiveEnabled()?{type:"enabled"}:{type:"disabled",reason:"Prompt editor is not available"}},(A,{dismiss:Q})=>{if(!A.isHistoryAvailable()||!A.isEffectiveEnabled()){Q();return}A.showPromptHistoryPicker(),Q()}),oD6=O4("prompt.openInEditor",{noun:"prompt",verb:"open in editor",description:"Edit prompt in $EDITOR",defaultKey:"ctrl+g",status:(A)=>A.isEffectiveEnabled()?{type:"enabled"}:{type:"disabled",reason:"Prompt editor is not available"}},async(A,{dismiss:Q})=>{if(!A.isEffectiveEnabled()){Q();return}try{await vd0(A.editorController())}finally{Q()}}),rD6=O4("prompt.clear",{noun:"prompt",verb:"clear",description:"Clear input",status:(A)=>{if(!A.isEffectiveEnabled())return{type:"disabled",reason:"Prompt editor is not available"};return A.editorController().text.trim().length>0?{type:"enabled"}:{type:"disabled",reason:"No prompt text to clear"}}},(A,{dismiss:Q})=>{if(!A.isEffectiveEnabled()){Q();return}A.editorController().clear(),Q()}),sD6=O4("prompt.copySelection",{noun:"prompt",verb:"copy selection",description:"Copy selection",status:(A)=>{if(!A.isEffectiveEnabled())return{type:"disabled",reason:"Prompt editor is not available"};return A.editorController().hasSelection?{type:"enabled"}:{type:"disabled",reason:"No selected text to copy"}}},(A,{context:Q,dismiss:$})=>{N4.maybeInvoke(Q,new IB(A.editorController().selectedText)),$()}),tD6=O4("prompt.pasteImageFromClipboard",{noun:"prompt",verb:"paste image from clipboard",description:"Paste image from clipboard",defaultKey:"ctrl+v",status:(A)=>{if(!A.isEffectiveEnabled())return{type:"disabled",reason:"Prompt editor is not available"};return A.imageCount()<B2?{type:"enabled"}:{type:"disabled",reason:`Maximum of ${B2} images per message`}}},async(A,{dismiss:Q})=>{Q(),await A.pasteImageFromClipboard()}),eD6=O4("thread.mention",{noun:"thread",verb:"mention",description:"Mention a thread",status:(A)=>A.isEffectiveEnabled()?{type:"enabled"}:{type:"disabled",reason:"Prompt editor is not available"}},(A,Q)=>{if(!A.isEffectiveEnabled()){Q.dismiss();return}A.mentionThread(Q)});function gd0(A,Q){return!A.ctrlKey&&!A.altKey&&!A.metaKey&&A.key===Q}class Ai extends d0{editorController;imageAttachmentsController;activeThreadID;enabled;onSubmitted;onEmptySubmitted;onUploadLockChange;focusNode;autofocus;minLines;textColor;fillAvailableHeight;topWidget;previousThreadIDForReference;onMentionPickerDismissHandlerChange;constructor(A){super();this.editorController=A.editorController,this.imageAttachmentsController=A.imageAttachmentsController,this.activeThreadID=A.activeThreadID,this.enabled=A.enabled,this.onSubmitted=A.onSubmitted,this.onEmptySubmitted=A.onEmptySubmitted,this.onUploadLockChange=A.onUploadLockChange,this.focusNode=A.focusNode,this.autofocus=A.autofocus,this.minLines=A.minLines,this.textColor=A.textColor,this.fillAvailableHeight=A.fillAvailableHeight??!1,this.topWidget=A.topWidget,this.previousThreadIDForReference=A.previousThreadIDForReference,this.onMentionPickerDismissHandlerChange=A.onMentionPickerDismissHandlerChange}createState(){return new lM4}}class lM4 extends m0{promptEditorFocusNode;autocompleteHandle={dismiss:()=>{}};pendingUploads=new Map;parkedSubmit=null;nextParkedSubmitId=0;imagePreviewOverlay=null;mentionPickerOverlay=null;promptHistoryPickerOverlay=null;removeImageAttachmentsListener=null;removeKeyInterceptor=null;unregisterCommands=null;historyIndex=-1;historyDraft=null;get imageEntries(){return this.widget.imageAttachmentsController.entries}get isUploadLocked(){return this.parkedSubmit!==null}get effectiveEnabled(){return this.widget.enabled&&!this.isUploadLocked}get history(){return TT.maybeOf(this.context)}initState(){this.promptEditorFocusNode=new PB({debugLabel:"PromptEditor"}),this.attachImageAttachmentsListener(this.widget.imageAttachmentsController),this.syncCommandRegistration(),this.removeKeyInterceptor=G1.instance.addKeyInterceptor((A)=>{if(this.promptHistoryPickerOverlay&&gd0(A,"Escape"))return this.dismissPromptHistoryPicker(),!0;if(this.mentionPickerOverlay&&gd0(A,"Escape"))return this.dismissMentionPicker(),!0;if(this.isUploadLocked&&this.promptEditorFocusNode.hasFocus&&gd0(A,"Escape"))return this.cancelPendingSubmit(),!0;return!1})}didUpdateWidget(A){if(A.imageAttachmentsController!==this.widget.imageAttachmentsController)this.removeImageAttachmentsListener?.(),this.removeImageAttachmentsListener=null,this.attachImageAttachmentsListener(this.widget.imageAttachmentsController);if(A.activeThreadID!==this.widget.activeThreadID){let Q=this.parkedSubmit;if(Q!==null&&Q.activeThreadID!==this.widget.activeThreadID)if(Q.activeThreadID===null&&this.widget.activeThreadID!==null)this.setState(()=>{this.parkedSubmit={...Q,activeThreadID:this.widget.activeThreadID}});else this.setParkedSubmit(null)}if(A.enabled!==this.widget.enabled)this.syncCommandRegistration()}dispose(){if(this.isUploadLocked)this.widget.onUploadLockChange(!1);this.dismissImagePreview(),this.dismissMentionPicker(),this.dismissPromptHistoryPicker(),this.removeImageAttachmentsListener?.(),this.removeImageAttachmentsListener=null,this.removeKeyInterceptor?.(),this.removeKeyInterceptor=null,this.unregisterCommands?.(),this.unregisterCommands=null,this.widget.onMentionPickerDismissHandlerChange?.(null),this.promptEditorFocusNode.dispose(),super.dispose()}createCommands(){let A={isHistoryAvailable:()=>Boolean(this.history),isEffectiveEnabled:()=>this.effectiveEnabled,editorController:()=>this.widget.editorController,imageCount:()=>this.imageEntries.length,showPromptHistoryPicker:()=>this.showPromptHistoryPicker(),pasteImageFromClipboard:()=>this.handlePasteImageFromClipboard(),mentionThread:(Q)=>this.mentionThread(Q)};return[aD6.bind(A),oD6.bind(A),rD6.bind(A),sD6.bind(A),tD6.bind(A),eD6.bind(A)]}registerCommands(){let A=sB.of(this.context),$=this.createCommands().map((B)=>A.register(B));return()=>{for(let B of $)B()}}syncCommandRegistration(){if(!this.widget.enabled){this.unregisterCommands?.(),this.unregisterCommands=null;return}if(this.unregisterCommands!==null)return;this.unregisterCommands=this.registerCommands()}navigateHistoryPrevious(){if(!this.history||this.isUploadLocked)return"handled";let A=this.history.previous();if(A!==null){if(this.historyIndex===-1)this.historyDraft=this.widget.editorController.text;this.historyIndex++,this.widget.editorController.text=A,this.widget.editorController.moveCursorToEnd()}return"handled"}mentionThread({controller:A,dismiss:Q}){A.pushWithDismiss(($)=>hd0({activeThreadID:this.widget.activeThreadID,loadThreads:()=>MQ.of(this.context).listThreads(),loadThreadTail:(B,E)=>MQ.of(this.context).loadThreadTail?.(B,E)??Promise.resolve(null),onSelectThread:(B)=>this.insertThreadMention(B),onDismiss:$,onThreadSelected:Q}))}showPromptHistoryPicker(){if(!this.history||!this.effectiveEnabled)return;this.dismissPromptHistoryPicker();let A=new aX(()=>new Sd0({entries:this.history?.getAll()??[],currentCwd:process.cwd(),onAccept:this.handlePromptHistorySelection,onDismiss:this.dismissPromptHistoryPicker}));this.promptHistoryPickerOverlay=A,ZJ.of(this.context).insert(A)}dismissPromptHistoryPicker=()=>{if(!this.promptHistoryPickerOverlay)return;this.promptHistoryPickerOverlay.remove(),this.promptHistoryPickerOverlay=null};handlePromptHistorySelection=(A)=>{if(!this.history||!this.effectiveEnabled){this.dismissPromptHistoryPicker();return}this.history.reset(),this.historyIndex=-1,this.historyDraft=null,this.widget.editorController.text=A,this.widget.editorController.moveCursorToEnd(),this.dismissPromptHistoryPicker()};navigateHistoryNext(){if(!this.history||this.isUploadLocked)return"handled";let A=this.history.next();if(A!==null)this.historyIndex--,this.widget.editorController.text=A,this.widget.editorController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.widget.editorController.text=this.historyDraft||"",this.widget.editorController.moveCursorToEnd(),this.historyDraft=null;return"handled"}attachImageAttachmentsListener(A){let Q=()=>{if(!this.mounted)return;this.setState()};A.addListener(Q),this.removeImageAttachmentsListener=()=>A.removeListener(Q)}handleDoubleAtTrigger=()=>{this.showMentionPicker()};showMentionPicker(){if(!this.effectiveEnabled)return;this.dismissMentionPicker();let A=new aX(()=>hd0({activeThreadID:this.widget.activeThreadID,loadThreads:()=>MQ.of(this.context).listThreads(),loadThreadTail:(Q,$)=>MQ.of(this.context).loadThreadTail?.(Q,$)??Promise.resolve(null),onSelectThread:(Q)=>{this.insertThreadMention(Q)},onDismiss:()=>this.dismissMentionPicker(),onThreadSelected:()=>this.dismissMentionPicker()}));this.mentionPickerOverlay=A,this.widget.onMentionPickerDismissHandlerChange?.(()=>this.dismissMentionPicker()),ZJ.of(this.context).insert(A)}dismissMentionPicker(){if(this.autocompleteHandle.dismiss(),this.mentionPickerOverlay)this.mentionPickerOverlay.remove(),this.mentionPickerOverlay=null,this.widget.onMentionPickerDismissHandlerChange?.(null)}insertThreadMention(A){if(!this.effectiveEnabled)return;pM4(this.widget.editorController,A)}acceptPreviousThreadHint=()=>{if(!this.effectiveEnabled)return;let A=this.widget.previousThreadIDForReference;if(!A)return;this.widget.editorController.text=`following: @${A} `};handleInsertImage=async(A)=>{return await this.tryInsertImage(A),!1};async tryInsertImage(A){if(this.isUploadLocked)return!1;if(this.imageEntries.length>=B2)return!1;let Q=await IM4(A);if(typeof Q==="string")return!1;let $=this.widget.imageAttachmentsController,B=Q.source.type==="base64",E=$.add(Q,{uploading:B});if(Q.source.type==="base64")this.uploadEntryInBackground(E,Q.source);return!0}handlePasteImageFromClipboard=async()=>{if(!this.effectiveEnabled)return;if(this.imageEntries.length>=B2){DQ.error(this.context,`Maximum of ${B2} images per message`);return}try{let A=await qM4();if(!A)return;if(!await this.tryInsertImage(A))DQ.error(this.context,"Failed to paste image from clipboard")}catch(A){S.error("Failed to paste image from clipboard",{error:A}),DQ.error(this.context,"Failed to paste image from clipboard")}};async uploadEntryInBackground(A,Q){let $=(async()=>{try{let{configService:B}=MQ.of(this.context),E=await zM4(Q,B);if(!this.mounted)return;let D=this.imageEntries.find((U)=>U.id===A);if(!D)return;let J=KM4(E)?D.image:{type:"image",source:{type:"url",url:E},sourcePath:D.image.sourcePath};this.widget.imageAttachmentsController.updateById(A,{image:J,uploading:!1})}catch(B){if(S.error("Failed to upload image attachment",{error:B}),!this.mounted)return;this.widget.imageAttachmentsController.updateById(A,{uploading:!1})}finally{this.pendingUploads.delete(A)}})();this.pendingUploads.set(A,$)}handlePopImage=()=>{if(this.isUploadLocked)return;let A=this.widget.imageAttachmentsController.popLast();if(A)this.pendingUploads.delete(A.id)};handleImageClick=(A)=>{if(this.isUploadLocked)return;let Q=this.imageEntries[A];if(!Q||Q.uploading)return;this.dismissImagePreview();let $=new aX(()=>new hl({image:Q.image,imageIndex:A,onDismiss:()=>this.dismissImagePreview(),onRemove:()=>{this.dismissImagePreview();let B=this.imageEntries[A];if(B)this.pendingUploads.delete(B.id);this.widget.imageAttachmentsController.removeAt(A)}}));this.imagePreviewOverlay=$,ZJ.of(this.context).insert($)};dismissImagePreview(){if(this.imagePreviewOverlay)this.imagePreviewOverlay.remove(),this.imagePreviewOverlay=null}handleSubmitted=(A)=>{if(this.isUploadLocked)return;if(A.trim()===":q"){N4.maybeInvoke(this.context,new vK);return}if(A.trim().length===0&&this.imageEntries.length===0){this.widget.onEmptySubmitted?.();return}if(this.pendingUploads.size>0){let Q=++this.nextParkedSubmitId;this.setParkedSubmit({id:Q,text:A,activeThreadID:this.widget.activeThreadID}),this.waitAndSubmit(Q).catch(($)=>{S.error("Failed to submit prompt after image uploads completed",{error:$})})}else this.submit(A)};submit(A){let Q=this.imageEntries.map((B)=>B.image),$=this.isUploadLocked;if(this.setState(()=>{this.parkedSubmit=null}),this.widget.imageAttachmentsController.clear(),$)this.widget.onUploadLockChange(!1);this.widget.onSubmitted(A,Q)}setParkedSubmit(A){let Q=this.isUploadLocked;this.setState(()=>{this.parkedSubmit=A});let $=A!==null;if(Q!==$)this.widget.onUploadLockChange($)}async waitAndSubmit(A){while(!0){if(await Promise.all([...this.pendingUploads.values()]),!this.mounted)return;let Q=this.parkedSubmit;if(Q===null||Q.id!==A)return;if(Q.activeThreadID!==this.widget.activeThreadID){this.setParkedSubmit(null);return}if(this.pendingUploads.size===0){this.submit(Q.text);return}}}cancelPendingSubmit(){if(this.parkedSubmit===null)return;this.setParkedSubmit(null),this.promptEditorFocusNode.requestFocus()}uploadingIndices(){let A=new Set;for(let Q=0;Q<this.imageEntries.length;Q++)if(this.imageEntries[Q]?.uploading)A.add(Q);return A}build(A){let Q=S4.of(A),$=new Map([[ic,new cA(()=>{return this.handlePasteImageFromClipboard(),"ignored"})]]),B=new Map([[wA.ctrl("v"),new ic]]);if(this.history)$.set(ac,new cA(()=>{return this.showPromptHistoryPicker(),"handled"})),$.set(y70,new cA(()=>this.navigateHistoryNext())),$.set(x70,new cA(()=>this.navigateHistoryPrevious())),B.set(wA.ctrl("n"),new y70),B.set(wA.ctrl("p"),new x70),B.set(wA.ctrl("r"),new ac);let E=new rQ({debugLabel:"PromptEditorShortcuts",shortcuts:B,child:new _d0({controller:this.widget.editorController,focusNode:this.promptEditorFocusNode,triggers:[new PT],autocompleteHandle:this.autocompleteHandle,completionBuilder:zT.of(A),autoOverlayPosition:!0,theme:Q.colorScheme,previousThreadId:this.widget.previousThreadIDForReference??void 0,onPreviousThreadHintAccepted:this.acceptPreviousThreadHint,onInsertImage:this.handleInsertImage,imageAttachments:this.imageEntries.map((J)=>J.image),popImage:this.handlePopImage,onImageClick:this.handleImageClick,uploadingImageIndices:this.uploadingIndices(),enabled:this.effectiveEnabled,onDoubleAtTrigger:this.handleDoubleAtTrigger,onSubmitted:this.handleSubmitted,fillAvailableHeight:this.widget.fillAvailableHeight,topWidget:this.widget.topWidget,autofocus:this.widget.autofocus,minLines:this.widget.minLines,textColor:this.widget.textColor})}),D=this.widget.focusNode?new E6({focusScopeNode:this.widget.focusNode,debugLabel:"EditorPanel",child:E}):E;return new N4({actions:$,child:D})}}class md0 extends d0{controller;activeThreadID;initialImages;onSubmitted;constructor(A){super();this.controller=A.controller,this.activeThreadID=A.activeThreadID,this.initialImages=A.initialImages,this.onSubmitted=A.onSubmitted}createState(){return new iM4}}class iM4 extends m0{imageAttachmentsController=new pq;initState(){this.imageAttachmentsController.setImages(this.widget.initialImages)}dispose(){super.dispose()}handleSubmit=(A,Q)=>{this.widget.onSubmitted(A,Q)};build(A){let Q=e0.of(A),$=Q.colors,B=Q.app.selectedMessage,E=[new g("esc",new A0({color:Q.app.keybind})),new g(" to cancel",new A0({color:$.foreground,dim:!0}))];return new E6({debugLabel:"Neo Message Editing",child:new up({child:new t1({children:[new GA({decoration:{color:$.background,border:U1.all(new Y1(B,2,"solid"))},padding:c0.only({left:1,right:1}),width:1/0,child:new Ai({editorController:this.widget.controller,imageAttachmentsController:this.imageAttachmentsController,activeThreadID:this.widget.activeThreadID,enabled:!0,onSubmitted:this.handleSubmit,onUploadLockChange:()=>{},autofocus:!0,minLines:1,textColor:B,previousThreadIDForReference:null})}),new m1({left:2,right:0,bottom:0,child:new D0({text:new g("",void 0,E)})})]})})})}}var R90=1,AJ6=60,QJ6=80;class el extends d0{threadController;copyOnSelectEnabled;activeThreadID;editingMessageId;editingController;onSubmitEdit;onLastVisibleMessageChange;autofocus;constructor(A){super();this.threadController=A.threadController,this.copyOnSelectEnabled=A.copyOnSelectEnabled,this.activeThreadID=A.activeThreadID,this.editingMessageId=A.editingMessageId,this.editingController=A.editingController,this.onSubmitEdit=A.onSubmitEdit,this.onLastVisibleMessageChange=A.onLastVisibleMessageChange,this.autofocus=A.autofocus??!1}createState(){return new sM4}}class sM4 extends m0{scrollController=new a6;listViewKey=new c3("message-view-list");tableOfContentsFocusNode=new a7({debugLabel:"NeoMessageTableOfContents"});threadControllerUnsubscription;expansionController=null;expansionSubscription=null;showThinking=!1;visibleEntries=[];tableOfContentsOpen=!1;tableOfContentsSignature="";tableOfContentsOriginalIndex=null;tableOfContentsHeadingKeys=[];tableOfContentsHideTimer=null;tableOfContentsNavigationOriginalIndex=null;tableOfContentsNavigationHovered=!1;tableOfContentsObservedScrollOffset=0;tableOfContentsSelectedIndex=0;visibleMessageReportScheduled=!1;initState(){this.setupThreadController(this.widget.threadController),this.scrollController.addListener(this.onScrollPositionChange),this.widget.threadController.onShowTableOfContents=this.showTableOfContents,this.widget.threadController.onTableOfContentsHoverEnd=this.scheduleTableOfContentsHide,this.widget.threadController.onToggleTableOfContents=this.toggleTableOfContents}didUpdateWidget(A){if(A.threadController!==this.widget.threadController)A.threadController.setHasTableOfContents(!1),A.threadController.onShowTableOfContents=null,A.threadController.onTableOfContentsHoverEnd=null,A.threadController.onToggleTableOfContents=null,this.unsubscribeCurrentThreadController(),this.setupThreadController(this.widget.threadController),this.widget.threadController.onShowTableOfContents=this.showTableOfContents,this.widget.threadController.onTableOfContentsHoverEnd=this.scheduleTableOfContentsHide,this.widget.threadController.onToggleTableOfContents=this.toggleTableOfContents}dispose(){this.unsubscribeCurrentThreadController(),this.expansionSubscription?.unsubscribe(),this.expansionSubscription=null,this.clearTableOfContentsHideTimer(),this.widget.threadController.setHasTableOfContents(!1),this.widget.threadController.onShowTableOfContents=null,this.widget.threadController.onTableOfContentsHoverEnd=null,this.widget.threadController.onToggleTableOfContents=null,this.scrollController.removeListener(this.onScrollPositionChange),this.scrollController.dispose(),this.tableOfContentsFocusNode.dispose()}build(A){let Q=e0.of(A),$=z9.of(A);if($!==this.expansionController)this.subscribeToExpansionController($);this.visibleEntries=oM4(this.widget.threadController.entries,this.showThinking);let B=this.visibleEntries,E=BJ6(B,this.listViewKey.getCurrentState(),this.scrollController,this.tableOfContentsNavigationOriginalIndex);if(this.widget.threadController.setHasTableOfContents(E!==null),E?.signature!==this.tableOfContentsSignature||E?.originalIndex!==this.tableOfContentsOriginalIndex){let U=this.tableOfContentsOpen&&this.tableOfContentsNavigationOriginalIndex!==null;this.tableOfContentsSignature=E?.signature??"",this.tableOfContentsOriginalIndex=E?.originalIndex??null,this.tableOfContentsOpen=U,this.tableOfContentsSelectedIndex=0,this.tableOfContentsNavigationHovered=!1,this.tableOfContentsHeadingKeys=E?.headings.map((Y,Z)=>new c3(`neo-message-toc-heading-${Z}`))??[]}let D=new Fd0({key:this.listViewKey,position:"bottom",autofocus:this.widget.autofocus,controller:this.scrollController,enableSelectionKeepAlive:!0,itemCount:B.length,itemKey:(U)=>new ZB(`message-view-entry-${B[U]?.originalIndex}`),itemBuilder:(U,Y)=>{let Z=B[Y],F=Z?.entry;if(oA(!!F,"MessageView missing transcript entry for realized list index"),!F)return new y0;return new mA({padding:c0.horizontal(1),child:this.entryToWidget(F,Z.originalIndex)})},itemSpacing:1,onVisibleItemsChange:(U)=>this.reportLastVisibleMessage(U,B)}),J=new t1({children:[new mA({padding:c0.only({right:R90}),child:D}),new m1({right:0,top:0,bottom:0,child:new y0({width:R90,child:new Ml({controller:this.scrollController,getScrollInfo:this.scrollbarInfo,thickness:R90,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack})})})]});return new t1({children:[new M5({child:J,copyOnSelectEnabled:this.widget.copyOnSelectEnabled,onCopy:this.onCopy,scrollController:this.scrollController,getScrollBounds:this.selectionScrollBounds}),...E&&this.tableOfContentsOpen?[this.buildTableOfContents(A,E)]:[]]})}onCopy=(A)=>{if(!A)return;N4.maybeInvoke(this.context,new IB(A))};reportLastVisibleMessage(A,Q){if(!this.widget.onLastVisibleMessageChange)return;for(let $=A.length-1;$>=0;$-=1){let B=Q[A[$].index]?.entry;if(!B)continue;if(P90(B))continue;let E=$J6(B);if(E!==void 0){this.widget.onLastVisibleMessageChange(E);return}}}scrollbarInfo=()=>{let A=Math.max(1,this.scrollController.viewportExtent);return{totalContent:this.scrollController.totalContentExtent,viewportSize:A,scrollOffset:this.scrollController.offset}};selectionScrollBounds=()=>{let A=this.listViewKey.currentElement?.renderObject;if(!(A instanceof bA))return null;let Q=A.localToGlobal({x:0,y:0});return{left:Q.x,top:Q.y,right:Q.x+A.size.width,bottom:Q.y+A.size.height}};subscribeToExpansionController(A){this.expansionSubscription?.unsubscribe(),this.expansionController=A,this.showThinking=rM4(A),this.expansionSubscription=A?.expanded$.subscribe({next:()=>{if(!this.mounted)return;let Q=rM4(A);if(this.showThinking===Q)return;this.setState(()=>{this.showThinking=Q})}})??null}entryToWidget(A,Q){if(A.type==="edit-tools-summary")return new wd0({tools:A.tools});if(A.type==="bash-tools-summary")return new al({summary:A});switch(A.type){case"message":if(A.role==="user"){let $=cd0(A.sourceMessageID);if($!==void 0&&$===this.widget.editingMessageId&&this.widget.editingController)return new md0({controller:this.widget.editingController,activeThreadID:this.widget.activeThreadID,initialImages:A.images,onSubmitted:(B,E)=>this.widget.onSubmitEdit($,B,E)});return new ud0({message:A,isSelected:Q===this.widget.threadController.selectedMessageIndex})}if(Q===this.tableOfContentsOriginalIndex)return new jT({message:A,headingKeys:this.tableOfContentsHeadingKeys});return new jT({message:A});case"tool":return new il(K90(A));case"activity-group":return new H90({group:A,childEntries:this.widget.threadController.lookupChildEntries(A.rowID),lookupChildEntries:this.widget.threadController.lookupChildEntries.bind(this.widget.threadController)});case"compaction":return new mA({padding:c0.only({left:2}),child:new D0({text:new g("Compacted",new A0({color:e0.of(this.context).colors.foreground,dim:!0,italic:!0}))})});case"thinking":return new nl({entry:A})}}setupThreadController(A){A.onSelectionChange=this.onSelectionChange,A.onScrollToTop=this.scrollToTop,A.onScrollToBottom=this.scrollToBottom,A.onPageUp=this.pageUp,A.onPageDown=this.pageDown,A.onHalfPageUp=this.halfPageUp,A.onHalfPageDown=this.halfPageDown,this.threadControllerUnsubscription=A.subscribe(this.onThreadControllerUpdate)}unsubscribeCurrentThreadController(){this.threadControllerUnsubscription?.()}scrollToTop=()=>{this.scrollController.animateTo(0,100)};scrollToBottom=()=>{this.scrollController.enableFollowMode(),this.scrollController.scrollToBottom()};pageUp=()=>{this.scrollController.animatePageUp()};pageDown=()=>{this.scrollController.animatePageDown()};halfPageUp=()=>{let A=this.scrollController.viewportExtent;if(A>0)this.scrollController.animatePageUp(Math.max(1,Math.floor(A/2)))};halfPageDown=()=>{let A=this.scrollController.viewportExtent;if(A>0)this.scrollController.animatePageDown(Math.max(1,Math.floor(A/2)))};onSelectionChange=(A)=>{if(A!==null){let Q=this.listViewKey.getCurrentState();oA(!!Q,"MessageView expected mounted ListViewState before scrolling");let $=oM4(this.widget.threadController.entries,this.showThinking).findIndex((E)=>E.originalIndex===A),B=Q.getEstimatedOffsetForIndex($===-1?A:$);this.scrollController.animateTo(B,{duration:150,curve:"easeInOutCubic"})}else this.scrollToBottom()};onThreadControllerUpdate=()=>{if(!this.mounted)return;this.setState(),this.scheduleLastVisibleMessageReport()};scheduleLastVisibleMessageReport(){if(!this.widget.onLastVisibleMessageChange||this.visibleMessageReportScheduled)return;this.visibleMessageReportScheduled=!0,cQ.instance.addPostFrameCallback(()=>{if(this.visibleMessageReportScheduled=!1,!this.mounted||!this.widget.onLastVisibleMessageChange)return;let A=this.listViewKey.getCurrentState()?.getVisibleItems();if(!A)return;this.reportLastVisibleMessage(A,this.visibleEntries)},"MessageView.last-visible-message-report")}buildTableOfContents(A,Q){let $=e0.of(A),B=new Y1($.colors.border,1,"rounded"),E=nM4(this.visibleEntries,Q.originalIndex),D=[];if(E.previous!==null)D.push(new iA({cursor:"pointer",onEnter:this.hoverTableOfContentsNavigation,onClick:()=>this.scrollToTableOfContentsMessage(E.previous.originalIndex),child:new D0({text:new g(`↑ ${E.previous.label}`,new A0({color:$.colors.secondary,dim:!0})),maxLines:1,overflow:"ellipsis"})}));for(let[J,U]of Q.headings.entries()){let Y=!this.tableOfContentsNavigationHovered&&J===this.tableOfContentsSelectedIndex;D.push(new iA({cursor:"pointer",onEnter:()=>this.selectTableOfContentsHeading(J),onClick:()=>this.scrollToHeading(J),child:new GA({padding:c0.horizontal(1),child:new D0({text:new g(`${Y?"› ":" "}${U.level===1?"# ":" ## "}${U.text}`,new A0({color:Y?$.colors.secondary:$.colors.foreground,bold:Y})),maxLines:1,overflow:"ellipsis"})})}))}if(Q.headings.length===0)D.push(new mA({padding:c0.horizontal(1),child:new D0({text:new g("— No Headings —",new A0({color:$.colors.foreground,dim:!0})),maxLines:1,overflow:"ellipsis"})}));if(E.next!==null)D.push(new iA({cursor:"pointer",onEnter:this.hoverTableOfContentsNavigation,onClick:()=>this.scrollToTableOfContentsMessage(E.next.originalIndex),child:new D0({text:new g(`↓ ${E.next.label}`,new A0({color:$.colors.secondary,dim:!0})),maxLines:1,overflow:"ellipsis"})}));return new m1({left:0,right:R90+1,bottom:0,child:new OA({mainAxisAlignment:"end",children:[new n6({fit:"loose",child:new iA({onEnter:this.focusTableOfContents,onExit:this.scheduleTableOfContentsHide,opaque:!1,child:new E6({focusScopeNode:this.tableOfContentsFocusNode,debugLabel:"NeoMessageTableOfContents",onKey:this.handleTableOfContentsKeyEvent,child:new h$({width:AJ6,padding:c0.horizontal(1),decoration:new v1($.colors.background,U1.all(B)),overlays:[{child:new D0({text:new g(" Outline ",new A0({color:$.colors.secondary,bold:!0})),maxLines:1,overflow:"ellipsis"}),position:"top",alignment:"left"}],child:new UA({crossAxisAlignment:"stretch",children:D})})})})})]})})}toggleTableOfContents=()=>{if(this.clearTableOfContentsHideTimer(),this.setState(()=>{this.tableOfContentsOpen=!this.tableOfContentsOpen,this.tableOfContentsNavigationOriginalIndex=null,this.tableOfContentsNavigationHovered=!1,this.tableOfContentsSelectedIndex=0}),this.tableOfContentsOpen)this.scheduleTableOfContentsFocus()};showTableOfContents=()=>{if(this.clearTableOfContentsHideTimer(),this.tableOfContentsOpen)return;this.setState(()=>{this.tableOfContentsOpen=!0,this.tableOfContentsNavigationHovered=!1,this.tableOfContentsSelectedIndex=0}),this.scheduleTableOfContentsFocus()};hideTableOfContents=()=>{this.clearTableOfContentsHideTimer(),this.setState(()=>{this.tableOfContentsOpen=!1,this.tableOfContentsNavigationOriginalIndex=null,this.tableOfContentsNavigationHovered=!1,this.tableOfContentsSelectedIndex=0})};scheduleTableOfContentsHide=()=>{this.clearTableOfContentsHideTimer(),this.tableOfContentsHideTimer=setTimeout(()=>{if(!this.mounted)return;this.hideTableOfContents()},QJ6)};clearTableOfContentsHideTimer=()=>{if(!this.tableOfContentsHideTimer)return;clearTimeout(this.tableOfContentsHideTimer),this.tableOfContentsHideTimer=null};scheduleTableOfContentsFocus(){cQ.instance.addPostFrameCallback(()=>{if(!this.mounted||!this.tableOfContentsOpen)return;this.tableOfContentsFocusNode.requestFocus()},"Neo outline focus")}focusTableOfContents=()=>{this.clearTableOfContentsHideTimer(),this.tableOfContentsFocusNode.requestFocus()};scrollToHeading(A){let $=this.tableOfContentsHeadingKeys[A]?.currentElement?.renderObject,B=this.listViewKey.currentElement?.renderObject;if(!($ instanceof bA)||!(B instanceof bA))return;let E=$.localToGlobal({x:0,y:0}),D=B.localToGlobal({x:0,y:0});this.scrollController.disableFollowMode(),this.scrollController.animateTo(this.scrollController.offset+E.y-D.y,{duration:150,curve:"easeInOutCubic"})}scrollToTableOfContentsMessage(A){if(A===null)return;let Q=this.visibleEntries.findIndex((B)=>B.originalIndex===A);if(Q===-1)return;let $=this.listViewKey.getCurrentState();if(!$)return;this.clearTableOfContentsHideTimer(),this.setState(()=>{this.tableOfContentsNavigationOriginalIndex=A}),this.scrollController.disableFollowMode(),this.scrollController.animateTo($.getEstimatedOffsetForIndex(Q),{duration:150,curve:"easeInOutCubic"})}selectTableOfContentsHeading(A){if(this.tableOfContentsSelectedIndex===A&&!this.tableOfContentsNavigationHovered)return;this.setState(()=>{this.tableOfContentsSelectedIndex=A,this.tableOfContentsNavigationHovered=!1})}hoverTableOfContentsNavigation=()=>{if(this.tableOfContentsNavigationHovered)return;this.setState(()=>{this.tableOfContentsNavigationHovered=!0})};handleTableOfContentsKeyEvent=(A)=>{if(A.eventType==="release")return"ignored";let Q=nM4(this.visibleEntries,this.tableOfContentsOriginalIndex);if(A.key==="ArrowUp"||A.key==="Up")return this.scrollToTableOfContentsMessage(Q.previous?.originalIndex??null),"handled";if(A.key==="ArrowDown"||A.key==="Down")return this.scrollToTableOfContentsMessage(Q.next?.originalIndex??null),"handled";if(this.tableOfContentsHeadingKeys.length===0){if(A.key==="Escape")return this.hideTableOfContents(),"handled";return"ignored"}let $=this.tableOfContentsHeadingKeys.length-1;if(A.key==="ArrowLeft"||A.key==="Left")return this.selectTableOfContentsHeading(Math.max(0,this.tableOfContentsSelectedIndex-1)),"handled";if(A.key==="ArrowRight"||A.key==="Right")return this.selectTableOfContentsHeading(Math.min($,this.tableOfContentsSelectedIndex+1)),"handled";if(A.key==="Enter")return this.scrollToHeading(this.tableOfContentsSelectedIndex),"handled";if(A.key==="Escape")return this.hideTableOfContents(),"handled";return"ignored"};onScrollPositionChange=()=>{if(!this.mounted)return;if(this.tableOfContentsObservedScrollOffset===this.scrollController.offset)return;this.tableOfContentsObservedScrollOffset=this.scrollController.offset,this.setState()}}function cd0(A){return S6.safeParse(A).data}function $J6(A){if(A.type==="message"){if(A.isStreaming)return;return cd0(A.sourceMessageID)}if(A.type==="compaction")return;return cd0(A.timestampLookupID)}function nM4(A,Q){if(Q===null)return{previous:null,next:null};let $=aM4(A,Q),B=[];for(let D of A){if(P90(D.entry))continue;if(!pd0(D.entry))continue;let J=aM4(A,D.originalIndex);if(B[B.length-1]?.promptOriginalIndex===J.promptOriginalIndex)B[B.length-1]=J;else B.push(J)}let E=B.findIndex((D)=>D.promptOriginalIndex===$.promptOriginalIndex);if(E===-1)return{previous:null,next:null};return{previous:B[E-1]??null,next:B[E+1]??null}}function aM4(A,Q){for(let $=A.length-1;$>=0;$-=1){let B=A[$];if(!B||B.originalIndex>=Q)continue;if(B.entry.type!=="message"||B.entry.role!=="user")continue;return{label:B.entry.text.replace(/\s+/g," ").trim()||"Previous prompt",originalIndex:Q,promptOriginalIndex:B.originalIndex}}return{label:"Previous response",originalIndex:Q,promptOriginalIndex:null}}function BJ6(A,Q,$,B){if(B!==null){let J=A.find((U)=>U.originalIndex===B);if(J&&!P90(J.entry)&&pd0(J.entry))return{headings:Lg0(J.entry.text),originalIndex:J.originalIndex,signature:J.entry.text}}let E=$.offset,D=E+$.viewportExtent;for(let J=A.length-1;J>=0;J-=1){let U=A[J]?.entry;if(!U||P90(U)||!pd0(U))continue;if(Q){let Z=Q.getEstimatedOffsetForIndex(J);if(Q.getEstimatedOffsetForIndex(J+1)<=E||Z>=D)continue}return{headings:Lg0(U.text),originalIndex:A[J].originalIndex,signature:U.text}}return null}function pd0(A){return A.type==="message"&&A.role==="assistant"&&A.isStreaming!==!0}function oM4(A,Q){let $=[];for(let E=0;E<A.length;E+=1){let D=A[E];if(!D)continue;if(!EJ6(D,Q))continue;$.push({entry:D,originalIndex:E})}let B=[];for(let E=0;E<$.length;E+=1){let D=$[E],J=D?.entry;if(!J)continue;if(dd0(J)&&dd0($[E+1]?.entry)){let U=[J.tool],Y=E,Z=$[Y+1]?.entry;while(dd0(Z))Y+=1,U.push(Z.tool),Z=$[Y+1]?.entry;B.push({entry:{type:"edit-tools-summary",tools:U},originalIndex:D.originalIndex}),E=Y;continue}B.push(D)}return B}function P90(A){return A.type==="edit-tools-summary"}function dd0(A){return A?.type==="tool"&&A.tool.kind==="file"}function EJ6(A,Q){if(A.type!=="thinking")return!0;return Q&&A.text.trim()!==""}function rM4(A){return A?.hasBeenToggled===!0&&A.expanded}J3();class nq extends eA{props;constructor(A){super();this.props=A}static rowText(A){return A.queuedMessage.content.filter(N00).map((Q)=>Q.text).join(" ").trim()}static imageCount(A){return A.queuedMessage.content.filter(H00).length}build(A){let{queuedMessages:Q,selectedIndex:$,enterToSteerMessageID:B,bottomRightLabel:E}=this.props,D=S4.of(A),J=e0.of(A),U=new Y1(D.colorScheme.border,1,"rounded"),Y=[];if(E)Y.push({child:E,position:"bottom",alignment:"right",offsetX:-1});let Z=Q.filter((K)=>K.steer),F=Q.filter((K)=>!K.steer),X=Z.length>0,I=F.length>0,G=[],V=0;if(X)G.push(...this.buildRows(Z,V,$,B??null,D,J)),V+=Z.length;if(X&&I)G.push(new QO4({borderSide:U}));if(I)G.push(...this.buildRows(F,V,$,B??null,D,J));return new h$({decoration:new v1(void 0,U1.all(U)),overlays:Y,child:new UA({mainAxisSize:"max",crossAxisAlignment:"stretch",children:G})})}buildRows(A,Q,$,B,E,D){return A.map((J,U)=>{let Y=Q+U;return new tM4({queuedMessage:J,visualIndex:Y,isSelected:Y===$,showEnterToSteerHint:B!==null&&J.queuedMessage.messageId===B&&!J.steer,theme:E,appTheme:D})})}}class tM4 extends eA{props;constructor(A){super();this.props=A}build(A){let{queuedMessage:Q,visualIndex:$,isSelected:B,showEnterToSteerHint:E,theme:D,appTheme:J}=this.props,U=Q.steer===!0,Y=B||U?D.colorScheme.foreground:D.colorScheme.mutedForeground,Z=new A0({color:Y,bold:B,dim:Q.pendingRemoval}),F=new A0({color:D.colorScheme.primary,bold:!0}),X=nq.rowText(Q),I=nq.imageCount(Q),G=new A0({color:D.colorScheme.success,dim:Q.pendingRemoval}),V=[];for(let z=0;z<I;z++)V.push(new g(`[${z+1}] `,G));let K=B?YJ6(D,J,U):UJ6(D,J,E);return new iA({cursor:o1.POINTER,onClick:()=>{N4.maybeInvoke(A,new ip($))},child:new mA({padding:c0.horizontal(1),child:new OA({children:[...V.length>0?[new D0({text:new g("",void 0,V),maxLines:1,overflow:"clip"})]:[],new P4({child:U?new eM4({text:`steering: ${X}`,baseStyle:Z,shimmerStyle:F}):new D0({text:new g("",void 0,[new g(X,Z)]),maxLines:1,overflow:"ellipsis"})}),...K?[new mA({padding:c0.only({left:3}),child:K})]:[]]})})})}}var ld0=10,DJ6=34;function JJ6(A){return 0.5-Math.cos(A*Math.PI)/2}class eM4 extends d0{props;constructor(A){super();this.props=A}createState(){return new AO4}}class AO4 extends m0{frame=0;intervalID=null;initState(){super.initState(),this.intervalID=setInterval(()=>{this.setState(()=>{this.frame++})},45)}dispose(){if(this.intervalID)clearInterval(this.intervalID),this.intervalID=null;super.dispose()}build(){let A=Q4(this.widget.props.text),Q=Math.max(5,Math.ceil(A.length/4)),$=this.frame%(ld0+DJ6),B=JJ6($/ld0),E=$<ld0?Math.floor(B*(A.length+Q))-Q:A.length,D=E+Q,J=A.map((U,Y)=>new g(U,Y>=E&&Y<D?this.widget.props.baseStyle.merge(this.widget.props.shimmerStyle):this.widget.props.baseStyle));return new D0({text:new g("",void 0,J),maxLines:1,overflow:"ellipsis"})}}function UJ6(A,Q,$){let B=new A0({color:A.colorScheme.mutedForeground,dim:!0});if(!$)return null;return new D0({text:new g("",void 0,[new g("Enter",new A0({color:Q.app.keybind})),new g(" to steer",B)]),maxLines:1,overflow:"clip"})}class QO4 extends eA{props;constructor(A){super();this.props=A}build(){return new GA({height:1,decoration:{border:new U1(this.props.borderSide)}})}}function YJ6(A,Q,$){let B=new A0({color:A.colorScheme.foreground}),E=new A0({color:Q.app.keybind}),D=$?[new g("Steering, ",B)]:[new g("Enter",E),new g(" to steer, ",B)];return new D0({text:new g("",void 0,[...D,new g("Backspace",E),new g(" to dequeue",B)]),maxLines:1,overflow:"clip"})}function $O4(A){let Q=[],$=[];for(let B of A)if(B.steer)Q.push(B);else $.push(B);return[...Q,...$]}E4();import ZJ6 from"node:path";var Qi="⚙";function T90(A,Q){let $=C6(A);if($.scheme!=="file")return $.toString();return $.fsPath.startsWith(Q+"/")?ZJ6.relative(Q,$.fsPath):$.fsPath}class id0 extends X6{onSizeChange;constructor({key:A,child:Q,onSizeChange:$}){super({key:A,child:Q});this.onSizeChange=$}createRenderObject(){return new BO4(this.onSizeChange)}updateRenderObject(A){A.updateCallback(this.onSizeChange)}}class BO4 extends bA{_onSizeChange;_lastReportedSize=null;_pendingReportedSize=null;_reportScheduled=!1;constructor(A){super();this._onSizeChange=A}updateCallback(A){this._onSizeChange=A}performLayout(){let A=this._lastConstraints;if(!A)return;let Q=this.children[0];if(!Q){let B=A.constrain(0,0);this.setSize(B.width,B.height),super.performLayout();return}Q.layout(A),Q.setOffset(0,0);let $=A.constrain(Q.size.width,Q.size.height);this.setSize($.width,$.height),this._scheduleSizeReport($),super.performLayout()}paint(A,Q=0,$=0){super.paint(A,Q,$)}_scheduleSizeReport(A){if(this._sizesEqual(this._lastReportedSize,A))return;if(this._pendingReportedSize=A,this._reportScheduled)return;this._reportScheduled=!0,cQ.instance.addPostFrameCallback(()=>{if(this._reportScheduled=!1,!this.attached||!this._pendingReportedSize)return;let Q=this._pendingReportedSize;if(this._pendingReportedSize=null,this._sizesEqual(this._lastReportedSize,Q))return;this._lastReportedSize=Q,this._onSizeChange(Q)},"MeasureSize.size-change")}_sizesEqual(A,Q){if(A===null||Q===null)return A===Q;return A.width===Q.width&&A.height===Q.height}}n5();var v90=220,FJ6=40,XJ6=5,nd0=30;class od0 extends eA{agentMode;label;leadingMarker;leadingMarkerColor;onLeadingMarkerClick;reasoningEffort;speedCostMultiplier;colorOverride;animate;reasoningEffortAnimation;horizontalPadding;constructor(A){super();this.agentMode=A.agentMode,this.label=A.label,this.leadingMarker=A.leadingMarker,this.leadingMarkerColor=A.leadingMarkerColor,this.onLeadingMarkerClick=A.onLeadingMarkerClick,this.reasoningEffort=A.reasoningEffort,this.speedCostMultiplier=A.speedCostMultiplier,this.colorOverride=A.color,this.animate=A.animate??!0,this.reasoningEffortAnimation=A.reasoningEffortAnimation??"promote",this.horizontalPadding=A.horizontalPadding??0}build(A){let Q=this.colorOverride??sy0(this.agentMode),$=new EO4({agentMode:this.agentMode,label:this.label,leadingMarker:this.leadingMarker,leadingMarkerColor:this.leadingMarkerColor,reasoningEffort:this.reasoningEffort,speedCostMultiplier:this.speedCostMultiplier,color:Q,animate:this.animate,reasoningEffortAnimation:this.reasoningEffortAnimation,horizontalPadding:this.horizontalPadding}),B=this.buildClickHandler(A);return new iA({onClick:B,cursor:"pointer",child:$})}buildClickHandler(A){let Q=N4.handler(A,new ZT),$=N4.handler(A,new jq);if(!Q&&!$&&!this.onLeadingMarkerClick)return;return(B)=>{let E=this.horizontalPadding;if(this.leadingMarker&&this.onLeadingMarkerClick&&B.button==="left"&&B.localPosition.x>=E&&B.localPosition.x<E+RA(this.leadingMarker)){this.onLeadingMarkerClick();return}if(B.modifiers.alt||B.button!=="left"){$?.();return}Q?.()}}}class EO4 extends d0{props;constructor(A){super();this.props=A}createState(){return new DO4}}class DO4 extends m0{effortAnimation=null;timer=null;didUpdateWidget(A){let Q=A.props.agentMode!==this.widget.props.agentMode,$=A.props.reasoningEffort!==this.widget.props.reasoningEffort;if(Q||!this.widget.props.animate)this.stopTimer(),this.effortAnimation=null;else if($&&this.widget.props.reasoningEffortAnimation==="swipe")this.stopTimer(),this.effortAnimation=null;else if($){let B=R00(A.props.agentMode,A.props.reasoningEffort,(A.props.label??T6(A.props.agentMode)?.displayName??A.props.agentMode).toLowerCase()),E=R00(this.widget.props.agentMode,this.widget.props.reasoningEffort,(this.widget.props.label??T6(this.widget.props.agentMode)?.displayName??this.widget.props.agentMode).toLowerCase());if(B.text!==E.text)this.effortAnimation={startedAt:Date.now(),from:B,to:E},this.startTimer();else this.stopTimer(),this.effortAnimation=null}}dispose(){this.stopTimer()}build(A){let Q=this.widget.props,$=R00(Q.agentMode,Q.reasoningEffort,(Q.label??T6(Q.agentMode)?.displayName??Q.agentMode).toLowerCase()),B=this.effortAnimation?Date.now()-this.effortAnimation.startedAt:0,E=this.buildFrame(A,$,B),D=KJ6(E),J=IJ6(Q),U=Q.animate&&!this.effortAnimation;return new y0({width:E.width,height:E.height,child:U?new kX({child:D.richText,contentKey:J}):D.widget})}buildFrame(A,Q,$){let B=this.widget.props;return VJ6({parts:Q,plan:GJ6(Q,this.effortAnimation,$),modeColor:B.color,warningColor:S4.of(A).colorScheme.warning,horizontalPadding:B.horizontalPadding,speedCostMultiplier:B.speedCostMultiplier,leadingMarker:B.leadingMarker,leadingMarkerColor:B.leadingMarkerColor})}startTimer(){if(this.timer)return;this.timer=setInterval(()=>{if(!this.effortAnimation){this.stopTimer();return}if(Date.now()-this.effortAnimation.startedAt>=v90){this.stopTimer(),this.setState(()=>{this.effortAnimation=null});return}this.setState()},FJ6)}stopTimer(){if(this.timer)clearInterval(this.timer),this.timer=null}}function IJ6(A){let Q=`${A.agentMode}:${A.label??""}`;return A.reasoningEffortAnimation==="swipe"?`${Q}:${A.reasoningEffort??""}`:Q}function GJ6(A,Q,$){if(!Q)return ad0(A.superscript);if(Q.to.plainReasoningIndex){if($>=v90)return ad0(Q.to.superscript);let E=Q.from.superscript==="",D=E?Math.max(0,$-nd0):$,J=E?v90-nd0:v90;return{suffix:"",reserveSuffixCell:!E||$>=nd0,incomingNumber:{value:Q.to.superscript,progress:HJ6(JO4(D/J))}}}return ad0(Q.to.superscript)}function ad0(A){return{suffix:A,reserveSuffixCell:!1,incomingNumber:null}}function VJ6({parts:A,plan:Q,modeColor:$,warningColor:B,horizontalPadding:E,speedCostMultiplier:D,leadingMarker:J,leadingMarkerColor:U}){let Y=new A0({color:$}),Z=new A0({color:U??$}),F=[],X=[],I=0,G=(z,W)=>{if(!z)return;F.push({text:z,x:I,style:W}),I+=RA(z)},V=" ".repeat(E);if(G(V,void 0),J)G(J,Z),G(" ",void 0);if(D)G("↯",new A0({color:B}));G(A.base,Y);let K=I;if(Q.suffix)G(Q.suffix,Y);else if(Q.reserveSuffixCell)G(" ",void 0);if(G(V,void 0),Q.incomingNumber){let z=K+XJ6,W=Math.round(K+(z-K)*(1-Q.incomingNumber.progress));X.push({text:Q.incomingNumber.value,x:W,yOffset:0,style:new A0({color:$,bold:!0})})}return{segments:F,overlays:X,width:Math.max(1,I),height:1}}function KJ6(A){let Q=new D0({text:new g("",void 0,A.segments.map(($)=>new g($.text,$.style))),maxLines:1,overflow:"clip"});if(A.height===1&&A.overlays.length===0&&zJ6(A))return{richText:Q,widget:Q};return{richText:Q,widget:new t1({children:[new y0({width:A.width,height:A.height}),...A.segments.map(WJ6),...A.overlays.map(CJ6)]})}}function zJ6(A){let Q=0;for(let $ of A.segments){if($.x!==Q)return!1;Q+=RA($.text)}return Q===A.width}function WJ6(A){return new m1({left:A.x,top:0,width:RA(A.text),height:1,child:new D0({text:new g(A.text,A.style),maxLines:1,overflow:"clip"})})}function CJ6(A){return new m1({left:A.x,top:A.yOffset,width:RA(A.text),height:1,child:new D0({text:new g(A.text,A.style),maxLines:1,overflow:"clip"})})}function JO4(A){return Math.max(0,Math.min(1,A))}function HJ6(A){return 1-(1-JO4(A))**2}xj();var NJ6=/(https?:\/\/[^\s]+)/g,qJ6=/[".,']+$/;function wJ6(A){let Q=A.match(qJ6);if(!Q?.[0])return{url:A,trailingText:""};return{url:A.slice(0,-Q[0].length),trailingText:Q[0]}}function UO4(A,Q){if(!Q)return;let $=[],B=0;for(let E of Q.matchAll(NJ6)){let{url:D,trailingText:J}=wJ6(E[0]),U=E.index??0;if(U>B)$.push(new g(Q.slice(B,U)));let Y=t$.createSpan(D,D);if($.push(new g(Y.text,Y.style,Y.children,Y.hyperlink,()=>{z$(A,D)})),J)$.push(new g(J));B=U+E[0].length}if(B<Q.length)$.push(new g(Q.slice(B)));return new M5({child:new D0({text:new g(void 0,void 0,$),selectable:!0})})}class rd0 extends d0{error;onResponse;presentationOptions;constructor({key:A,error:Q,onResponse:$,presentationOptions:B}){super({key:A});this.error=Q,this.onResponse=$,this.presentationOptions=B??{}}createState(){return new ZO4}}class ZO4 extends m0{hideAddCreditsActionForCurrentError=!1;didCopy=!1;countdownInterval=null;initState(){this.startCountdownIfNeeded()}didUpdateWidget(A){if(A.error.retryAt!==this.widget.error.retryAt)this.startCountdownIfNeeded();if(A.error.message===this.widget.error.message)return;this.hideAddCreditsActionForCurrentError=!1,this.didCopy=!1}dispose(){this.stopCountdown()}startCountdownIfNeeded(){this.stopCountdown();let{retryAt:A}=this.widget.error;if(A===void 0||A<=Date.now())return;this.countdownInterval=setInterval(()=>{if(this.widget.error.retryAt===void 0){this.stopCountdown();return}if(this.widget.error.retryAt<=Date.now())this.stopCountdown();this.setState()},1000)}stopCountdown(){if(this.countdownInterval!==null)clearInterval(this.countdownInterval),this.countdownInterval=null}computeRetryCountdown(){let{retryAt:A}=this.widget.error;if(A===void 0)return;return Math.max(0,Math.ceil((A-Date.now())/1000))}buildClipboardText(A){let Q=OV(YO4(this.widget.error)).trim(),$=[A.title,A.description];if(Q&&Q!==A.description)$.push(`Original error: ${Q}`);return $.join(`
|
|
2878
2878
|
|
|
2879
|
-
`)}copyErrorToClipboard(A,Q){let $=this.buildClipboardText(Q);N4.maybeInvoke(A,new IB($)),this.setState(()=>{this.didCopy=!0})}build(A){let Q=e0.of(A),$=this.widget.presentationOptions.ampURL??MQ.of(A).ampURL,B=yj(YO4(this.widget.error),this.widget.presentationOptions),E=this.hideAddCreditsActionForCurrentError?B.actions.filter((Y)=>Y!=="add-credits"):B.actions,D=this.computeRetryCountdown(),J=E.filter((Y)=>Y!=="dismiss"&&Y!=="new-thread").map((Y)=>({value:Y,label:Pj0(Y,{ampURL:$,retryCountdown:D})}));J.push({value:"copy",label:this.didCopy?"Copy to Clipboard ✓":"Copy to Clipboard"}),J.push({value:"dismiss",label:Pj0("dismiss")});let U=UO4(A,B.description);return new E6({debugLabel:"AgentErrorWidget",child:new xX({title:B.title,body:U,options:J,onSelect:(Y)=>{let Z=Y??"dismiss";if(Z==="copy"){this.copyErrorToClipboard(A,B);return}if(Z==="add-credits"){if(z$(A,new URL("/pay",$)),!this.hideAddCreditsActionForCurrentError)this.setState(()=>{this.hideAddCreditsActionForCurrentError=!0});this.widget.onResponse(Z);return}if(this.hideAddCreditsActionForCurrentError)this.setState(()=>{this.hideAddCreditsActionForCurrentError=!1});this.widget.onResponse(Z)},borderColor:Q.colors.destructive,autofocus:!0,showDismissalMessage:!1,enableMouseInteraction:!1})})}}function YO4(A){return{message:A.message}}function uJ6(A){let Q=Math.max(0,Math.floor(A/4));if(Q<1000)return`${Q} tok`;if(Q<1e4)return`${(Q/1000).toFixed(2)}k tok`;if(Q<1e6)return`${(Q/1000).toFixed(1)}k tok`;return`${(Q/1e6).toFixed(1)}M tok`}var FO4=[JT,TK],MJ6=150,OJ6=new ZB("border-status-reconnect-text");function XO4(A){return zO4(A)!==null}function IO4(A,Q){let $=zO4(A);return $?RA($,Q):0}class Ac0 extends d0{hints;status;session;cancelling;connectionError;statusMessage;constructor(A){super();this.hints=A.hints,this.status=A.status,this.session=A.session,this.cancelling=A.cancelling,this.connectionError=A.connectionError??null,this.statusMessage=A.statusMessage??null}createState(){return new GO4}}class GO4 extends m0{timer=null;initState(){super.initState(),this.updateTimer()}didUpdateWidget(A){if(super.didUpdateWidget(A),A.session.transport.nextRetryAt!==this.widget.session.transport.nextRetryAt)this.updateTimer()}dispose(){this.stopTimer(),super.dispose()}updateTimer(){if(this.widget.session.transport.nextRetryAt===void 0){this.stopTimer();return}if(this.timer)return;this.timer=setInterval(()=>{if(!this.mounted)return;this.setState()},1000),this.timer.unref()}stopTimer(){if(!this.timer)return;clearInterval(this.timer),this.timer=null}build(A){let Q=e0.of(A),$=[ST()],B=CO4({clientStatus:this.widget.status.current,cancelling:this.widget.cancelling,session:this.widget.session}),E=this.widget.session.transport.state==="reconnecting",D=sd0({session:this.widget.session,connectionError:this.widget.connectionError}),J=this.widget.statusMessage,U=KO4(this.widget.hints),Y=WO4({clientStatus:this.widget.status.current,cancelling:this.widget.cancelling,connectionError:D,statusMessage:J,hint:U,stageBytes:this.widget.status.stageBytes});if(D)PJ6(Q,D,$);else if(J)ed0(Q,J,$);else if(U){if(B||U===TK)td0(Q,$);TJ6($,vJ6(U,A))}else if(B)if(E)jJ6(Q,B,$);else td0(Q,$),ed0(Q,B,$);if($.length===1)return new y0({width:0,height:0});if(Y!==null)RJ6(Q,Y,$);return $.push(ST()),new OA({children:$,mainAxisSize:"max",mainAxisAlignment:"start"})}}function VO4(A,Q){let $=A.withSpinner?` ∼ ${A.message} `:` ${A.message} `;return RA($,Q)}class Qc0 extends eA{props;constructor(A){super();this.props=A}build(A){let Q=e0.of(A),$=[ST()];if(this.props.withSpinner)td0(Q,$);return ed0(Q,this.props.message,$),$.push(ST()),new OA({children:$,mainAxisSize:"max",mainAxisAlignment:"start"})}}function KO4(A){for(let Q=FO4.length-1;Q>=0;Q--){let $=FO4[Q];if(A.has($))return $}return}function zO4(A){let Q=CO4({clientStatus:A.status.current,cancelling:A.cancelling,session:A.session}),$=KO4(A.hints),B=WO4({clientStatus:A.status.current,cancelling:A.cancelling,connectionError:sd0({session:A.session,connectionError:A.connectionError??null}),statusMessage:A.statusMessage??null,hint:$,stageBytes:A.status.stageBytes}),E=B===null?"":` ${B}`,D=A.session.transport.state==="reconnecting",J=sd0({session:A.session,connectionError:A.connectionError??null});if(J)return` ${J} `;if(A.statusMessage)return` ${A.statusMessage} `;if($)return` ${Q||$===TK?"∼ ":""}${LJ6($)} `;if(Q){if(D)return` ${Q}${E} `;return` ∼ ${Q}${E} `}return null}function sd0(A){let Q=A.session.transport.state;switch(Q){case"reconnecting":return null;case"authenticating":case"connected":case"connecting":case"disconnected":return A.connectionError;default:return $c0(Q)}}function WO4(A){if(A.stageBytes===null)return null;if(A.connectionError!==null)return null;if(A.statusMessage!==null)return null;if(A.hint!==void 0)return null;if(A.cancelling)return null;if(A.clientStatus!==A.stageBytes.stage)return null;if(A.stageBytes.bytes<=0)return null;return uJ6(A.stageBytes.bytes)}function LJ6(A){switch(A){case TK:return"Loading thread";case JT:return"Enter to reference previous thread";default:return $c0(A)}}function td0(A,Q){Q.push(new iX({color:A.colors.primary})),Q.push(ST())}function ST(){return new D0({text:new g(" ")})}function _90(A,Q){let $=new D0({text:A,textAlign:"left",maxLines:1,overflow:"clip"}),B={durationMs:MJ6,child:$};if(Q!==void 0)B.key=Q;return new kX(B)}function ed0(A,Q,$,B={}){let E=new g(Q,new A0({color:A.colors.foreground,dim:!0}));if(B.animated===!1){$.push(new D0({text:E,textAlign:"left",maxLines:1,overflow:"clip"}));return}$.push(_90(E))}function jJ6(A,Q,$){let E=Q.startsWith("◌ ")?Q.slice(2):Q;$.push(_90(new g("",void 0,[new g("◌ ",new A0({color:A.colors.primary})),new g(E,new A0({color:A.colors.foreground,dim:!0}))]),OJ6))}function RJ6(A,Q,$){$.push(ST()),$.push(new D0({text:new g(Q,new A0({color:A.colors.foreground,dim:!0})),maxLines:1}))}function PJ6(A,Q,$){$.push(_90(new g(Q,new A0({color:A.colors.destructive}))))}function TJ6(A,Q){A.push(_90(Q))}function vJ6(A,Q){let $=e0.of(Q),B=new A0({color:$.app.keybind}),E=new A0({color:$.colors.foreground,dim:!0});switch(A){case TK:return new g("Loading thread",E);case JT:return new g("",void 0,[new g("Enter",B),new g(" to reference previous thread",E)])}}function CO4(A){if(A.session.transport.state==="reconnecting")return _J6(A.session);if(A.session.resume.state==="replaying")return"Catching up";if(A.clientStatus==="disconnected")return"Disconnected";if(A.cancelling)return"Cancelling";switch(A.clientStatus){case"connecting":return"Connecting";case"preparing_thread":return"Connecting";case"compacting":return"Auto-compacting";case"sending":return"Sending";case"waiting_for_executor":return"Starting";case"working":return"Waiting";case"thinking":return"Thinking";case"streaming":return"Streaming";case"running_tools":return"Running tools";case"awaiting_approval":return"Waiting for approval";case"error":return"Error";case"idle":return null;default:return $c0(A.clientStatus)}}function $c0(A){throw Error(`Unhandled border status case: ${String(A)}`)}function _J6(A){let Q=A.transport.nextRetryAt;if(Q===void 0)return"◌ Reconnecting";return`◌ Reconnecting in ${Math.max(1,Math.ceil((Q-Date.now())/1000))}s`}var SJ6=!1;class Bc0 extends eA{build(A){if(!SJ6)return new y0;let Q=e0.of(A);return new GA({decoration:new v1(Zq("smart",Q.app.agentModeLabelTheme)),child:new mA({padding:c0.horizontal(1),child:new D0({text:new g("DEVELOPMENT BUILD (neo)",new A0({color:Q.app.selectionForeground,bold:!0})),textAlign:"center"})})})}}E2();class wO4 extends XB{color;constructor({color:A,key:Q}){super({key:Q});this.color=A}createRenderObject(){return new uO4(this.color)}updateRenderObject(A){A.color=this.color}}class uO4 extends bA{color;constructor(A){super();this.color=A}performLayout(){let A=this._lastConstraints;if(A)this.setSize(A.maxWidth,1)}paint(A,Q,$){let B=Math.floor(this.size.width);for(let E=0;E<B;E++)A.setChar(Q+E,$,"─",{fg:this.color},1)}}var kJ6=30,MO4={keys:"Ctrl+O",description:"command palette"},OO4={keys:"Ctrl+R",description:"prompt history"},fJ6={keys:"$ or $$",description:"shell commands"},LO4={keys:"Ctrl+V",description:"paste images"},S90={keys:"Shift+Enter",description:"newline"},jO4={keys:"Ctrl+S",description:"switch modes"},RO4={keys:"Alt+D",description:"toggle reasoning effort"},PO4={keys:"Alt+T",description:"expand/collapse details"},TO4={keys:"Ctrl+G",description:"edit in $EDITOR"},vO4={keys:"Tab/Shift+Tab",description:"navigate messages"},_O4={keys:"@ / @@",description:"mention files/threads"},SO4={keys:"?",description:"toggle this help"},HO4={keys:"Ctrl/Cmd+Enter",description:"submit"},NO4={keys:"",description:""},xJ6=[{keys:"Alt+S",description:"toggle sidebar focus"},{keys:"Enter",description:"open selected thread"},{keys:"e",description:"archive selected thread"}],yJ6={left:[MO4,fJ6,S90,RO4,TO4,_O4],right:[OO4,LO4,jO4,PO4,vO4,SO4]},bJ6={left:[MO4,LO4,jO4,TO4,_O4,SO4],right:[OO4,S90,RO4,PO4,vO4]};function qO4(A){if(!A.keys&&!A.description)return 0;return RA(A.keys)+1+RA(A.description)}function Ec0(A,Q,$){if(!A.keys&&!A.description)return[];return[new g(A.keys,Q),new g(" ",$),new g(A.description,$)]}function hJ6(A,Q){let $=A==="neo"?bJ6:yJ6;if(Q)return $;return{left:$.left.map((B)=>B.keys===S90.keys?HO4:B),right:$.right.map((B)=>B.keys===S90.keys?HO4:B)}}function gJ6({layout:A,submitOnEnter:Q,displayKeys:$}){let B=hJ6(A,Q),E=(U)=>{return{keys:$(U.keys),description:U.description}},D=[],J=Math.max(B.left.length,B.right.length);for(let U=0;U<J;U++)D.push({left:E(B.left[U]??NO4),right:E(B.right[U]??NO4)});return D}class Dc0 extends eA{submitOnEnter;layout;constructor(A={}){super(A.key?{key:A.key}:{});this.submitOnEnter=A.submitOnEnter??!0,this.layout=A.layout??"classic"}build(A){let $=S4.of(A).colorScheme,E=e0.of(A).app,D=new A0({color:E.keybind}),J=new A0({color:$.foreground,dim:!0}),U=x2()&&!Ry0,Y=(G)=>{return(G==="Shift+Enter"&&U?"Alt+Enter":G).split("/").map((K)=>RX(K)).join("/")},Z=gJ6({layout:this.layout,submitOnEnter:this.submitOnEnter,displayKeys:Y}),F=Math.max(kJ6,...Z.map((G)=>qO4(G.left))),X=Z.map((G)=>{let V=qO4(G.left),K=" ".repeat(Math.max(0,F-V));return new D0({text:new g("",void 0,[...Ec0(G.left,D,J),new g(K+" ",J),...Ec0(G.right,D,J)])})});if(this.layout==="neo"){X.push(new y0({height:1})),X.push(new D0({text:new g("Sidebar",new A0({color:E.command,bold:!0}))}));for(let G of xJ6){let V={keys:Y(G.keys),description:G.description};X.push(new D0({text:new g("",void 0,[...Ec0(V,D,J)])}))}}if(U)X.push(new y0({height:1})),X.push(new iA({onClick:()=>z$(A,"https://ampcode.com/manual/appendix#amp-cli-tmux"),cursor:"pointer",child:new D0({text:new g("",void 0,[new g("Enable ",J),new g("extended-keys",new A0({color:E.command})),new g(" in tmux to use ",J),new g("Shift+Enter",D),new g(". See ",J),t$.createSpan("https://ampcode.com/manual/appendix#amp-cli-tmux","https://ampcode.com/manual/appendix#amp-cli-tmux",new A0({color:E.link,underline:!0}))])})}));let I=new OA({children:[new P4({child:new wO4({color:$.border})})]});return new UA({crossAxisAlignment:"start",mainAxisSize:"min",children:[...X,I]})}}class Jc0 extends OT{_mode="auto";_isResizing=!1;_isHandleHovered=!1;get mode(){return this._mode}get isResizing(){return this._isResizing}get isHandleHovered(){return this._isHandleHovered}_update(A,Q,$){let B=this._mode!==A||this._isResizing!==Q||this._isHandleHovered!==$;if(this._mode=A,this._isResizing=Q,this._isHandleHovered=$,B)this.notifyListeners()}}class Uc0 extends d0{child;minRows;maxRows;initialRows;initialMode;dragThresholdRows;handleLeftInset;handleRightInset;onHandleDoubleClick;controller;constructor({key:A,child:Q,minRows:$=3,maxRows:B=12,initialRows:E=null,initialMode:D="auto",dragThresholdRows:J=0,handleLeftInset:U=0,handleRightInset:Y=0,onHandleDoubleClick:Z,controller:F}){super(A?{key:A}:{});if($>B)throw Error("minRows must be <= maxRows");if(J<0)throw Error("dragThresholdRows must be >= 0");if(Y<0)throw Error("handleRightInset must be >= 0");if(U<0)throw Error("handleLeftInset must be >= 0");this.child=Q,this.minRows=$,this.maxRows=B,this.initialRows=E,this.initialMode=D,this.dragThresholdRows=J,this.handleLeftInset=U,this.handleRightInset=Y,this.onHandleDoubleClick=Z,this.controller=F}createState(){return new kO4}}class kO4 extends m0{_mode="auto";_heightRows=3;_dragSession=null;_isHandleHovered=!1;initState(){super.initState(),this._syncToInitialProps()}didUpdateWidget(A){if(super.didUpdateWidget(A),A.initialMode!==this.widget.initialMode||A.initialRows!==this.widget.initialRows){this._syncToInitialProps();return}this._heightRows=this._clampRows(this._heightRows)}build(A){let Q=this._mode==="manual"?new GA({height:this._heightRows,child:this.widget.child}):new GA({constraints:new A4(0,Number.POSITIVE_INFINITY,this.widget.minRows,this.widget.maxRows),child:this.widget.child});return new t1({children:[Q,this._buildHandleOverlay()]})}get _effectiveMinRows(){return this.widget.minRows}_buildHandleOverlay(){return new m1({top:0,left:this.widget.handleLeftInset,right:this.widget.handleRightInset,height:1,child:new iA({cursor:o1.NS_RESIZE,onClick:this._handleHandlePress,onDrag:this._handleHandleDrag,onRelease:this._handleHandleRelease,onEnter:()=>this._setHandleHovered(!0),onExit:()=>this._setHandleHovered(!1),child:new y0({height:1})})})}_notifyController(){this.widget.controller?._update(this._mode,!!this._dragSession,this._isHandleHovered)}_setHandleHovered(A){if(this._isHandleHovered===A)return;this.setState(()=>{this._isHandleHovered=A,this._notifyController()})}_handleHandlePress=(A)=>{if(A.button!=="left")return;let Q=this._currentRenderedHeightRows(),$=this._toTerminalRow(A.position.y),B=A.clickCount===2?this.widget.onHandleDoubleClick?.({mode:this._mode,currentRows:Q,minRows:this._effectiveMinRows,maxRows:this.widget.maxRows}):void 0,E=this._mode==="manual"&&A.clickCount===2&&B===void 0;this.setState(()=>{this._dragSession={modeAtStart:this._mode,baseHeightRows:Q,startRow:$,currentRow:$,resetToAutoOnRelease:E,doubleClickOverride:B},this._notifyController()})};_handleHandleDrag=(A)=>{if(A.button!=="left"||!this._dragSession)return;let Q=this._toTerminalRow(A.position.y),$=this._dragSession,B=Q-$.startRow,E=$.modeAtStart==="manual"||Math.abs(B)>=this.widget.dragThresholdRows;this.setState(()=>{if($.currentRow=Q,B!==0)$.resetToAutoOnRelease=!1,$.doubleClickOverride=void 0;if(E)this._mode="manual",this._heightRows=this._clampRows($.baseHeightRows-B);this._notifyController()})};_handleHandleRelease=(A)=>{if(A.button!=="left"||!this._dragSession)return;let Q=this._dragSession,$=Q.currentRow-Q.startRow,B=Q.doubleClickOverride==="auto-min"&&$===0,E=Q.doubleClickOverride==="manual-max"&&$===0,D=Q.resetToAutoOnRelease&&$===0,J=Q.modeAtStart==="auto"&&this._mode==="auto"&&this.widget.dragThresholdRows===0&&$===0;this.setState(()=>{if(B)this._mode="auto",this._heightRows=this._clampRows(this._effectiveMinRows);else if(E)this._mode="manual",this._heightRows=this._clampRows(this.widget.maxRows);else if(D)this._mode="auto";else if(J)this._mode="manual",this._heightRows=this._clampRows(Q.baseHeightRows);this._dragSession=null,this._notifyController()})};_syncToInitialProps(){this._mode=this.widget.initialMode,this._heightRows=this._resolveInitialRows(),this._dragSession=null,this._notifyController()}_resolveInitialRows(){return this._clampRows(this.widget.initialRows??this._effectiveMinRows)}_clampRows(A){return Math.max(this._effectiveMinRows,Math.min(A,this.widget.maxRows))}_currentRenderedHeightRows(){return this.context.findRenderObject()?.size.height??this._heightRows}_toTerminalRow(A){return Math.floor(A)}}var mJ6=22,dJ6=14;class Yc0 extends d0{childBuilder;minBodyRows;maxBodyRows;initialRows;initialMode;dragThresholdRows;onHandleDoubleClick;topLeftLabel;topRightLabel;bottomLeftLabel;bottomRightLabel;borderColor;topRightLabelHandleInset;constructor(A){let{key:Q,minBodyRows:$=3,maxBodyRows:B=12,initialRows:E=null,initialMode:D="auto",dragThresholdRows:J=0,onHandleDoubleClick:U,topLeftLabel:Y,topRightLabel:Z,bottomLeftLabel:F,bottomRightLabel:X,borderColor:I,topRightLabelHandleInset:G}=A;super(Q?{key:Q}:{});this.childBuilder="childBuilder"in A&&A.childBuilder?A.childBuilder:()=>A.child,this.minBodyRows=$,this.maxBodyRows=B,this.initialRows=E,this.initialMode=D,this.dragThresholdRows=J,this.onHandleDoubleClick=U,this.topLeftLabel=Y,this.topRightLabel=Z,this.bottomLeftLabel=F,this.bottomRightLabel=X,this.borderColor=I,this.topRightLabelHandleInset=G}createState(){return new fO4}}class fO4 extends m0{_controller=new Jc0;_onControllerChanged=()=>{this.setState(()=>{})};initState(){super.initState(),this._controller.addListener(this._onControllerChanged)}dispose(){this._controller.removeListener(this._onControllerChanged),this._controller.dispose(),super.dispose()}build(A){let Q=S4.of(A),$=this.widget.borderColor??Q.colorScheme.border,E=this._controller.isResizing||this._controller.isHandleHovered?2:1,D=[];if(this.widget.topLeftLabel)D.push({child:this.widget.topLeftLabel,position:"top",alignment:"left"});if(this.widget.topRightLabel)D.push({child:this.widget.topRightLabel,position:"top",alignment:"right"});if(this.widget.bottomLeftLabel)D.push({child:this.widget.bottomLeftLabel,position:"bottom",alignment:"left",offsetX:-1});if(this.widget.bottomRightLabel)D.push({child:this.widget.bottomRightLabel,position:"bottom",alignment:"right"});return new Uc0({controller:this._controller,minRows:this.widget.minBodyRows+2,maxRows:this.widget.maxBodyRows+2,initialRows:this.widget.initialRows,initialMode:this.widget.initialMode,dragThresholdRows:this.widget.dragThresholdRows,handleLeftInset:this.widget.topLeftLabel?mJ6:0,handleRightInset:this.widget.topRightLabel?this.widget.topRightLabelHandleInset??dJ6:0,onHandleDoubleClick:this.widget.onHandleDoubleClick,child:new h$({decoration:new v1(Q.colorScheme.background,new U1(new Y1($,E,"rounded"),new Y1($,1,"rounded"),new Y1($,1,"rounded"),new Y1($,1,"rounded"))),overlays:D,child:this.widget.childBuilder(this._controller.mode)})})}}var xO4={message:"Uploading — Esc to keep editing",withSpinner:!0},cJ6=O4("prompt.dequeue",{noun:"prompt",verb:"dequeue",description:"Dequeue prompts",keywords:["pop"],status:(A)=>{if(A.isUploadLocked())return{type:"disabled",reason:"Prompt editor is not available"};if(!A.isEffectiveEditorEnabled())return{type:"disabled",reason:"Cannot use prompt: dequeue while editing or selecting a message"};return A.queuedMessages().length>0?{type:"enabled"}:{type:"disabled",reason:"Can only use prompt: dequeue when there are queued messages"}}},(A,{dismiss:Q})=>{A.dequeueAll(),Q()}),pJ6=O4("prompt.steerQueuedMessage",{noun:"prompt",verb:"steer queued message",description:"Steer with the next queued prompt",status:(A)=>{if(A.queuedMessages().some((Q)=>!Q.steer))return{type:"enabled"};return A.queuedMessages().length>0?{type:"disabled",reason:"All queued messages are already marked as steering"}:{type:"disabled",reason:"Can only use prompt: steer queued message when there are queued messages"}}},(A,{dismiss:Q})=>{A.steerNextQueuedMessage(),Q()});function lJ6(A,Q){return!A.ctrlKey&&!A.altKey&&!A.metaKey&&A.key===Q}class Zc0 extends d0{props;constructor(A){super();this.props=A}createState(){return new yO4}}class yO4 extends m0{promptEditorEmpty=!1;isUploadLocked=!1;dismissMentionPicker=null;isShowingShortcutsHelp=!1;removeKeyInterceptor=null;removeEditorTextListener=null;unregisterCommands=null;get effectiveEditorEnabled(){return this.widget.props.editorEnabled&&!this.isUploadLocked}initState(){this.isShowingShortcutsHelp=this.widget.props.showShortcutsHelp??!1,this.promptEditorEmpty=this.widget.props.editorController.text==="",this.widget.props.editorFocusNode.addListener(this.handleEditorFocusChange),this.attachEditorTextListener(this.widget.props.editorController),this.unregisterCommands=this.registerCommands(),this.removeKeyInterceptor=G1.instance.addKeyInterceptor((A)=>{let Q=this.widget.props.editorController;if(this.dismissMentionPicker&&lJ6(A,"Escape"))return this.dismissMentionPicker(),!0;if(!this.promptOwnsKeybindings())return!1;if(A.key==="?"){if(this.effectiveEditorEnabled&&Q.text===""&&Q.cursorPosition===0)return this.setState(()=>{this.isShowingShortcutsHelp=!this.isShowingShortcutsHelp}),!0}if(A.key==="/"){if(this.effectiveEditorEnabled&&Q.text===""&&Q.cursorPosition===0){if(N4.maybeInvoke(this.context,new Ql)==="handled")return!0}}if(this.isShowingShortcutsHelp){if(this.setState(()=>{this.isShowingShortcutsHelp=!1}),A.key==="Escape")return!0;return!1}return!1})}didUpdateWidget(A){if(A.props.editorController!==this.widget.props.editorController)this.removeEditorTextListener?.(),this.removeEditorTextListener=null,this.promptEditorEmpty=this.widget.props.editorController.text==="",this.attachEditorTextListener(this.widget.props.editorController);if(!A.props.editorEnabled&&this.widget.props.editorEnabled&&this.widget.props.editorFocusNode.hasFocus)this.widget.props.editorFocusNode.requestFocus()}dispose(){this.unregisterCommands?.(),this.unregisterCommands=null,this.removeEditorTextListener?.(),this.removeEditorTextListener=null,this.removeKeyInterceptor?.(),this.removeKeyInterceptor=null,this.dismissMentionPicker=null,this.widget.props.editorFocusNode.removeListener(this.handleEditorFocusChange),super.dispose()}attachEditorTextListener(A){let Q=()=>this.syncEditorTextState(A);A.addListener(Q),this.removeEditorTextListener=()=>A.removeListener(Q)}handleEditorFocusChange=()=>{this.setState()};syncEditorTextState(A){let Q=this.promptEditorEmpty;if(this.promptEditorEmpty=A.text==="",Q!==this.promptEditorEmpty)this.setState()}promptOwnsKeybindings(){return this.widget.props.editorFocusNode.hasFocus}createCommands(){let A={isUploadLocked:()=>this.isUploadLocked,isEffectiveEditorEnabled:()=>this.effectiveEditorEnabled,queuedMessages:()=>this.widget.props.queuedMessages,dequeueAll:this.handleDequeueAll,steerNextQueuedMessage:()=>this.widget.props.onSteerNextQueuedMessage()};return[cJ6.bind(A),pJ6.bind(A)]}registerCommands(){let A=sB.of(this.context),$=this.createCommands().map((B)=>A.register(B));return()=>{for(let B of $)B()}}handleDequeueAll=()=>{if(this.isUploadLocked)return;let A=this.widget.props.queuedMessages;if(A.length===0)return;let Q=[],$=[];for(let B of A){let E=B.queuedMessage.content.filter((J)=>J.type==="text").map((J)=>J.text).join("").trim();if(E)Q.push(E);let D=B.queuedMessage.content.filter((J)=>J.type==="image");$.push(...D)}this.widget.props.onDequeueAllMessages(),this.widget.props.editorController.text=Q.join(`
|
|
2879
|
+
`)}copyErrorToClipboard(A,Q){let $=this.buildClipboardText(Q);N4.maybeInvoke(A,new IB($)),this.setState(()=>{this.didCopy=!0})}build(A){let Q=e0.of(A),$=this.widget.presentationOptions.ampURL??MQ.of(A).ampURL,B=yj(YO4(this.widget.error),this.widget.presentationOptions),E=this.hideAddCreditsActionForCurrentError?B.actions.filter((Y)=>Y!=="add-credits"):B.actions,D=this.computeRetryCountdown(),J=E.filter((Y)=>Y!=="dismiss"&&Y!=="new-thread").map((Y)=>({value:Y,label:Pj0(Y,{ampURL:$,retryCountdown:D})}));J.push({value:"copy",label:this.didCopy?"Copy to Clipboard ✓":"Copy to Clipboard"}),J.push({value:"dismiss",label:Pj0("dismiss")});let U=UO4(A,B.description);return new E6({debugLabel:"AgentErrorWidget",child:new xX({title:B.title,body:U,options:J,onSelect:(Y)=>{let Z=Y??"dismiss";if(Z==="copy"){this.copyErrorToClipboard(A,B);return}if(Z==="add-credits"){if(z$(A,new URL("/pay",$)),!this.hideAddCreditsActionForCurrentError)this.setState(()=>{this.hideAddCreditsActionForCurrentError=!0});this.widget.onResponse(Z);return}if(this.hideAddCreditsActionForCurrentError)this.setState(()=>{this.hideAddCreditsActionForCurrentError=!1});this.widget.onResponse(Z)},borderColor:Q.colors.destructive,autofocus:!0,showDismissalMessage:!1,enableMouseInteraction:!1})})}}function YO4(A){return{message:A.message}}function uJ6(A){let Q=Math.max(0,Math.floor(A/4));if(Q<1000)return`${Q} tok`;if(Q<1e4)return`${(Q/1000).toFixed(2)}k tok`;if(Q<1e6)return`${(Q/1000).toFixed(1)}k tok`;return`${(Q/1e6).toFixed(1)}M tok`}var FO4=[JT,TK],MJ6=150,OJ6=new ZB("border-status-reconnect-text");function XO4(A){return zO4(A)!==null}function IO4(A,Q){let $=zO4(A);return $?RA($,Q):0}class Ac0 extends d0{hints;status;session;cancelling;connectionError;statusMessage;constructor(A){super();this.hints=A.hints,this.status=A.status,this.session=A.session,this.cancelling=A.cancelling,this.connectionError=A.connectionError??null,this.statusMessage=A.statusMessage??null}createState(){return new GO4}}class GO4 extends m0{timer=null;initState(){super.initState(),this.updateTimer()}didUpdateWidget(A){if(super.didUpdateWidget(A),A.session.transport.nextRetryAt!==this.widget.session.transport.nextRetryAt)this.updateTimer()}dispose(){this.stopTimer(),super.dispose()}updateTimer(){if(this.widget.session.transport.nextRetryAt===void 0){this.stopTimer();return}if(this.timer)return;this.timer=setInterval(()=>{if(!this.mounted)return;this.setState()},1000),this.timer.unref()}stopTimer(){if(!this.timer)return;clearInterval(this.timer),this.timer=null}build(A){let Q=e0.of(A),$=[ST()],B=CO4({clientStatus:this.widget.status.current,cancelling:this.widget.cancelling,session:this.widget.session}),E=this.widget.session.transport.state==="reconnecting",D=sd0({session:this.widget.session,connectionError:this.widget.connectionError}),J=this.widget.statusMessage,U=KO4(this.widget.hints),Y=WO4({clientStatus:this.widget.status.current,cancelling:this.widget.cancelling,connectionError:D,statusMessage:J,hint:U,stageBytes:this.widget.status.stageBytes});if(D)PJ6(Q,D,$);else if(J)ed0(Q,J,$);else if(U){if(B||U===TK)td0(Q,$);TJ6($,vJ6(U,A))}else if(B)if(E)jJ6(Q,B,$);else td0(Q,$),ed0(Q,B,$);if($.length===1)return new y0({width:0,height:0});if(Y!==null)RJ6(Q,Y,$);return $.push(ST()),new OA({children:$,mainAxisSize:"max",mainAxisAlignment:"start"})}}function VO4(A,Q){let $=A.withSpinner?` ∼ ${A.message} `:` ${A.message} `;return RA($,Q)}class Qc0 extends eA{props;constructor(A){super();this.props=A}build(A){let Q=e0.of(A),$=[ST()];if(this.props.withSpinner)td0(Q,$);return ed0(Q,this.props.message,$),$.push(ST()),new OA({children:$,mainAxisSize:"max",mainAxisAlignment:"start"})}}function KO4(A){for(let Q=FO4.length-1;Q>=0;Q--){let $=FO4[Q];if(A.has($))return $}return}function zO4(A){let Q=CO4({clientStatus:A.status.current,cancelling:A.cancelling,session:A.session}),$=KO4(A.hints),B=WO4({clientStatus:A.status.current,cancelling:A.cancelling,connectionError:sd0({session:A.session,connectionError:A.connectionError??null}),statusMessage:A.statusMessage??null,hint:$,stageBytes:A.status.stageBytes}),E=B===null?"":` ${B}`,D=A.session.transport.state==="reconnecting",J=sd0({session:A.session,connectionError:A.connectionError??null});if(J)return` ${J} `;if(A.statusMessage)return` ${A.statusMessage} `;if($)return` ${Q||$===TK?"∼ ":""}${LJ6($)} `;if(Q){if(D)return` ${Q}${E} `;return` ∼ ${Q}${E} `}return null}function sd0(A){let Q=A.session.transport.state;switch(Q){case"reconnecting":return null;case"authenticating":case"connected":case"connecting":case"disconnected":return A.connectionError;default:return $c0(Q)}}function WO4(A){if(A.stageBytes===null)return null;if(A.connectionError!==null)return null;if(A.statusMessage!==null)return null;if(A.hint!==void 0)return null;if(A.cancelling)return null;if(A.clientStatus!==A.stageBytes.stage)return null;if(A.stageBytes.bytes<=0)return null;return uJ6(A.stageBytes.bytes)}function LJ6(A){switch(A){case TK:return"Loading thread";case JT:return"Enter to reference previous thread";default:return $c0(A)}}function td0(A,Q){Q.push(new iX({color:A.colors.primary})),Q.push(ST())}function ST(){return new D0({text:new g(" ")})}function _90(A,Q){let $=new D0({text:A,textAlign:"left",maxLines:1,overflow:"clip"}),B={durationMs:MJ6,child:$};if(Q!==void 0)B.key=Q;return new kX(B)}function ed0(A,Q,$,B={}){let E=new g(Q,new A0({color:A.colors.foreground,dim:!0}));if(B.animated===!1){$.push(new D0({text:E,textAlign:"left",maxLines:1,overflow:"clip"}));return}$.push(_90(E))}function jJ6(A,Q,$){let E=Q.startsWith("◌ ")?Q.slice(2):Q;$.push(_90(new g("",void 0,[new g("◌ ",new A0({color:A.colors.primary})),new g(E,new A0({color:A.colors.foreground,dim:!0}))]),OJ6))}function RJ6(A,Q,$){$.push(ST()),$.push(new D0({text:new g(Q,new A0({color:A.colors.foreground,dim:!0})),maxLines:1}))}function PJ6(A,Q,$){$.push(_90(new g(Q,new A0({color:A.colors.destructive}))))}function TJ6(A,Q){A.push(_90(Q))}function vJ6(A,Q){let $=e0.of(Q),B=new A0({color:$.app.keybind}),E=new A0({color:$.colors.foreground,dim:!0});switch(A){case TK:return new g("Loading thread",E);case JT:return new g("",void 0,[new g("Enter",B),new g(" to reference previous thread",E)])}}function CO4(A){if(A.session.transport.state==="reconnecting")return _J6(A.session);if(A.session.resume.state==="replaying")return"Catching up";if(A.clientStatus==="disconnected")return"Disconnected";if(A.cancelling)return"Cancelling";switch(A.clientStatus){case"connecting":return"Connecting";case"preparing_thread":return"Connecting";case"compacting":return"Auto-compacting";case"sending":return"Sending";case"waiting_for_executor":return"Starting";case"working":return"Waiting";case"thinking":return"Thinking";case"streaming":return"Streaming";case"running_tools":return"Running tools";case"awaiting_approval":return"Waiting for approval";case"error":return"Error";case"idle":return null;default:return $c0(A.clientStatus)}}function $c0(A){throw Error(`Unhandled border status case: ${String(A)}`)}function _J6(A){let Q=A.transport.nextRetryAt;if(Q===void 0)return"◌ Reconnecting";return`◌ Reconnecting in ${Math.max(1,Math.ceil((Q-Date.now())/1000))}s`}var SJ6=!1;class Bc0 extends eA{build(A){if(!SJ6)return new y0;let Q=e0.of(A);return new GA({decoration:new v1(Zq("smart",Q.app.agentModeLabelTheme)),child:new mA({padding:c0.horizontal(1),child:new D0({text:new g("DEVELOPMENT BUILD (neo)",new A0({color:Q.app.selectionForeground,bold:!0})),textAlign:"center"})})})}}E2();class wO4 extends XB{color;constructor({color:A,key:Q}){super({key:Q});this.color=A}createRenderObject(){return new uO4(this.color)}updateRenderObject(A){A.color=this.color}}class uO4 extends bA{color;constructor(A){super();this.color=A}performLayout(){let A=this._lastConstraints;if(A)this.setSize(A.maxWidth,1)}paint(A,Q,$){let B=Math.floor(this.size.width);for(let E=0;E<B;E++)A.setChar(Q+E,$,"─",{fg:this.color},1)}}var kJ6=30,MO4={keys:"Ctrl+O",description:"command palette"},OO4={keys:"Ctrl+R",description:"prompt history"},fJ6={keys:"$ or $$",description:"shell commands"},LO4={keys:"Ctrl+V",description:"paste images"},S90={keys:"Shift+Enter",description:"newline"},jO4={keys:"Ctrl+S",description:"switch modes"},RO4={keys:"Alt+D",description:"toggle reasoning effort"},PO4={keys:"Alt+T",description:"expand/collapse details"},TO4={keys:"Ctrl+G",description:"edit in $EDITOR"},vO4={keys:"Tab/Shift+Tab",description:"navigate messages"},_O4={keys:"@ / @@",description:"mention files/threads"},SO4={keys:"?",description:"toggle this help"},HO4={keys:"Ctrl/Cmd+Enter",description:"submit"},NO4={keys:"",description:""},xJ6=[{keys:"Alt+S",description:"toggle sidebar focus"},{keys:"Enter",description:"open selected thread"},{keys:"e",description:"archive selected thread"}],yJ6={left:[MO4,fJ6,S90,RO4,TO4,_O4],right:[OO4,LO4,jO4,PO4,vO4,SO4]},bJ6={left:[MO4,LO4,jO4,TO4,_O4,SO4],right:[OO4,S90,RO4,PO4,vO4]};function qO4(A){if(!A.keys&&!A.description)return 0;return RA(A.keys)+1+RA(A.description)}function Ec0(A,Q,$){if(!A.keys&&!A.description)return[];return[new g(A.keys,Q),new g(" ",$),new g(A.description,$)]}function hJ6(A,Q){let $=A==="neo"?bJ6:yJ6;if(Q)return $;return{left:$.left.map((B)=>B.keys===S90.keys?HO4:B),right:$.right.map((B)=>B.keys===S90.keys?HO4:B)}}function gJ6({layout:A,submitOnEnter:Q,displayKeys:$}){let B=hJ6(A,Q),E=(U)=>{return{keys:$(U.keys),description:U.description}},D=[],J=Math.max(B.left.length,B.right.length);for(let U=0;U<J;U++)D.push({left:E(B.left[U]??NO4),right:E(B.right[U]??NO4)});return D}class Dc0 extends eA{submitOnEnter;layout;constructor(A={}){super(A.key?{key:A.key}:{});this.submitOnEnter=A.submitOnEnter??!0,this.layout=A.layout??"classic"}build(A){let $=S4.of(A).colorScheme,E=e0.of(A).app,D=new A0({color:E.keybind}),J=new A0({color:$.foreground,dim:!0}),U=x2()&&!Ry0,Y=(G)=>{return(G==="Shift+Enter"&&U?"Alt+Enter":G).split("/").map((K)=>RX(K)).join("/")},Z=gJ6({layout:this.layout,submitOnEnter:this.submitOnEnter,displayKeys:Y}),F=Math.max(kJ6,...Z.map((G)=>qO4(G.left))),X=Z.map((G)=>{let V=qO4(G.left),K=" ".repeat(Math.max(0,F-V));return new D0({text:new g("",void 0,[...Ec0(G.left,D,J),new g(K+" ",J),...Ec0(G.right,D,J)])})});if(this.layout==="neo"){X.push(new y0({height:1})),X.push(new D0({text:new g("Sidebar",new A0({color:E.command,bold:!0}))}));for(let G of xJ6){let V={keys:Y(G.keys),description:G.description};X.push(new D0({text:new g("",void 0,[...Ec0(V,D,J)])}))}}if(U)X.push(new y0({height:1})),X.push(new iA({onClick:()=>z$(A,"https://ampcode.com/manual/appendix#amp-cli-tmux"),cursor:"pointer",child:new D0({text:new g("",void 0,[new g("Enable ",J),new g("extended-keys",new A0({color:E.command})),new g(" in tmux to use ",J),new g("Shift+Enter",D),new g(". See ",J),t$.createSpan("https://ampcode.com/manual/appendix#amp-cli-tmux","https://ampcode.com/manual/appendix#amp-cli-tmux",new A0({color:E.link,underline:!0}))])})}));let I=new OA({children:[new P4({child:new wO4({color:$.border})})]});return new UA({crossAxisAlignment:"start",mainAxisSize:"min",children:[...X,I]})}}class Jc0 extends OT{_mode="auto";_isResizing=!1;_isHandleHovered=!1;get mode(){return this._mode}get isResizing(){return this._isResizing}get isHandleHovered(){return this._isHandleHovered}_update(A,Q,$){let B=this._mode!==A||this._isResizing!==Q||this._isHandleHovered!==$;if(this._mode=A,this._isResizing=Q,this._isHandleHovered=$,B)this.notifyListeners()}}class Uc0 extends d0{child;minRows;maxRows;initialRows;initialMode;dragThresholdRows;handleLeftInset;handleRightInset;onHandleDoubleClick;controller;constructor({key:A,child:Q,minRows:$=3,maxRows:B=12,initialRows:E=null,initialMode:D="auto",dragThresholdRows:J=0,handleLeftInset:U=0,handleRightInset:Y=0,onHandleDoubleClick:Z,controller:F}){super(A?{key:A}:{});if($>B)throw Error("minRows must be <= maxRows");if(J<0)throw Error("dragThresholdRows must be >= 0");if(Y<0)throw Error("handleRightInset must be >= 0");if(U<0)throw Error("handleLeftInset must be >= 0");this.child=Q,this.minRows=$,this.maxRows=B,this.initialRows=E,this.initialMode=D,this.dragThresholdRows=J,this.handleLeftInset=U,this.handleRightInset=Y,this.onHandleDoubleClick=Z,this.controller=F}createState(){return new kO4}}class kO4 extends m0{_mode="auto";_heightRows=3;_dragSession=null;_isHandleHovered=!1;initState(){super.initState(),this._syncToInitialProps()}didUpdateWidget(A){if(super.didUpdateWidget(A),A.initialMode!==this.widget.initialMode||A.initialRows!==this.widget.initialRows){this._syncToInitialProps();return}this._heightRows=this._clampRows(this._heightRows)}build(A){let Q=this._mode==="manual"?new GA({height:this._heightRows,child:this.widget.child}):new GA({constraints:new A4(0,Number.POSITIVE_INFINITY,this.widget.minRows,this.widget.maxRows),child:this.widget.child});return new t1({children:[Q,this._buildHandleOverlay()]})}get _effectiveMinRows(){return this.widget.minRows}_buildHandleOverlay(){return new m1({top:0,left:this.widget.handleLeftInset,right:this.widget.handleRightInset,height:1,child:new iA({cursor:o1.NS_RESIZE,onClick:this._handleHandlePress,onDrag:this._handleHandleDrag,onRelease:this._handleHandleRelease,onEnter:()=>this._setHandleHovered(!0),onExit:()=>this._setHandleHovered(!1),child:new y0({height:1})})})}_notifyController(){this.widget.controller?._update(this._mode,!!this._dragSession,this._isHandleHovered)}_setHandleHovered(A){if(this._isHandleHovered===A)return;this.setState(()=>{this._isHandleHovered=A,this._notifyController()})}_handleHandlePress=(A)=>{if(A.button!=="left")return;let Q=this._currentRenderedHeightRows(),$=this._toTerminalRow(A.position.y),B=A.clickCount===2?this.widget.onHandleDoubleClick?.({mode:this._mode,currentRows:Q,minRows:this._effectiveMinRows,maxRows:this.widget.maxRows}):void 0,E=this._mode==="manual"&&A.clickCount===2&&B===void 0;this.setState(()=>{this._dragSession={modeAtStart:this._mode,baseHeightRows:Q,startRow:$,currentRow:$,resetToAutoOnRelease:E,doubleClickOverride:B},this._notifyController()})};_handleHandleDrag=(A)=>{if(A.button!=="left"||!this._dragSession)return;let Q=this._toTerminalRow(A.position.y),$=this._dragSession,B=Q-$.startRow,E=$.modeAtStart==="manual"||Math.abs(B)>=this.widget.dragThresholdRows;this.setState(()=>{if($.currentRow=Q,B!==0)$.resetToAutoOnRelease=!1,$.doubleClickOverride=void 0;if(E)this._mode="manual",this._heightRows=this._clampRows($.baseHeightRows-B);this._notifyController()})};_handleHandleRelease=(A)=>{if(A.button!=="left"||!this._dragSession)return;let Q=this._dragSession,$=Q.currentRow-Q.startRow,B=Q.doubleClickOverride==="auto-min"&&$===0,E=Q.doubleClickOverride==="manual-max"&&$===0,D=Q.resetToAutoOnRelease&&$===0,J=Q.modeAtStart==="auto"&&this._mode==="auto"&&this.widget.dragThresholdRows===0&&$===0;this.setState(()=>{if(B)this._mode="auto",this._heightRows=this._clampRows(this._effectiveMinRows);else if(E)this._mode="manual",this._heightRows=this._clampRows(this.widget.maxRows);else if(D)this._mode="auto";else if(J)this._mode="manual",this._heightRows=this._clampRows(Q.baseHeightRows);this._dragSession=null,this._notifyController()})};_syncToInitialProps(){this._mode=this.widget.initialMode,this._heightRows=this._resolveInitialRows(),this._dragSession=null,this._notifyController()}_resolveInitialRows(){return this._clampRows(this.widget.initialRows??this._effectiveMinRows)}_clampRows(A){return Math.max(this._effectiveMinRows,Math.min(A,this.widget.maxRows))}_currentRenderedHeightRows(){return this.context.findRenderObject()?.size.height??this._heightRows}_toTerminalRow(A){return Math.floor(A)}}var mJ6=22,dJ6=14;class Yc0 extends d0{childBuilder;minBodyRows;maxBodyRows;initialRows;initialMode;dragThresholdRows;onHandleDoubleClick;topLeftLabel;topRightLabel;bottomLeftLabel;bottomRightLabel;borderColor;topRightLabelHandleInset;constructor(A){let{key:Q,minBodyRows:$=3,maxBodyRows:B=12,initialRows:E=null,initialMode:D="auto",dragThresholdRows:J=0,onHandleDoubleClick:U,topLeftLabel:Y,topRightLabel:Z,bottomLeftLabel:F,bottomRightLabel:X,borderColor:I,topRightLabelHandleInset:G}=A;super(Q?{key:Q}:{});this.childBuilder="childBuilder"in A&&A.childBuilder?A.childBuilder:()=>A.child,this.minBodyRows=$,this.maxBodyRows=B,this.initialRows=E,this.initialMode=D,this.dragThresholdRows=J,this.onHandleDoubleClick=U,this.topLeftLabel=Y,this.topRightLabel=Z,this.bottomLeftLabel=F,this.bottomRightLabel=X,this.borderColor=I,this.topRightLabelHandleInset=G}createState(){return new fO4}}class fO4 extends m0{_controller=new Jc0;_onControllerChanged=()=>{this.setState(()=>{})};initState(){super.initState(),this._controller.addListener(this._onControllerChanged)}dispose(){this._controller.removeListener(this._onControllerChanged),this._controller.dispose(),super.dispose()}build(A){let Q=S4.of(A),$=this.widget.borderColor??Q.colorScheme.border,E=this._controller.isResizing||this._controller.isHandleHovered?2:1,D=[];if(this.widget.topLeftLabel)D.push({child:this.widget.topLeftLabel,position:"top",alignment:"left"});if(this.widget.topRightLabel)D.push({child:this.widget.topRightLabel,position:"top",alignment:"right"});if(this.widget.bottomLeftLabel)D.push({child:this.widget.bottomLeftLabel,position:"bottom",alignment:"left",offsetX:-1});if(this.widget.bottomRightLabel)D.push({child:this.widget.bottomRightLabel,position:"bottom",alignment:"right"});return new Uc0({controller:this._controller,minRows:this.widget.minBodyRows+2,maxRows:this.widget.maxBodyRows+2,initialRows:this.widget.initialRows,initialMode:this.widget.initialMode,dragThresholdRows:this.widget.dragThresholdRows,handleLeftInset:this.widget.topLeftLabel?mJ6:0,handleRightInset:this.widget.topRightLabel?this.widget.topRightLabelHandleInset??dJ6:0,onHandleDoubleClick:this.widget.onHandleDoubleClick,child:new h$({decoration:new v1(Q.colorScheme.background,new U1(new Y1($,E,"rounded"),new Y1($,1,"rounded"),new Y1($,1,"rounded"),new Y1($,1,"rounded"))),overlays:D,child:this.widget.childBuilder(this._controller.mode)})})}}var xO4={message:"Uploading — Esc to keep editing",withSpinner:!0},cJ6=O4("prompt.dequeue",{noun:"prompt",verb:"dequeue",description:"Dequeue prompts",keywords:["pop"],status:(A)=>{if(A.isUploadLocked())return{type:"disabled",reason:"Prompt editor is not available"};if(!A.isEffectiveEditorEnabled())return{type:"disabled",reason:"Cannot use prompt: dequeue while editing or selecting a message"};return A.queuedMessages().length>0?{type:"enabled"}:{type:"disabled",reason:"Can only use prompt: dequeue when there are queued messages"}}},(A,{dismiss:Q})=>{A.dequeueAll(),Q()}),pJ6=O4("prompt.steerQueuedMessage",{noun:"prompt",verb:"steer queued message",description:"Steer with the next queued prompt",status:(A)=>{if(A.queuedMessages().some((Q)=>!Q.steer))return{type:"enabled"};return A.queuedMessages().length>0?{type:"disabled",reason:"All queued messages are already marked as steering"}:{type:"disabled",reason:"Can only use prompt: steer queued message when there are queued messages"}}},(A,{dismiss:Q})=>{A.steerNextQueuedMessage(),Q()});function lJ6(A,Q){return!A.ctrlKey&&!A.altKey&&!A.metaKey&&A.key===Q}class Zc0 extends d0{props;constructor(A){super();this.props=A}createState(){return new yO4}}class yO4 extends m0{promptEditorEmpty=!1;isUploadLocked=!1;dismissMentionPicker=null;isShowingShortcutsHelp=!1;removeKeyInterceptor=null;removeEditorTextListener=null;unregisterCommands=null;get effectiveEditorEnabled(){return this.widget.props.editorEnabled&&!this.isUploadLocked}initState(){this.isShowingShortcutsHelp=this.widget.props.showShortcutsHelp??!1,this.promptEditorEmpty=this.widget.props.editorController.text==="",this.widget.props.editorFocusNode.addListener(this.handleEditorFocusChange),this.attachEditorTextListener(this.widget.props.editorController),this.unregisterCommands=this.registerCommands(),this.removeKeyInterceptor=G1.instance.addKeyInterceptor((A)=>{let Q=this.widget.props.editorController;if(this.dismissMentionPicker&&lJ6(A,"Escape"))return this.dismissMentionPicker(),!0;if(!this.promptOwnsKeymap())return!1;if(A.key==="?"){if(this.effectiveEditorEnabled&&Q.text===""&&Q.cursorPosition===0)return this.setState(()=>{this.isShowingShortcutsHelp=!this.isShowingShortcutsHelp}),!0}if(A.key==="/"){if(this.effectiveEditorEnabled&&Q.text===""&&Q.cursorPosition===0){if(N4.maybeInvoke(this.context,new Ql)==="handled")return!0}}if(this.isShowingShortcutsHelp){if(this.setState(()=>{this.isShowingShortcutsHelp=!1}),A.key==="Escape")return!0;return!1}return!1})}didUpdateWidget(A){if(A.props.editorController!==this.widget.props.editorController)this.removeEditorTextListener?.(),this.removeEditorTextListener=null,this.promptEditorEmpty=this.widget.props.editorController.text==="",this.attachEditorTextListener(this.widget.props.editorController);if(!A.props.editorEnabled&&this.widget.props.editorEnabled&&this.widget.props.editorFocusNode.hasFocus)this.widget.props.editorFocusNode.requestFocus()}dispose(){this.unregisterCommands?.(),this.unregisterCommands=null,this.removeEditorTextListener?.(),this.removeEditorTextListener=null,this.removeKeyInterceptor?.(),this.removeKeyInterceptor=null,this.dismissMentionPicker=null,this.widget.props.editorFocusNode.removeListener(this.handleEditorFocusChange),super.dispose()}attachEditorTextListener(A){let Q=()=>this.syncEditorTextState(A);A.addListener(Q),this.removeEditorTextListener=()=>A.removeListener(Q)}handleEditorFocusChange=()=>{this.setState()};syncEditorTextState(A){let Q=this.promptEditorEmpty;if(this.promptEditorEmpty=A.text==="",Q!==this.promptEditorEmpty)this.setState()}promptOwnsKeymap(){return this.widget.props.editorFocusNode.hasFocus}createCommands(){let A={isUploadLocked:()=>this.isUploadLocked,isEffectiveEditorEnabled:()=>this.effectiveEditorEnabled,queuedMessages:()=>this.widget.props.queuedMessages,dequeueAll:this.handleDequeueAll,steerNextQueuedMessage:()=>this.widget.props.onSteerNextQueuedMessage()};return[cJ6.bind(A),pJ6.bind(A)]}registerCommands(){let A=sB.of(this.context),$=this.createCommands().map((B)=>A.register(B));return()=>{for(let B of $)B()}}handleDequeueAll=()=>{if(this.isUploadLocked)return;let A=this.widget.props.queuedMessages;if(A.length===0)return;let Q=[],$=[];for(let B of A){let E=B.queuedMessage.content.filter((J)=>J.type==="text").map((J)=>J.text).join("").trim();if(E)Q.push(E);let D=B.queuedMessage.content.filter((J)=>J.type==="image");$.push(...D)}this.widget.props.onDequeueAllMessages(),this.widget.props.editorController.text=Q.join(`
|
|
2880
2880
|
`).trim(),this.widget.props.imageAttachmentsController.setImages($.slice(-B2))};getEnterToSteerMessageID(){let A=this.widget.props.doubleEnterQueuedMessageID;if(A===null||!this.effectiveEditorEnabled||!this.widget.props.editorFocusNode.hasFocus||!this.promptEditorEmpty||this.widget.props.imageAttachmentsController.entries.length>0)return null;let Q=this.widget.props.queuedMessages,$=Q[Q.length-1];if(!$||$.steer||$.pendingRemoval)return null;return $.queuedMessage.messageId===A?A:null}buildTopWidget(){return new UA({crossAxisAlignment:"start",mainAxisSize:"min",children:[this.isShowingShortcutsHelp?new Dc0({layout:"neo"}):y0.shrink()]})}buildBottomLeftLabel(A){if(!this.isUploadLocked)return this.widget.props.bottomLeftLabel;let Q=X4.of(A);return new y0({width:Math.min(Math.max(0,Math.floor(Q.size.width*0.6)),VO4(xO4,Q.supportsEmojiWidth)),child:new Qc0(xO4)})}build(A){let{queuedMessages:Q,selectedQueuedMessageIndex:$,maxBodyRows:B}=this.widget.props,E=this.buildTopWidget(),D=Q.length>0,J=this.effectiveEditorEnabled,U=S4.of(A),{observerOnly:Y}=MQ.of(A),Z=Y||this.widget.props.toolsRunElsewhere?U.colorScheme.info:void 0,F=this.widget.props.topRightLabel,X=this.buildBottomLeftLabel(A),I=this.widget.props.imageAttachmentsController.entries.length>0?4:0,G=this.getEnterToSteerMessageID(),V=[];if(D)V.push(new mA({padding:c0.horizontal(1),child:new nq({queuedMessages:Q,selectedIndex:$,enterToSteerMessageID:G,bottomRightLabel:F})}));return V.push(new Yc0({initialRows:3,minBodyRows:3,maxBodyRows:B+I,topLeftLabel:this.widget.props.topLeftLabel,topRightLabel:D?void 0:F,bottomLeftLabel:X,bottomRightLabel:this.widget.props.bottomRightLabel,...Z?{borderColor:Z}:{},...this.widget.props.topRightLabelHandleInset!==void 0?{topRightLabelHandleInset:this.widget.props.topRightLabelHandleInset}:{},onHandleDoubleClick:({currentRows:K,maxRows:z})=>K>=z?"auto-min":"manual-max",childBuilder:(K)=>new mA({padding:c0.horizontal(1),child:new Ai({editorController:this.widget.props.editorController,imageAttachmentsController:this.widget.props.imageAttachmentsController,activeThreadID:this.widget.props.activeThreadID,enabled:this.widget.props.editorEnabled,onSubmitted:this.widget.props.onSubmitted,onEmptySubmitted:this.widget.props.onEmptySubmitted,onUploadLockChange:this.handleUploadLockChange,focusNode:this.widget.props.editorFocusNode,fillAvailableHeight:K==="manual",topWidget:E,previousThreadIDForReference:this.widget.props.previousThreadIDForReference,onMentionPickerDismissHandlerChange:(z)=>{this.dismissMentionPicker=z}})})})),new iA({opaque:!1,onClick:!J?()=>N4.maybeInvoke(this.context,new ap):void 0,child:new y50({children:V})})}handleUploadLockChange=(A)=>{if(this.isUploadLocked===A)return;this.setState(()=>{this.isUploadLocked=A}),this.widget.props.onUploadLockChange(A)}}E4();import{homedir as iJ6}from"node:os";import sK from"node:path";function bO4(A,Q,$){if(!A)return null;let B=A.workingDirectory??A.workspaceRoot;if(!B)return null;let E;try{E=g0.parse(B).fsPath}catch{return null}let D=nJ6(E),J=aJ6(D),U=A.git?.branch;return oJ6(J,U,Q,$)}function nJ6(A){let Q=iJ6();if(A===Q)return"~";if(A.startsWith(Q+sK.sep))return"~"+A.slice(Q.length);return A}function aJ6(A){let Q=A.split(sK.sep).filter(Boolean);if(Q.length<=5)return A;return[Q.slice(0,2).join(sK.sep),"…",Q.slice(-2).join(sK.sep)].join(sK.sep)}function oJ6(A,Q,$,B){if($<=0)return"";let E=Q?` (${Q})`:"",D=A+E;if(RA(D,B)<=$)return D;let J=A.split(sK.sep);if(J.length>2){let Y=[J[0],"…",J[J.length-1]].join(sK.sep)+E;if(RA(Y,B)<=$)return Y}return o7(D,$,B)}var hO4="command:";function gO4(A,Q,$=[]){let B=X4.of(A),E=S4.of(A),D=Math.max(0,B.size.width-10),J=$.map((R)=>R.value).filter((R)=>R.text.trim()),U=" ─ ",Y=J.length>0?RA(" ─ ",B.supportsEmojiWidth):0,Z=J.map((R)=>R.text.trim()),F=Z.reduce((R,_)=>R+RA(_,B.supportsEmojiWidth),Math.max(0,Z.length-1)),X=J.length>0?Math.min(F,Math.floor(D/3)):0,I=bO4(Q,Math.max(0,D-X-Y),B.supportsEmojiWidth);if(!I&&J.length===0)return;let G=new A0({color:E.colorScheme.foreground,dim:!0}),V=G.copyWith({bold:!0}),K=new A0({color:e0.of(A).app.link,underline:!0}),z=new A0({color:E.colorScheme.border}),W=[new D0({text:new g(" ")})],C=I?RA(I,B.supportsEmojiWidth):0,N=Math.max(0,Math.min(X,D-C-Y)),w=0,u="…",L=RA(u,B.supportsEmojiWidth);for(let R=0;R<J.length;R++){let _=J[R];if(!_)continue;if(w>0){if(N<1)break;W.push(new D0({text:new g(" ",G)})),N-=1}let P=_.text.trim(),f=P;if(RA(P,B.supportsEmojiWidth)>N)f=N<=L?N===L?u:"":`${o7(P,N-L,B.supportsEmojiWidth,"")}${u}`;if(!f)break;let h={text:f};if(_.url!==void 0)h.url=_.url;W.push(rJ6(A,h,G,V,K)),N-=RA(f,B.supportsEmojiWidth),w++}if(I&&w>0)W.push(new D0({text:new g(" ─ ",z)}));if(I)W.push(new D0({text:new g(I,G)}));return W.push(new D0({text:new g(" ")})),new OA({mainAxisSize:"min",children:W})}function rJ6(A,Q,$,B,E){if(!Q.url)return new D0({text:new g(Q.text,$)});let D=sJ6(Q.url);if(D)return new t$({uri:Q.url,text:Q.text,style:$,hoverStyle:B,onClick:(J)=>{if(!sB.maybeOf(J)?.runByID(D,J))DQ.error(J,`Command not found: ${D}`)}});return new t$({uri:Q.url,text:Q.text,style:$,hoverStyle:E})}function sJ6(A){if(!A.startsWith(hO4))return null;let Q;try{Q=decodeURIComponent(A.slice(hO4.length)).trim()}catch{return null}return Q||null}var tJ6=(A)=>{};class $i extends eA{props;constructor(A){super();this.props=A}onSubmitted=(A,Q)=>{let $=A.trim(),B=[];if($.length>0)B.push({type:"text",text:$});B.push(...Q),this.props.onSubmit(B),this.props.editorController.clear()};onEmptySubmitted=()=>{this.props.onEmptySubmit?.()};build(A){let{child:Q,editorController:$,hints:B,status:E,session:D,cancelling:J,agentMode:U,reasoningEffort:Y,speedCostMultiplier:Z,statusMessage:F,queuedMessages:X,selectedQueuedMessageIndex:I,editorEnabled:G,connectionError:V,activeError:K,onErrorResponse:z}=this.props,W=X4.of(A),{width:C,height:H}=W.size,N=gO4(A,this.props.environment,this.props.statusItems??[]),w=this.props.pluginAgentModeURI,u=new od0({agentMode:U,label:this.props.agentModeLabel,leadingMarker:this.props.agentModeLabel?Qi:void 0,leadingMarkerColor:e0.of(A).colors.mutedForeground,onLeadingMarkerClick:w?()=>{z$(A,w)}:void 0,reasoningEffort:Y,speedCostMultiplier:Z,color:this.props.agentModeColor??Zq(U,"default"),horizontalPadding:1}),L=S4.of(A).colorScheme.border,R=()=>new D0({text:new g("─",new A0({color:L})),maxLines:1}),_=[this.props.usageGauge??y0.shrink(),R(),new mO4({agentModeLabel:u,hasOutline:this.props.threadController?.hasTableOfContents??!1,borderColor:L,outlineColor:S4.of(A).colorScheme.secondary,onShowOutline:()=>this.props.threadController?.onShowTableOfContents?.(),onHideOutline:()=>this.props.threadController?.onTableOfContentsHoverEnd?.(),onToggleOutline:()=>this.props.threadController?.onToggleTableOfContents?.()})],P=new OA({mainAxisSize:"min",children:_}),f=this.props.threadController?.hasTableOfContents?32:28,h={hints:B,status:E,session:D,cancelling:J,connectionError:V,statusMessage:F},x=XO4(h)?new y0({width:Math.min(Math.max(0,Math.floor(C*0.6)),IO4(h,W.supportsEmojiWidth)),child:new Ac0(h)}):void 0,v=new Map([[wA.key("ArrowUp"),new YT],[wA.key("Tab"),new YT],[wA.key("ArrowDown"),new UT],[wA.shift("Tab"),new UT],[wA.key("Enter"),new np],[wA.key("Backspace"),new lp],[wA.alt("k"),new rp],[wA.alt("j"),new op],[wA.key("PageUp"),new tp],[wA.key("PageDown"),new ep],[wA.key("Home"),new sp],[wA.key("End"),new Al]]),k=K?new rd0({error:K,onResponse:(d)=>z?.(d)}):new Zc0({editorController:$,editorFocusNode:this.props.editorFocusNode,imageAttachmentsController:this.props.imageAttachmentsController,activeThreadID:this.props.activeThreadID,queuedMessages:X,selectedQueuedMessageIndex:I,doubleEnterQueuedMessageID:this.props.doubleEnterQueuedMessageID,editorEnabled:G,maxBodyRows:Math.floor(W.size.height/3),onSubmitted:this.onSubmitted,onEmptySubmitted:this.onEmptySubmitted,onUploadLockChange:this.props.onEditorUploadLockChange,onSteerNextQueuedMessage:this.props.onSteerNextQueuedMessage,onDequeueAllMessages:this.props.onDequeueAllMessages,showShortcutsHelp:this.props.showShortcutsHelp,toolsRunElsewhere:this.props.toolsRunElsewhere??!1,topRightLabel:P,topRightLabelHandleInset:f,bottomLeftLabel:x,bottomRightLabel:N,previousThreadIDForReference:this.props.previousThreadIDForReference??null}),c=[new Bc0,new P4({child:Q}),new id0({child:k,onSizeChange:this.props.onEditorPanelSizeChange??tJ6})];return new rQ({debugLabel:"ThreadUIShortcuts",shortcuts:v,child:new ZJ({child:new GA({constraints:A4.tight(C,H),child:new UA({mainAxisSize:"max",crossAxisAlignment:"stretch",children:c})})})})}}class mO4 extends eA{props;constructor(A){super();this.props=A}build(A){return new OA({mainAxisSize:"min",children:[this.props.agentModeLabel,...this.props.hasOutline?[new D0({text:new g("─",new A0({color:this.props.borderColor})),maxLines:1}),new iA({cursor:"pointer",onEnter:this.props.onShowOutline,onExit:this.props.onHideOutline,onClick:this.props.onToggleOutline,child:new D0({text:new g(" ≡ ",new A0({color:this.props.outlineColor})),maxLines:1})})]:[]]})}}E3();var dO4=["KB","MB","GB","TB","PB"];function Fc0(A,Q){let $=Q?.decimalPlaces??2;if(A<1024)return`${A} ${z1(A,"byte")}`;let B=A/1024,E=0;while(B>=1024&&E<dO4.length-1)B/=1024,E+=1;let D=dO4[E];if(!D)throw Error(`(bug) missing byte size unit for index ${E}`);return`${B.toFixed($)} ${D}`}function cO4(A){let Q=Math.max(0,Math.floor(A));if(Q>=1e9)return`${(Q/1e9).toFixed(2)}B`;if(Q>=1e6)return`${(Q/1e6).toFixed(2)}M`;if(Q>=1000)return`${Math.round(Q/1000)}k`;return`${Q}`}i0();F$();hA();var eJ6=18,A26=[70,50,35,25],k90="0123456789",Q26="₀₁₂₃₄₅₆₇₈₉",$26="⁰¹²³⁴⁵⁶⁷⁸⁹",f90=6;function x90(A,Q){return[...Array.from({length:Math.max(0,Q-A.length)},()=>" "),...A]}function Bi(A){return k90.includes(A)?k90:null}function B26(A){let Q=k90.indexOf(A);return Q>=0?Q26[Q]??A:" "}function E26(A){let Q=k90.indexOf(A);return Q>=0?$26[Q]??A:" "}function D26(A,Q,$){switch($){case 0:return Bi(A)?B26(A):A;case 1:return"¯";case 2:return"─";case 3:return"_";case 4:return E26(Q);default:return Q}}function J26(A,Q,$){switch($){case 0:return A;case 1:return"¯";case 2:return"─";case 3:return"_";default:return Q}}function pO4(A,Q,$={}){if(A===Q)return 0;let B=Bi(Q);if(!B)return $.animateNonDigits?f90:1;let E=B.indexOf(Q),D=Bi(A),J;if(D===B){let U=B.indexOf(A),Y=(E-U+B.length)%B.length;J=Y===0?B.length:Y}else J=E+1;return J*f90}function U26(A,Q,$,B={}){if($<=0)return A;let E=pO4(A,Q,B);if($>=E)return Q;let D=Bi(Q);if(!D)return B.animateNonDigits?J26(A,Q,$-1):Q;let J=Math.floor(($-1)/f90),U=($-1)%f90,Y,Z;if(Bi(A)===D){let X=D.indexOf(A);Y=D[(X+J)%D.length]??Q,Z=D[(X+J+1)%D.length]??Q}else if(J===0)Y=A,Z=D[0]??Q;else Y=D[J-1]??Q,Z=D[J]??Q;return D26(Y,Z,U)}function Y26(A,Q,$={}){let B=Q4(A),E=Q4(Q),D=Math.max(B.length,E.length);if(D===0)return 0;let J=x90(B,D),U=x90(E,D),Y=0;for(let Z=0;Z<D;Z++){let F=J[Z]??" ",X=U[Z]??" ",I=pO4(F,X,$);if(I>Y)Y=I}return Y}function Z26({from:A,to:Q,frame:$,animateNonDigits:B=!1}){let E=Q4(A),D=Q4(Q),J=Math.max(E.length,D.length);if(J===0)return"";let U=x90(E,J),Y=x90(D,J),Z=[];for(let F=0;F<J;F++){let X=U[F]??" ",I=Y[F]??" ";Z.push(U26(X,I,$,{animateNonDigits:B}))}return Z.join("")}class Xc0 extends d0{props;constructor(A){super(A.key!==void 0?{key:A.key}:{});this.props=A}createState(){return new lO4}}class lO4 extends m0{fromText=null;toText="";frame=0;totalFrames=0;timer=null;initState(){super.initState();let A=this.widget.props.initialText;if(A!==void 0&&A!==this.widget.props.text)this.startAnimation(A,this.widget.props.text);else this.toText=this.widget.props.text}didUpdateWidget(A){if(super.didUpdateWidget(A),A.props.text!==this.widget.props.text)this.startAnimation(this.toText,this.widget.props.text)}dispose(){this.stopTimer(),super.dispose()}currentDisplayedText(){if(this.fromText===null)return this.toText;return Z26({from:this.fromText,to:this.toText,frame:this.frame,animateNonDigits:this.widget.props.animateNonDigits??!1})}startAnimation(A,Q){if(this.stopTimer(),this.fromText=A,this.toText=Q,this.frame=0,this.totalFrames=Y26(A,Q,{animateNonDigits:this.widget.props.animateNonDigits??!1}),this.totalFrames===0){this.fromText=null;return}this.scheduleNextFrame()}scheduleNextFrame(){let A=this.widget.props.easeInIntervalsMs??A26,Q=this.widget.props.tickIntervalMs??eJ6,$=A[this.frame]??Q;this.timer=setTimeout(()=>{if(this.timer=null,!this.mounted)return;if(this.frame+=1,this.frame>=this.totalFrames){this.fromText=null,this.setState();return}this.setState(),this.scheduleNextFrame()},$)}stopTimer(){if(this.timer)clearTimeout(this.timer),this.timer=null}build(A){return new D0({text:new g(this.currentDisplayedText(),this.widget.props.style),maxLines:1})}}var nO4="cost",F26=5000,iO4=10;function aO4(A){let Q=0;for(let $ of A){if($.role!=="assistant")continue;let B=$.usage;if(!B)continue;Q+=B.totalInputTokens+B.outputTokens}return Q}function X26(A){let Q=A?.gauge;if(Q===!1||Q==="tokens"||Q==="cost")return Q;return nO4}class Ic0 extends d0{props;constructor(A){super();this.props=A}createState(){return new oO4}}class oO4 extends m0{mode=nO4;showCosts=!0;costInfo=null;fetchInFlight=!1;lastFetchAt=0;throttleTimer=null;isHovered=!1;configSubscription=null;initState(){super.initState(),this.configSubscription=this.widget.props.configService.config.pipe(tA((A)=>({mode:X26(A.settings),showCosts:A.settings.showCosts??!0})),FQ((A,Q)=>A.mode===Q.mode&&A.showCosts===Q.showCosts)).subscribe({next:({mode:A,showCosts:Q})=>{if(!this.mounted)return;if(this.mode!==A||this.showCosts!==Q)this.setState(()=>{this.mode=A,this.showCosts=Q});if(Q&&A==="cost"&&this.costInfo===null)this.scheduleThrottledFetch()}})}didUpdateWidget(A){if(super.didUpdateWidget(A),A.props.activeThreadID!==this.widget.props.activeThreadID){if(this.costInfo=null,this.lastFetchAt=0,this.cancelThrottleTimer(),this.mode!==!1)this.scheduleThrottledFetch();return}if(this.mode!==!1&&A.props.cumulativeBilledTokens!==this.widget.props.cumulativeBilledTokens)this.scheduleThrottledFetch();if(this.mode==="cost"&&this.showCosts&&this.costInfo===null)this.scheduleThrottledFetch()}dispose(){this.cancelThrottleTimer(),this.configSubscription?.unsubscribe(),this.configSubscription=null,super.dispose()}cancelThrottleTimer(){if(this.throttleTimer)clearTimeout(this.throttleTimer),this.throttleTimer=null}scheduleThrottledFetch(){if(!this.widget.props.activeThreadID)return;if(this.throttleTimer||this.fetchInFlight)return;let A=Date.now()-this.lastFetchAt,Q=Math.max(0,F26-A);this.throttleTimer=setTimeout(()=>{this.throttleTimer=null,this.fetchCost()},Q)}async fetchCost(){let A=this.widget.props.activeThreadID;if(!A||this.fetchInFlight)return;this.fetchInFlight=!0,this.lastFetchAt=Date.now();try{let Q=await j4.threadDisplayCostInfo({threadID:A},{config:this.widget.props.configService});if(!this.mounted)return;if(Q.ok)this.setState(()=>{this.costInfo=Q.result});else S.debug("UsageGauge cost fetch returned non-ok",{threadID:A})}catch(Q){S.debug("UsageGauge cost fetch failed",{error:Q,threadID:A})}finally{this.fetchInFlight=!1}}handleClick=()=>{let A=this.mode==="cost"?"tokens":"cost";if(this.setState(()=>{this.mode=A}),A==="cost"&&this.costInfo===null)this.scheduleThrottledFetch();this.widget.props.configService.updateSettings("gauge",A,"global").catch((Q)=>{S.debug("UsageGauge failed to persist gauge setting",{error:Q,next:A})})};handleEnter=()=>{if(this.isHovered)return;this.setState(()=>{this.isHovered=!0})};handleExit=()=>{if(!this.isHovered)return;this.setState(()=>{this.isHovered=!1})};renderLabel(){if(this.mode==="tokens")return`${cO4(this.widget.props.cumulativeBilledTokens)} tok`;let A=this.costInfo?.totalCostUSD;if(A===null||A===void 0)return null;return cq(A,{decimalPlaces:"more-if-tiny",intent:"cost"})}build(A){if(this.mode===!1||!this.showCosts||!this.widget.props.activeThreadID)return y0.shrink();let Q=this.gaugeWidth();return new y0({width:Q,height:1,child:this.buildGaugeChild(A,Q)})}gaugeWidth(){let A=this.renderLabel();if(A===null)return iO4;let Q=" ".repeat(this.widget.props.horizontalPadding??1);return Math.max(RA(`${Q}${A}${Q}`),iO4)}buildGaugeChild(A,Q){let $=this.renderLabel();if($===null)return y0.shrink();let B=S4.of(A).colorScheme,E=X4.of(A).capabilities.animationSupport!=="disabled",D=new A0({color:B.foreground,dim:!0,bold:this.isHovered}),J=" ".repeat(this.widget.props.horizontalPadding??1),U=`${J}${$}${J}`,Y=RA(U),Z="─".repeat(Y),F=E?new Xc0({text:U,style:D,initialText:Z,animateNonDigits:!0,key:new ZB(`gauge:${this.widget.props.activeThreadID}:${this.mode}`)}):new D0({text:new g(U,D),maxLines:1});return new OA({mainAxisAlignment:"end",children:[new y0({width:Q,height:1,child:new OA({mainAxisAlignment:"end",children:[new iA({onClick:this.handleClick,onEnter:this.handleEnter,onExit:this.handleExit,cursor:"pointer",child:F})]})})]})}}function I26(A){let Q=A?.match(/^#([0-9a-f]{6})$/i);if(!Q?.[1])return;return{type:"rgb",value:{r:Number.parseInt(Q[1].slice(0,2),16),g:Number.parseInt(Q[1].slice(2,4),16),b:Number.parseInt(Q[1].slice(4,6),16)}}}class Gc0 extends d0{editorController;editorFocusNode;copyOnSelectEnabled;client;observer;observerOnly;agentModeDisplay;hints;ideStatus;statusItems;pluginConfirmationBlocked;onPromptSubmitted;onEditorUploadLockChange;editorUploadLocked;notificationService;environmentFallback;constructor(A){super({key:new CK(A.observingClient.client)});this.editorController=A.editorController,this.editorFocusNode=A.editorFocusNode,this.copyOnSelectEnabled=A.copyOnSelectEnabled,this.client=A.observingClient.client,this.observer=A.observingClient.observer,this.observerOnly=A.observingClient.observerOnly??!1,this.agentModeDisplay=A.observingClient.agentModeDisplay,this.hints=A.hints,this.ideStatus=A.ideStatus,this.statusItems=A.statusItems,this.pluginConfirmationBlocked=A.pluginConfirmationBlocked,this.onPromptSubmitted=A.onPromptSubmitted,this.onEditorUploadLockChange=A.onEditorUploadLockChange,this.editorUploadLocked=A.editorUploadLocked,this.notificationService=A.notificationService,this.environmentFallback=A.environmentFallback}createState(){return new rO4}}function G26(A){return S6.safeParse(A).data}var V26=O4("amp.reconnect",{noun:"amp",verb:"reconnect",description:"Disconnect and reconnect the active thread",status:{type:"enabled"}},(A,{dismiss:Q})=>{A.reconnect(),Q()}),K26=O4("amp.disconnect",{noun:"amp",verb:"disconnect",description:"Disconnect the active thread without reconnecting",status:{type:"enabled"}},(A,{dismiss:Q})=>{A.disconnect(),Q()});class rO4 extends m0{terminalTitleController=new bl;imageAttachmentsController=new pq;visibleMessageReadTracker=new Dd0({isTerminalFocused:qK,onTerminalFocusChange:py0,markMessageRead:(A)=>this.widget.client.markMessageRead(A)});threadController=null;agentState=new p3(this,"idle");connectionError=new p3(this,null);pendingSend=new p3(this,!1);observerSnapshot=new p3(this,null);queuedMessages=new p3(this,[]);activeError=new p3(this,null);threadSettings=new p3(this,null);environment=new p3(this,null);cancelling=null;cancelHintTimer=new Hp(this,1000);controllerUnsubscription=null;cancelledSubscription=null;agentMessageIdSubscription=null;queuedMessagesRemovalSubscription=null;titleSubscription=null;agentBusySubscription=null;imagePreviewOverlay=null;editingMessageId=null;editingController=null;doubleEnterMessage=null;pendingQueuedMessageRestore=null;editorUploadLocked=!1;unregisterCommands=null;initState(){this.editorUploadLocked=this.widget.editorUploadLocked,this.unregisterCommands=this.registerCommands(),this.subscribeToEditorController(),this.recreateThreadController(),this.visibleMessageReadTracker.start(),this.subscribeToObserver()}didUpdateWidget(A){if(A.editorController!==this.widget.editorController)this.unsubscribeFromEditorController(A.editorController),this.subscribeToEditorController();if(A.editorUploadLocked!==this.widget.editorUploadLocked)this.editorUploadLocked=this.widget.editorUploadLocked;if(A.pluginConfirmationBlocked!==this.widget.pluginConfirmationBlocked)this.terminalTitleController.setPluginConfirmationBlocked(this.widget.pluginConfirmationBlocked);if(A.client!==this.widget.client||A.observer!==this.widget.observer)this.recreateThreadController(),this.resetThreadClientState(),this.terminalTitleController.clear(),this.subscribeToObserver()}resetThreadClientState(){this.pendingQueuedMessageRestore=null,this.visibleMessageReadTracker.reset(),this.agentState.dispose(),this.connectionError.dispose(),this.pendingSend.dispose(),this.observerSnapshot.dispose(),this.queuedMessages.dispose(),this.activeError.dispose(),this.threadSettings.dispose(),this.environment.dispose()}subscribeToObserver(){this.cancelledSubscription?.unsubscribe(),this.agentMessageIdSubscription?.unsubscribe(),this.queuedMessagesRemovalSubscription?.unsubscribe(),this.titleSubscription?.unsubscribe(),this.agentBusySubscription?.unsubscribe(),this.agentState.subscribe(this.widget.observer.agentState()),this.connectionError.subscribe(this.widget.observer.connectionError()),this.pendingSend.subscribe(this.widget.observer.pendingSend()),this.observerSnapshot.setValue(this.widget.observer.observerSnapshot().getValue()),this.observerSnapshot.subscribe(this.widget.observer.observerSnapshot()),this.queuedMessages.subscribe(this.widget.observer.queuedMessages()),this.activeError.subscribe(this.widget.observer.activeError()),this.threadSettings.subscribe(this.widget.observer.threadSettings()),this.environment.subscribe(this.widget.client.environmentChanges()),this.titleSubscription=this.widget.observer.title().subscribe((A)=>{this.terminalTitleController.setTitle(A)}),this.terminalTitleController.setPluginConfirmationBlocked(this.widget.pluginConfirmationBlocked),this.agentBusySubscription=this.widget.observer.agentState().subscribe((A)=>{let Q=A!=="idle"&&A!=="error";this.terminalTitleController.setBusy(Q)}),this.widget.notificationService.attach(this.widget.observer.agentState(),this.widget.observer.activeError(),{prepareTerminalTitleForNotification:()=>this.terminalTitleController.prepareForNotification()}),this.queuedMessagesRemovalSubscription=this.widget.observer.queuedMessageRemovalEvents().subscribe((A)=>this.restoreLocallyRemovedQueuedMessage(A)),this.cancelledSubscription=this.widget.observer.cancelled().subscribe((A)=>{if(!this.mounted||!this.cancelledMessageMatchesLocalCancel(A))return;this.setState(()=>{this.cancelling=null})}),this.agentMessageIdSubscription=this.widget.observer.agentMessageId().subscribe((A)=>{if(!this.mounted||!this.agentMessageIdClearsLocalCancel(A))return;this.setState(()=>{this.cancelling=null})})}cancelledMessageMatchesLocalCancel(A){if(this.cancelling===null)return!1;if(this.cancelling.messageId===null)return!0;return A.messageId===this.cancelling.messageId}agentMessageIdClearsLocalCancel(A){if(this.cancelling===null)return!1;if(this.cancelling.messageId===null)return!0;return A===null||A!==this.cancelling.messageId}subscribeToThreadController(){let A=this.threadController;if(!A)return;this.controllerUnsubscription=A.subscribe(()=>{this.setState()})}recreateThreadController(){this.controllerUnsubscription?.(),this.threadController?.dispose(),this.threadController=new gl(this.widget.observer.reader()),this.subscribeToThreadController()}onEscPressed=()=>{if(this.editingMessageId!==null)return this.cancelEdit(),"handled";if(this.threadController?.hasSelection)return this.threadController.clearSelection(),"handled";if(this.cancelling!==null)return"handled";if(!m3(this.agentState.getValue()))return"ignored";if(this.cancelHintTimer.isActive()){this.cancelHintTimer.clear();let A=this.widget.observer.agentMessageId().getValue();this.setState(()=>{this.cancelling={messageId:A}}),this.widget.client.cancelAgentLoop().catch((Q)=>{S.warn("Failed to cancel agent loop",{error:Q})})}else this.cancelHintTimer.activate();return"handled"};onEditIntent=()=>{if(this.editingMessageId!==null)return"ignored";let A=this.threadController;if(!A)return"ignored";let Q=A.selectedMessageIndex;if(Q===null)return"ignored";let $=A.entries[Q];if(!$||$.type!=="message"||$.role!=="user")return"ignored";let B=G26($.sourceMessageID);if(B===void 0)return"ignored";let E=new EZ;return E.text=$.text,E.cursorPosition=$.text.length,this.editingMessageId=B,this.editingController=E,this.clearDoubleEnterMessage(),"handled"};cancelEdit(){this.editingController?.dispose(),this.editingMessageId=null,this.editingController=null,this.setState()}onSubmitEdit=(A,Q,$)=>{let B=Q.trim();if(B.length===0&&$.length===0)return;let E=[];if(B.length>0)E.push({type:"text",text:B});E.push(...$),this.widget.client.editUserMessage(A,E,IF4()).catch((D)=>{S.warn("Failed to edit user message",{error:D})}),this.editingController?.dispose(),this.editingMessageId=null,this.editingController=null,this.threadController?.clearSelection(),this.threadController?.onScrollToBottom?.(),this.setState()};onLastVisibleMessageChange=(A)=>{this.visibleMessageReadTracker.reportLastVisibleMessage(A)};dispose(){this.unregisterCommands?.(),this.unregisterCommands=null,this.dismissImagePreview(),this.unsubscribeFromEditorController(this.widget.editorController),this.doubleEnterMessage=null,this.editingController?.dispose(),this.editingController=null,this.editingMessageId=null,this.cancelling=null,this.pendingQueuedMessageRestore=null,this.cancelledSubscription?.unsubscribe(),this.cancelledSubscription=null,this.agentMessageIdSubscription?.unsubscribe(),this.agentMessageIdSubscription=null,this.queuedMessagesRemovalSubscription?.unsubscribe(),this.queuedMessagesRemovalSubscription=null,this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.agentBusySubscription?.unsubscribe(),this.agentBusySubscription=null,this.visibleMessageReadTracker.dispose(),this.widget.notificationService.detach(),this.terminalTitleController.dispose(),this.controllerUnsubscription?.(),this.threadController?.dispose(),this.imageAttachmentsController.dispose(),super.dispose()}createCommands(){let A={reconnect:()=>this.reconnectActiveThread(),disconnect:()=>this.disconnectActiveThread()};return[V26.bind(A),K26.bind(A)]}registerCommands(){let A=sB.of(this.context),$=this.createCommands().map((B)=>A.register(B));return()=>{for(let B of $)B()}}async reconnectActiveThread(){let A=DQ.maybeOf(this.context),Q=this.widget.client.getThreadId();try{await this.widget.client.reconnect()}catch($){S.error("Failed to reconnect thread",{error:$,threadID:Q});let B=$ instanceof Error?$.message:String($);A?.show(`Reconnect failed: ${B}`,"error",4000)}}async disconnectActiveThread(){let A=DQ.maybeOf(this.context),Q=this.widget.client.getThreadId(),$=A?.show(Q?`Disconnecting ${Q}...`:"Disconnecting thread...","warning",60000);try{if(await this.widget.client.disconnectAndWait(),A&&$!==void 0)A.update($,Q?`Disconnected ${Q}`:"Disconnected thread","success",2000)}catch(B){S.error("Failed to disconnect thread",{error:B,threadID:Q});let E=B instanceof Error?B.message:String(B);if(A&&$!==void 0)A.update($,`Disconnect failed: ${E}`,"error",4000)}}onShowImagePreview=(A,Q,$)=>{this.showOverlay(A,()=>new hl({image:Q,imageIndex:$,onDismiss:()=>this.dismissImagePreview()}))};onShowFileImagePreview=(A)=>{this.showOverlay(this.context,()=>new J70({filePath:A,onDismiss:()=>this.dismissImagePreview()}))};onShowPainterSaveDialog=(A,Q,$)=>{this.showOverlay(A,()=>new J70({filePath:$,imageBlock:Q,onDismiss:()=>this.dismissImagePreview()}))};showOverlay(A,Q){this.dismissImagePreview();let $=new aX(Q);this.imagePreviewOverlay=$,ZJ.of(A).insert($)}dismissImagePreview(){if(this.imagePreviewOverlay)this.imagePreviewOverlay.remove(),this.imagePreviewOverlay=null}onErrorResponse=(A)=>{let{client:Q,observer:$}=this.widget;switch(A){case"retry":$.dismissActiveError(),Q.retryAgentLoop().catch((B)=>{S.warn("Failed to retry agent loop",{error:B})});break;case"dismiss":Q.dismissActiveError($.getActiveErrorSeq()??void 0).catch((B)=>{S.warn("Failed to dismiss active error",{error:B})}),$.dismissActiveError();break;case"add-credits":break}};getSelectedQueuedMessage(){let A=this.threadController?.selectedQueuedMessageIndex;if(A===null||A===void 0)return null;return $O4(this.queuedMessages.getValue())[A]??null}steerNextQueuedMessage=()=>{let A=this.queuedMessages.getValue().find((Q)=>!Q.steer);if(!A)return;this.widget.client.steerQueuedMessage(A.queuedMessage.messageId).catch((Q)=>{S.warn("Failed to steer queued message",{error:Q})})};subscribeToEditorController(){this.widget.editorController.addListener(this.clearDoubleEnterMessageOnEdit)}unsubscribeFromEditorController(A){A.removeListener(this.clearDoubleEnterMessageOnEdit)}clearDoubleEnterMessageOnEdit=()=>{if(this.doubleEnterMessage===null||this.widget.editorController.text==="")return;this.clearDoubleEnterMessage()};clearDoubleEnterMessage(){this.setState(()=>{this.doubleEnterMessage=null})}setDoubleEnterMessage(A){this.setState(()=>{this.doubleEnterMessage=A})}getDoubleEnterMessage(){let A=this.doubleEnterMessage;if(A===null)return null;let Q=this.queuedMessages.getValue().find(($)=>$.queuedMessage.messageId===A);if(Q&&!Q.steer&&!Q.pendingRemoval)return A;if(Q)return this.doubleEnterMessage=null,null;if(this.pendingSend.getValue())return null;return this.doubleEnterMessage=null,null}trySubmitDoubleEnterMessage(){let A=this.getDoubleEnterMessage();if(!A)return;if(this.clearDoubleEnterMessage(),!m3(this.agentState.getValue())||this.editingMessageId!==null||this.threadController?.hasSelection)return;this.widget.client.steerQueuedMessage(A).catch((Q)=>{S.warn("Failed to steer queued message",{error:Q})})}handleEditorUploadLockChange=(A)=>{this.editorUploadLocked=A,this.widget.onEditorUploadLockChange(A)};restoreLocallyRemovedQueuedMessage(A){let Q=this.pendingQueuedMessageRestore;if(!Q||A.serverMessage.queuedMessageId!==Q.queuedMessage.messageId)return;if(this.pendingQueuedMessageRestore=null,this.editorUploadLocked)return;this.popRemovedQueuedMessageIntoEditor(Q)}popRemovedQueuedMessageIntoEditor(A){let Q=this.widget.editorController.text,$=nq.rowText(A);this.widget.editorController.text=Q===""?$:`${Q}
|
|
2881
2881
|
|
|
2882
2882
|
${$}`,this.imageAttachmentsController.setImages(A.queuedMessage.content.filter(H00)),this.threadController?.clearSelection()}build(A){let{editorController:Q,client:$}=this.widget,B=this.threadController,E=this.widget.observer.agentMode,D=this.widget.observer.reasoningEffort,J=this.queuedMessages.getValue(),U=this.getDoubleEnterMessage();B.setQueuedMessageCount(J.length);let{configService:Y}=MQ.of(A),Z=$.getThreadId()??null,F=aO4(this.widget.observer.protocolMessages()),X=this.threadSettings.getValue(),I=new Ic0({activeThreadID:Z,configService:Y,cumulativeBilledTokens:F}),G=Jd0(E,X),V=this.observerSnapshot.getValue()??this.widget.observer.observerSnapshot().getValue(),K=this.widget.observerOnly||V.session.identity.requiredRole==="observer",z=new cA(()=>{return this.onEscPressed()}),W=new cA(()=>{let b=this.getSelectedQueuedMessage();if(!b)return"ignored";return $.steerQueuedMessage(b.queuedMessage.messageId).catch((p)=>{S.warn("Failed to steer queued message",{error:p})}),"handled"}),C=new cA(()=>{let b=this.getSelectedQueuedMessage();if(!b)return"ignored";return this.pendingQueuedMessageRestore=b,$.removeQueuedMessage(b.queuedMessage.messageId).catch((p)=>{S.warn("Failed to remove queued message",{error:p})}),this.clearDoubleEnterMessage(),"handled"}),H=new cA(()=>{if(B.selectPrevious())return"handled";return"ignored"}),N=new cA(()=>{if(B.selectNext())return"handled";return"ignored"}),w=new cA(()=>{return B.onPageUp?.(),"handled"}),u=new cA(()=>{return B.onPageDown?.(),"handled"}),L=new cA(()=>{return B.onHalfPageUp?.(),"handled"}),R=new cA(()=>{return B.onHalfPageDown?.(),"handled"}),_=new cA(()=>{return B.onScrollToTop?.(),"handled"}),P=new cA(()=>{return B.onScrollToBottom?.(),"handled"}),f=new cA(()=>{if(B.hasSelection)B.clearSelection();if(this.editingMessageId===null)this.widget.editorFocusNode.requestFocus();return"handled"}),h=new cA(()=>this.onEditIntent()),x=new cA((b)=>{if(B.selectQueuedMessage(b.visualIndex))return"handled";return"ignored"}),c=[new N4({actions:new Map([[w70,z],[u70,h],[ap,f],[ip,x],[np,W],[lp,C],[YT,H],[UT,N],[tp,w],[ep,u],[rp,L],[op,R],[sp,_],[Al,P]]),child:new rQ({debugLabel:"ActiveThreadShortcuts",shortcuts:new Map([[wA.key("Escape"),new w70],[wA.key("e"),new u70]]),child:new lX({onShowImagePreview:this.onShowFileImagePreview,child:new lK({onShowImagePreview:this.onShowImagePreview,onShowSaveDialog:this.onShowPainterSaveDialog,child:new $i({threadController:B,child:new el({threadController:B,copyOnSelectEnabled:this.widget.copyOnSelectEnabled,activeThreadID:Z,editingMessageId:this.editingMessageId,editingController:this.editingController,onSubmitEdit:this.onSubmitEdit,onLastVisibleMessageChange:this.onLastVisibleMessageChange}),editorController:Q,editorFocusNode:this.widget.editorFocusNode,imageAttachmentsController:this.imageAttachmentsController,activeThreadID:Z,usageGauge:I,queuedMessages:J,selectedQueuedMessageIndex:B.selectedQueuedMessageIndex,doubleEnterQueuedMessageID:U,onSteerNextQueuedMessage:this.steerNextQueuedMessage,onDequeueAllMessages:()=>{this.pendingQueuedMessageRestore=null,this.clearDoubleEnterMessage();for(let b of this.queuedMessages.getValue())$.removeQueuedMessage(b.queuedMessage.messageId).catch((p)=>{S.warn("Failed to remove queued message",{error:p})});B.clearSelection()},onEditorUploadLockChange:this.handleEditorUploadLockChange,editorEnabled:!B.hasSelection&&this.editingMessageId===null,hints:this.widget.hints,status:V.status,session:V.session,connectionError:this.connectionError.getValue(),cancelling:this.cancelling!==null,toolsRunElsewhere:K,agentMode:E,agentModeLabel:this.widget.agentModeDisplay?.label,agentModeColor:I26(this.widget.agentModeDisplay?.color),reasoningEffort:D,speedCostMultiplier:G,activeError:this.activeError.getValue(),onErrorResponse:this.onErrorResponse,ideStatus:this.widget.ideStatus,statusItems:this.widget.statusItems,environment:this.environment.getValue()??this.widget.environmentFallback,onSubmit:(b)=>{let p=b.find((t)=>t.type==="text");if(p&&p.type==="text")this.widget.onPromptSubmitted(p.text);let n=D50(this.widget.ideStatus),a=m3(this.agentState.getValue()),X0=KK();if($.sendUserMessage(b,void 0,{messageId:X0,userState:n}).catch((t)=>{S.warn("Failed to send user message",{error:t})}),a)this.setDoubleEnterMessage(X0);else this.clearDoubleEnterMessage();B.onScrollToBottom?.()},onEmptySubmit:()=>this.trySubmitDoubleEnterMessage()})})})})})],d=b70(this.cancelHintTimer.isActive()?{key:"Esc",description:"again to cancel"}:null);if(d)c.push(d);return new t1({children:c})}}var sO4=O4("thread.archive",{noun:"thread",verb:"archive",description:"Archive thread and start a new thread",status:(A)=>A.getThreadContext()?{type:"enabled"}:{type:"disabled",reason:"Cannot archive an empty thread"}},async(A,{context:Q,dismiss:$})=>{let B=A.getThreadContext()?.client.getThreadId();if(!B)return;let E=DQ.maybeOf(Q),D=await A.archiveThread(B);if($(),D===null)N4.maybeInvoke(Q,new Lq);else E?.show(`Failed to archive thread: ${D.message}`,"error")}),tO4=O4("thread.archiveAndQuit",{noun:"thread",verb:"archive and quit",description:"Archive thread and quit",status:(A)=>A.getThreadContext()?{type:"enabled"}:{type:"disabled",reason:"Cannot archive an empty thread"}},async(A,{context:Q,dismiss:$})=>{let B=A.getThreadContext()?.client.getThreadId();if(!B)return;let E=DQ.maybeOf(Q),D=await A.archiveThread(B);if($(),D===null)N4.maybeInvoke(Q,new vK);else E?.show(`Failed to archive thread: ${D.message}`,"error")});function y90(A){if(A>=1000)return`${(A/1000).toFixed(1)}k`;return A.toString()}class Vc0 extends d0{threadID;analyzeContext;onDismiss;constructor(A){super();this.threadID=A.threadID,this.analyzeContext=A.analyzeContext,this.onDismiss=A.onDismiss}createState(){return new eO4}}class eO4 extends m0{analysis=null;error=null;loading=!0;abortController=null;initState(){this.abortController=new AbortController,this.loadAnalysis()}dispose(){this.abortController?.abort(),this.abortController=null}async loadAnalysis(){try{let A=await this.widget.analyzeContext(this.widget.threadID,this.abortController?.signal);if(!this.mounted)return;this.setState(()=>{this.analysis=A,this.loading=!1})}catch(A){if(!this.mounted)return;this.setState(()=>{this.error=A instanceof Error?A.message:String(A),this.loading=!1})}}build(A){return new E1({header:"Context Usage Analysis",maxWidth:76,maxHeight:28,onDismiss:this.widget.onDismiss,child:new vB({child:new M5({child:this.buildContent(A)})})})}buildContent(A){let Q=S4.of(A).colorScheme,$=new A0({color:Q.secondary}),B=new A0({color:Q.foreground}),E=new A0({color:Q.foreground,dim:!0}),D=new A0({color:Q.destructive});if(this.loading)return new D0({text:new g("Analyzing context tokens…",$),selectable:!0});if(this.error)return new D0({text:new g(`Error: ${this.error}`,D),selectable:!0});if(!this.analysis)return new D0({text:new g("No analysis available",$),selectable:!0});return new D0({text:new g("",void 0,this.buildAnalysisSpans({analysis:this.analysis,labelStyle:$,valueStyle:B,percentStyle:E})),selectable:!0})}buildAnalysisSpans(A){let{analysis:Q,labelStyle:$,valueStyle:B,percentStyle:E}=A,D=[];D.push(new g("Model: ",$)),D.push(new g(Q.modelDisplayName,B)),D.push(new g(` (${y90(Q.maxContextTokens)} context)
|
|
@@ -2910,11 +2910,11 @@ Ctrl-X, Y, Z to unlock`;if(this.widget.centerContent)H=this.widget.centerContent
|
|
|
2910
2910
|
`));if(U.tools.length===0)J.push(new g(` └─ No tools available
|
|
2911
2911
|
`,E));else for(let F of U.tools)aU6(J,F,$);J.push(new g(`
|
|
2912
2912
|
`))}return J}function aU6(A,Q,$){let{colors:B,app:E}=$,D=oU6(Q.status,$);if(A.push(new g(` ${D.icon} `,new A0({color:D.color}))),A.push(new g(Q.name,new A0({color:Q.status==="pending"?B.warning:E.command}))),Q.status==="pending")A.push(new g(" discovering...",new A0({color:B.foreground,dim:!0})));else if(Q.description)A.push(new g(` ${iL4(Q.description,50)}`,new A0({color:B.foreground,dim:!0})));if(Q.error)A.push(new g(` ${iL4(Q.error,40)}`,new A0({color:E.toolError})));A.push(new g(`
|
|
2913
|
-
`))}function oU6(A,Q){let{colors:$,app:B}=Q;switch(A){case"pending":return{icon:"◌",color:$.warning};case"registered":return{icon:"•",color:$.mutedForeground};case"failed":return{icon:"✗",color:B.toolError};case"duplicate":return{icon:"◇",color:$.warning};default:return{icon:"?",color:$.foreground}}}function iL4(A,Q){let $=A.replace(/\s+/g," ").trim();if(RA($)<=Q)return $;let B="...",E=RA(B);if(Q<=E)return o7(B,Q);return`${o7($,Q-E,!0,"")}${B}`}var nc0="https://ampcode.com/news/neo",ac0=[{title:"Meet the new Amp CLI",body:[]},{title:"Rebuilt From The Ground Up",body:["Same close-up terminal workflow. Completely different underneath."]},{title:"Just Keep Typing",body:["Context is summarized automatically at ~90%.","No handoff flow. No context percentage to babysit."]},{title:"Queueing and Steering",body:["Sending a message now queues by default instead of cancelling tools.","Use steering when you want the agent to see something sooner."]},{title:"Remote Control",body:["Start a thread in the CLI, then keep going from ampcode.com.","Watch live updates and queue follow-ups from any device."]},{title:"Customize Amp with Amp",body:[{text:"Amp now has a ",linkText:"complete plugin API",href:"https://ampcode.com/manual/plugin-api",textAfter:"."},"Add tools, commands, control UI, and hook into events."]},{title:"Permissions",body:[{text:"By default (when no ",highlightText:"amp.permissions",textAfterHighlight:" setting is present), Amp no longer asks for confirmation before running any tools and commands. And you can now implement your own custom permission logic with ",linkText:"plugins",href:"https://ampcode.com/manual/plugin-api",textAfter:"."}]},{title:null,body:["Check out the full news post for more:",{text:nc0,href:nc0}]}];function rU6(A){return[{title:"Upgrade your Amp CLI",body:[{text:"This npm-based distribution of Amp CLI has been deprecated. To use the ",linkText:"new Amp CLI",href:nc0,textAfter:" you'll need to switch to the binary install:",linkWidget:!0},"",{codeBlock:["npm uninstall -g @sourcegraph/amp",A]}]}]}function sU6(){if(process.platform==="win32")return'powershell -c "irm https://ampcode.com/install.ps1 | iex"';return"curl -fsSL https://ampcode.com/install.sh | bash"}var fT=50,aq=40,lc0=1000,tU6=420,eU6=760,AY6=-250,QY6=1100,l90=33,rL4=0.999,$Y6=2.1,BY6=720,EY6=420,Ej4="Meet the new",Dj4="Amp",Jj4="CLI",oc0=Q4(Ej4).length,DY6=Q4(Dj4).length,JY6=Q4(Jj4).length,i90={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}},sL4={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},tL4={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}},eL4=[i90,sL4,tL4,i90,sL4,tL4,i90],UY6=i90;class rc0 extends d0{onDismiss;onQuit;animationProgress;animationsEnabled;variant;binaryInstallCommand;introStages;dismissible;constructor(A){super();this.onDismiss=A.onDismiss,this.onQuit=A.onQuit,this.animationProgress=A.animationProgress,this.animationsEnabled=A.animationsEnabled??!0,this.variant=A.variant??"intro",this.binaryInstallCommand=A.binaryInstallCommand??sU6(),this.introStages=this.variant==="npm-migration"?rU6(this.binaryInstallCommand):ac0,this.dismissible=this.variant!=="npm-migration"}createState(){return new Uj4}}class Uj4 extends m0{startedAt=performance.now();animationTimer=null;stageTransitionTimer=null;firstStageTitleTimer=null;firstStageHintTimer=null;firstStageRevealTimer=null;firstStageTitleRevealStartedAt=null;firstStageHintRevealStartedAt=null;stageTransitionStartedAt=performance.now();animationStartProgress=0;animationTargetProgress=1;animationDurationMs=lc0;onAnimationComplete=null;animationProgress=0;introStage=0;previousIntroStage=null;stageTransitionProgress=1;stageTransitionDirection=1;firstStageTitleVisible=!1;firstStageHintVisible=!1;firstStageTitleRevealProgress=0;firstStageHintRevealProgress=0;dismissTimer=null;dismissStartedAt=performance.now();dismissProgress=0;isDismissing=!1;splashOrbGlow=new P5(42);initState(){super.initState(),this.startAnimationIfNeeded()}didUpdateWidget(A){if(super.didUpdateWidget(A),A.animationProgress!==this.widget.animationProgress||A.animationsEnabled!==this.widget.animationsEnabled)this.startAnimationIfNeeded()}dispose(){this.stopAnimation(),this.stopStageTransitionTimer(),this.stopFirstStageRevealTimers(),this.stopDismissAnimation(),super.dispose()}startAnimationIfNeeded(){if(this.stopAnimation(),this.stopFirstStageRevealTimers(),this.widget.animationProgress!==void 0){this.animationProgress=LE(this.widget.animationProgress),this.firstStageTitleVisible=this.animationProgress>=rL4,this.firstStageHintVisible=this.animationProgress>=rL4,this.firstStageTitleRevealProgress=this.firstStageTitleVisible?1:0,this.firstStageHintRevealProgress=this.firstStageHintVisible?1:0;return}if(!this.widget.animationsEnabled){this.stopStageTransitionTimer(),this.stopDismissAnimation(),this.animationProgress=1,this.isDismissing=!1,this.dismissProgress=0,this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1,this.previousIntroStage=null,this.stageTransitionProgress=1;return}if(this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0,this.startProgressAnimation({from:0,to:1,durationMs:lc0,onComplete:()=>{if(!this.widget.dismissible)this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1})}}),this.widget.dismissible)this.startFirstStageRevealSequence()}startDismissAnimation(){if(this.isDismissing)return;if(!this.widget.animationsEnabled){this.widget.onDismiss();return}this.stopFirstStageRevealTimers(),this.stopStageTransitionTimer(),this.dismissStartedAt=performance.now(),this.setState(()=>{this.isDismissing=!0,this.dismissProgress=0}),this.dismissTimer=setInterval(()=>{let A=performance.now()-this.dismissStartedAt,Q=LE(A/eU6);if(this.setState(()=>{this.dismissProgress=Q}),Q>=1)this.stopDismissAnimation(),this.widget.onDismiss()},l90)}canNavigateIntroStage(){if(this.isDismissing)return!1;if(!this.firstStageHintVisible)return!1;if(this.introStage===0&&this.firstStageHintRevealProgress<1)return!1;return!0}advanceIntroStage(){if(!this.canNavigateIntroStage())return;if(this.isFinalIntroStage()){if(this.widget.dismissible)this.startDismissAnimation();return}this.moveIntroStage(1)}dismissFromFinalIntroStage(){if(!this.widget.dismissible||!this.canNavigateIntroStage()||!this.isFinalIntroStage())return!1;return this.startDismissAnimation(),!0}nextIntroStage(){if(!this.canNavigateIntroStage()||this.isFinalIntroStage())return;this.moveIntroStage(1)}goToPreviousIntroStage(){if(!this.canNavigateIntroStage()||this.introStage<=0)return;this.moveIntroStage(-1)}isFinalIntroStage(){return this.introStage>=this.widget.introStages.length-1}moveIntroStage(A){let Q=this.introStage+A;if(this.stopStageTransitionTimer(),this.stageTransitionStartedAt=performance.now(),this.setState(()=>{this.previousIntroStage=this.introStage,this.introStage=Q,this.stageTransitionDirection=A}),this.widget.animationProgress!==void 0||!this.widget.animationsEnabled){this.setState(()=>{this.previousIntroStage=null,this.stageTransitionProgress=1});return}this.setState(()=>{this.stageTransitionProgress=0}),this.stageTransitionTimer=setInterval(()=>{let $=performance.now()-this.stageTransitionStartedAt,B=LE($/tU6);if(this.setState(()=>{if(this.stageTransitionProgress=B,B>=1)this.previousIntroStage=null}),B>=1)this.stopStageTransitionTimer()},l90)}startProgressAnimation({from:A,to:Q,durationMs:$,onComplete:B}){this.stopAnimation(),this.startedAt=performance.now(),this.animationStartProgress=A,this.animationTargetProgress=Q,this.animationDurationMs=$,this.onAnimationComplete=B,this.animationProgress=A,this.animationTimer=setInterval(()=>{let E=performance.now()-this.startedAt,D=LE(E/this.animationDurationMs),J=this.animationStartProgress+(this.animationTargetProgress-this.animationStartProgress)*xT(D);if(this.setState(()=>{this.animationProgress=J}),D>=1)this.stopAnimation(),this.onAnimationComplete?.(),this.onAnimationComplete=null},l90)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null}stopStageTransitionTimer(){if(this.stageTransitionTimer)clearInterval(this.stageTransitionTimer),this.stageTransitionTimer=null}startFirstStageRevealSequence(){if(this.stopFirstStageRevealTimers(),!this.widget.animationsEnabled){this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1});return}this.setState(()=>{this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0});let A=Math.max(0,lc0+AY6),Q=A+QY6;this.firstStageTitleTimer=setTimeout(()=>{this.firstStageTitleRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageTitleRevealProgress=0}),this.startFirstStageRevealTimer()},A),this.firstStageHintTimer=setTimeout(()=>{this.firstStageHintRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageHintVisible=!0,this.firstStageHintRevealProgress=0}),this.startFirstStageRevealTimer()},Q)}startFirstStageRevealTimer(){if(this.firstStageRevealTimer)return;this.firstStageRevealTimer=setInterval(()=>{let A=performance.now(),Q=this.firstStageTitleRevealStartedAt?LE((A-this.firstStageTitleRevealStartedAt)/BY6):this.firstStageTitleRevealProgress,$=this.firstStageHintRevealStartedAt?LE((A-this.firstStageHintRevealStartedAt)/EY6):this.firstStageHintRevealProgress;if(this.setState(()=>{this.firstStageTitleRevealProgress=Q,this.firstStageHintRevealProgress=$}),Q>=1&&$>=1)this.stopFirstStageRevealTimer()},l90)}stopFirstStageRevealTimers(){if(this.stopFirstStageRevealTimer(),this.firstStageTitleRevealStartedAt=null,this.firstStageHintRevealStartedAt=null,this.firstStageTitleTimer)clearTimeout(this.firstStageTitleTimer),this.firstStageTitleTimer=null;if(this.firstStageHintTimer)clearTimeout(this.firstStageHintTimer),this.firstStageHintTimer=null}stopFirstStageRevealTimer(){if(this.firstStageRevealTimer)clearInterval(this.firstStageRevealTimer),this.firstStageRevealTimer=null}stopDismissAnimation(){if(this.dismissTimer)clearInterval(this.dismissTimer),this.dismissTimer=null}currentOrbPalette(){let A=Aj4(this.introStage),Q=this.previousIntroStage===null||this.stageTransitionProgress>=1?A:Qj4(Aj4(this.previousIntroStage),A,xT(this.stageTransitionProgress));return this.dismissProgress>0?Qj4(Q,UY6,xT(this.dismissProgress)):Q}build(A){let Q=S4.of(A).colorScheme,$=e0.of(A),B=this.currentOrbPalette(),E=e7(1,"deep",B),D=X4.of(A).size,U=this.widget.animationProgress??this.animationProgress,Y=Math.max(D.width/fT,D.height/aq)*$Y6,Z=Y+(1-Y)*U,F=xT(this.dismissProgress),X=Math.max(fT,Math.round(fT*Z)),I=Math.max(aq,Math.round(aq*Z)),G=Math.round((D.width-X)/2),V=Math.round((D.height-I)/2),K=Math.max(0,Math.floor((D.width-fT)/2)),z=-Math.floor(aq/2),W=Math.round(G+(K-G)*U),C=Math.round(V+(z-V)*U),H=W+X/2,N=C+I/2,w=YY6({dismissProgress:this.dismissProgress,easedDismissProgress:F,introOrbScale:Z,normalOrbCenterX:H,normalOrbCenterY:N,size:D}),u=Math.max(fT,Math.round(fT*w.orbScale)),L=Math.max(aq,Math.round(aq*w.orbScale)),R=w.orbCenterX,_=w.orbCenterY,P=Math.round(R-u/2),f=Math.round(_-L/2),h=Math.max(3,Math.min(D.height-5,Math.floor(aq/2)+2)),x=Math.max(h+3,D.height-3),v=w.textDissolveProgress,k=this.isFinalIntroStage()?w.backdropDissolveProgress:0,c=this.firstStageTitleVisible&&v<1,d=c&&this.firstStageHintVisible,b=d&&this.widget.dismissible&&this.introStage>0&&!this.isFinalIntroStage(),p=this.introStage===0?this.firstStageTitleRevealProgress:1,n=this.introStage===0?this.firstStageHintRevealProgress:1,a=Math.max(24,Math.min(74,D.width-4)),X0=Math.min(12,Math.max(8,D.height-h-6)),t=Math.max(0,Math.floor((D.width-a)/2)),Z0=Math.max(0,Math.min(D.height-X0,Math.floor(D.height*0.55-X0/2))),R0=this.widget.animationProgress!==void 0||!this.widget.animationsEnabled?new bK({width:u,height:L,agentMode:"deep",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,seed:42,fps:0,onClick:()=>{}}):new bK({width:u,height:L,agentMode:"deep",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,onClick:()=>{}});return new E6({autofocus:!0,canRequestFocus:!0,debugLabel:"WelcomeTakeover",onKey:(B0)=>{if(B0.key==="Enter")return this.advanceIntroStage(),"handled";if(!this.widget.dismissible&&B0.key==="c"&&B0.ctrlKey)return this.widget.onQuit?.(),"handled";if(!this.widget.dismissible&&B0.key==="q")return this.widget.onQuit?.(),"handled";if((B0.key===" "||B0.key==="Space")&&!this.isFinalIntroStage())return this.advanceIntroStage(),"handled";if(B0.key==="Escape"||B0.key==="Esc"){if(!this.widget.dismissible)return this.widget.onQuit?.(),"handled";return this.dismissFromFinalIntroStage()?"handled":"ignored"}if(B0.key==="ArrowRight")return this.nextIntroStage(),"handled";if(B0.key==="ArrowLeft")return this.goToPreviousIntroStage(),"handled";return"ignored"},child:new t1({fit:"expand",children:[new Yj4({color:Q.background,dissolveProgress:k}),new t1({fit:"expand",children:[new iA({onClick:()=>{},child:y0.expand()}),new m1({left:P,top:f,width:u,height:L,child:R0}),...c?[new m1({left:t,top:Z0,width:a,height:X0,child:FY6({introStages:this.widget.introStages,stage:this.introStage,previousStage:this.previousIntroStage,progress:this.stageTransitionProgress,direction:this.stageTransitionDirection,width:a,height:X0,foreground:Q.foreground,mutedForeground:Q.mutedForeground,accent:E,link:$.app.link,keybind:$.app.keybind,titleRevealProgress:p,dissolveProgress:v,context:A})})]:[],...d?[...b?[new m1({left:t,top:Math.max(0,x-1),width:a,height:1,child:new D0({text:zY6({stage:this.introStage,featureStageCount:Math.max(0,this.widget.introStages.length-2),foreground:Q.mutedForeground,dissolveProgress:v}),textAlign:"center"})})]:[],new m1({left:t,top:x,width:a,height:1,child:CY6({finalStage:this.isFinalIntroStage(),dismissible:this.widget.dismissible,foreground:Q.mutedForeground,keybind:$.app.keybind,revealProgress:n,dissolveProgress:v,context:A})})]:[]]})]})})}}class Yj4 extends XB{color;dissolveProgress;constructor({color:A,dissolveProgress:Q}){super();this.color=A,this.dissolveProgress=Q}createRenderObject(){return new Zj4(this.color,this.dissolveProgress)}updateRenderObject(A){A.update(this.color,this.dissolveProgress)}}class Zj4 extends bA{color;dissolveProgress;constructor(A,Q){super();this.color=A,this.dissolveProgress=Q}update(A,Q){this.color=A,this.dissolveProgress=Q,this.markNeedsPaint()}performLayout(){let A=this._lastConstraints;oA(!!A,"performLayout called without constraints");let Q=A.constrain(A.biggest.width,A.biggest.height);this.setSize(Q.width,Q.height),super.performLayout()}paint(A,Q=0,$=0){let B=Math.floor(Q+this.offset.x),E=Math.floor($+this.offset.y),D=Math.floor(this.size.width),J=Math.floor(this.size.height),U={bg:this.color},Y=LE(this.dissolveProgress);if(Y<=0){A.fill(B,E,D,J," ",U);return}if(Y>=1)return;for(let Z=0;Z<J;Z++)for(let F=0;F<D;F++)if(!ZY6(F,Z,D,J,Y))A.fill(B+F,E+Z,1,1," ",U)}}function LE(A){return Math.min(1,Math.max(0,A))}function xT(A){return 1-(1-A)**3}function Aj4(A){return eL4[A]??eL4[0]}function Qj4(A,Q,$){return{primary:Mq(A.primary,Q.primary,$),secondary:Mq(A.secondary,Q.secondary,$)}}function YY6({dismissProgress:A,easedDismissProgress:Q,introOrbScale:$,normalOrbCenterX:B,normalOrbCenterY:E,size:D}){return{orbScale:$+($*0.86-$)*Q,orbCenterX:B+(D.width*0.54-B)*Q,orbCenterY:E-D.height*0.44*Q,textDissolveProgress:LE(A/0.52),backdropDissolveProgress:xT(LE((A-0.12)/0.88))}}function ZY6(A,Q,$,B,E){let D=B<=1?0:Q/(B-1),J=Fj4(A+Q*Math.max(1,$));return(1-D)*0.72+J*0.28<E}function FY6({introStages:A,stage:Q,previousStage:$,progress:B,direction:E,width:D,height:J,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V}){if($===null||B>=1)return ic0({introStages:A,stage:Q,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V});let K=xT(B),z=E*Math.round((1-K)*D),W=-E*Math.round(K*D);return new Xq(new t1({fit:"expand",children:[new m1({left:W,top:0,width:D,height:J,child:ic0({introStages:A,stage:$,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:$===0?1:I,dissolveProgress:G,context:V})}),new m1({left:z,top:0,width:D,height:J,child:ic0({introStages:A,stage:Q,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V})})]}))}function ic0({introStages:A,stage:Q,foreground:$,mutedForeground:B,accent:E,link:D,keybind:J,titleRevealProgress:U,dissolveProgress:Y,context:Z}){let F=A[Q]??A[0]??ac0[0],X=new A0({color:E,bold:!0}),I=new A0({color:$}),G=A===ac0&&Q===0,V=[...F.title===null?[]:[new D0({text:G?n90(GY6({progress:U,foreground:E,pulseColor:E}),Y):new g($8(F.title,Y),X),textAlign:"center"})],...F.body.length>0?[XY6()]:[],...F.body.map((K)=>IY6(K,I,B,D,J,Y,Z))];return new pQ({child:new mA({padding:c0.horizontal(1),child:new UA({crossAxisAlignment:"stretch",mainAxisAlignment:"center",mainAxisSize:"min",children:V})})})}function XY6(){return y0.height(1)}function IY6(A,Q,$,B,E,D,J){if(typeof A==="string")return new D0({text:new g($8(A,D),Q),textAlign:"center"});if("codeBlock"in A)return new M5({onCopy:(U,Y)=>{if(Y)DQ.success(J,"Copied to clipboard",2000)},child:new UA({mainAxisSize:"min",children:A.codeBlock.map((U)=>new D0({text:new g($8(U,D),new A0({color:E})),textAlign:"center",selectable:!0}))})});if("keybind"in A){let U=new D0({text:new g("",void 0,[new g($8(A.text,D),new A0({color:$,dim:!0})),new g($8(A.keybind,D,Q4(A.text).length),new A0({color:E}))]),textAlign:"center",selectable:"selectable"in A?A.selectable:!1});if("selectable"in A)return new pQ({child:new M5({child:U})});return U}if("highlightText"in A){let U=t$.createSpan(A.href,A.linkText,new A0({color:B,underline:!0})),Y=lX.of(J),Z=new g("",void 0,[new g(A.text,Q),new g(A.highlightText,new A0({color:E})),new g(A.textAfterHighlight,Q),new g(U.text,U.style,U.children,U.hyperlink,()=>{z$(J,A.href,{forceExternal:!1,onShowImagePreview:Y})}),new g(A.textAfter,Q)]);return new D0({text:n90(Z,D),textAlign:"center"})}if("linkText"in A){if(A.linkWidget)return new UA({mainAxisSize:"min",children:[new D0({text:new g($8(A.text,D),Q),textAlign:"center"}),new pQ({child:new OA({mainAxisSize:"min",children:[t$.createWidget(J,A.href,$8(A.linkText,D),new A0({color:B,underline:!0})),new D0({text:new g($8(A.textAfter,D),Q)})]})})]});let U=t$.createSpan(A.href,A.linkText,new A0({color:B,underline:!0})),Y=lX.of(J),Z=new g("",void 0,[new g(A.text,Q),new g(U.text,U.style,U.children,U.hyperlink,()=>{z$(J,A.href,{forceExternal:!1,onShowImagePreview:Y})}),new g(A.textAfter,Q)]);return new D0({text:n90(Z,D),textAlign:"center"})}if(D>0)return new D0({text:new g($8(A.text,D),new A0({color:B,underline:!0})),textAlign:"center"});return new pQ({child:t$.createWidget(J,A.href,A.text,new A0({color:B,underline:!0}))})}function GY6({progress:A,foreground:Q,pulseColor:$}){let B=new A0({color:Q,bold:!0}),E=new A0({color:KY6({progress:A,foreground:Q,pulseColor:$}),bold:!0});return new g("",void 0,[new g(VY6(A).padEnd(oc0," "),B),new g(" ",B),new g($j4(Dj4,DY6,A,0.72),B),new g(" ",B),new g($j4(Jj4,JY6,A,0.88),E)])}function VY6(A){let Q=Q4(Ej4),$=Math.min(oc0,Math.ceil(LE(A/0.62)*oc0));return Q.slice(0,$).join("")}function $j4(A,Q,$,B){return $>=B?A:"".padEnd(Q," ")}function KY6({progress:A,foreground:Q,pulseColor:$}){if(A<0.88||A>=1)return Q;let B=LE((A-0.88)/0.12);return Math.cos(B*Math.PI*4)*(1-B)>0.12?$:Q}function zY6({stage:A,featureStageCount:Q,foreground:$,dissolveProgress:B}){return new g($8(`${A}/${Q}`,B),new A0({color:$,dim:!0}))}function WY6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D}){let J=new A0({color:B}),U=new A0({color:$,dim:!0}),Y=Q?A?"Enter":"Space":"Esc",Z=Q?A?" to get started":" to continue":" to quit",F="",X="",I=`${Z}`;if(!Q)return new g("",void 0,[new g(Y,J),new g(Z,U),new g("",J),new g("",U)]);let G=Bj4(Y,E),V=Bj4(I,LE((E*(Q4(Y).length+Q4(I).length)-Q4(Y).length)/Q4(I).length));return new g("",void 0,[new g($8(G,D),J),new g($8(V.slice(0,Z.length),D),U),new g($8(V.slice(Z.length,Z.length+0),D),J),new g($8(V.slice(Z.length+0),D),U)])}function CY6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D,context:J}){if(Q)return new D0({text:WY6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D}),textAlign:"center"});let U=new A0({color:B}),Y=new A0({color:$,dim:!0});return new M5({onCopy:(Z,F)=>{if(F)DQ.success(J,"Copied to clipboard",2000)},child:new D0({text:new g("",void 0,[new g("q",U),new g(" to quit",Y)]),textAlign:"center",selectable:!0})})}function Bj4(A,Q){let $=Q4(A),B=Math.min($.length,Math.ceil(LE(Q)*$.length));return $.slice(0,B).join("").padEnd($.length," ")}function n90(A,Q,$=0){if(Q<=0)return A;let B=$+Q4(A.text??"").length,E=A.children?.map((D)=>{let J=n90(D,Q,B);return B+=Q4(D.toPlainText()).length,J});return new g(A.text?$8(A.text,Q,$):A.text,A.style,E,A.hyperlink,A.onClick)}function $8(A,Q,$=0){if(Q<=0)return A;return Q4(A).map((E,D)=>{if(E.trim()==="")return E;return Fj4($+D)<Q?" ":E}).join("")}function Fj4(A){let Q=Math.sin((A+1)*12.9898)*43758.5453;return Q-Math.floor(Q)}function NY6(A){let $=A.observer.protocolMessages().filter((B)=>B.role==="assistant").at(-1);if(!$)return null;return $.content.filter((B)=>B.type==="text").map((B)=>B.text).join("")}function Xj4(A){A.client.cancelAgentLoop().catch((Q)=>{S.warn("Failed to cancel plugin agent run",{error:Q})})}function qY6(A,Q={}){return new Promise(($,B)=>{if(Q.signal?.aborted){Xj4(A),B(Error("Agent run cancelled"));return}let E=!1,D=null,J=setTimeout(()=>{D?.(),Y.unsubscribe(),B(Error("Timed out waiting for agent response"))},Q.timeoutMs??600000),U=()=>{clearTimeout(J),Y.unsubscribe(),Xj4(A),B(Error("Agent run cancelled"))};if(Q.signal!==void 0)Q.signal.addEventListener("abort",U,{once:!0}),D=()=>Q.signal?.removeEventListener("abort",U);let Y=A.observer.agentState().subscribe((Z)=>{if(m3(Z)){E=!0;return}if(!E)return;let F=NY6(A);if(F===null)return;clearTimeout(J),D?.(),Y.unsubscribe(),$(F)})})}var wY6=O4("thread.switch",{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["resume"],status:{type:"enabled"},sortBoost:100},(A,{controller:Q,dismiss:$})=>{Q.pushWithDismiss((B)=>bd0({activeThreadID:A.getActiveThreadID(),loadThreads:A.loadThreads,loadThreadTail:A.appContext.loadThreadTail,onSelectThread:A.onSwitchThread,onDismiss:B,onThreadSelected:$}))}),uY6=O4("thread.switchToPrevious",{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],status:(A)=>A.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},(A,{dismiss:Q})=>{A.navigateBack(),Q()}),MY6=O4("thread.switchToNext",{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],status:(A)=>A.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},(A,{dismiss:Q})=>{A.navigateForward(),Q()}),OY6=O4("mcp.info",{noun:"mcp",verb:"info",description:"Show MCP servers and tools",status:{type:"enabled"}},(A,{controller:Q,dismiss:$})=>{Q.push(new Sm0({mcpServers:A.appContext.mcpServers,onDismiss:$}))}),LY6=O4("toolbox.list",{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",status:{type:"enabled"}},(A,{controller:Q})=>{Q.pushWithDismiss(($)=>new pc0({toolboxes:A.appContext.toolboxes,onDismiss:$}))}),jY6=O4("news.open",{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","blog","announcements"],status:{type:"enabled"}},async(A,{context:Q,dismiss:$})=>{try{await z$(Q,"https://ampcode.com/chronicle")}finally{$()}}),RY6=O4("settings.openInEditor",{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config"],status:{type:"enabled"}},(A)=>{wK(A.appContext.settingsFilePath).catch((Q)=>{S.error("Failed to open settings file in editor",{error:Q})})}),PY6=O4("ide.connect",{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains"],status:{type:"enabled"}},(A,{controller:Q,dismiss:$})=>{Q.pushWithDismiss((B)=>new _m0({onCancel:B,onSelect:(E)=>{A.handleIdeSelection(E),$()}}))}),TY6=O4("amp.help",{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["manual","?"],status:{type:"enabled"}},(A,{controller:Q,context:$,dismiss:B})=>{Q.push(new eg0({commands:sB.of($).commands,keymapShortcuts:A.getKeymapShortcuts(),onDismiss:B}))}),vY6=O4("amp.showWelcome",{noun:"amp",verb:"show welcome",description:"Show the welcome message again",status:{type:"enabled"}},(A,{dismiss:Q})=>{Q(),A.showWelcome()}),_Y6=O4("amp.endCredits",{noun:"amp",verb:"end credits",description:"Roll the full-screen Amp credits",status:{type:"enabled"}},(A,{dismiss:Q})=>{Q(),A.showEndCredits()}),SY6=O4("amp.showVersion",{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["v"],status:{type:"enabled"}},(A,{controller:Q,dismiss:$})=>{Q.push(new E1({header:"Amp Version",maxWidth:72,onDismiss:$,child:new D0({text:new g(V50({version:"0.0.1780773165-gd9c390",buildTimestamp:"2026-06-06T19:16:58.648Z",buildType:"release"}))})}))}),kY6=O4("amp.quit",{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","bye"],status:{type:"enabled"}},(A,{context:Q})=>{N4.maybeInvoke(Q,new vK)});class sc0 extends d0{listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;updateService;initialThreadIDs;showWelcome;welcomeVariant;onWelcomeDismissed;notificationService;mcpTrustHandler;onThreadArchived;onActiveThreadChange;onRelaunchRequested;onFirstFrame;initialUserInput;getDefaultNewThreadVisibility;observeThreadSummaries;openThreadPickerOnStart;workspaceSettingsFilePath;context;constructor(A){super();this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.updateService=A.updateService,this.initialThreadIDs=A.initialThreadIDs??[],this.showWelcome=A.showWelcome??!1,this.welcomeVariant=A.welcomeVariant??"intro",this.onWelcomeDismissed=A.onWelcomeDismissed,this.notificationService=A.notificationService,this.mcpTrustHandler=A.mcpTrustHandler,this.onThreadArchived=A.onThreadArchived,this.onActiveThreadChange=A.onActiveThreadChange,this.onRelaunchRequested=A.onRelaunchRequested,this.onFirstFrame=A.onFirstFrame,this.initialUserInput=A.initialUserInput,this.getDefaultNewThreadVisibility=A.getDefaultNewThreadVisibility,this.observeThreadSummaries=A.observeThreadSummaries,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.workspaceSettingsFilePath=A.workspaceSettingsFilePath,this.context=A.context}createState(){return new Gj4}}class Gj4 extends m0{editorController=new EZ;commandPalette=new ry0(this);commandRegistry=new sg0;keymapCommandRunner=new wh0(this.commandRegistry,()=>this.context);toastController=new Db0;relaunchNotificationController=new pg0;exitHintTimer=new Hp(this,1000);ideStatus=new p3(this,{});threadNavigationHistory=new ng0;appShortcutManager=new tc;keymapController=new Ky0({runCommand:(A)=>this.keymapCommandRunner.run(A),getCommandDescription:(A)=>{let Q=this.commandRegistry.findByID(A);return Q?.status.type==="enabled"?Q.description:null},onBindingsChange:()=>{if(this.syncAppShortcutManager(),this.mounted)this.setState()},onHintChange:()=>{if(this.mounted)this.setState()}});draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;activeThreadIDSubscription=null;activePluginMessageSubscription=null;activePluginUIRequestsSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;executorAlreadyConnectedDialog=null;switchThreadPickerVisible=!1;welcomeVisible=!1;endCreditsVisible=!1;invadersHighScore=0;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;emptyThreadTerminalTitleController=new bl;pluginIntegration=null;mcpTrustIntegration=null;updateRelaunchIntegration=null;noticesPollingTimeout=null;notices;editorFocusNode=new a7({debugLabel:"EditorPanel"});loadThreads=async()=>{return this.widget.context.listThreads()};focusEditor=()=>{this.editorFocusNode.requestFocus()};focusEditorAfterNextFrame(){cQ.instance.addPostFrameCallback(()=>{if(!this.mounted)return;this.focusEditor()},"Neo focus editor")}analyzeContextForThread=async(A,Q)=>{return PI4({ampURL:this.widget.context.ampURL,configService:this.widget.configService,threadID:A,signal:Q})};onSwitchThread=(A)=>{return this.connectToExistingThread(A,{recordNavigation:!0,rethrowError:!0})};onSelectSidebarThread=async(A)=>{this.focusEditor(),await this.onSwitchThread(A)};threadListSidebar=new cc0({state:this,isBlocked:()=>this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal(),getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,getWorkspaceRoot:()=>this.widget.context.workspaceRoot,loadThreads:this.loadThreads,observeThreadSummaries:()=>this.widget.observeThreadSummaries(),archiveThread:(A)=>this.archiveThread(A),onSelectThread:this.onSelectSidebarThread,focusMainContent:this.focusEditor,getInitialVisible:()=>this.widget.context.threadListSidebarVisible});sendFeedbackReport=async(A)=>L80({configService:this.widget.configService,settingsFilePath:this.widget.context.settingsFilePath},A);archiveThread=async(A)=>{let Q=await KW4({configService:this.widget.configService},A);if(Q===null){let $=this.activeThreadContext?.client.getThreadId()??null;if(this.widget.clientPool.disconnectThread(A),this.widget.onThreadArchived?.(A),$===A)this.startNewDraftThread()}return Q};addThreadLabel=async(A,Q)=>{let $=await GC4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};removeThreadLabel=async(A,Q)=>{let $=await VC4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};initState(){if(jX.getInstance().interceptConsole(),this.invadersHighScore=this.widget.context.invadersHighScore??0,this.syncAppShortcutManager(),this.keymapController.connect(($)=>G1.instance.addKeyInterceptor($,{position:"front"})),this.notices=new jg0(this.widget.configService,($)=>this.setState($)),cQ.instance.addPostFrameCallback(()=>{setTimeout(()=>this.widget.onFirstFrame?.(),0),this.noticesPollingTimeout=setTimeout(()=>{this.noticesPollingTimeout=null,this.notices.startPolling()},500)},"Neo notices polling"),this.widget.showWelcome)this.welcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:$,error:B})=>{if(S.error("Neo failed to connect to thread",{threadID:$,error:B}),!$)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configSubscription=this.widget.configService.config.subscribe(($)=>{this.keymapController.sync($.settings.keymap??{}),this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(P00($.settings)))}),this.updateRelaunchIntegration=new ag0({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested,relaunchNotificationController:this.relaunchNotificationController,updateService:this.widget.updateService}),this.updateRelaunchIntegration.init(),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput,Q=this.widget.initialThreadIDs[0];if(Q){let $={};if(A)$.initialUserInput=A;this.connectToInitialThreads(Q,$)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.context.sessionAgentMode);this.pluginIntegration=new dg0({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,context:this.widget.context,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread,readThreadMessages:this.readPluginThreadMessages,readThreadTitle:this.readPluginThreadTitle,subscribeThreadTitle:this.subscribePluginThreadTitle,runAgent:this.runPluginAgent,onBlockingConfirmDialogChange:this.syncEmptyThreadPluginConfirmationTitle}),this.pluginIntegration.init(),this.mcpTrustIntegration=new Mh0({state:this,mcpTrustHandler:this.widget.mcpTrustHandler,toastController:this.toastController,workspaceSettingsFilePath:this.widget.workspaceSettingsFilePath}),this.mcpTrustIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=G1.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}createCommands(){let A={appContext:this.widget.context,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSwitchThread:this.onSwitchThread,canNavigateBack:()=>this.threadNavigationHistory.canNavigateBack(),canNavigateForward:()=>this.threadNavigationHistory.canNavigateForward(),navigateBack:()=>this.navigateBack(),navigateForward:()=>this.navigateForward(),handleIdeSelection:this.handleIdeSelection,getKeymapShortcuts:()=>this.keymapController.getShortcuts(),showWelcome:()=>this.showWelcome(),showEndCredits:()=>this.showEndCredits()},Q=this.widget.context.pluginService?kN4({pluginService:this.widget.context.pluginService,workspaceRoot:this.widget.context.workspaceRoot,logFilePath:this.widget.context.logFilePath,toastController:this.toastController}):[];return[dN4({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),wY6.bind(A),...this.threadListSidebar.commands(),uY6.bind(A),xw4({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),MY6.bind(A),OY6.bind(A),LY6.bind(A),jY6.bind(A),RY6.bind(A),PY6.bind(A),TY6.bind(A),vY6.bind(A),_Y6.bind(A),SY6.bind(A),kY6.bind(A),...Q,...ZC4(this.widget.context.logFilePath)]}registerAppCommands(){let Q=this.createCommands().map(($)=>this.commandRegistry.register($));return()=>{for(let $ of Q)$()}}build(A){let Q=this.buildHints(),$=this.ideStatus.getValue(),B=this.notices.current,E=new yc0({initialAgentMode:this.widget.context.sessionAgentMode,initialPluginAgentModeKey:this.widget.context.initialPluginAgentModeKey,analyzeContextForThread:this.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,editorFocusNode:this.editorFocusNode,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,sendFeedbackReport:this.sendFeedbackReport,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:$,statusItems:this.pluginIntegration?.getStatusItems()??[],pluginConfirmationBlocked:this.pluginIntegration?.hasBlockingConfirmDialog()??!1,notificationService:this.widget.notificationService,notice:this.activeThreadContext||this.welcomeVisible?null:B,onDismissNotice:(V)=>this.notices.dismiss(V)}),D=X4.of(A),J=D.capabilities.animationSupport!=="disabled",U=this.threadListSidebar.visibleWidth(),Y=Math.max(0,D.size.width-U),F=[new GA({constraints:A4.tight(D.size.width,D.size.height),child:this.threadListSidebar.buildBody(E)})];if(this.commandPalette.isEnabled())F.push(new E6({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new tg0({keymapShortcuts:this.keymapController.getShortcuts(),onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.welcomeVisible)F.push(bd0({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,loadThreadTail:this.widget.context.loadThreadTail,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.welcomeVisible)F.push(new E6({debugLabel:"WelcomeDialogOverlay",child:new rc0({onDismiss:this.dismissWelcome,onQuit:()=>G1.instance.stop(),animationsEnabled:J,variant:this.widget.welcomeVariant})}));let X=this.executorAlreadyConnectedDialog;if(X)F.push(new E6({debugLabel:"ExecutorAlreadyConnectedDialogOverlay",child:new Pm0({existingExecutorPid:X.existingExecutorPid,onChoice:this.handleExecutorAlreadyConnectedChoice})}));if(F.push(...this.mcpTrustIntegration?.buildDialogLayers()??[]),F.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.context.isInternalUser)F.push(new Qm0({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:a90.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,observerSnapshot$:this.activeThreadContext?.observer.observerSnapshot()??null}));if(this.focusDebugVisible)F.push(new Tm0);if(this.endCreditsVisible)F.push(new um0({onComplete:this.completeEndCredits,highScore:this.invadersHighScore,onHighScoreChange:this.updateInvadersHighScore}));let I=this.keymapController.getHint(),G=b70(this.exitHintTimer.isActive()?{key:"Ctrl+C",description:"again to exit"}:I?{key:I.leader,description:"...",options:I.options}:null);if(G)F.push(G);return new MQ({context:this.widget.context,child:new sB({commandRegistry:this.commandRegistry,child:new zT({completionBuilder:this.widget.completionBuilder,child:new DQ({controller:this.toastController,child:new N4({actions:this.buildActions(),child:new rQ({debugLabel:"AppShortcuts",shortcuts:this.buildShortcuts(),manager:this.appShortcutManager,child:this.keymapCommandRunner.captureContext(new VQ({debugLabel:"AppShellFocus",canRequestFocus:!1,skipTraversal:!0,child:new Jb0({controller:this.toastController,complexToastControllers:[this.relaunchNotificationController,...B&&this.activeThreadContext&&!this.welcomeVisible?[this.notices]:[]],child:new Am0({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new Oq({left:U,width:Y,child:this.keymapCommandRunner.buildModalStack(new t1({children:F}))})})})}))})})})})})})}buildShortcuts(){let A=new Map,Q=new Set,$=(E,D)=>{A.set(E,D),Q.add(E.toString())},B=(E,D)=>{if(Q.has(E.toString()))return;$(E,D)};for(let E of this.keymapController.getBindings())if(E.activator instanceof wA)$(E.activator,new j70(E.commandID));B(wA.ctrl("c"),new M70),B(wA.ctrl("o"),new L70),B(wA.alt("i"),new P70),B(wA.alt("p"),new nc),B(wA.ctrl("."),new _70),B(wA.ctrl("t"),new f70);for(let[E,D]of this.threadListSidebar.shortcutEntries())B(E,D);if(a90.env.NODE_ENV==="development"&&a90.platform==="darwin")B(wA.meta("r"),new O70);return A}syncAppShortcutManager(){for(let A of this.appShortcutManager.getAllShortcuts().keys())this.appShortcutManager.removeShortcut(A);for(let[A,Q]of this.buildShortcuts())this.appShortcutManager.addShortcut(A,Q)}buildActions(){let A=new cA(()=>{if(b2.hasAnyCopyableSelection())return b2.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new cA(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),$=new cA(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),B=new cA((G)=>{return this.keymapCommandRunner.run(G.commandID)?"handled":"ignored"}),E=new cA(()=>{return this.startNewDraftThread(),"handled"}),D=new cA(()=>{return G1.instance.stop(),"handled"}),J=new cA(()=>{return Pl({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),"handled"}),U=new cA((G)=>{if(!G.text)return"ignored";return G1.instance.tuiInstance.clipboard.writeText(G.text).then((V)=>{if(V.ok)this.toastController.show(G.successMessage,"success",2000);else this.toastController.show(`${G.failureMessage}: ${V.userFacingErrorMessage}`,"error",4000)}).catch((V)=>{S.error("Failed to copy Neo text to clipboard",{error:V}),this.toastController.show(G.failureMessage,"error",2000)}),"handled"}),Y=new cA(()=>{return G1.instance.toggleFrameStatsOverlay(),"handled"}),Z=new cA(()=>this.notices.dismissCurrent()?"handled":"ignored"),F=new cA(()=>{if(!this.widget.context.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),X=Qq4({getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,context:this.widget.context,toastController:this.toastController,startNewDraftThread:this.startNewDraftThread,sendFeedbackReport:this.sendFeedbackReport}),I=new cA(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[M70,A],[Lq,E],[vK,D],[O70,J],[IB,U],[Ql,$],[j70,B],[L70,Q],[P70,F],...this.threadListSidebar.actionEntries(),[_70,Z],...X,[nc,Y],[f70,I]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.cancelOwnerUIRequests(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),this.widget.onActiveThreadChange?.(null),this.syncEmptyThreadPluginConfirmationTitle(),A.prompt!==void 0)this.editorController.text=A.prompt;this.focusEditorAfterNextFrame()}syncEmptyThreadPluginConfirmationTitle=()=>{this.emptyThreadTerminalTitleController.setPluginConfirmationBlocked(this.activeThreadContext===null&&(this.pluginIntegration?.hasBlockingConfirmDialog()??!1))};closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=this.applySessionDefaultsToThreadSettings(await hP(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){S.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.context.sessionAgentMode,$=A,B=oN(Q),E=Z50(this.widget.context,Q);if(B!==void 0&&E!==void 0)$={...$,[B]:E};return U50($,{agentMode:Q,explicitEffort:this.widget.context.explicitReasoningEffort,sessionState:this.widget.context})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=Ij4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(m9(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=Ij4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(TK);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),G1.instance.stop();else this.exitHintTimer.activate()};dismissWelcome=()=>{if(!this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!1}),this.widget.onWelcomeDismissed?.()};updateInvadersHighScore=(A)=>{if(A<=this.invadersHighScore)return;this.setState(()=>{this.invadersHighScore=A}),eD((Q)=>({...Q,neoInvadersHighScore:Math.max(Q.neoInvadersHighScore,A)})).catch((Q)=>{S.warn("Failed to save Neo Invaders high score",{error:Q instanceof Error?Q.message:String(Q)})})};showWelcome=()=>{if(this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!0})};showEndCredits=()=>{if(this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!0})};completeEndCredits=()=>{if(!this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!1})};promptExecutorAlreadyConnected(A){return new Promise((Q)=>{this.setState(()=>{this.executorAlreadyConnectedDialog={existingExecutorPid:A.existingExecutorPid,resolve:($)=>{Q($==="watch"?"observe":"disconnect")}}})})}handleExecutorAlreadyConnectedChoice=(A)=>{if(this.resolveExecutorAlreadyConnectedDialog(A),A==="exit")G1.instance.stop()};resolveExecutorAlreadyConnectedDialog(A){let Q=this.executorAlreadyConnectedDialog;if(!Q)return;this.setState(()=>{this.executorAlreadyConnectedDialog=null}),Q.resolve(A)}closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1}),this.focusEditorAfterNextFrame()};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,$=null,B,E,D)=>{await this.ensureDraftThreadSettingsInitialized();let J=this.activeThreadContext?.client.getThreadId(),U=A.find(N00);if(U)this.widget.history.add(U.text,a90.cwd()),this.widget.history.reset();let Y=$?void 0:await this.widget.getDefaultNewThreadVisibility?.(),Z=$??Y??null,F=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,Z??void 0,E,D);if(this.sendUserMessage(F,A,E?void 0:Q,E?void 0:B),!E)this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings);this.threadNavigationHistory.recordNavigation(J),this.setActiveClient(F)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.context.sessionAgentMode=A;let $=Q["reasoning.effort"];if($!==void 0)this.widget.context.lastReasoningEffortByMode={...this.widget.context.lastReasoningEffortByMode??{},[A]:$};let B=oN(A),E=B?Q[B]:void 0;if(E!==void 0)this.widget.context.lastSpeedByMode={...this.widget.context.lastSpeedByMode??{},[A]:E};eD((D)=>{let J={...D,agentMode:A};if($!==void 0)J={...J,lastReasoningEffortByMode:{...J.lastReasoningEffortByMode??{},[A]:$}};if(E!==void 0)J={...J,lastSpeedByMode:{...J.lastSpeedByMode??{},[A]:E}};return J}).catch((D)=>{S.warn("Failed to persist Neo session defaults for new message",{error:D instanceof Error?D.message:String(D)})})}sendUserMessage(A,Q,$,B,E){let D=D50(this.ideStatus.getValue());if(B===void 0){A.client.sendUserMessage(Q,$,{steer:E?.steer,userState:D}).catch((J)=>{S.warn("Failed to send user message",{error:J})});return}A.client.sendUserMessage(Q,$,{reasoningEffort:B,steer:E?.steer,userState:D}).catch((J)=>{S.warn("Failed to send user message",{error:J})})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};getRelaunchThreadIDs=()=>{let A=new Set,Q=this.getActiveThreadID();if(Q)A.add(Q);for(let $ of this.widget.clientPool.activeThreadIDs)A.add($);return[...A]};appendPluginMessagesToThread=async(A,Q,$)=>{let B=this.activeThreadContext;if(!B){if(Q){for(let D of A)await this.widget.clientPool.appendUserMessageToThread(Q,D.content,$);return}throw Error("appendToThread is not available - no active thread")}let E=B.client.getThreadId();if(Q&&E!==Q){for(let D of A)await this.widget.clientPool.appendUserMessageToThread(Q,D.content,$);return}for(let D of A)this.sendUserMessage(B,[{type:"text",text:D.content}],void 0,void 0,$)};readPluginThreadMessages=async(A,Q)=>{let $=this.activeThreadContext;if(!$)throw Error("thread.messages is not available - no active thread");let B=$.client.getThreadId();if(Q&&B!==Q)throw Error("thread.messages is only available for the active thread");return xoA(yoA($.observer.protocolMessages()),A)};readPluginThreadTitle=async(A)=>{let Q=this.activeThreadContext;if(!Q)throw Error("thread.title is not available - no active thread");let $=Q.client.getThreadId();if(A&&$!==A)throw Error("thread.title is only available for the active thread");return Q.observer.title().getValue()??null};subscribePluginThreadTitle=(A,Q)=>{let $=this.activeThreadContext;if(!$)throw Error("thread.title.subscribe is not available - no active thread");let B=$.client.getThreadId();if(A&&B!==A)throw Error("thread.title.subscribe is only available for the active thread");return $.observer.title().subscribe((E)=>{Q.next(E??null)})};runPluginAgent=async(A,Q,$)=>{await this.ensureDraftThreadSettingsInitialized();let B=this.widget.clientPool.createNewThread(this.widget.context.sessionAgentMode,this.draftThreadSettings,void 0,A,Q.agentModeDisplay,Q.parentThreadID,{trackAsLastActive:!1,executorClientID:iY.parse(`neo-subagent-${HY6()}`)});this.sendUserMessage(B,[{type:"text",text:Q.message}]);try{let E=await qY6(B,{timeoutMs:Q.timeoutMs,signal:$}),D=B.client.getThreadId();return D?{threadID:D,text:E}:{text:E}}finally{this.widget.clientPool.disconnect(B)}};async connectToExistingThread(A,Q={}){let $=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let B=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:(E)=>this.promptExecutorAlreadyConnected(E)});if(this.setActiveClient(B),Q.recordNavigation&&$!==A)this.threadNavigationHistory.recordNavigation($);if(Q.initialUserInput)this.sendUserMessage(B,[{type:"text",text:Q.initialUserInput}])}catch(B){if(S.error("Failed to load thread",{error:B,threadID:A}),this.toastController.show(`Failed to load ${A}: ${B instanceof Error?B.message:String(B)}`,"error",4000),Q.rethrowError)throw B}finally{this.setState(()=>{this.connectingToThreadID=null})}}async connectToInitialThreads(A,Q={}){await this.connectToExistingThread(A,Q);let $=this.widget.initialThreadIDs.filter((B)=>B!==A);await Promise.all($.map((B)=>this.resumeBackgroundThread(B)))}async resumeBackgroundThread(A){try{await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:async()=>"observe"})}catch(Q){S.error("Failed to resume background thread",{error:Q,threadID:A}),this.toastController.show(`Failed to resume ${A}: ${Q instanceof Error?Q.message:String(Q)}`,"error",4000)}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}setActiveClient({client:A,observer:Q,agentModeDisplay:$}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q,agentModeDisplay:$}}),this.syncEmptyThreadPluginConfirmationTitle(),this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe((B)=>{this.widget.onActiveThreadChange?.(B)}),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription?.unsubscribe(),this.pluginIntegration?.cancelOwnerUIRequests(),this.activePluginMessageSubscription=Q.pluginMessages().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage(B,(E)=>{A.sendPluginMessage(E)})}),this.activePluginUIRequestsSubscription=Q.pluginUIRequests().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage({type:"plugin_message",message:{type:"event",event:"plugin.ui.snapshot",data:{requests:[...B]}}},(E)=>{A.sendPluginMessage(E)})})}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){S.error("Failed to connect to IDE",{error:Q});let $=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${$}`,"error",4000)}};dispose(){if(this.keymapController.dispose(),this.keymapCommandRunner.dispose(),this.unregisterCommands?.(),this.unregisterCommands=null,this.threadListSidebar.dispose(),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.emptyThreadTerminalTitleController.dispose(),this.mcpTrustIntegration?.dispose(),this.mcpTrustIntegration=null,this.updateRelaunchIntegration?.dispose(),this.updateRelaunchIntegration=null,this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.noticesPollingTimeout)clearTimeout(this.noticesPollingTimeout),this.noticesPollingTimeout=null;this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.notices.dispose(),this.widget.notificationService.detach(),this.toastController.dispose(),this.editorFocusNode.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.executorAlreadyConnectedDialog!==null||this.welcomeVisible||(this.mcpTrustIntegration?.hasBlockingDialog()??!1)||this.endCreditsVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function Ij4(A,Q,$){let B={...A};for(let E of fY6(Q,$)){if(!m9(A[E],Q[E]))continue;let D=$[E];if(D===void 0)delete B[E];else B[E]=D}return B}function fY6(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}function Vj4(){return jI4()}function gY6(A,Q){let $=mY6(A,Q),B=new Map(A.map((J)=>[J.id,J.description])),E=Object.entries($),D=E.map(([J,U],Y)=>{let Z=Y===E.length-1?"":",",F=` ${JSON.stringify(J)}: ${JSON.stringify(U)}${Z}`,I=` // ${(J==="leader"?"Leader key for <leader> shortcuts":B.get(J)??"Configured, not discovered").replaceAll(/[\r\n\u2028\u2029]/g," ")}`;return U===null?P0.dim(F+I):F+P0.dim(I)});return D.unshift("{"),D.push("}"),D.join(`
|
|
2913
|
+
`))}function oU6(A,Q){let{colors:$,app:B}=Q;switch(A){case"pending":return{icon:"◌",color:$.warning};case"registered":return{icon:"•",color:$.mutedForeground};case"failed":return{icon:"✗",color:B.toolError};case"duplicate":return{icon:"◇",color:$.warning};default:return{icon:"?",color:$.foreground}}}function iL4(A,Q){let $=A.replace(/\s+/g," ").trim();if(RA($)<=Q)return $;let B="...",E=RA(B);if(Q<=E)return o7(B,Q);return`${o7($,Q-E,!0,"")}${B}`}var nc0="https://ampcode.com/news/neo",ac0=[{title:"Meet the new Amp CLI",body:[]},{title:"Rebuilt From The Ground Up",body:["Same close-up terminal workflow. Completely different underneath."]},{title:"Just Keep Typing",body:["Context is summarized automatically at ~90%.","No handoff flow. No context percentage to babysit."]},{title:"Queueing and Steering",body:["Sending a message now queues by default instead of cancelling tools.","Use steering when you want the agent to see something sooner."]},{title:"Remote Control",body:["Start a thread in the CLI, then keep going from ampcode.com.","Watch live updates and queue follow-ups from any device."]},{title:"Customize Amp with Amp",body:[{text:"Amp now has a ",linkText:"complete plugin API",href:"https://ampcode.com/manual/plugin-api",textAfter:"."},"Add tools, commands, control UI, and hook into events."]},{title:"Permissions",body:[{text:"By default (when no ",highlightText:"amp.permissions",textAfterHighlight:" setting is present), Amp no longer asks for confirmation before running any tools and commands. And you can now implement your own custom permission logic with ",linkText:"plugins",href:"https://ampcode.com/manual/plugin-api",textAfter:"."}]},{title:null,body:["Check out the full news post for more:",{text:nc0,href:nc0}]}];function rU6(A){return[{title:"Upgrade your Amp CLI",body:[{text:"This npm-based distribution of Amp CLI has been deprecated. To use the ",linkText:"new Amp CLI",href:nc0,textAfter:" you'll need to switch to the binary install:",linkWidget:!0},"",{codeBlock:["npm uninstall -g @sourcegraph/amp",A]}]}]}function sU6(){if(process.platform==="win32")return'powershell -c "irm https://ampcode.com/install.ps1 | iex"';return"curl -fsSL https://ampcode.com/install.sh | bash"}var fT=50,aq=40,lc0=1000,tU6=420,eU6=760,AY6=-250,QY6=1100,l90=33,rL4=0.999,$Y6=2.1,BY6=720,EY6=420,Ej4="Meet the new",Dj4="Amp",Jj4="CLI",oc0=Q4(Ej4).length,DY6=Q4(Dj4).length,JY6=Q4(Jj4).length,i90={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}},sL4={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},tL4={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}},eL4=[i90,sL4,tL4,i90,sL4,tL4,i90],UY6=i90;class rc0 extends d0{onDismiss;onQuit;animationProgress;animationsEnabled;variant;binaryInstallCommand;introStages;dismissible;constructor(A){super();this.onDismiss=A.onDismiss,this.onQuit=A.onQuit,this.animationProgress=A.animationProgress,this.animationsEnabled=A.animationsEnabled??!0,this.variant=A.variant??"intro",this.binaryInstallCommand=A.binaryInstallCommand??sU6(),this.introStages=this.variant==="npm-migration"?rU6(this.binaryInstallCommand):ac0,this.dismissible=this.variant!=="npm-migration"}createState(){return new Uj4}}class Uj4 extends m0{startedAt=performance.now();animationTimer=null;stageTransitionTimer=null;firstStageTitleTimer=null;firstStageHintTimer=null;firstStageRevealTimer=null;firstStageTitleRevealStartedAt=null;firstStageHintRevealStartedAt=null;stageTransitionStartedAt=performance.now();animationStartProgress=0;animationTargetProgress=1;animationDurationMs=lc0;onAnimationComplete=null;animationProgress=0;introStage=0;previousIntroStage=null;stageTransitionProgress=1;stageTransitionDirection=1;firstStageTitleVisible=!1;firstStageHintVisible=!1;firstStageTitleRevealProgress=0;firstStageHintRevealProgress=0;dismissTimer=null;dismissStartedAt=performance.now();dismissProgress=0;isDismissing=!1;splashOrbGlow=new P5(42);initState(){super.initState(),this.startAnimationIfNeeded()}didUpdateWidget(A){if(super.didUpdateWidget(A),A.animationProgress!==this.widget.animationProgress||A.animationsEnabled!==this.widget.animationsEnabled)this.startAnimationIfNeeded()}dispose(){this.stopAnimation(),this.stopStageTransitionTimer(),this.stopFirstStageRevealTimers(),this.stopDismissAnimation(),super.dispose()}startAnimationIfNeeded(){if(this.stopAnimation(),this.stopFirstStageRevealTimers(),this.widget.animationProgress!==void 0){this.animationProgress=LE(this.widget.animationProgress),this.firstStageTitleVisible=this.animationProgress>=rL4,this.firstStageHintVisible=this.animationProgress>=rL4,this.firstStageTitleRevealProgress=this.firstStageTitleVisible?1:0,this.firstStageHintRevealProgress=this.firstStageHintVisible?1:0;return}if(!this.widget.animationsEnabled){this.stopStageTransitionTimer(),this.stopDismissAnimation(),this.animationProgress=1,this.isDismissing=!1,this.dismissProgress=0,this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1,this.previousIntroStage=null,this.stageTransitionProgress=1;return}if(this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0,this.startProgressAnimation({from:0,to:1,durationMs:lc0,onComplete:()=>{if(!this.widget.dismissible)this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1})}}),this.widget.dismissible)this.startFirstStageRevealSequence()}startDismissAnimation(){if(this.isDismissing)return;if(!this.widget.animationsEnabled){this.widget.onDismiss();return}this.stopFirstStageRevealTimers(),this.stopStageTransitionTimer(),this.dismissStartedAt=performance.now(),this.setState(()=>{this.isDismissing=!0,this.dismissProgress=0}),this.dismissTimer=setInterval(()=>{let A=performance.now()-this.dismissStartedAt,Q=LE(A/eU6);if(this.setState(()=>{this.dismissProgress=Q}),Q>=1)this.stopDismissAnimation(),this.widget.onDismiss()},l90)}canNavigateIntroStage(){if(this.isDismissing)return!1;if(!this.firstStageHintVisible)return!1;if(this.introStage===0&&this.firstStageHintRevealProgress<1)return!1;return!0}advanceIntroStage(){if(!this.canNavigateIntroStage())return;if(this.isFinalIntroStage()){if(this.widget.dismissible)this.startDismissAnimation();return}this.moveIntroStage(1)}dismissFromFinalIntroStage(){if(!this.widget.dismissible||!this.canNavigateIntroStage()||!this.isFinalIntroStage())return!1;return this.startDismissAnimation(),!0}nextIntroStage(){if(!this.canNavigateIntroStage()||this.isFinalIntroStage())return;this.moveIntroStage(1)}goToPreviousIntroStage(){if(!this.canNavigateIntroStage()||this.introStage<=0)return;this.moveIntroStage(-1)}isFinalIntroStage(){return this.introStage>=this.widget.introStages.length-1}moveIntroStage(A){let Q=this.introStage+A;if(this.stopStageTransitionTimer(),this.stageTransitionStartedAt=performance.now(),this.setState(()=>{this.previousIntroStage=this.introStage,this.introStage=Q,this.stageTransitionDirection=A}),this.widget.animationProgress!==void 0||!this.widget.animationsEnabled){this.setState(()=>{this.previousIntroStage=null,this.stageTransitionProgress=1});return}this.setState(()=>{this.stageTransitionProgress=0}),this.stageTransitionTimer=setInterval(()=>{let $=performance.now()-this.stageTransitionStartedAt,B=LE($/tU6);if(this.setState(()=>{if(this.stageTransitionProgress=B,B>=1)this.previousIntroStage=null}),B>=1)this.stopStageTransitionTimer()},l90)}startProgressAnimation({from:A,to:Q,durationMs:$,onComplete:B}){this.stopAnimation(),this.startedAt=performance.now(),this.animationStartProgress=A,this.animationTargetProgress=Q,this.animationDurationMs=$,this.onAnimationComplete=B,this.animationProgress=A,this.animationTimer=setInterval(()=>{let E=performance.now()-this.startedAt,D=LE(E/this.animationDurationMs),J=this.animationStartProgress+(this.animationTargetProgress-this.animationStartProgress)*xT(D);if(this.setState(()=>{this.animationProgress=J}),D>=1)this.stopAnimation(),this.onAnimationComplete?.(),this.onAnimationComplete=null},l90)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null}stopStageTransitionTimer(){if(this.stageTransitionTimer)clearInterval(this.stageTransitionTimer),this.stageTransitionTimer=null}startFirstStageRevealSequence(){if(this.stopFirstStageRevealTimers(),!this.widget.animationsEnabled){this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1});return}this.setState(()=>{this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0});let A=Math.max(0,lc0+AY6),Q=A+QY6;this.firstStageTitleTimer=setTimeout(()=>{this.firstStageTitleRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageTitleRevealProgress=0}),this.startFirstStageRevealTimer()},A),this.firstStageHintTimer=setTimeout(()=>{this.firstStageHintRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageHintVisible=!0,this.firstStageHintRevealProgress=0}),this.startFirstStageRevealTimer()},Q)}startFirstStageRevealTimer(){if(this.firstStageRevealTimer)return;this.firstStageRevealTimer=setInterval(()=>{let A=performance.now(),Q=this.firstStageTitleRevealStartedAt?LE((A-this.firstStageTitleRevealStartedAt)/BY6):this.firstStageTitleRevealProgress,$=this.firstStageHintRevealStartedAt?LE((A-this.firstStageHintRevealStartedAt)/EY6):this.firstStageHintRevealProgress;if(this.setState(()=>{this.firstStageTitleRevealProgress=Q,this.firstStageHintRevealProgress=$}),Q>=1&&$>=1)this.stopFirstStageRevealTimer()},l90)}stopFirstStageRevealTimers(){if(this.stopFirstStageRevealTimer(),this.firstStageTitleRevealStartedAt=null,this.firstStageHintRevealStartedAt=null,this.firstStageTitleTimer)clearTimeout(this.firstStageTitleTimer),this.firstStageTitleTimer=null;if(this.firstStageHintTimer)clearTimeout(this.firstStageHintTimer),this.firstStageHintTimer=null}stopFirstStageRevealTimer(){if(this.firstStageRevealTimer)clearInterval(this.firstStageRevealTimer),this.firstStageRevealTimer=null}stopDismissAnimation(){if(this.dismissTimer)clearInterval(this.dismissTimer),this.dismissTimer=null}currentOrbPalette(){let A=Aj4(this.introStage),Q=this.previousIntroStage===null||this.stageTransitionProgress>=1?A:Qj4(Aj4(this.previousIntroStage),A,xT(this.stageTransitionProgress));return this.dismissProgress>0?Qj4(Q,UY6,xT(this.dismissProgress)):Q}build(A){let Q=S4.of(A).colorScheme,$=e0.of(A),B=this.currentOrbPalette(),E=e7(1,"deep",B),D=X4.of(A).size,U=this.widget.animationProgress??this.animationProgress,Y=Math.max(D.width/fT,D.height/aq)*$Y6,Z=Y+(1-Y)*U,F=xT(this.dismissProgress),X=Math.max(fT,Math.round(fT*Z)),I=Math.max(aq,Math.round(aq*Z)),G=Math.round((D.width-X)/2),V=Math.round((D.height-I)/2),K=Math.max(0,Math.floor((D.width-fT)/2)),z=-Math.floor(aq/2),W=Math.round(G+(K-G)*U),C=Math.round(V+(z-V)*U),H=W+X/2,N=C+I/2,w=YY6({dismissProgress:this.dismissProgress,easedDismissProgress:F,introOrbScale:Z,normalOrbCenterX:H,normalOrbCenterY:N,size:D}),u=Math.max(fT,Math.round(fT*w.orbScale)),L=Math.max(aq,Math.round(aq*w.orbScale)),R=w.orbCenterX,_=w.orbCenterY,P=Math.round(R-u/2),f=Math.round(_-L/2),h=Math.max(3,Math.min(D.height-5,Math.floor(aq/2)+2)),x=Math.max(h+3,D.height-3),v=w.textDissolveProgress,k=this.isFinalIntroStage()?w.backdropDissolveProgress:0,c=this.firstStageTitleVisible&&v<1,d=c&&this.firstStageHintVisible,b=d&&this.widget.dismissible&&this.introStage>0&&!this.isFinalIntroStage(),p=this.introStage===0?this.firstStageTitleRevealProgress:1,n=this.introStage===0?this.firstStageHintRevealProgress:1,a=Math.max(24,Math.min(74,D.width-4)),X0=Math.min(12,Math.max(8,D.height-h-6)),t=Math.max(0,Math.floor((D.width-a)/2)),Z0=Math.max(0,Math.min(D.height-X0,Math.floor(D.height*0.55-X0/2))),R0=this.widget.animationProgress!==void 0||!this.widget.animationsEnabled?new bK({width:u,height:L,agentMode:"deep",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,seed:42,fps:0,onClick:()=>{}}):new bK({width:u,height:L,agentMode:"deep",glyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,onClick:()=>{}});return new E6({autofocus:!0,canRequestFocus:!0,debugLabel:"WelcomeTakeover",onKey:(B0)=>{if(B0.key==="Enter")return this.advanceIntroStage(),"handled";if(!this.widget.dismissible&&B0.key==="c"&&B0.ctrlKey)return this.widget.onQuit?.(),"handled";if(!this.widget.dismissible&&B0.key==="q")return this.widget.onQuit?.(),"handled";if((B0.key===" "||B0.key==="Space")&&!this.isFinalIntroStage())return this.advanceIntroStage(),"handled";if(B0.key==="Escape"||B0.key==="Esc"){if(!this.widget.dismissible)return this.widget.onQuit?.(),"handled";return this.dismissFromFinalIntroStage()?"handled":"ignored"}if(B0.key==="ArrowRight")return this.nextIntroStage(),"handled";if(B0.key==="ArrowLeft")return this.goToPreviousIntroStage(),"handled";return"ignored"},child:new t1({fit:"expand",children:[new Yj4({color:Q.background,dissolveProgress:k}),new t1({fit:"expand",children:[new iA({onClick:()=>{},child:y0.expand()}),new m1({left:P,top:f,width:u,height:L,child:R0}),...c?[new m1({left:t,top:Z0,width:a,height:X0,child:FY6({introStages:this.widget.introStages,stage:this.introStage,previousStage:this.previousIntroStage,progress:this.stageTransitionProgress,direction:this.stageTransitionDirection,width:a,height:X0,foreground:Q.foreground,mutedForeground:Q.mutedForeground,accent:E,link:$.app.link,keybind:$.app.keybind,titleRevealProgress:p,dissolveProgress:v,context:A})})]:[],...d?[...b?[new m1({left:t,top:Math.max(0,x-1),width:a,height:1,child:new D0({text:zY6({stage:this.introStage,featureStageCount:Math.max(0,this.widget.introStages.length-2),foreground:Q.mutedForeground,dissolveProgress:v}),textAlign:"center"})})]:[],new m1({left:t,top:x,width:a,height:1,child:CY6({finalStage:this.isFinalIntroStage(),dismissible:this.widget.dismissible,foreground:Q.mutedForeground,keybind:$.app.keybind,revealProgress:n,dissolveProgress:v,context:A})})]:[]]})]})})}}class Yj4 extends XB{color;dissolveProgress;constructor({color:A,dissolveProgress:Q}){super();this.color=A,this.dissolveProgress=Q}createRenderObject(){return new Zj4(this.color,this.dissolveProgress)}updateRenderObject(A){A.update(this.color,this.dissolveProgress)}}class Zj4 extends bA{color;dissolveProgress;constructor(A,Q){super();this.color=A,this.dissolveProgress=Q}update(A,Q){this.color=A,this.dissolveProgress=Q,this.markNeedsPaint()}performLayout(){let A=this._lastConstraints;oA(!!A,"performLayout called without constraints");let Q=A.constrain(A.biggest.width,A.biggest.height);this.setSize(Q.width,Q.height),super.performLayout()}paint(A,Q=0,$=0){let B=Math.floor(Q+this.offset.x),E=Math.floor($+this.offset.y),D=Math.floor(this.size.width),J=Math.floor(this.size.height),U={bg:this.color},Y=LE(this.dissolveProgress);if(Y<=0){A.fill(B,E,D,J," ",U);return}if(Y>=1)return;for(let Z=0;Z<J;Z++)for(let F=0;F<D;F++)if(!ZY6(F,Z,D,J,Y))A.fill(B+F,E+Z,1,1," ",U)}}function LE(A){return Math.min(1,Math.max(0,A))}function xT(A){return 1-(1-A)**3}function Aj4(A){return eL4[A]??eL4[0]}function Qj4(A,Q,$){return{primary:Mq(A.primary,Q.primary,$),secondary:Mq(A.secondary,Q.secondary,$)}}function YY6({dismissProgress:A,easedDismissProgress:Q,introOrbScale:$,normalOrbCenterX:B,normalOrbCenterY:E,size:D}){return{orbScale:$+($*0.86-$)*Q,orbCenterX:B+(D.width*0.54-B)*Q,orbCenterY:E-D.height*0.44*Q,textDissolveProgress:LE(A/0.52),backdropDissolveProgress:xT(LE((A-0.12)/0.88))}}function ZY6(A,Q,$,B,E){let D=B<=1?0:Q/(B-1),J=Fj4(A+Q*Math.max(1,$));return(1-D)*0.72+J*0.28<E}function FY6({introStages:A,stage:Q,previousStage:$,progress:B,direction:E,width:D,height:J,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V}){if($===null||B>=1)return ic0({introStages:A,stage:Q,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V});let K=xT(B),z=E*Math.round((1-K)*D),W=-E*Math.round(K*D);return new Xq(new t1({fit:"expand",children:[new m1({left:W,top:0,width:D,height:J,child:ic0({introStages:A,stage:$,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:$===0?1:I,dissolveProgress:G,context:V})}),new m1({left:z,top:0,width:D,height:J,child:ic0({introStages:A,stage:Q,foreground:U,mutedForeground:Y,accent:Z,link:F,keybind:X,titleRevealProgress:I,dissolveProgress:G,context:V})})]}))}function ic0({introStages:A,stage:Q,foreground:$,mutedForeground:B,accent:E,link:D,keybind:J,titleRevealProgress:U,dissolveProgress:Y,context:Z}){let F=A[Q]??A[0]??ac0[0],X=new A0({color:E,bold:!0}),I=new A0({color:$}),G=A===ac0&&Q===0,V=[...F.title===null?[]:[new D0({text:G?n90(GY6({progress:U,foreground:E,pulseColor:E}),Y):new g($8(F.title,Y),X),textAlign:"center"})],...F.body.length>0?[XY6()]:[],...F.body.map((K)=>IY6(K,I,B,D,J,Y,Z))];return new pQ({child:new mA({padding:c0.horizontal(1),child:new UA({crossAxisAlignment:"stretch",mainAxisAlignment:"center",mainAxisSize:"min",children:V})})})}function XY6(){return y0.height(1)}function IY6(A,Q,$,B,E,D,J){if(typeof A==="string")return new D0({text:new g($8(A,D),Q),textAlign:"center"});if("codeBlock"in A)return new M5({onCopy:(U,Y)=>{if(Y)DQ.success(J,"Copied to clipboard",2000)},child:new UA({mainAxisSize:"min",children:A.codeBlock.map((U)=>new D0({text:new g($8(U,D),new A0({color:E})),textAlign:"center",selectable:!0}))})});if("keybind"in A){let U=new D0({text:new g("",void 0,[new g($8(A.text,D),new A0({color:$,dim:!0})),new g($8(A.keybind,D,Q4(A.text).length),new A0({color:E}))]),textAlign:"center",selectable:"selectable"in A?A.selectable:!1});if("selectable"in A)return new pQ({child:new M5({child:U})});return U}if("highlightText"in A){let U=t$.createSpan(A.href,A.linkText,new A0({color:B,underline:!0})),Y=lX.of(J),Z=new g("",void 0,[new g(A.text,Q),new g(A.highlightText,new A0({color:E})),new g(A.textAfterHighlight,Q),new g(U.text,U.style,U.children,U.hyperlink,()=>{z$(J,A.href,{forceExternal:!1,onShowImagePreview:Y})}),new g(A.textAfter,Q)]);return new D0({text:n90(Z,D),textAlign:"center"})}if("linkText"in A){if(A.linkWidget)return new UA({mainAxisSize:"min",children:[new D0({text:new g($8(A.text,D),Q),textAlign:"center"}),new pQ({child:new OA({mainAxisSize:"min",children:[t$.createWidget(J,A.href,$8(A.linkText,D),new A0({color:B,underline:!0})),new D0({text:new g($8(A.textAfter,D),Q)})]})})]});let U=t$.createSpan(A.href,A.linkText,new A0({color:B,underline:!0})),Y=lX.of(J),Z=new g("",void 0,[new g(A.text,Q),new g(U.text,U.style,U.children,U.hyperlink,()=>{z$(J,A.href,{forceExternal:!1,onShowImagePreview:Y})}),new g(A.textAfter,Q)]);return new D0({text:n90(Z,D),textAlign:"center"})}if(D>0)return new D0({text:new g($8(A.text,D),new A0({color:B,underline:!0})),textAlign:"center"});return new pQ({child:t$.createWidget(J,A.href,A.text,new A0({color:B,underline:!0}))})}function GY6({progress:A,foreground:Q,pulseColor:$}){let B=new A0({color:Q,bold:!0}),E=new A0({color:KY6({progress:A,foreground:Q,pulseColor:$}),bold:!0});return new g("",void 0,[new g(VY6(A).padEnd(oc0," "),B),new g(" ",B),new g($j4(Dj4,DY6,A,0.72),B),new g(" ",B),new g($j4(Jj4,JY6,A,0.88),E)])}function VY6(A){let Q=Q4(Ej4),$=Math.min(oc0,Math.ceil(LE(A/0.62)*oc0));return Q.slice(0,$).join("")}function $j4(A,Q,$,B){return $>=B?A:"".padEnd(Q," ")}function KY6({progress:A,foreground:Q,pulseColor:$}){if(A<0.88||A>=1)return Q;let B=LE((A-0.88)/0.12);return Math.cos(B*Math.PI*4)*(1-B)>0.12?$:Q}function zY6({stage:A,featureStageCount:Q,foreground:$,dissolveProgress:B}){return new g($8(`${A}/${Q}`,B),new A0({color:$,dim:!0}))}function WY6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D}){let J=new A0({color:B}),U=new A0({color:$,dim:!0}),Y=Q?A?"Enter":"Space":"Esc",Z=Q?A?" to get started":" to continue":" to quit",F="",X="",I=`${Z}`;if(!Q)return new g("",void 0,[new g(Y,J),new g(Z,U),new g("",J),new g("",U)]);let G=Bj4(Y,E),V=Bj4(I,LE((E*(Q4(Y).length+Q4(I).length)-Q4(Y).length)/Q4(I).length));return new g("",void 0,[new g($8(G,D),J),new g($8(V.slice(0,Z.length),D),U),new g($8(V.slice(Z.length,Z.length+0),D),J),new g($8(V.slice(Z.length+0),D),U)])}function CY6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D,context:J}){if(Q)return new D0({text:WY6({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:E,dissolveProgress:D}),textAlign:"center"});let U=new A0({color:B}),Y=new A0({color:$,dim:!0});return new M5({onCopy:(Z,F)=>{if(F)DQ.success(J,"Copied to clipboard",2000)},child:new D0({text:new g("",void 0,[new g("q",U),new g(" to quit",Y)]),textAlign:"center",selectable:!0})})}function Bj4(A,Q){let $=Q4(A),B=Math.min($.length,Math.ceil(LE(Q)*$.length));return $.slice(0,B).join("").padEnd($.length," ")}function n90(A,Q,$=0){if(Q<=0)return A;let B=$+Q4(A.text??"").length,E=A.children?.map((D)=>{let J=n90(D,Q,B);return B+=Q4(D.toPlainText()).length,J});return new g(A.text?$8(A.text,Q,$):A.text,A.style,E,A.hyperlink,A.onClick)}function $8(A,Q,$=0){if(Q<=0)return A;return Q4(A).map((E,D)=>{if(E.trim()==="")return E;return Fj4($+D)<Q?" ":E}).join("")}function Fj4(A){let Q=Math.sin((A+1)*12.9898)*43758.5453;return Q-Math.floor(Q)}function NY6(A){let $=A.observer.protocolMessages().filter((B)=>B.role==="assistant").at(-1);if(!$)return null;return $.content.filter((B)=>B.type==="text").map((B)=>B.text).join("")}function Xj4(A){A.client.cancelAgentLoop().catch((Q)=>{S.warn("Failed to cancel plugin agent run",{error:Q})})}function qY6(A,Q={}){return new Promise(($,B)=>{if(Q.signal?.aborted){Xj4(A),B(Error("Agent run cancelled"));return}let E=!1,D=null,J=setTimeout(()=>{D?.(),Y.unsubscribe(),B(Error("Timed out waiting for agent response"))},Q.timeoutMs??600000),U=()=>{clearTimeout(J),Y.unsubscribe(),Xj4(A),B(Error("Agent run cancelled"))};if(Q.signal!==void 0)Q.signal.addEventListener("abort",U,{once:!0}),D=()=>Q.signal?.removeEventListener("abort",U);let Y=A.observer.agentState().subscribe((Z)=>{if(m3(Z)){E=!0;return}if(!E)return;let F=NY6(A);if(F===null)return;clearTimeout(J),D?.(),Y.unsubscribe(),$(F)})})}var wY6=O4("thread.switch",{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["resume"],status:{type:"enabled"},sortBoost:100},(A,{controller:Q,dismiss:$})=>{Q.pushWithDismiss((B)=>bd0({activeThreadID:A.getActiveThreadID(),loadThreads:A.loadThreads,loadThreadTail:A.appContext.loadThreadTail,onSelectThread:A.onSwitchThread,onDismiss:B,onThreadSelected:$}))}),uY6=O4("thread.switchToPrevious",{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],status:(A)=>A.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},(A,{dismiss:Q})=>{A.navigateBack(),Q()}),MY6=O4("thread.switchToNext",{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],status:(A)=>A.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},(A,{dismiss:Q})=>{A.navigateForward(),Q()}),OY6=O4("mcp.info",{noun:"mcp",verb:"info",description:"Show MCP servers and tools",status:{type:"enabled"}},(A,{controller:Q,dismiss:$})=>{Q.push(new Sm0({mcpServers:A.appContext.mcpServers,onDismiss:$}))}),LY6=O4("toolbox.list",{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",status:{type:"enabled"}},(A,{controller:Q})=>{Q.pushWithDismiss(($)=>new pc0({toolboxes:A.appContext.toolboxes,onDismiss:$}))}),jY6=O4("news.open",{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","blog","announcements"],status:{type:"enabled"}},async(A,{context:Q,dismiss:$})=>{try{await z$(Q,"https://ampcode.com/chronicle")}finally{$()}}),RY6=O4("settings.openInEditor",{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config"],status:{type:"enabled"}},(A)=>{wK(A.appContext.settingsFilePath).catch((Q)=>{S.error("Failed to open settings file in editor",{error:Q})})}),PY6=O4("ide.connect",{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains"],status:{type:"enabled"}},(A,{controller:Q,dismiss:$})=>{Q.pushWithDismiss((B)=>new _m0({onCancel:B,onSelect:(E)=>{A.handleIdeSelection(E),$()}}))}),TY6=O4("amp.help",{noun:"amp",verb:"help",description:"Show help & keymaps",keywords:["manual","?"],status:{type:"enabled"}},(A,{controller:Q,context:$,dismiss:B})=>{Q.push(new eg0({commands:sB.of($).commands,keymapShortcuts:A.getKeymapShortcuts(),onDismiss:B}))}),vY6=O4("amp.showWelcome",{noun:"amp",verb:"show welcome",description:"Show the welcome message again",status:{type:"enabled"}},(A,{dismiss:Q})=>{Q(),A.showWelcome()}),_Y6=O4("amp.endCredits",{noun:"amp",verb:"end credits",description:"Roll the full-screen Amp credits",status:{type:"enabled"}},(A,{dismiss:Q})=>{Q(),A.showEndCredits()}),SY6=O4("amp.showVersion",{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["v"],status:{type:"enabled"}},(A,{controller:Q,dismiss:$})=>{Q.push(new E1({header:"Amp Version",maxWidth:72,onDismiss:$,child:new D0({text:new g(V50({version:"0.0.1780774659-gd08a06",buildTimestamp:"2026-06-06T19:41:38.475Z",buildType:"release"}))})}))}),kY6=O4("amp.quit",{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","bye"],status:{type:"enabled"}},(A,{context:Q})=>{N4.maybeInvoke(Q,new vK)});class sc0 extends d0{listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;updateService;initialThreadIDs;showWelcome;welcomeVariant;onWelcomeDismissed;notificationService;mcpTrustHandler;onThreadArchived;onActiveThreadChange;onRelaunchRequested;onFirstFrame;initialUserInput;getDefaultNewThreadVisibility;observeThreadSummaries;openThreadPickerOnStart;workspaceSettingsFilePath;context;constructor(A){super();this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.updateService=A.updateService,this.initialThreadIDs=A.initialThreadIDs??[],this.showWelcome=A.showWelcome??!1,this.welcomeVariant=A.welcomeVariant??"intro",this.onWelcomeDismissed=A.onWelcomeDismissed,this.notificationService=A.notificationService,this.mcpTrustHandler=A.mcpTrustHandler,this.onThreadArchived=A.onThreadArchived,this.onActiveThreadChange=A.onActiveThreadChange,this.onRelaunchRequested=A.onRelaunchRequested,this.onFirstFrame=A.onFirstFrame,this.initialUserInput=A.initialUserInput,this.getDefaultNewThreadVisibility=A.getDefaultNewThreadVisibility,this.observeThreadSummaries=A.observeThreadSummaries,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.workspaceSettingsFilePath=A.workspaceSettingsFilePath,this.context=A.context}createState(){return new Gj4}}class Gj4 extends m0{editorController=new EZ;commandPalette=new ry0(this);commandRegistry=new sg0;keymapCommandRunner=new wh0(this.commandRegistry,()=>this.context);toastController=new Db0;relaunchNotificationController=new pg0;exitHintTimer=new Hp(this,1000);ideStatus=new p3(this,{});threadNavigationHistory=new ng0;appShortcutManager=new tc;keymapController=new Ky0({runCommand:(A)=>this.keymapCommandRunner.run(A),getCommandDescription:(A)=>{let Q=this.commandRegistry.findByID(A);return Q?.status.type==="enabled"?Q.description:null},onBindingsChange:()=>{if(this.syncAppShortcutManager(),this.mounted)this.setState()},onHintChange:()=>{if(this.mounted)this.setState()}});draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;activeThreadIDSubscription=null;activePluginMessageSubscription=null;activePluginUIRequestsSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;executorAlreadyConnectedDialog=null;switchThreadPickerVisible=!1;welcomeVisible=!1;endCreditsVisible=!1;invadersHighScore=0;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;emptyThreadTerminalTitleController=new bl;pluginIntegration=null;mcpTrustIntegration=null;updateRelaunchIntegration=null;noticesPollingTimeout=null;notices;editorFocusNode=new a7({debugLabel:"EditorPanel"});loadThreads=async()=>{return this.widget.context.listThreads()};focusEditor=()=>{this.editorFocusNode.requestFocus()};focusEditorAfterNextFrame(){cQ.instance.addPostFrameCallback(()=>{if(!this.mounted)return;this.focusEditor()},"Neo focus editor")}analyzeContextForThread=async(A,Q)=>{return PI4({ampURL:this.widget.context.ampURL,configService:this.widget.configService,threadID:A,signal:Q})};onSwitchThread=(A)=>{return this.connectToExistingThread(A,{recordNavigation:!0,rethrowError:!0})};onSelectSidebarThread=async(A)=>{this.focusEditor(),await this.onSwitchThread(A)};threadListSidebar=new cc0({state:this,isBlocked:()=>this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal(),getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,getWorkspaceRoot:()=>this.widget.context.workspaceRoot,loadThreads:this.loadThreads,observeThreadSummaries:()=>this.widget.observeThreadSummaries(),archiveThread:(A)=>this.archiveThread(A),onSelectThread:this.onSelectSidebarThread,focusMainContent:this.focusEditor,getInitialVisible:()=>this.widget.context.threadListSidebarVisible});sendFeedbackReport=async(A)=>L80({configService:this.widget.configService,settingsFilePath:this.widget.context.settingsFilePath},A);archiveThread=async(A)=>{let Q=await KW4({configService:this.widget.configService},A);if(Q===null){let $=this.activeThreadContext?.client.getThreadId()??null;if(this.widget.clientPool.disconnectThread(A),this.widget.onThreadArchived?.(A),$===A)this.startNewDraftThread()}return Q};addThreadLabel=async(A,Q)=>{let $=await GC4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};removeThreadLabel=async(A,Q)=>{let $=await VC4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};initState(){if(jX.getInstance().interceptConsole(),this.invadersHighScore=this.widget.context.invadersHighScore??0,this.syncAppShortcutManager(),this.keymapController.connect(($)=>G1.instance.addKeyInterceptor($,{position:"front"})),this.notices=new jg0(this.widget.configService,($)=>this.setState($)),cQ.instance.addPostFrameCallback(()=>{setTimeout(()=>this.widget.onFirstFrame?.(),0),this.noticesPollingTimeout=setTimeout(()=>{this.noticesPollingTimeout=null,this.notices.startPolling()},500)},"Neo notices polling"),this.widget.showWelcome)this.welcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:$,error:B})=>{if(S.error("Neo failed to connect to thread",{threadID:$,error:B}),!$)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configSubscription=this.widget.configService.config.subscribe(($)=>{this.keymapController.sync($.settings.keymap??{}),this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(P00($.settings)))}),this.updateRelaunchIntegration=new ag0({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested,relaunchNotificationController:this.relaunchNotificationController,updateService:this.widget.updateService}),this.updateRelaunchIntegration.init(),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput,Q=this.widget.initialThreadIDs[0];if(Q){let $={};if(A)$.initialUserInput=A;this.connectToInitialThreads(Q,$)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.context.sessionAgentMode);this.pluginIntegration=new dg0({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,context:this.widget.context,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread,readThreadMessages:this.readPluginThreadMessages,readThreadTitle:this.readPluginThreadTitle,subscribeThreadTitle:this.subscribePluginThreadTitle,runAgent:this.runPluginAgent,onBlockingConfirmDialogChange:this.syncEmptyThreadPluginConfirmationTitle}),this.pluginIntegration.init(),this.mcpTrustIntegration=new Mh0({state:this,mcpTrustHandler:this.widget.mcpTrustHandler,toastController:this.toastController,workspaceSettingsFilePath:this.widget.workspaceSettingsFilePath}),this.mcpTrustIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=G1.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}createCommands(){let A={appContext:this.widget.context,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSwitchThread:this.onSwitchThread,canNavigateBack:()=>this.threadNavigationHistory.canNavigateBack(),canNavigateForward:()=>this.threadNavigationHistory.canNavigateForward(),navigateBack:()=>this.navigateBack(),navigateForward:()=>this.navigateForward(),handleIdeSelection:this.handleIdeSelection,getKeymapShortcuts:()=>this.keymapController.getShortcuts(),showWelcome:()=>this.showWelcome(),showEndCredits:()=>this.showEndCredits()},Q=this.widget.context.pluginService?kN4({pluginService:this.widget.context.pluginService,workspaceRoot:this.widget.context.workspaceRoot,logFilePath:this.widget.context.logFilePath,toastController:this.toastController}):[];return[dN4({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),wY6.bind(A),...this.threadListSidebar.commands(),uY6.bind(A),xw4({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),MY6.bind(A),OY6.bind(A),LY6.bind(A),jY6.bind(A),RY6.bind(A),PY6.bind(A),TY6.bind(A),vY6.bind(A),_Y6.bind(A),SY6.bind(A),kY6.bind(A),...Q,...ZC4(this.widget.context.logFilePath)]}registerAppCommands(){let Q=this.createCommands().map(($)=>this.commandRegistry.register($));return()=>{for(let $ of Q)$()}}build(A){let Q=this.buildHints(),$=this.ideStatus.getValue(),B=this.notices.current,E=new yc0({initialAgentMode:this.widget.context.sessionAgentMode,initialPluginAgentModeKey:this.widget.context.initialPluginAgentModeKey,analyzeContextForThread:this.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,editorFocusNode:this.editorFocusNode,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,sendFeedbackReport:this.sendFeedbackReport,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:$,statusItems:this.pluginIntegration?.getStatusItems()??[],pluginConfirmationBlocked:this.pluginIntegration?.hasBlockingConfirmDialog()??!1,notificationService:this.widget.notificationService,notice:this.activeThreadContext||this.welcomeVisible?null:B,onDismissNotice:(V)=>this.notices.dismiss(V)}),D=X4.of(A),J=D.capabilities.animationSupport!=="disabled",U=this.threadListSidebar.visibleWidth(),Y=Math.max(0,D.size.width-U),F=[new GA({constraints:A4.tight(D.size.width,D.size.height),child:this.threadListSidebar.buildBody(E)})];if(this.commandPalette.isEnabled())F.push(new E6({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new tg0({keymapShortcuts:this.keymapController.getShortcuts(),onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.welcomeVisible)F.push(bd0({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,loadThreadTail:this.widget.context.loadThreadTail,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.welcomeVisible)F.push(new E6({debugLabel:"WelcomeDialogOverlay",child:new rc0({onDismiss:this.dismissWelcome,onQuit:()=>G1.instance.stop(),animationsEnabled:J,variant:this.widget.welcomeVariant})}));let X=this.executorAlreadyConnectedDialog;if(X)F.push(new E6({debugLabel:"ExecutorAlreadyConnectedDialogOverlay",child:new Pm0({existingExecutorPid:X.existingExecutorPid,onChoice:this.handleExecutorAlreadyConnectedChoice})}));if(F.push(...this.mcpTrustIntegration?.buildDialogLayers()??[]),F.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.context.isInternalUser)F.push(new Qm0({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:a90.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,observerSnapshot$:this.activeThreadContext?.observer.observerSnapshot()??null}));if(this.focusDebugVisible)F.push(new Tm0);if(this.endCreditsVisible)F.push(new um0({onComplete:this.completeEndCredits,highScore:this.invadersHighScore,onHighScoreChange:this.updateInvadersHighScore}));let I=this.keymapController.getHint(),G=b70(this.exitHintTimer.isActive()?{key:"Ctrl+C",description:"again to exit"}:I?{key:I.leader,description:"...",options:I.options}:null);if(G)F.push(G);return new MQ({context:this.widget.context,child:new sB({commandRegistry:this.commandRegistry,child:new zT({completionBuilder:this.widget.completionBuilder,child:new DQ({controller:this.toastController,child:new N4({actions:this.buildActions(),child:new rQ({debugLabel:"AppShortcuts",shortcuts:this.buildShortcuts(),manager:this.appShortcutManager,child:this.keymapCommandRunner.captureContext(new VQ({debugLabel:"AppShellFocus",canRequestFocus:!1,skipTraversal:!0,child:new Jb0({controller:this.toastController,complexToastControllers:[this.relaunchNotificationController,...B&&this.activeThreadContext&&!this.welcomeVisible?[this.notices]:[]],child:new Am0({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new Oq({left:U,width:Y,child:this.keymapCommandRunner.buildModalStack(new t1({children:F}))})})})}))})})})})})})}buildShortcuts(){let A=new Map,Q=new Set,$=(E,D)=>{A.set(E,D),Q.add(E.toString())},B=(E,D)=>{if(Q.has(E.toString()))return;$(E,D)};for(let E of this.keymapController.getBindings())if(E.activator instanceof wA)$(E.activator,new j70(E.commandID));B(wA.ctrl("c"),new M70),B(wA.ctrl("o"),new L70),B(wA.alt("i"),new P70),B(wA.alt("p"),new nc),B(wA.ctrl("."),new _70),B(wA.ctrl("t"),new f70);for(let[E,D]of this.threadListSidebar.shortcutEntries())B(E,D);if(a90.env.NODE_ENV==="development"&&a90.platform==="darwin")B(wA.meta("r"),new O70);return A}syncAppShortcutManager(){for(let A of this.appShortcutManager.getAllShortcuts().keys())this.appShortcutManager.removeShortcut(A);for(let[A,Q]of this.buildShortcuts())this.appShortcutManager.addShortcut(A,Q)}buildActions(){let A=new cA(()=>{if(b2.hasAnyCopyableSelection())return b2.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new cA(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),$=new cA(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),B=new cA((G)=>{return this.keymapCommandRunner.run(G.commandID)?"handled":"ignored"}),E=new cA(()=>{return this.startNewDraftThread(),"handled"}),D=new cA(()=>{return G1.instance.stop(),"handled"}),J=new cA(()=>{return Pl({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),"handled"}),U=new cA((G)=>{if(!G.text)return"ignored";return G1.instance.tuiInstance.clipboard.writeText(G.text).then((V)=>{if(V.ok)this.toastController.show(G.successMessage,"success",2000);else this.toastController.show(`${G.failureMessage}: ${V.userFacingErrorMessage}`,"error",4000)}).catch((V)=>{S.error("Failed to copy Neo text to clipboard",{error:V}),this.toastController.show(G.failureMessage,"error",2000)}),"handled"}),Y=new cA(()=>{return G1.instance.toggleFrameStatsOverlay(),"handled"}),Z=new cA(()=>this.notices.dismissCurrent()?"handled":"ignored"),F=new cA(()=>{if(!this.widget.context.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),X=Qq4({getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,context:this.widget.context,toastController:this.toastController,startNewDraftThread:this.startNewDraftThread,sendFeedbackReport:this.sendFeedbackReport}),I=new cA(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[M70,A],[Lq,E],[vK,D],[O70,J],[IB,U],[Ql,$],[j70,B],[L70,Q],[P70,F],...this.threadListSidebar.actionEntries(),[_70,Z],...X,[nc,Y],[f70,I]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.cancelOwnerUIRequests(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),this.widget.onActiveThreadChange?.(null),this.syncEmptyThreadPluginConfirmationTitle(),A.prompt!==void 0)this.editorController.text=A.prompt;this.focusEditorAfterNextFrame()}syncEmptyThreadPluginConfirmationTitle=()=>{this.emptyThreadTerminalTitleController.setPluginConfirmationBlocked(this.activeThreadContext===null&&(this.pluginIntegration?.hasBlockingConfirmDialog()??!1))};closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=this.applySessionDefaultsToThreadSettings(await hP(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){S.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.context.sessionAgentMode,$=A,B=oN(Q),E=Z50(this.widget.context,Q);if(B!==void 0&&E!==void 0)$={...$,[B]:E};return U50($,{agentMode:Q,explicitEffort:this.widget.context.explicitReasoningEffort,sessionState:this.widget.context})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=Ij4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(m9(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=Ij4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(TK);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),G1.instance.stop();else this.exitHintTimer.activate()};dismissWelcome=()=>{if(!this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!1}),this.widget.onWelcomeDismissed?.()};updateInvadersHighScore=(A)=>{if(A<=this.invadersHighScore)return;this.setState(()=>{this.invadersHighScore=A}),eD((Q)=>({...Q,neoInvadersHighScore:Math.max(Q.neoInvadersHighScore,A)})).catch((Q)=>{S.warn("Failed to save Neo Invaders high score",{error:Q instanceof Error?Q.message:String(Q)})})};showWelcome=()=>{if(this.welcomeVisible)return;this.setState(()=>{this.welcomeVisible=!0})};showEndCredits=()=>{if(this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!0})};completeEndCredits=()=>{if(!this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!1})};promptExecutorAlreadyConnected(A){return new Promise((Q)=>{this.setState(()=>{this.executorAlreadyConnectedDialog={existingExecutorPid:A.existingExecutorPid,resolve:($)=>{Q($==="watch"?"observe":"disconnect")}}})})}handleExecutorAlreadyConnectedChoice=(A)=>{if(this.resolveExecutorAlreadyConnectedDialog(A),A==="exit")G1.instance.stop()};resolveExecutorAlreadyConnectedDialog(A){let Q=this.executorAlreadyConnectedDialog;if(!Q)return;this.setState(()=>{this.executorAlreadyConnectedDialog=null}),Q.resolve(A)}closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1}),this.focusEditorAfterNextFrame()};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,$=null,B,E,D)=>{await this.ensureDraftThreadSettingsInitialized();let J=this.activeThreadContext?.client.getThreadId(),U=A.find(N00);if(U)this.widget.history.add(U.text,a90.cwd()),this.widget.history.reset();let Y=$?void 0:await this.widget.getDefaultNewThreadVisibility?.(),Z=$??Y??null,F=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,Z??void 0,E,D);if(this.sendUserMessage(F,A,E?void 0:Q,E?void 0:B),!E)this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings);this.threadNavigationHistory.recordNavigation(J),this.setActiveClient(F)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.context.sessionAgentMode=A;let $=Q["reasoning.effort"];if($!==void 0)this.widget.context.lastReasoningEffortByMode={...this.widget.context.lastReasoningEffortByMode??{},[A]:$};let B=oN(A),E=B?Q[B]:void 0;if(E!==void 0)this.widget.context.lastSpeedByMode={...this.widget.context.lastSpeedByMode??{},[A]:E};eD((D)=>{let J={...D,agentMode:A};if($!==void 0)J={...J,lastReasoningEffortByMode:{...J.lastReasoningEffortByMode??{},[A]:$}};if(E!==void 0)J={...J,lastSpeedByMode:{...J.lastSpeedByMode??{},[A]:E}};return J}).catch((D)=>{S.warn("Failed to persist Neo session defaults for new message",{error:D instanceof Error?D.message:String(D)})})}sendUserMessage(A,Q,$,B,E){let D=D50(this.ideStatus.getValue());if(B===void 0){A.client.sendUserMessage(Q,$,{steer:E?.steer,userState:D}).catch((J)=>{S.warn("Failed to send user message",{error:J})});return}A.client.sendUserMessage(Q,$,{reasoningEffort:B,steer:E?.steer,userState:D}).catch((J)=>{S.warn("Failed to send user message",{error:J})})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};getRelaunchThreadIDs=()=>{let A=new Set,Q=this.getActiveThreadID();if(Q)A.add(Q);for(let $ of this.widget.clientPool.activeThreadIDs)A.add($);return[...A]};appendPluginMessagesToThread=async(A,Q,$)=>{let B=this.activeThreadContext;if(!B){if(Q){for(let D of A)await this.widget.clientPool.appendUserMessageToThread(Q,D.content,$);return}throw Error("appendToThread is not available - no active thread")}let E=B.client.getThreadId();if(Q&&E!==Q){for(let D of A)await this.widget.clientPool.appendUserMessageToThread(Q,D.content,$);return}for(let D of A)this.sendUserMessage(B,[{type:"text",text:D.content}],void 0,void 0,$)};readPluginThreadMessages=async(A,Q)=>{let $=this.activeThreadContext;if(!$)throw Error("thread.messages is not available - no active thread");let B=$.client.getThreadId();if(Q&&B!==Q)throw Error("thread.messages is only available for the active thread");return xoA(yoA($.observer.protocolMessages()),A)};readPluginThreadTitle=async(A)=>{let Q=this.activeThreadContext;if(!Q)throw Error("thread.title is not available - no active thread");let $=Q.client.getThreadId();if(A&&$!==A)throw Error("thread.title is only available for the active thread");return Q.observer.title().getValue()??null};subscribePluginThreadTitle=(A,Q)=>{let $=this.activeThreadContext;if(!$)throw Error("thread.title.subscribe is not available - no active thread");let B=$.client.getThreadId();if(A&&B!==A)throw Error("thread.title.subscribe is only available for the active thread");return $.observer.title().subscribe((E)=>{Q.next(E??null)})};runPluginAgent=async(A,Q,$)=>{await this.ensureDraftThreadSettingsInitialized();let B=this.widget.clientPool.createNewThread(this.widget.context.sessionAgentMode,this.draftThreadSettings,void 0,A,Q.agentModeDisplay,Q.parentThreadID,{trackAsLastActive:!1,executorClientID:iY.parse(`neo-subagent-${HY6()}`)});this.sendUserMessage(B,[{type:"text",text:Q.message}]);try{let E=await qY6(B,{timeoutMs:Q.timeoutMs,signal:$}),D=B.client.getThreadId();return D?{threadID:D,text:E}:{text:E}}finally{this.widget.clientPool.disconnect(B)}};async connectToExistingThread(A,Q={}){let $=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let B=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:(E)=>this.promptExecutorAlreadyConnected(E)});if(this.setActiveClient(B),Q.recordNavigation&&$!==A)this.threadNavigationHistory.recordNavigation($);if(Q.initialUserInput)this.sendUserMessage(B,[{type:"text",text:Q.initialUserInput}])}catch(B){if(S.error("Failed to load thread",{error:B,threadID:A}),this.toastController.show(`Failed to load ${A}: ${B instanceof Error?B.message:String(B)}`,"error",4000),Q.rethrowError)throw B}finally{this.setState(()=>{this.connectingToThreadID=null})}}async connectToInitialThreads(A,Q={}){await this.connectToExistingThread(A,Q);let $=this.widget.initialThreadIDs.filter((B)=>B!==A);await Promise.all($.map((B)=>this.resumeBackgroundThread(B)))}async resumeBackgroundThread(A){try{await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.context.observerOnly,onExecutorAlreadyConnected:async()=>"observe"})}catch(Q){S.error("Failed to resume background thread",{error:Q,threadID:A}),this.toastController.show(`Failed to resume ${A}: ${Q instanceof Error?Q.message:String(Q)}`,"error",4000)}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}setActiveClient({client:A,observer:Q,agentModeDisplay:$}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q,agentModeDisplay:$}}),this.syncEmptyThreadPluginConfirmationTitle(),this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe((B)=>{this.widget.onActiveThreadChange?.(B)}),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription?.unsubscribe(),this.pluginIntegration?.cancelOwnerUIRequests(),this.activePluginMessageSubscription=Q.pluginMessages().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage(B,(E)=>{A.sendPluginMessage(E)})}),this.activePluginUIRequestsSubscription=Q.pluginUIRequests().subscribe((B)=>{this.pluginIntegration?.handlePluginMessage({type:"plugin_message",message:{type:"event",event:"plugin.ui.snapshot",data:{requests:[...B]}}},(E)=>{A.sendPluginMessage(E)})})}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){S.error("Failed to connect to IDE",{error:Q});let $=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${$}`,"error",4000)}};dispose(){if(this.keymapController.dispose(),this.keymapCommandRunner.dispose(),this.unregisterCommands?.(),this.unregisterCommands=null,this.threadListSidebar.dispose(),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.emptyThreadTerminalTitleController.dispose(),this.mcpTrustIntegration?.dispose(),this.mcpTrustIntegration=null,this.updateRelaunchIntegration?.dispose(),this.updateRelaunchIntegration=null,this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.noticesPollingTimeout)clearTimeout(this.noticesPollingTimeout),this.noticesPollingTimeout=null;this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.notices.dispose(),this.widget.notificationService.detach(),this.toastController.dispose(),this.editorFocusNode.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.executorAlreadyConnectedDialog!==null||this.welcomeVisible||(this.mcpTrustIntegration?.hasBlockingDialog()??!1)||this.endCreditsVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function Ij4(A,Q,$){let B={...A};for(let E of fY6(Q,$)){if(!m9(A[E],Q[E]))continue;let D=$[E];if(D===void 0)delete B[E];else B[E]=D}return B}function fY6(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}function Vj4(){return jI4()}function gY6(A,Q){let $=mY6(A,Q),B=new Map(A.map((J)=>[J.id,J.description])),E=Object.entries($),D=E.map(([J,U],Y)=>{let Z=Y===E.length-1?"":",",F=` ${JSON.stringify(J)}: ${JSON.stringify(U)}${Z}`,I=` // ${(J==="leader"?"Leader key for <leader> shortcuts":B.get(J)??"Configured, not discovered").replaceAll(/[\r\n\u2028\u2029]/g," ")}`;return U===null?P0.dim(F+I):F+P0.dim(I)});return D.unshift("{"),D.push("}"),D.join(`
|
|
2914
2914
|
`)+`
|
|
2915
2915
|
`}function mY6(A,Q){let $=Vy0(Q),B=Q.leader,E={leader:B===null||typeof B==="string"&&f2(B)?B:Iy0};for(let D of A){let J=$.filter((Y)=>Y.commandID===D.id).map((Y)=>Y.key),U=D.defaultKey?[...J,D.defaultKey]:J;if(U.length===0)E[D.id]=null;if(U.length===1)E[D.id]=U[0];if(U.length>1)E[D.id]=U}for(let[D,J]of Object.entries(Q)){if(D==="leader"||E[D]!==void 0)continue;E[D]=J}return E}async function dY6(A){await yY6(hY6.dirname(A),{recursive:!0});try{await bY6(A,`{
|
|
2916
2916
|
}
|
|
2917
|
-
`,{encoding:"utf-8",flag:"wx",mode:384})}catch(Q){if(Q.code!=="EEXIST")throw Q}}async function cY6(A){await dY6(A);let Q=xP();try{xY6(Q,[A],{stdio:"inherit"})}catch($){throw S.error("Failed to open settings file in editor",{editor:Q,settingsPath:A,error:$}),Error(`Failed to open ${Q}`)}}function Kj4(A,Q){let $=A.command("config").summary("Manage Amp configuration").description("Manage Amp configuration").action(()=>{$.outputHelp(),process.exit(0)});$.command("edit").summary("Open the Amp settings file in $EDITOR").description("Open the Amp settings file in $EDITOR. By default, this opens user settings. Use --workspace to edit the workspace-specific .amp/settings.json file.").option("--global","Edit user settings (default)").option("--workspace","Edit workspace settings").action(async(B,E)=>{if(B.global&&B.workspace)throw Error("Use only one of --global or --workspace");let D=await Q(E.optsWithGlobals()),J=B.workspace?D.getWorkspaceSettingsPath():D.getSettingsFilePath();await cY6(J),process.exit(0)}),$.command("keymap").summary("List command
|
|
2917
|
+
`,{encoding:"utf-8",flag:"wx",mode:384})}catch(Q){if(Q.code!=="EEXIST")throw Q}}async function cY6(A){await dY6(A);let Q=xP();try{xY6(Q,[A],{stdio:"inherit"})}catch($){throw S.error("Failed to open settings file in editor",{editor:Q,settingsPath:A,error:$}),Error(`Failed to open ${Q}`)}}function Kj4(A,Q){let $=A.command("config").summary("Manage Amp configuration").description("Manage Amp configuration").action(()=>{$.outputHelp(),process.exit(0)});$.command("edit").summary("Open the Amp settings file in $EDITOR").description("Open the Amp settings file in $EDITOR. By default, this opens user settings. Use --workspace to edit the workspace-specific .amp/settings.json file.").option("--global","Edit user settings (default)").option("--workspace","Edit workspace settings").action(async(B,E)=>{if(B.global&&B.workspace)throw Error("Use only one of --global or --workspace");let D=await Q(E.optsWithGlobals()),J=B.workspace?D.getWorkspaceSettingsPath():D.getSettingsFilePath();await cY6(J),process.exit(0)}),$.command("keymap").summary("List command keymap entries").description("List all command IDs, descriptions, and effective keymap entries").allowExcessArguments(!1).action(async(B,E)=>{let J=await(await Q(E.optsWithGlobals())).get("keymap")??{};process.stdout.write(gY6(Vj4(),J)),process.exit(0)})}i0();import{execFile as pY6}from"node:child_process";import{promisify as lY6}from"node:util";var iY6=lY6(pY6),nY6=["private","workspace"];function aY6(A){switch(A){case"private":return{visibility:"private",sharedGroupIDs:[]};case"workspace":return{visibility:"thread_workspace_shared"};case"group":return{visibility:"private",shareWithAllCreatorGroups:!0}}}function tc0(A){return A.endsWith("/")?A.slice(0,-1):A}function oY6(A){let Q=s30(A);try{let E=new URL(Q);return tc0(`${E.host}${E.pathname}`).replace(/^\//,"")}catch{}let $=Q.match(/^[^@]+@([^:/]+)[:/](.+)$/);if($?.[1]&&$[2])return tc0(`${$[1]}/${$[2]}`).replace(/\.git$/,"");let B=Q.match(/^([^:]+):(.+)$/);if(B?.[1]&&B[2])return tc0(`${B[1]}/${B[2]}`).replace(/\.git$/,"");return null}async function Wj4(A){try{let{stdout:Q}=await iY6("git",["remote","get-url","origin"],{cwd:A}),$=Q.trim();if(!$)return null;return oY6($)}catch{return null}}function rY6(A){let Q=[...nY6];if(A?.team?.disablePrivateThreads){let $=Q.indexOf("private");if($!==-1)Q.splice($,1)}if(A?.team?.groups&&A.team.groups.length>0)Q.push("group");return Q}function sY6(A){if(A?.team?.groups!==void 0)return Error(["Group visibility is not available. ",`You are not a member of any group in this workspace.
|
|
2918
2918
|
`].join(""));return Error(`Group visibility is not available.
|
|
2919
2919
|
`)}function zj4(A,Q){let B=[`Invalid ${A?`visibility for amp.defaultVisibility.${A}`:"visibility"}. `,`Must be one of: ${Q.join(", ")}.
|
|
2920
2920
|
`].join("");return Error(B)}function tY6(A,Q){return Q.includes(A)}function Cj4(A,Q,$){if(A===void 0||A===null)return;let B=rY6(Q);if(typeof A!=="string")return zj4($,B);if(A==="group"&&!B.includes("group"))return sY6(Q);if(tY6(A,B))return A;return zj4($,B)}async function eY6(A,Q,$){let B=await Wj4(Q);if(!B)return;let E;try{E=await A.get("defaultVisibility")}catch(J){S.warn("Failed to read defaultVisibility setting",{error:J});return}let D=E?.[B];return Cj4(D,$,B)}async function o90(A,Q,$,B){if(B)return B;let E=await eY6(A,Q,$);if(E instanceof Error)return E;if(E===void 0)return;return aY6(E)}function Hj4(A,Q){return Cj4(A,Q)}async function Nj4(A,Q,$){let B=await Wj4(Q);if(!B)return Error("No git origin remote found for this repository.");let D={...await A.get("defaultVisibility","global")??{},[B]:$};return await A.set("defaultVisibility",D,"global"),{repoKey:B}}import{stderr as eK}from"node:process";i0();var AWB=Buffer.from([1]),QWB=Buffer.from([2]),$WB=Buffer.from([3]),BWB=Buffer.from([4]),EWB=Buffer.from([5]),DWB=Buffer.from([6]),JWB=Buffer.from([8]),UWB=Buffer.from([11]),YWB=Buffer.from([12]),ZWB=Buffer.from([14]),FWB=Buffer.from([16]),XWB=Buffer.from([21]),IWB=Buffer.from([23]),GWB=Buffer.from([25]),VWB=Buffer.from([7]),KWB=Buffer.from([15]),zWB=Buffer.from([17]),WWB=Buffer.from([18]),CWB=Buffer.from([19]),HWB=Buffer.from([20]),NWB=Buffer.from([22]),qWB=Buffer.from([24]),wWB=Buffer.from([26]),uWB=Buffer.from([27]),MWB=Buffer.from([13]),OWB=Buffer.from([10]),LWB=Buffer.from([127]),jWB=Buffer.from([9]),RWB=Buffer.from([27,91,90]),PWB=Buffer.from([27,91,65]),TWB=Buffer.from([27,91,66]),vWB=Buffer.from([27,91,67]),_WB=Buffer.from([27,91,68]),SWB=Buffer.from([27,91,49,59,50,65]),kWB=Buffer.from([27,91,49,59,50,66]),fWB=Buffer.from([27,91,49,59,50,67]),xWB=Buffer.from([27,91,49,59,50,68]),yWB=Buffer.from([27,91,53,126]),bWB=Buffer.from([27,91,54,126]),hWB=Buffer.from([27,91,72]),gWB=Buffer.from([27,91,70]),mWB=Buffer.from([27,91,49,126]),dWB=Buffer.from([27,91,52,126]),cWB=Buffer.from([27,91,55,126]),pWB=Buffer.from([27,91,56,126]),lWB=Buffer.from([27,91,51,126]),iWB=Buffer.from([27,91,50,126]),nWB=Buffer.from([27,91,71]),aWB=Buffer.from([27,91,49,48,126]),oWB=Buffer.from([27,91,49,49,126]),rWB=Buffer.from([27,91,49,50,126]),sWB=Buffer.from([27,91,49,51,126]),tWB=Buffer.from([27,91,49,52,126]),eWB=Buffer.from([27,91,49,53,126]),ACB=Buffer.from([27,91,49,55,126]),QCB=Buffer.from([27,91,49,56,126]),$CB=Buffer.from([27,91,49,57,126]),BCB=Buffer.from([27,91,50,48,126]),ECB=Buffer.from([27,91,50,49,126]),DCB=Buffer.from([27,91,50,51,126]),JCB=Buffer.from([27,91,50,52,126]),UCB=Buffer.from([27,91,50,53,126]),YCB=Buffer.from([27,91,50,54,126]),ZCB=Buffer.from([27,91,50,56,126]),FCB=Buffer.from([27,91,50,57,126]),XCB=Buffer.from([27,91,51,49,126]),ICB=Buffer.from([27,91,51,50,126]),GCB=Buffer.from([27,91,51,51,126]),VCB=Buffer.from([27,91,51,52,126]),KCB=Buffer.from([27,79,80]),zCB=Buffer.from([27,79,81]),WCB=Buffer.from([27,79,82]),CCB=Buffer.from([27,79,83]),HCB=Buffer.from([27,91,49,80]),NCB=Buffer.from([27,91,49,81]),qCB=Buffer.from([27,91,49,82]),wCB=Buffer.from([27,91,49,83]),uCB=Buffer.from([27,102]),MCB=Buffer.from([27,98]),OCB=Buffer.from([27,100]),LCB=Buffer.from([27,127]),jCB=Buffer.from([27,91,49,59,51,65]),RCB=Buffer.from([27,91,49,59,51,66]),PCB=Buffer.from([27,91,49,59,53,65]),TCB=Buffer.from([27,91,49,59,53,66]),vCB=Buffer.from([27,91,49,59,53,68]),_CB=Buffer.from([27,91,49,59,53,67]),SCB=Buffer.from([27,91,49,50,55,59,53,117]),kCB=Buffer.from([27,91,50,55,59,50,59,49,51,126]),fCB=Buffer.from([27,91,50,55,59,53,59,49,51,126]),xCB=Buffer.from([27,91,50,55,59,56,59,49,51,126]),qj4={ESC:Buffer.from([27,91,50,55,117]),CTRL_A:Buffer.from([27,91,57,55,59,53,117]),CTRL_B:Buffer.from([27,91,57,56,59,53,117]),CTRL_C:Buffer.from([27,91,57,57,59,53,117]),CTRL_D:Buffer.from([27,91,49,48,48,59,53,117]),CTRL_E:Buffer.from([27,91,49,48,49,59,53,117]),CTRL_F:Buffer.from([27,91,49,48,50,59,53,117]),CTRL_H:Buffer.from([27,91,49,48,52,59,53,117]),CTRL_K:Buffer.from([27,91,49,48,55,59,53,117]),CTRL_L:Buffer.from([27,91,49,48,56,59,53,117]),CTRL_N:Buffer.from([27,91,49,49,48,59,53,117]),CTRL_P:Buffer.from([27,91,49,49,50,59,53,117]),CTRL_U:Buffer.from([27,91,49,49,55,59,53,117]),CTRL_W:Buffer.from([27,91,49,49,57,59,53,117]),CTRL_Y:Buffer.from([27,91,49,50,49,59,53,117]),CTRL_G:Buffer.from([27,91,49,48,51,59,53,117]),CTRL_O:Buffer.from([27,91,49,49,49,59,53,117]),CTRL_Q:Buffer.from([27,91,49,49,51,59,53,117]),CTRL_R:Buffer.from([27,91,49,49,52,59,53,117]),CTRL_S:Buffer.from([27,91,49,49,53,59,53,117]),CTRL_T:Buffer.from([27,91,49,49,54,59,53,117]),CTRL_V:Buffer.from([27,91,49,49,56,59,53,117]),CTRL_X:Buffer.from([27,91,49,50,48,59,53,117]),CTRL_Z:Buffer.from([27,91,49,50,50,59,53,117]),ALT_B:Buffer.from([27,91,57,56,59,51,117]),ALT_F:Buffer.from([27,91,49,48,50,59,51,117]),ALT_D:Buffer.from([27,91,49,48,48,59,51,117]),ALT_BACKSPACE:Buffer.from([27,91,49,50,55,59,51,117]),ALT_ARROW_UP:Buffer.from([27,91,49,59,51,65]),ALT_ARROW_DOWN:Buffer.from([27,91,49,59,51,66]),CTRL_ARROW_UP:Buffer.from([27,91,49,59,53,65]),CTRL_ARROW_DOWN:Buffer.from([27,91,49,59,53,66]),CTRL_ARROW_LEFT:Buffer.from([27,91,49,59,53,68]),CTRL_ARROW_RIGHT:Buffer.from([27,91,49,59,53,67]),CTRL_BACKSPACE:Buffer.from([27,91,49,50,55,59,53,117]),SHIFT_BACKSPACE:Buffer.from([27,91,49,50,55,59,50,117]),SHIFT_TAB:Buffer.from([27,91,57,59,50,117]),SHIFT_ENTER:Buffer.from([27,91,49,51,59,50,117]),CTRL_ENTER:Buffer.from([27,91,49,51,59,53,117]),PAGE_UP:Buffer.from([27,91,53,117]),PAGE_DOWN:Buffer.from([27,91,54,117]),HOME:Buffer.from([27,91,72,117]),END:Buffer.from([27,91,70,117]),DEL:Buffer.from([27,91,81,117]),enable(){process.stderr.write("\x1B[=1u")},disable(){process.stderr.write("\x1B[=0u"),process.stderr.write("\x1B[<u")}};var AZ6=process.env.AMP_DEBUG!==void 0&&process.env.AMP_DEBUG!=="0"&&!!process.env.AMP_DEBUG,q3={unknownCommand:(A)=>`Unknown command "${A}". Run 'amp --help' for the full list.`,badFlag:(A)=>`Invalid flag "${A}". See 'amp --help' for valid options.`,notLoggedIn:"Not logged in. Run 'amp login' to authenticate.",invalidAPIKey:"Invalid or missing API key. Run 'amp login' to authenticate.",authExpired:"Access token expired. Run 'amp login' to refresh.",networkTimeout:"Network timeout. Check your connection or proxy settings and retry.",networkOffline:"Cannot reach Amp servers. Are you offline?",serverError:"Amp server returned an error. Try again in a moment.",terminalTooSmall:"Terminal is too small. Resize the pane or window to at least 9 rows and try again.",webSocketConnectionFailed:"WebSocket connection failed. Check your connection or proxy settings and retry.",threadNotFound:(A)=>`Thread ${A} not found or you don't have access. Verify the ID.`,invalidThreadId:"Invalid thread ID format.",internalBug:`Unexpected error inside Amp CLI.${AZ6?" Run with AMP_DEBUG=1 to see detailed logs.":""}`,nodeVersion:(A)=>`Amp CLI requires Node.js v20+. Current version: ${A}`};function B8(A){throw new VA(`Invalid thread ID or URL: ${A}`,1,"Provide a valid thread ID (e.g., T-5928a90d-d53b-488f-a829-4e36442142ee) or thread URL (e.g., https://ampcode.com/threads/T-5928a90d-d53b-488f-a829-4e36442142ee)")}function QZ6(A){if(!(A instanceof Error))return!1;let Q=(A.message??"").toLowerCase()+(A.stack??"").toLowerCase();return["thread","threadservice","threadsync","threadworker","threadhistory","threadsummary","thread-"].some((B)=>Q.includes(B))}function Az(){try{S.debug("cleanupTerminal() called"),qj4.disable(),eK.write("\x1B[?25h")}catch(A){}}function ec0(A){if(A instanceof VA)return{message:A.userMessage,suggestion:A.suggestion};if(A instanceof oX4)return{message:A.message};if(A instanceof Error){let Q=(A.message??"").toLowerCase();if(Q.includes("401")||Q.includes("unauthorized"))return{message:q3.invalidAPIKey};if(Q.includes("403")||Q.includes("forbidden"))return{message:q3.authExpired};if(Q.includes("timeout")||Q.includes("etimedout"))return{message:q3.networkTimeout};if(Q.includes("websocket connection failed")||Q.includes("websocket closed during connect")||Q.includes("expected 101 status code")||Q.includes("failed to get wstoken")||Q.includes("websocket is not connected"))return{message:q3.webSocketConnectionFailed};if(Q.includes("enotfound")||Q.includes("econnrefused")||Q.includes("unable to connect"))return{message:q3.networkOffline};if(/api request .* failed: 5\d\d/.test(Q))return{message:q3.serverError};if(Q.includes("minrows must be <= maxrows"))return{message:q3.terminalTooSmall};if(Q.includes("thread")&&Q.includes("not found"))return{message:"Thread not found or you don't have access."};if(Q.includes("fetch failed")||Q.includes("failed to fetch"))return{message:q3.networkOffline}}return{message:q3.internalBug}}function wj4(A,Q){let $=process.env.AMP_DEBUG==="1"||process.argv.includes("--debug");S.error("CLI Error",A);let{message:B,suggestion:E}=ec0(A);if(eK.write(P0.red.bold("Error: ")+B+`
|
|
@@ -3070,13 +3070,13 @@ ${K}`))}},error:(V)=>{if(!G)G=!0,Z(Error(`Failed to spawn brew: ${V.message}`))}
|
|
|
3070
3070
|
${K}`;if(J==="pnpm"&&K.includes("Unable to find the global bin directory"))z+=`
|
|
3071
3071
|
|
|
3072
3072
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
3073
|
-
npm install -g ${D}`;Z(Error(z))}},error:(V)=>{if(!I)I=!0,Z(Error(`Failed to spawn ${J}: ${V.message}`))},complete:()=>{if(!I)I=!0,Y()}})})}i0();hA();i0();import{readFile as YI6,realpath as ZI6}from"node:fs/promises";import{dirname as IP4,join as FI6}from"node:path";async function GP4(A){switch(A){case"binary":case"brew":return XI6(Ki());case"npm":case"pnpm":case"yarn":case"bun":return II6()}}async function XI6(A){let Q=await HK(A,["--version"],5000);if(Q.reason!=="success")return S.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function II6(){try{let A=process.argv[1];if(!A)return null;let Q=await ZI6(A),$=IP4(IP4(Q));return await GI6(FI6($,"package.json"))}catch(A){return S.debug("failed to read installed version from package.json",{error:A}),null}}async function GI6(A){let Q=await YI6(A,"utf8"),$=JSON.parse(Q);if(!$.name||!Oy0($.name))return S.debug("package.json name mismatch",{pkgJsonPath:A,name:$.name}),null;return $.version||null}i0();import{spawn as VI6}from"node:child_process";function fp0(A){if(A=A.replace(/\/$/,""),!A.startsWith("http://")&&!A.startsWith("https://"))A=`https://${A}`;try{return new URL(A),A}catch{return S.warn(`Invalid registry URL: ${A}, falling back to npmjs.org`),"https://registry.npmjs.org"}}var WE0=null,Wi=null;function VP4(A){return new Promise((Q)=>{let $=VI6("npm",["config","get",A],{stdio:["ignore","pipe","ignore"],timeout:5000,shell:process.platform==="win32"}),B="";$.stdout.on("data",(E)=>{B+=E.toString()}),$.on("close",(E,D)=>{if(E!==0||D==="SIGTERM"){Q(null);return}let J=B.trim();Q(J&&J!=="undefined"?J:null)}),$.on("error",()=>{Q(null)})})}async function CE0(){if(WE0)return WE0;if(Wi)return Wi;Wi=(async()=>{let A=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(A)return fp0(A);let Q=await VP4("@sourcegraph:registry");if(Q)return fp0(Q);let $=await VP4("registry");if($)return fp0($);return"https://registry.npmjs.org"})();try{return WE0=await Wi,WE0}finally{Wi=null}}var KI6=3600000,zI6=5000;function xp0(A,Q,$={}){let B=new L4,E=B.pipe(_$({shouldCountRefs:!1})),D=$.startDelayMs??0,J=$.checkIntervalMs??KI6,U=!1,Y=()=>{U=!0};return setImmediate(async()=>{let Z=S.getChild("update");if(D>0){if(await LV(D),U)return}let F=E.subscribe({next:(I)=>{Z.debug("emit new state",I)}}),X=A;try{while(!U){let I=await WI6(X,Q,Z,B);if(I.stop)return;if(I.updatedTo)X=I.updatedTo;if(I.emittedVisibleState){if(await LV(zI6),U)return;B.next("hidden")}if(J<=0)return;let G=1000,V=J;while(V>0&&!U){let K=Math.min(G,V);await LV(K),V-=K}}}finally{F.unsubscribe(),B.complete()}}),{state:E,dispose:Y}}async function WI6(A,Q,$,B){let E={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return $.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),E.stop=!0,E;let D=await Q.get("updates.mode");if(D==="disabled")return $.debug("checking disabled"),E.stop=!0,E;let J=await sY(),U=J==="binary"||J==="brew",Y=U?void 0:await NK();$.debug("checking",{currentVersion:A,mode:D,packageManager:J,isBinaryDistribution:U,npmPackageName:Y});let Z;if(U)Z=await X50(A);else{let I=await CE0();Z=await F50(A,I,Y)}if(!(Z.latestVersion&&Z.hasUpdate))return $.debug("no update available"),E;let F=(I)=>{B.next(I),E.emittedVisibleState=!0};if(J){let I=await GP4(J);if(I&&Ap(I,Z.latestVersion)>=0){if($.debug("on-disk version already up to date",{currentVersion:A,installedVersion:I,latestVersion:Z.latestVersion}),E.updatedTo=I,Ap(A,I)<0){let G=await PX(I),V={from:A,to:I,externallyUpdated:!0,...G};if(G.status==="same")$.info("on-disk already updated by another instance",V),F("updated");else $.warn("on-disk already updated by another instance, with PATH warning",V),F("updated-with-warning")}return E}}let X=()=>{if(Z.currentVersionAge!==void 0&&Z.latestVersionAge!==void 0){let I=Z.currentVersionAge-Z.latestVersionAge,G=0.5;if(Math.abs(I)<0.5)return $.debug("versions too close together, suppressing update warning",{currentVersionAge:Z.currentVersionAge,latestVersionAge:Z.latestVersionAge,ageDifferenceHours:I}),!0}return!1};if(!D)D=J==="pnpm"?"warn":"auto",$.debug("no configured update mode; selected default based on package manager",{packageManager:J,mode:D});if(J==="brew"){if(!X())F("update-available-brew");return E}if(J==="binary"&&process.execPath!==Ki()){if($.debug("non-standard binary path, showing warning"),!X())F("update-available-unrecognized-path");return E}if(D==="warn"){if(!X())F("update-available");return E}if(!J){if($.debug("auto-update not supported, falling back to warn mode"),!X())F("update-available");return E}try{await zi(Z.latestVersion,J),E.updatedTo=Z.latestVersion;let I=await PX(Z.latestVersion),G={from:Z.currentVersion,to:Z.latestVersion,...I};if(I.status==="same")$.info("success",G),F("updated");else $.warn("success with warning",G),F("updated-with-warning")}catch(I){F("update-error")}return E}catch(D){return $.debug("check failed",{error:D}),E}}Kg();import{stderr as IJ}from"node:process";function KP4(A){let Q=new MX().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(B)=>{await Pp0(B.force||!1,B.verbose||!1,"0.0.
|
|
3073
|
+
npm install -g ${D}`;Z(Error(z))}},error:(V)=>{if(!I)I=!0,Z(Error(`Failed to spawn ${J}: ${V.message}`))},complete:()=>{if(!I)I=!0,Y()}})})}i0();hA();i0();import{readFile as YI6,realpath as ZI6}from"node:fs/promises";import{dirname as IP4,join as FI6}from"node:path";async function GP4(A){switch(A){case"binary":case"brew":return XI6(Ki());case"npm":case"pnpm":case"yarn":case"bun":return II6()}}async function XI6(A){let Q=await HK(A,["--version"],5000);if(Q.reason!=="success")return S.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function II6(){try{let A=process.argv[1];if(!A)return null;let Q=await ZI6(A),$=IP4(IP4(Q));return await GI6(FI6($,"package.json"))}catch(A){return S.debug("failed to read installed version from package.json",{error:A}),null}}async function GI6(A){let Q=await YI6(A,"utf8"),$=JSON.parse(Q);if(!$.name||!Oy0($.name))return S.debug("package.json name mismatch",{pkgJsonPath:A,name:$.name}),null;return $.version||null}i0();import{spawn as VI6}from"node:child_process";function fp0(A){if(A=A.replace(/\/$/,""),!A.startsWith("http://")&&!A.startsWith("https://"))A=`https://${A}`;try{return new URL(A),A}catch{return S.warn(`Invalid registry URL: ${A}, falling back to npmjs.org`),"https://registry.npmjs.org"}}var WE0=null,Wi=null;function VP4(A){return new Promise((Q)=>{let $=VI6("npm",["config","get",A],{stdio:["ignore","pipe","ignore"],timeout:5000,shell:process.platform==="win32"}),B="";$.stdout.on("data",(E)=>{B+=E.toString()}),$.on("close",(E,D)=>{if(E!==0||D==="SIGTERM"){Q(null);return}let J=B.trim();Q(J&&J!=="undefined"?J:null)}),$.on("error",()=>{Q(null)})})}async function CE0(){if(WE0)return WE0;if(Wi)return Wi;Wi=(async()=>{let A=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(A)return fp0(A);let Q=await VP4("@sourcegraph:registry");if(Q)return fp0(Q);let $=await VP4("registry");if($)return fp0($);return"https://registry.npmjs.org"})();try{return WE0=await Wi,WE0}finally{Wi=null}}var KI6=3600000,zI6=5000;function xp0(A,Q,$={}){let B=new L4,E=B.pipe(_$({shouldCountRefs:!1})),D=$.startDelayMs??0,J=$.checkIntervalMs??KI6,U=!1,Y=()=>{U=!0};return setImmediate(async()=>{let Z=S.getChild("update");if(D>0){if(await LV(D),U)return}let F=E.subscribe({next:(I)=>{Z.debug("emit new state",I)}}),X=A;try{while(!U){let I=await WI6(X,Q,Z,B);if(I.stop)return;if(I.updatedTo)X=I.updatedTo;if(I.emittedVisibleState){if(await LV(zI6),U)return;B.next("hidden")}if(J<=0)return;let G=1000,V=J;while(V>0&&!U){let K=Math.min(G,V);await LV(K),V-=K}}}finally{F.unsubscribe(),B.complete()}}),{state:E,dispose:Y}}async function WI6(A,Q,$,B){let E={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return $.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),E.stop=!0,E;let D=await Q.get("updates.mode");if(D==="disabled")return $.debug("checking disabled"),E.stop=!0,E;let J=await sY(),U=J==="binary"||J==="brew",Y=U?void 0:await NK();$.debug("checking",{currentVersion:A,mode:D,packageManager:J,isBinaryDistribution:U,npmPackageName:Y});let Z;if(U)Z=await X50(A);else{let I=await CE0();Z=await F50(A,I,Y)}if(!(Z.latestVersion&&Z.hasUpdate))return $.debug("no update available"),E;let F=(I)=>{B.next(I),E.emittedVisibleState=!0};if(J){let I=await GP4(J);if(I&&Ap(I,Z.latestVersion)>=0){if($.debug("on-disk version already up to date",{currentVersion:A,installedVersion:I,latestVersion:Z.latestVersion}),E.updatedTo=I,Ap(A,I)<0){let G=await PX(I),V={from:A,to:I,externallyUpdated:!0,...G};if(G.status==="same")$.info("on-disk already updated by another instance",V),F("updated");else $.warn("on-disk already updated by another instance, with PATH warning",V),F("updated-with-warning")}return E}}let X=()=>{if(Z.currentVersionAge!==void 0&&Z.latestVersionAge!==void 0){let I=Z.currentVersionAge-Z.latestVersionAge,G=0.5;if(Math.abs(I)<0.5)return $.debug("versions too close together, suppressing update warning",{currentVersionAge:Z.currentVersionAge,latestVersionAge:Z.latestVersionAge,ageDifferenceHours:I}),!0}return!1};if(!D)D=J==="pnpm"?"warn":"auto",$.debug("no configured update mode; selected default based on package manager",{packageManager:J,mode:D});if(J==="brew"){if(!X())F("update-available-brew");return E}if(J==="binary"&&process.execPath!==Ki()){if($.debug("non-standard binary path, showing warning"),!X())F("update-available-unrecognized-path");return E}if(D==="warn"){if(!X())F("update-available");return E}if(!J){if($.debug("auto-update not supported, falling back to warn mode"),!X())F("update-available");return E}try{await zi(Z.latestVersion,J),E.updatedTo=Z.latestVersion;let I=await PX(Z.latestVersion),G={from:Z.currentVersion,to:Z.latestVersion,...I};if(I.status==="same")$.info("success",G),F("updated");else $.warn("success with warning",G),F("updated-with-warning")}catch(I){F("update-error")}return E}catch(D){return $.debug("check failed",{error:D}),E}}Kg();import{stderr as IJ}from"node:process";function KP4(A){let Q=new MX().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(B)=>{await Pp0(B.force||!1,B.verbose||!1,"0.0.1780774659-gd08a06"),process.exit()});A.addCommand(Q,{hidden:!0});let $=new MX("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(B)=>{await NI6(B.targetVersion)});A.addCommand($)}function CI6(A){let Q=Boolean(A.isTTY),$=0,B=!1;function E(){if(!Q||!B)return;A.write(`
|
|
3074
3074
|
`),B=!1,$=0}function D(J){if(!Q)return;let U=J.padEnd($," ");A.write(`\r${U}`),B=!0,$=U.length}return{flushProgressLine:E,renderProgress:D}}function HI6(A){if(A.source==="npm"&&A.latestVersionAge!==void 0&&A.latestVersionAge>36)IJ.write(P0.yellow(`The latest Amp CLI version reported by npm is older than expected. Be aware that you may be using an npm proxy with a corporate policy to delay package updates.
|
|
3075
3075
|
`))}async function NI6(A){let $=process.platform==="win32"&&tN()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:B,renderProgress:E}=CI6(IJ);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")IJ.write(P0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
3076
3076
|
|
|
3077
3077
|
`));try{if(!A){IJ.write(P0.blue(`Checking for updates...
|
|
3078
|
-
`));let U=!1,Y;if(tN()){let Z=await X50("0.0.
|
|
3079
|
-
`));let X=await PX("0.0.
|
|
3078
|
+
`));let U=!1,Y;if(tN()){let Z=await X50("0.0.1780774659-gd08a06");U=Z.hasUpdate,Y=Z.latestVersion}else{let Z=await CE0(),F=await NK(),X=await F50("0.0.1780774659-gd08a06",Z,F);HI6(X),U=X.hasUpdate,Y=X.latestVersion}if(!U){let Z=Qp("0.0.1780774659-gd08a06"),F=Z?.age?`released ${Z.age} ago`:`built ${MV(new Date("2026-06-06T19:41:38.475Z"))} ago`;IJ.write(P0.green(`✓ Amp is already up to date on version ${"0.0.1780774659-gd08a06"} (${F})
|
|
3079
|
+
`));let X=await PX("0.0.1780774659-gd08a06",$);if(X.warning)IJ.write(`
|
|
3080
3080
|
`+P0.yellow(X.warning)+`
|
|
3081
3081
|
`);process.exit(0)}if(!Y)IJ.write(P0.yellow("[WARN] could not find latest version")),process.exit(0);A=Y}IJ.write(P0.blue(`Updating to version ${A}...
|
|
3082
3082
|
`)),await zi(A,void 0,(U)=>{B(),IJ.write(P0.dim(`Running: ${U}
|
|
@@ -5051,7 +5051,7 @@ Start Amp from a smaller directory.`};function eX(A,Q){if(!PR4())return;S.debug(
|
|
|
5051
5051
|
`)}function xv4(A,Q){A.command("usage").description("Show your current Amp usage and credit balance").action(async($,B)=>{let E=B.optsWithGlobals(),D=await Q(E),J=await cT(D),U=await j4.userDisplayBalanceInfo({},{config:J});if(!U.ok){if(U.error.code==="auth-required")process.stderr.write(P0.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(P0.red("Error: ")+U.error.message+`
|
|
5052
5052
|
`),process.exit(1)}process.stdout.write(await eW6(U.result.displayText)+`
|
|
5053
5053
|
`),process.exit(0)})}var uw6=ti.join(oU,"logs","headless.log"),li0=ti.join(ty,"device-id.json");$I4();async function Mw6(){let A=await Promise.all(lC.map(async(Q)=>{try{return{query:Q,hasConfigs:(await Q.listConfigs()).length>0}}catch($){return S.debug("Failed to detect query-based IDE integration",{ideName:Q.ideName,error:$}),{query:Q,hasConfigs:!1}}}));for(let Q of A)if(Q.hasConfigs)return Q.query;return}function Zf4(){Mw6().then((A)=>{if(A){let Q=p00(A.ideName);if(Q)hC(Q)}})}try{if(process.platform==="win32")await Promise.resolve().then(() => k4(Hv(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){H7.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
|
|
5054
|
-
`)}function Ow6(A){process.emitWarning=(Q,$,B,E)=>{let D=typeof Q==="string"?Q:Q.message||String(Q),J=$||"Warning",U=!1;A.warn(D,{name:J,code:B})}}function _B(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")k00("dangerouslyAllowAll",Q.dangerouslyAllowAll)}function Lw6(A,Q){if(!p9(Q))return;if(!MC(Q.user.email)){if(A.model)throw new VA("The --model flag is only available for Amp employees.",1);k00("internal.model",void 0);return}if(A.model)k00("internal.model",Pw6(A.model))}function Bf4(A){let Q=A.indexOf(":");if(Q===-1)throw new VA(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let $=A.slice(0,Q).trim(),B=A.slice(Q+1).trim();if(!$||!B)throw new VA(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function jw6(A){if(A===void 0)return;let Q=A.trim();if(sy(Q))return Q;throw new VA(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function Rw6(A,Q){if(dC(A))return;throw new VA(`Reasoning effort "${Q}" is not available for ${A} mode.`,1)}function Pw6(A){if(!A.includes("="))return Bf4(A),A;let Q={};for(let $ of A.split(",")){let B=$.trim();if(!B)continue;let E=B.indexOf("=");if(E===-1)throw new VA(`Invalid mode-specific model entry "${B}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let D=B.slice(0,E).trim(),J=B.slice(E+1).trim();if(!D)throw new VA(`Missing mode name in "${B}". Expected "mode=provider:model".`,1);if(!J)throw new VA(`Missing model value for mode "${D}". Expected "${D}=provider:model".`,1);Bf4(J),Q[D]=J}if(Object.keys(Q).length===0)throw new VA("No valid model overrides found in --model flag value.",1);return Q}function OD0(A,Q,$){let B=Number(A);if(!Number.isInteger(B)||B<$.min)throw new d30(`${Q} must be an integer >= ${$.min}`);if($.max!==void 0&&B>$.max)throw new d30(`${Q} must be an integer <= ${$.max}`);return B}function Tw6(A,Q){return A?.some(($)=>$.name===Q&&$.enabled)??!1}async function vw6(A,Q){let $=await j4.getUserInfo({},{config:A});return $.ok?Tw6($.result.features,Q):!1}function _w6(A){return A!=="pending"}function Kw(A){if(!p9(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function Sw6(A){let Q=Kw(A);if(Q)return Q.id;if(gC(A))throw Error(A.error.message);throw Error("unreachable")}function kw6(A){try{let Q=new URL(A);return Q.hostname==="localhost"||Q.hostname==="127.0.0.1"}catch{return A.includes("localhost")||A.includes("127.0.0.1")}}function fw6(A){let B=kw6(A)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new VA(`Couldn't connect to the Amp server at ${A}.`,1,B)}function ai0(A,Q){let $=ec0(Error(A.error.message));if($.message===q3.networkOffline||$.message===q3.networkTimeout)return fw6(Q);if($.message!==q3.internalBug)return new VA($.message,1,$.suggestion);return new VA(A.error.message.replace(/^Error: /,""),1)}async function xw6(){if(process.versions.bun)return!1;try{return await sY()==="npm"}catch(A){return S.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var Ef4=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH or with AMP_FORCE_BEL; enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??eJ,description:`Custom settings file path (overrides the default location ${eJ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(S).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${lc})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","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:D9(),description:(A)=>A?"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:(A)=>A?"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:(A)=>A?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:i9.SMART.key,description:`Set the agent mode (${BY({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Show migration instructions for the removed legacy runtime",hidden:!0},{name:"orb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"hideWelcome",long:"hide-welcome",type:"switch",description:"Skip the welcome experience on startup",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],Df4=(A)=>("deprecated"in A)&&A.deprecated===!0,yw6=(A)=>("hidden"in A)&&A.hidden===!0,bw6=(A)=>("default"in A),hw6=(A)=>("default"in A)?A.default:void 0;function Jf4(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let $=jw6(Q.effort);if($!==void 0){if(ei(Q.mode))Rw6(Q.mode,$)}return $}var gw6="Amp Neo is now Amp and available to everyone. If you need to finish work in the old Amp, you can use an older version. For instructions on how to do that and more information: https://ampcode.com/news/drop-the-neo";function ei(A){return Object.values(i9).some((Q)=>Q.key===A)}function mw6(A,Q){if(ei(A))return A;throw new VA(`${Q} does not support plugin-defined agent modes`,1)}function Ff4(A,Q){if(ei(Q))return{agentMode:Q};let $=A.agentModes.list().find((E)=>E.key===Q||E.label===Q);if(!$){let E=BY({}).map((U)=>U.mode).join(", "),D=A.agentModes.list().map((U)=>U.label).join(", "),J=D?` Plugin modes: ${D}.`:"";throw new VA(`Unknown agent mode '${Q}'. Built-in modes: ${E}.${J}`,1)}let B={label:$.label};if($.color!==void 0)B.color=$.color;return{agentMode:i9.SMART.key,agent:$.agent,agentModeDisplay:B,pluginAgentModeKey:$.key}}async function dw6(A,Q,$){if(A.getOptionValueSourceWithGlobals("mode")!=="cli")return;return await Q.initialized,Ff4(Q,$)}function cw6(A,Q){let $=Q.args[0],B=Q.commands.map((D)=>D.name());if($&&!$.includes(" ")&&$.length<30&&!/[./\\]/.test($)){let D=B.filter((U)=>$.includes(U)||U.includes($)),J="Run amp --help for a list of available commands.";if(D.length>0)J=`Did you mean: ${D.join(", ")}? Or run amp --help for all commands.`;throw new VA(q3.unknownCommand($),1,J)}}var LD0=g0.file(ww6.homedir()),ii0=process.env.XDG_CONFIG_HOME?g0.file(process.env.XDG_CONFIG_HOME):BA.joinPath(LD0,".config");async function e$(A,Q,$){let B=$?.deferAuth??!1,E=$?.skipToolProviders??!1;QhA("0.0.
|
|
5054
|
+
`)}function Ow6(A){process.emitWarning=(Q,$,B,E)=>{let D=typeof Q==="string"?Q:Q.message||String(Q),J=$||"Warning",U=!1;A.warn(D,{name:J,code:B})}}function _B(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")k00("dangerouslyAllowAll",Q.dangerouslyAllowAll)}function Lw6(A,Q){if(!p9(Q))return;if(!MC(Q.user.email)){if(A.model)throw new VA("The --model flag is only available for Amp employees.",1);k00("internal.model",void 0);return}if(A.model)k00("internal.model",Pw6(A.model))}function Bf4(A){let Q=A.indexOf(":");if(Q===-1)throw new VA(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let $=A.slice(0,Q).trim(),B=A.slice(Q+1).trim();if(!$||!B)throw new VA(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function jw6(A){if(A===void 0)return;let Q=A.trim();if(sy(Q))return Q;throw new VA(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function Rw6(A,Q){if(dC(A))return;throw new VA(`Reasoning effort "${Q}" is not available for ${A} mode.`,1)}function Pw6(A){if(!A.includes("="))return Bf4(A),A;let Q={};for(let $ of A.split(",")){let B=$.trim();if(!B)continue;let E=B.indexOf("=");if(E===-1)throw new VA(`Invalid mode-specific model entry "${B}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let D=B.slice(0,E).trim(),J=B.slice(E+1).trim();if(!D)throw new VA(`Missing mode name in "${B}". Expected "mode=provider:model".`,1);if(!J)throw new VA(`Missing model value for mode "${D}". Expected "${D}=provider:model".`,1);Bf4(J),Q[D]=J}if(Object.keys(Q).length===0)throw new VA("No valid model overrides found in --model flag value.",1);return Q}function OD0(A,Q,$){let B=Number(A);if(!Number.isInteger(B)||B<$.min)throw new d30(`${Q} must be an integer >= ${$.min}`);if($.max!==void 0&&B>$.max)throw new d30(`${Q} must be an integer <= ${$.max}`);return B}function Tw6(A,Q){return A?.some(($)=>$.name===Q&&$.enabled)??!1}async function vw6(A,Q){let $=await j4.getUserInfo({},{config:A});return $.ok?Tw6($.result.features,Q):!1}function _w6(A){return A!=="pending"}function Kw(A){if(!p9(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function Sw6(A){let Q=Kw(A);if(Q)return Q.id;if(gC(A))throw Error(A.error.message);throw Error("unreachable")}function kw6(A){try{let Q=new URL(A);return Q.hostname==="localhost"||Q.hostname==="127.0.0.1"}catch{return A.includes("localhost")||A.includes("127.0.0.1")}}function fw6(A){let B=kw6(A)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new VA(`Couldn't connect to the Amp server at ${A}.`,1,B)}function ai0(A,Q){let $=ec0(Error(A.error.message));if($.message===q3.networkOffline||$.message===q3.networkTimeout)return fw6(Q);if($.message!==q3.internalBug)return new VA($.message,1,$.suggestion);return new VA(A.error.message.replace(/^Error: /,""),1)}async function xw6(){if(process.versions.bun)return!1;try{return await sY()==="npm"}catch(A){return S.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var Ef4=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH or with AMP_FORCE_BEL; enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??eJ,description:`Custom settings file path (overrides the default location ${eJ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(S).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${lc})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","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:D9(),description:(A)=>A?"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:(A)=>A?"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:(A)=>A?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:i9.SMART.key,description:`Set the agent mode (${BY({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Show migration instructions for the removed legacy runtime",hidden:!0},{name:"orb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"hideWelcome",long:"hide-welcome",type:"switch",description:"Skip the welcome experience on startup",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],Df4=(A)=>("deprecated"in A)&&A.deprecated===!0,yw6=(A)=>("hidden"in A)&&A.hidden===!0,bw6=(A)=>("default"in A),hw6=(A)=>("default"in A)?A.default:void 0;function Jf4(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let $=jw6(Q.effort);if($!==void 0){if(ei(Q.mode))Rw6(Q.mode,$)}return $}var gw6="Amp Neo is now Amp and available to everyone. If you need to finish work in the old Amp, you can use an older version. For instructions on how to do that and more information: https://ampcode.com/news/drop-the-neo";function ei(A){return Object.values(i9).some((Q)=>Q.key===A)}function mw6(A,Q){if(ei(A))return A;throw new VA(`${Q} does not support plugin-defined agent modes`,1)}function Ff4(A,Q){if(ei(Q))return{agentMode:Q};let $=A.agentModes.list().find((E)=>E.key===Q||E.label===Q);if(!$){let E=BY({}).map((U)=>U.mode).join(", "),D=A.agentModes.list().map((U)=>U.label).join(", "),J=D?` Plugin modes: ${D}.`:"";throw new VA(`Unknown agent mode '${Q}'. Built-in modes: ${E}.${J}`,1)}let B={label:$.label};if($.color!==void 0)B.color=$.color;return{agentMode:i9.SMART.key,agent:$.agent,agentModeDisplay:B,pluginAgentModeKey:$.key}}async function dw6(A,Q,$){if(A.getOptionValueSourceWithGlobals("mode")!=="cli")return;return await Q.initialized,Ff4(Q,$)}function cw6(A,Q){let $=Q.args[0],B=Q.commands.map((D)=>D.name());if($&&!$.includes(" ")&&$.length<30&&!/[./\\]/.test($)){let D=B.filter((U)=>$.includes(U)||U.includes($)),J="Run amp --help for a list of available commands.";if(D.length>0)J=`Did you mean: ${D.join(", ")}? Or run amp --help for all commands.`;throw new VA(q3.unknownCommand($),1,J)}}var LD0=g0.file(ww6.homedir()),ii0=process.env.XDG_CONFIG_HOME?g0.file(process.env.XDG_CONFIG_HOME):BA.joinPath(LD0,".config");async function e$(A,Q,$){let B=$?.deferAuth??!1,E=$?.skipToolProviders??!1;QhA("0.0.1780774659-gd08a06");let D=y00({storage:A.settings,secretStorage:A.secrets,workspaceRoot:process.cwd(),defaultAmpURL:A.ampURL,homeDir:LD0,userConfigDir:ii0}),J=A.secrets.get("apiKey",A.ampURL),U=eO(D),Y=null,Z=()=>{return},F=new Promise((B0)=>{Z=B0}),X=J.then(async(B0)=>{if(!B0&&!B)await F;return Y??=U.subscribe(()=>{}),n4(U.pipe(Y5(_w6)))});X.catch(()=>{return}),Iv4(D);let I=await D.getLatest();S.debug("Global configuration initialized",{settingsKeys:Object.keys(I.settings)});let G=!1;{let B0=await J;if(G=Boolean(B0),S.info("API key lookup before login",{found:Boolean(B0),ampURL:A.ampURL,deferAuth:B}),!B0)if(B)S.info("No API key found, continuing startup with deferred auth");else{fQ.write(`No API key found. Starting login flow...
|
|
5055
5055
|
`);let C0=await pw6(A),l=await A.secrets.get("apiKey",A.ampURL);if(S.info("Login flow completed",{success:C0,storedKeyPresent:Boolean(l),ampURL:A.ampURL}),!C0)await oY(),process.exit(1);G=!0,Z()}}{let B0=await D.getLatest(),C0=B0.settings.url,l=B0.secrets.isSet?.[C0];S.info("Config secrets state after login",{configURL:C0,apiKeySet:l?.apiKey??!1})}let V=B?"pending":await X;if(!B)S.info("Server status resolved",{status:"ready",isAuthenticated:p9(V),isError:gC(V),errorMessage:gC(V)?V.error.message:void 0});Lw6(Q,V);let K=X.then((B0)=>Sw6(B0));K.catch(()=>{return});let z=p9(V),W=!1;if(process.env.AMP_DISABLE_PLUGINS==="1")S.warn("Ignoring AMP_DISABLE_PLUGINS outside development");let C=W?"off":"all",{toolService:H,dispose:N}=RJ4({configService:D}),w=new Map,u=()=>w.clear(),L=new UO0(D,A.settings.getWorkspaceRootPath()),R=XeA({configService:D}),_=JoA({configService:D,trustStore:L,skillMCPServers:R.skillMCPServers,uploadImageAttachments:z,createOAuthProvider:async(B0,C0,l)=>{let i=`${B0}:${C0}`,$0=w.get(i);if($0)return S.debug("Reusing existing OAuth provider for server",{serverName:B0,serverUrl:C0}),$0;S.debug("Creating OAuth provider for server",{serverName:B0,serverUrl:C0});let s=(async()=>{let E0=new tC(A.secrets),Q0=await E0.getClientInfo(B0,C0),G0=l?.scopes??Q0?.scopes,V0=iR4();S.info("OAuth headless mode check",{useHeadless:V0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:fQ.isTTY});let w0;if(V0)w0=A.executeMode?lR4():pR4(B0);let I0=new eq0({storage:E0,serverName:B0,serverUrl:C0,clientId:l?.clientId??Q0?.clientId,clientSecret:l?.clientSecret??Q0?.clientSecret,authUrl:l?.authUrl??Q0?.authUrl,tokenUrl:l?.tokenUrl??Q0?.tokenUrl,scopes:G0,headlessAuthHandler:w0});return S.debug("OAuth provider created",{serverName:B0,serverUrl:C0,hasManualClientId:!!(l?.clientId??Q0?.clientId),willUseDCR:!(l?.clientId??Q0?.clientId),scopes:G0,headlessMode:V0,executeMode:A.executeMode}),I0})();return w.set(i,s),s}}),P=Jj0({configService:D,spawn:MQ0}),f=Q.headless?jT4():void 0,h=f??new SE0({configService:D}),x=h instanceof SE0?h:void 0;if(x)x.pluginExecutorKind="local";let v=new H4(null),k=null,c=z&&!W?[...vT4(I.settings)?[{name:"permissions",entryPoint:El0}]:[],{name:"thread-visibility",entryPoint:kT4(D,()=>X.then(Kw),()=>k,(B0)=>{k=B0}),alwaysLoad:!0}]:[],d=qO0({configService:D,platform:h,loadGlobalPlugins:Hp0(D),pluginFilter:C,activeThread$:v,internalPlugins:c}),b=JrA(d),p=[_,P,b],n;if(E)n=new Map;else if(A.executeMode){let B0=await y04({toolService:H,providers:p,initialTimeout:15000});n=B0.registrations;for(let[C0,l]of B0.initErrors)S.warn(`${C0} provider initialization slow or failed:`,l)}else n=Uj0({toolService:H,providers:p});if(Q.jetbrains)hC("JetBrains");else if(Q.ide&&$G4())hC("VS Code");else if(Q.ide&&BG4())hC("Neovim");else if(Q.ide&&A.executeMode)Zf4();if(A.executeMode)$hA(!0);let a,X0=S3.status.pipe(tA((B0)=>Boolean(B0.connected&&B0.authenticated&&B0.ideName&&EgA(B0.ideName))),FQ()).subscribe((B0)=>{if(B0){if(!a)a=H.registerTool(x04)}else a?.dispose(),a=void 0}),t;if(!A.executeMode){let B0=await A.settings.get("fuzzy.alwaysIncludePaths")??[];t=new XE0(process.cwd(),{alwaysIncludePaths:B0},!0)}else t=new class extends XE0{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let Z0=Yg(D);S.info("Starting Amp background services");let K0=new Vl0,R0={configService:D,toolService:H,mcpService:_,skillService:R,toolboxService:P,trustStore:L,threadRemote:Z0,setThreadMeta:Z0.setThreadMeta,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:t,terminal:K0,pluginService:d,pluginPlatform:x,headlessPluginPlatform:f,activeThread$:v,serverStatus:V,serverStatusPromise:X,viewerUserIDPromise:K,hasAPIKeyAtStartup:G,consumeDraftNewThreadVisibility:()=>{let B0=k;return k=null,B0}};return{...R0,async asyncDispose(){if(R0.mcpService.hasAuthenticatingClients())S.info("Waiting for OAuth authentication to complete before exit..."),await R0.mcpService.waitForAuthentication();for(let B0 of n.values())B0.dispose();await R0.mcpService.dispose(),u(),R0.configService.unsubscribe(),Y?.unsubscribe(),N(),R0.fuzzyServer.dispose(),R0.settingsStorage[Symbol.dispose](),X0.unsubscribe(),a?.dispose(),await R0.pluginService.dispose()}}}async function pw6(A){if(!A.executeMode){if(!await TE0("Would you like to log in to Amp? [(y)es, (n)o]: "))return fQ.write(`Login cancelled. Run the command again to retry.
|
|
5056
5056
|
`),!1}return await Xf4(A)}async function Xf4(A){let Q=Cw6(32).toString("hex"),$=await sp0(A.ampURL,Q),B=new AbortController;try{await aJ($,B.signal)}catch(D){S.error("Error opening browser",{error:D})}let E=await sp0(A.ampURL,Q,!1);fQ.write(`If your browser does not open automatically, visit:
|
|
5057
5057
|
|
|
@@ -5059,7 +5059,7 @@ ${P0.blue.bold(E)}
|
|
|
5059
5059
|
|
|
5060
5060
|
`);try{return await YT4(A.ampURL,Q,A.secrets,B),fQ.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(D){return S.error("Login failed",{error:D}),H7.write(`
|
|
5061
5061
|
Login failed: ${D instanceof Error?D.message:String(D)}
|
|
5062
|
-
`),!1}}async function lw6(A,Q,$){let B=await Q.get("apiKey",A);if(!B)throw new VA("No Amp API key found. Run `amp login` first.",1);let E=Ww6("curl",["-H",`Authorization: Bearer ${B}`,...$],{stdio:"inherit"});process.exitCode=await new Promise((D,J)=>{E.on("error",J),E.on("close",(U)=>D(U??1))})}function iw6(A){let Q=new MX().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, unlisted, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)Az(),process.exit(0);let N=H.originalError??H;uj4(N)}),nI4(Q,{version:"0.0.
|
|
5062
|
+
`),!1}}async function lw6(A,Q,$){let B=await Q.get("apiKey",A);if(!B)throw new VA("No Amp API key found. Run `amp login` first.",1);let E=Ww6("curl",["-H",`Authorization: Bearer ${B}`,...$],{stdio:"inherit"});process.exitCode=await new Promise((D,J)=>{E.on("error",J),E.on("close",(U)=>D(U??1))})}function iw6(A){let Q=new MX().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, unlisted, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)Az(),process.exit(0);let N=H.originalError??H;uj4(N)}),nI4(Q,{version:"0.0.1780774659-gd08a06",buildTimestamp:"2026-06-06T19:41:38.475Z",buildType:"release"}),Q.addHelpText("after",eR4()),Q.configureHelp({formatHelp:AP4}),Q.command("logout").description("Log out by removing stored API key").action(async(H,N)=>{let w=N.optsWithGlobals(),u=await nQ(w);await Bu6(u)}),Q.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,N)=>{let w=N.optsWithGlobals(),u=await nQ(w);await $u6(u,await Yl0(w,u.settings))}),iT4(Q,nQ);let B=Q.command("internal",{hidden:!0}).description("Internal commands").command("curl [args...]").description("Internal: run curl with the current Amp API key as a bearer token").allowUnknownOption(!0).allowExcessArguments(!0).action(async(...H)=>{let N=H.find((R)=>typeof R==="object"&&R!==null&&typeof R.optsWithGlobals==="function")??B,w=H.filter((R)=>R!==N).flatMap((R)=>Array.isArray(R)?R:typeof R==="string"?[R]:[]),u=N.optsWithGlobals(),L=await nQ(u);await lw6(L.ampURL,L.secrets,w),process.exit(process.exitCode??0)});Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(H,N,w)=>{let u=w.optsWithGlobals(),L=await nQ(u);await _R4(H??"get",L.ampURL,L.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit [args...]",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements Git signing helper interfaces. Used inside sandboxes for commit signing.").allowUnknownOption(!0).allowExcessArguments(!0).action(async(H,N,w)=>{let u=w.optsWithGlobals(),L=await nQ(u);await kR4(L,H),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(H)=>{await _P4({raw:H.raw===!0}),process.exit(process.exitCode??0)}),vv4(Q,{createContext:nQ,createThreadDependencies:e$,initializeCLIOverrides:_B}),Q.command("live-sync [threadIDOrURL]",{hidden:!0}).summary("Mirror live DTW thread changes into the current checkout").description("Experimental: watch a v2 thread URL or ID and mirror its live working-tree changes into your local checkout, or apply the current snapshot once and exit.").addHelpText("after",["","Examples:"," amp live-sync T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync --apply T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync https://ampcode.com/threads/T-5928a90d-d53b-488f-a829-4e36442142ee"].join(`
|
|
5063
5063
|
`)).option("--apply <threadIDOrURL>","Apply the current DTW thread snapshot once and exit").option("--checkout","Automatically check out the thread commit when it differs").option("--skip-checkout","Skip the startup checkout prompt when commits differ").action(async(H,N,w)=>{if(H&&N.apply)throw new VA("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let u=N.apply??H;if(!u||u.trim().length===0)fQ.write(`live-sync watches a v2 thread and mirrors its live changes locally. Use --apply <thread-id> to materialize the current snapshot once and exit.
|
|
5064
5064
|
|
|
5065
5065
|
`),w.outputHelp(),process.exit(0);let L=D3(u)??B8(u),R=w.optsWithGlobals(),_=await nQ(R);_B(w,R);let P=await e$(_,R),f=!1;try{if(N.checkout&&N.skipCheckout)throw new VA("Choose either --checkout or --skip-checkout, not both.",1);if(gC(P.serverStatus))throw ai0(P.serverStatus,_.ampURL);await rP4({ampURL:_.ampURL,threadId:L,configService:P.configService,threadSnapshotReader:{get:P.threadRemote.getThread},apiKey:process.env.AMP_API_KEY,applyOnce:typeof N.apply==="string",checkoutMode:N.checkout?"always":N.skipCheckout?"never":"prompt",promptForYesNo:TE0}),f=!0}finally{if(await P.asyncDispose(),f)process.exit(0)}});let E=async(H,N,w)=>{y00({storage:N.settings,secretStorage:N.secrets,workspaceRoot:process.cwd(),defaultAmpURL:N.ampURL,homeDir:LD0,userConfigDir:ii0});let u={...N,executeMode:!1};await ni0(u,{...H,openThreadSwitcher:!0},w)},D=Q.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").option("--include-archived","Include archived threads in the list").option("--limit <number>","Maximum number of threads to return",(H)=>OD0(H,"--limit",{min:1,max:500})).option("--offset <number>","Number of threads to skip",(H)=>OD0(H,"--offset",{min:0})).action(async(H,N)=>{let w=N.optsWithGlobals(),u=await nQ(w);await Yf4(w,u,N)});D.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, unlisted, workspace, group)").action(async(H,N)=>{let w=N.optsWithGlobals(),u=await nQ(w);await zu6(w,u,N)}),D.command("continue [threadIDOrURLs...]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, interactive mode shows a picker. Use --last to continue the last thread for the current mode directly. When multiple thread are given, all are resumed and the first is shown in the foreground.").option("--last","Continue the last thread for the current mode directly").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(H,N,w)=>{let u=w.optsWithGlobals(),L=await nQ(u),R=Array.isArray(H)?H:[];if(N.pick)H7.write(`${P0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
|
|
@@ -5084,8 +5084,8 @@ ${_}
|
|
|
5084
5084
|
|
|
5085
5085
|
`)},async input(){return},async confirm(){return!1},async select(){return},async ask(){return{result:"uncertain",probability:0.5,reason:"AI not available"}}},loadGlobalPlugins:Hp0(u),pluginFilter:process.env.PLUGINS??"all"}),asyncDispose:async()=>{}}}),tT4(Q,async(H)=>{let N=H.optsWithGlobals(),w=await nQ(N);_B(H,N);let u=await e$(w,N),L=await u.secretStorage.get("apiKey",w.ampURL);if(!L)throw await u.asyncDispose(),new VA("API key required. Please run `amp login` first.",1);return{configService:u.configService,actorOptions:{apiKey:L,ampURL:w.ampURL,workspaceRoot:process.cwd(),dependencies:u},cleanupTerminal:Az,asyncDispose:u.asyncDispose.bind(u)}}),Qv4(Q,async(H)=>{let N=H.optsWithGlobals(),w=await nQ(N);_B(H,N);let u=await e$(w,N),L=await u.secretStorage.get("apiKey",w.ampURL);if(!L)throw await u.asyncDispose(),new VA("API key required. Please run `amp login` first.",1);return{configService:u.configService,actorOptions:{apiKey:L,ampURL:w.ampURL,workspaceRoot:process.cwd(),dependencies:u},cleanupTerminal:Az,asyncDispose:u.asyncDispose.bind(u)}}),Zv4(Q,async(H)=>{let N=H.optsWithGlobals(),w=await nQ(N);_B(H,N);let u=await e$(w,N);return{settings:w.settings,configService:u.configService,skillService:u.skillService,asyncDispose:u.asyncDispose.bind(u)}}),wT4(Q,async(H)=>{let N=H.optsWithGlobals();return await nQ(N)}),VT4(Q,async(H)=>{let N=await nQ(H);return{settings:N.settings,secretStorage:N.secrets,getThreadDeps:async(w)=>{_B(w,H);let u=await e$(N,H);return{mcpService:u.mcpService,settings:N.settings,asyncDispose:u.asyncDispose.bind(u)}}}}),eX4(Q,nQ),Kj4(Q,async(H)=>oH0(await Zl0(H))),xv4(Q,nQ),Fv4(Q,nQ);function Z(H,N,w){let L=typeof H.description==="string"?H.description:w===void 0?H.description(!0):H.description(w),R=new sD(N,L),_=hw6(H);if(_)R.default(_);if(R.hidden=yw6(H)||Df4(H),"choices"in H&&Array.isArray(H.choices))if("hiddenChoices"in H){let P=[...H.choices],f=Array.isArray(H.hiddenChoices)?H.hiddenChoices:[],h=new Set([...P,...f]);R.argParser((x)=>{if(!h.has(x))throw new d30(`Allowed choices are ${P.join(", ")}.`);return x})}else R.choices([...H.choices]);return R}for(let H of Ef4){switch(H.type){case"flag":{Q.addOption(Z(H,`--${H.long}`)),Q.addOption(Z(H,`--no-${H.long}`,!1));break}case"switch":{Q.addOption(Z(H,`--${H.long}`,!0));break}case"optional-option":{Q.addOption(Z(H,`${"short"in H?`-${H.short}, `:""}--${H.long} [value]`));break}default:{Q.addOption(Z(H,`${"short"in H?`-${H.short}, `:""}--${H.long} <value>`));break}}if("aliases"in H&&Array.isArray(H.aliases))for(let N of H.aliases){let w=new sD(`--${N}`,H.description);w.hidden=!0,w.implies({[H.name]:!0}),Q.addOption(w)}}Q.hook("preAction",(H,N)=>{let w=N.optsWithGlobals();if(w.takeMeBack)J6(gw6);if(w.archive&&!process.env.AMP_SDK_VERSION)J6("--archive is now the default and has been removed. Rerun without --archive. (If you want to not archive, use --no-archive-after-execute.)")});let F=new sD("-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);Q.addOption(F);let X=new sD("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp(!0);Q.addOption(X);let I=new sD("--stream-json","When used with --execute, output in Claude Code-compatible stream JSON format instead of plain text.").default(!1);Q.addOption(I);let G=new sD("--stream-json-thinking","Include thinking blocks in stream JSON output (non-Claude Code extension). Implies --stream-json.").default(!1);Q.addOption(G);let V=new sD("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);Q.addOption(V);let K=new sD("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);Q.addOption(K);let z=new sD("--no-archive-after-execute","When used with --execute on a new thread, leave the thread unarchived after the command finishes.");Q.addOption(z);let W=new sD("--archive").default(!1).hideHelp(!0);Q.addOption(W);let C=new sD("-l, --label <label>","When used with --execute, add a label to the thread. Repeat the flag for multiple labels.").argParser((H,N)=>{if(N===void 0)return[H];return[...N,H]});return Q.addOption(C),Q.action(async(H,N)=>{let w=H,u=await nQ(w);if(Object.keys(w).forEach((L)=>{let R=Ef4.find((_)=>_.name===L);if(R&&Df4(R)&&!bw6(R))H7.write(P0.yellow(`Warning: '--${L}' flag is deprecated
|
|
5086
5086
|
`))}),N.args.length>0)cw6(u,N);await ni0(u,w,N)}),KP4(Q),Q}async function If4(A,Q){await eD(($)=>gP($,A,Q))}async function nw6(A){if(A.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof A.execute==="string"){let Q=(await Fl0()).trimEnd();return{userInput:A.execute,stdinInput:Q||null}}return{userInput:(await Fl0()).trimEnd(),stdinInput:null}}function aw6(A,Q,$){if(A.remote&&!Q)throw new VA("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(A.streamJson&&!Q)throw new VA("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new VA("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new VA("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new VA("The --stats and --stream-json flags are mutually exclusive output formats",1,'Use one or the other: amp --execute "your message" --stats OR amp --execute "your message" --stream-json');if(A.stats&&!Q)throw new VA("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archiveAfterExecute===!1&&!Q)throw new VA("The --no-archive-after-execute flag requires --execute mode",1,'Use: amp --execute "your message" --no-archive-after-execute');if(A.streamJsonInput&&typeof A.execute==="string"&&A.execute.trim()!=="")throw new VA("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Q&&$===""&&!A.streamJsonInput&&!A.headless)throw new VA("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
|
|
5087
|
-
Or pipe via stdin: echo "your message" | amp --execute`)}function ow6(){PdA([f00.parse({tool:"*",action:"allow"})]),BdA({bypass:!0})}function rw6(A){if(A.threadId&&!k7(A.threadId))delete A.threadId}async function ni0(A,Q,$){if(Q.headless)return sw6(A,Q,$);let B=await e$(A,Q);if(Q.showWelcome&&Q.hideWelcome)throw await B.asyncDispose(),new VA("Cannot use --show-welcome and --hide-welcome together",1);let E=!A.executeMode&&await xw6();return ow6(),rw6(Q),tw6(A,Q,$,B,{showNpmMigrationWelcome:E})}async function sw6(A,Q,$){let B=(z,W)=>{let C=Number(process.hrtime.bigint()-W)/1e6,H=QI4();S.info("Startup phase",{phase:z,phaseMs:Math.round(C),sinceMainMs:H===null?void 0:Math.round(H)})};_B($,Q);let E=process.hrtime.bigint(),D=await e$(A,Q);B("runMainThread:createThreadDependencies",E);let{serverStatus:J}=D;if(gC(J))throw ai0(J,A.ampURL);let U=p9(J)?J:null,Y=U?.user.email,Z=Kw(J),F=qi(Q,Z);if(F instanceof Error)J6(F.message);if(U&&ei(Q.mode)&&!O00(Q.mode,Y))throw new VA(`Agent mode '${Q.mode}' is only available for Amp employees`,1);Jy0();let X=await D.secretStorage.get("apiKey",A.ampURL);if(!X)throw new VA("API key required for headless mode. Please run `amp login` first.",1);let I=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(I&&!k7(I))throw new VA(`Invalid thread ID: ${I}`,1);let G=I?void 0:await Vu6({dependencies:D,apiKey:X,visibility:F??void 0}),V=I??G?.threadId;if(!V)throw new VA("Failed to resolve headless thread ID",1);let K=await rR4(V);if(K.status==="already-running")await D.asyncDispose(),await oY(),process.exit(0);try{await bR4({ampURL:A.ampURL,apiKey:X,workspaceRoot:process.cwd(),threadId:V,ownerUserId:G?.ownerUserId,threadVersion:G?.threadVersion,agentMode:G?.agentMode,initialToolDiscovery:Promise.all([D.mcpService.initialized,D.toolboxService.initialized,D.pluginService.initialized]).then(()=>{return}),configService:D.configService,mcpService:D.mcpService,toolService:D.toolService,skillService:D.skillService,pluginService:D.pluginService,pluginPlatform:D.headlessPluginPlatform,setActiveThreadID:(z)=>D.activeThread$.next(z)})}finally{await K.release(),await D.asyncDispose()}await oY(),process.exit(0)}async function tw6(A,Q,$,B,E){let{userInput:D,stdinInput:J}=await nw6(Q),U=!!Q.streamJson||!!Q.streamJsonThinking;aw6({...Q,streamJson:U},A.executeMode,D),_B($,Q),YI4(),Jy0();let Y=Q.threadId,Z=Q.resumeThreadIDs??(Y?[Y]:[]),F=Q.observe?D3(Q.observe)??B8(Q.observe):void 0,X=await B.serverStatusPromise;if(gC(X))throw ai0(X,A.ampURL);let I=Kw(X),G=()=>vw6(B.configService,ekA.V2_LOCAL_THREAD_CHANGES),V=qi(Q,I);if(V instanceof Error)J6(V.message);if(A.executeMode&&Q.remote){if(!ei(Q.mode))throw new VA("Remote execute mode does not support plugin-defined agent modes",1);if(!p9(X)||!MC(X.user.email))throw new VA("Remote execute mode is only available for Amp employees",1);await hT4(D,J,B.configService,Q.mode),await B.asyncDispose(),await oY(),process.exit(0)}let K=null,z=async()=>{let H=B.consumeDraftNewThreadVisibility();if(H!==null)return H;return K??=(async()=>{let N=await o90(A.settings,process.cwd(),I,V);if(N instanceof Error)J6(N.message);return N})(),K},W=await B.secretStorage.get("apiKey",A.ampURL);if(!W)throw new VA("API key required. Please run `amp login` first.",1);let C=p9(X)&&MC(X.user.email);if(A.executeMode){if(Z.length>1)throw new VA("Execute mode can only resume one thread.",1);CT4(B.mcpService,A.settings);try{await B.pluginService.initialized;let H=Ff4(B.pluginService,Q.mode),N=Jf4($,Q),w=await rN(),u=Y?N:Hy0({agentMode:H.agentMode,explicitEffort:N,sessionState:w}),L=Y?void 0:U50(await hP(B.configService),{agentMode:H.agentMode,explicitEffort:N,sessionState:w}),R=Y?void 0:await z(),{threadID:_}=await dT({apiKey:W,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:B,userInput:D,stdinInput:J,stats:!!Q.stats,streamJson:U,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:H.agentMode,reasoningEffort:H.agent?void 0:u,agent:H.agent,labels:Q.label,initialThreadID:Y,initialThreadMeta:R,initialSettings:L});if(await If4(_,"execute"),Q.archive||!Y&&Q.archiveAfterExecute!==!1)await B.threadRemote.archiveThread(_,!0)}finally{await B.asyncDispose()}await oY(),process.exit(0)}else{let H=Jf4($,Q),N=await dw6($,B.pluginService,Q.mode),w=E.showNpmMigrationWelcome?"npm-migration":"intro",u=xp0("0.0.
|
|
5088
|
-
`);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,$=process.stdout.isTTY&&process.stderr.isTTY;S.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let B=await XoA({get:async(U)=>{if(U!==Hh)return;try{let Y=await Nw6(li0,"utf-8");return JSON.parse(Y).installationID}catch{return}},set:async(U,Y)=>{if(U!==Hh)return;await Hw6(ti.dirname(li0),{recursive:!0}),await qw6(li0,JSON.stringify({installationID:Y},null,2),{mode:384})}},{clientType:"cli",platform:t40()});BhA(B);let E=await Zl0({...A,workspaceTrust:{current:!0,changes:Fy},getHook:process.env.AMP_URL?(U,Y)=>{if(U==="url")return Promise.resolve(process.env.AMP_URL);return Y()}:void 0});if(A.mcpConfig){let U=await zT4(A.mcpConfig);E=WT4(E,U)}let D=ti.dirname(E.getSettingsFilePath());_J4(ty,D),E=oH0(E);let J=await E.get("url","admin")??await E.get("url","global");if(!J)J=S8;if(S.info("Resolved Amp URL",{ampURL:J,settingsFile:E.getSettingsFilePath(),workspaceRoot:E.getWorkspaceRootPath()}),!iO(J))S.info("Targeting custom Amp server",{ampURL:J});return{executeMode:Q,isTTY:$,ampURL:J,settings:E,secrets:$v4(await Yl0(A,E))}}function ew6(A){let Q={};for(let $=0;$<A.length;$++){let B=A[$];if(B?.startsWith("--")){let D=B.slice(2).replace(/-([a-z])/g,(U,Y)=>Y.toUpperCase()),J=A[$+1];if(J&&!J.startsWith("--"))Q[D]=J,$++}}return Q}function Au6(A,Q){let $=A.includes("--headless")||A.some((E)=>E.startsWith("--headless=")),B=ti.resolve(Q.logFile??process.env.AMP_LOG_FILE??($?uw6:lc));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:B}}async function Qu6(){AI4();let A=ew6(process.argv),Q=Au6(process.argv,A),$=ZI4(Q);oB0("silent");let B=process.argv.includes("--no-color"),E=process.argv.includes("--color"),D=process.stdout.isTTY&&process.stderr.isTTY;if(B||!E&&!D)P0.level=0;if(Ow6(S),S.info("Starting Amp CLI.",{version:"0.0.
|
|
5087
|
+
Or pipe via stdin: echo "your message" | amp --execute`)}function ow6(){PdA([f00.parse({tool:"*",action:"allow"})]),BdA({bypass:!0})}function rw6(A){if(A.threadId&&!k7(A.threadId))delete A.threadId}async function ni0(A,Q,$){if(Q.headless)return sw6(A,Q,$);let B=await e$(A,Q);if(Q.showWelcome&&Q.hideWelcome)throw await B.asyncDispose(),new VA("Cannot use --show-welcome and --hide-welcome together",1);let E=!A.executeMode&&await xw6();return ow6(),rw6(Q),tw6(A,Q,$,B,{showNpmMigrationWelcome:E})}async function sw6(A,Q,$){let B=(z,W)=>{let C=Number(process.hrtime.bigint()-W)/1e6,H=QI4();S.info("Startup phase",{phase:z,phaseMs:Math.round(C),sinceMainMs:H===null?void 0:Math.round(H)})};_B($,Q);let E=process.hrtime.bigint(),D=await e$(A,Q);B("runMainThread:createThreadDependencies",E);let{serverStatus:J}=D;if(gC(J))throw ai0(J,A.ampURL);let U=p9(J)?J:null,Y=U?.user.email,Z=Kw(J),F=qi(Q,Z);if(F instanceof Error)J6(F.message);if(U&&ei(Q.mode)&&!O00(Q.mode,Y))throw new VA(`Agent mode '${Q.mode}' is only available for Amp employees`,1);Jy0();let X=await D.secretStorage.get("apiKey",A.ampURL);if(!X)throw new VA("API key required for headless mode. Please run `amp login` first.",1);let I=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(I&&!k7(I))throw new VA(`Invalid thread ID: ${I}`,1);let G=I?void 0:await Vu6({dependencies:D,apiKey:X,visibility:F??void 0}),V=I??G?.threadId;if(!V)throw new VA("Failed to resolve headless thread ID",1);let K=await rR4(V);if(K.status==="already-running")await D.asyncDispose(),await oY(),process.exit(0);try{await bR4({ampURL:A.ampURL,apiKey:X,workspaceRoot:process.cwd(),threadId:V,ownerUserId:G?.ownerUserId,threadVersion:G?.threadVersion,agentMode:G?.agentMode,initialToolDiscovery:Promise.all([D.mcpService.initialized,D.toolboxService.initialized,D.pluginService.initialized]).then(()=>{return}),configService:D.configService,mcpService:D.mcpService,toolService:D.toolService,skillService:D.skillService,pluginService:D.pluginService,pluginPlatform:D.headlessPluginPlatform,setActiveThreadID:(z)=>D.activeThread$.next(z)})}finally{await K.release(),await D.asyncDispose()}await oY(),process.exit(0)}async function tw6(A,Q,$,B,E){let{userInput:D,stdinInput:J}=await nw6(Q),U=!!Q.streamJson||!!Q.streamJsonThinking;aw6({...Q,streamJson:U},A.executeMode,D),_B($,Q),YI4(),Jy0();let Y=Q.threadId,Z=Q.resumeThreadIDs??(Y?[Y]:[]),F=Q.observe?D3(Q.observe)??B8(Q.observe):void 0,X=await B.serverStatusPromise;if(gC(X))throw ai0(X,A.ampURL);let I=Kw(X),G=()=>vw6(B.configService,ekA.V2_LOCAL_THREAD_CHANGES),V=qi(Q,I);if(V instanceof Error)J6(V.message);if(A.executeMode&&Q.remote){if(!ei(Q.mode))throw new VA("Remote execute mode does not support plugin-defined agent modes",1);if(!p9(X)||!MC(X.user.email))throw new VA("Remote execute mode is only available for Amp employees",1);await hT4(D,J,B.configService,Q.mode),await B.asyncDispose(),await oY(),process.exit(0)}let K=null,z=async()=>{let H=B.consumeDraftNewThreadVisibility();if(H!==null)return H;return K??=(async()=>{let N=await o90(A.settings,process.cwd(),I,V);if(N instanceof Error)J6(N.message);return N})(),K},W=await B.secretStorage.get("apiKey",A.ampURL);if(!W)throw new VA("API key required. Please run `amp login` first.",1);let C=p9(X)&&MC(X.user.email);if(A.executeMode){if(Z.length>1)throw new VA("Execute mode can only resume one thread.",1);CT4(B.mcpService,A.settings);try{await B.pluginService.initialized;let H=Ff4(B.pluginService,Q.mode),N=Jf4($,Q),w=await rN(),u=Y?N:Hy0({agentMode:H.agentMode,explicitEffort:N,sessionState:w}),L=Y?void 0:U50(await hP(B.configService),{agentMode:H.agentMode,explicitEffort:N,sessionState:w}),R=Y?void 0:await z(),{threadID:_}=await dT({apiKey:W,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:B,userInput:D,stdinInput:J,stats:!!Q.stats,streamJson:U,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:H.agentMode,reasoningEffort:H.agent?void 0:u,agent:H.agent,labels:Q.label,initialThreadID:Y,initialThreadMeta:R,initialSettings:L});if(await If4(_,"execute"),Q.archive||!Y&&Q.archiveAfterExecute!==!1)await B.threadRemote.archiveThread(_,!0)}finally{await B.asyncDispose()}await oY(),process.exit(0)}else{let H=Jf4($,Q),N=await dw6($,B.pluginService,Q.mode),w=E.showNpmMigrationWelcome?"npm-migration":"intro",u=xp0("0.0.1780774659-gd08a06",B.settingsStorage,{startDelayMs:3000}),L=new tp0(B.mcpService,A.settings.getWorkspaceRootPath()),R=Yg(B.configService),_=new Cl0(B.fuzzyServer),P=process.cwd();await LP4({ampURL:A.ampURL,apiKey:W,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??Z7(A.ampURL),configService:B.configService,toolService:B.toolService,pluginPlatform:B.pluginPlatform,pluginService:B.pluginService,skillService:B.skillService,mcpService:B.mcpService,readFileSystemDirectory:({uri:f})=>bT({workspaceRoot:P},f),canUseV2LocalThreadChanges:G,completionBuilder:_,updateService:u,workspaceRoot:P,listThreads:()=>R.listThreads(),getThreadFromServer:(f)=>R.getThread(f),getThreadTail:async(f,h)=>{let x=await j4.getThreadTail({thread:f,limit:h},{config:B.configService});if(!x.ok){if(x.error.code==="thread-not-found")return null;throw Error(x.error.message??x.error.code)}return{...x.result.thread.data,messages:x.result.messages}},toolboxes:B.toolboxService.toolboxes,isInternalUser:C,settingsFilePath:B.settingsStorage.getSettingsFilePath(),workspaceSettingsFilePath:B.settingsStorage.getWorkspaceSettingsPath(),mcpTrustHandler:L,setActiveThreadID:(f)=>B.activeThread$.next(f),dispose:()=>{return L.dispose(),u.dispose(),B.asyncDispose()}},{initialThreadIDs:F?[F]:Z,initialUserInput:D||void 0,getDefaultNewThreadVisibility:z,onFirstFrame:Q.ide?Zf4:void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!F,hideWelcome:!!Q.hideWelcome,showWelcome:Q.showWelcome,welcomeVariant:w,initialAgentMode:N?.agentMode,initialPluginAgentModeKey:N?.pluginAgentModeKey,initialReasoningEffort:H}),process.exit(0)}}async function nQ(A){if(S.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)H7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
5088
|
+
`);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,$=process.stdout.isTTY&&process.stderr.isTTY;S.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let B=await XoA({get:async(U)=>{if(U!==Hh)return;try{let Y=await Nw6(li0,"utf-8");return JSON.parse(Y).installationID}catch{return}},set:async(U,Y)=>{if(U!==Hh)return;await Hw6(ti.dirname(li0),{recursive:!0}),await qw6(li0,JSON.stringify({installationID:Y},null,2),{mode:384})}},{clientType:"cli",platform:t40()});BhA(B);let E=await Zl0({...A,workspaceTrust:{current:!0,changes:Fy},getHook:process.env.AMP_URL?(U,Y)=>{if(U==="url")return Promise.resolve(process.env.AMP_URL);return Y()}:void 0});if(A.mcpConfig){let U=await zT4(A.mcpConfig);E=WT4(E,U)}let D=ti.dirname(E.getSettingsFilePath());_J4(ty,D),E=oH0(E);let J=await E.get("url","admin")??await E.get("url","global");if(!J)J=S8;if(S.info("Resolved Amp URL",{ampURL:J,settingsFile:E.getSettingsFilePath(),workspaceRoot:E.getWorkspaceRootPath()}),!iO(J))S.info("Targeting custom Amp server",{ampURL:J});return{executeMode:Q,isTTY:$,ampURL:J,settings:E,secrets:$v4(await Yl0(A,E))}}function ew6(A){let Q={};for(let $=0;$<A.length;$++){let B=A[$];if(B?.startsWith("--")){let D=B.slice(2).replace(/-([a-z])/g,(U,Y)=>Y.toUpperCase()),J=A[$+1];if(J&&!J.startsWith("--"))Q[D]=J,$++}}return Q}function Au6(A,Q){let $=A.includes("--headless")||A.some((E)=>E.startsWith("--headless=")),B=ti.resolve(Q.logFile??process.env.AMP_LOG_FILE??($?uw6:lc));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:B}}async function Qu6(){AI4();let A=ew6(process.argv),Q=Au6(process.argv,A),$=ZI4(Q);oB0("silent");let B=process.argv.includes("--no-color"),E=process.argv.includes("--color"),D=process.stdout.isTTY&&process.stderr.isTTY;if(B||!E&&!D)P0.level=0;if(Ow6(S),S.info("Starting Amp CLI.",{version:"0.0.1780774659-gd08a06",buildTimestamp:"2026-06-06T19:41:38.475Z"}),process.platform==="win32"&&tN())FP4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new VA(q3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await iw6($).parseAsync(process.argv)}TJ4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await Qu6().catch(r90)});async function $u6(A,Q){let $=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!$)await A.settings.set("url",process.env.AMP_URL,"global"),fQ.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
5089
5089
|
`);else if(!iO(A.ampURL))fQ.write(`Logging in to ${new URL(A.ampURL).hostname}
|
|
5090
5090
|
`);let B=process.env.AMP_API_KEY;if(B)fQ.write(`API key found in environment variable, storing...
|
|
5091
5091
|
`),await Q.set("apiKey",B,A.ampURL),fQ.write(`API key successfully stored.
|