@sourcegraph/amp 0.0.1778476494-g8a21dc → 0.0.1778480457-g5efd50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +71 -71
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -4620,7 +4620,7 @@ function YA(A){return mJ5(A,eZ0(A))}function ZA(A,Q){if(Q.length<BS4){let B=cJ5(
4620
4620
  //! Licensed under the MIT License (https://mit-license.org/)
4621
4621
  function i6({initialBufferLength:A=1024,maxBufferLength:Q=33554432}){if(dQ)F7(lY(A),LU),F7(lY(Q),LU),F7(A<=Q,"initialBufferLength must be lower than or equal to maxBufferLength");return{initialBufferLength:A,maxBufferLength:Q}}RQ();RQ();RQ();var vS4=v4(Sa(),1),mS4=v4(Sa(),1);var zS4="/connect",nJ5="/websocket",WS4="/websocket/";var HS4="x-rivet-encoding",Rr0="x-rivet-conn-params";var aJ5="x-rivet-token",oJ5="x-rivet-target",rJ5="x-rivet-actor";var sJ5="x-rivet-skip-ready-wait",tJ5="rivet",eJ5="rivet_target.",AY5="rivet_actor.",QY5="rivet_encoding.",BY5="rivet_conn_params.",$Y5="rivet_token.",JY5="rivet_skip_ready_wait",YY5="rivet_test_ack_hook.";var qS4=class extends Error{};var ga=class extends qS4{constructor(A,Q){super(`HTTP request error: ${A}`,{cause:Q==null?void 0:Q.cause})}},QF0=class extends qS4{constructor(){super("Attempting to interact with a disposed actor connection.")}};function Cr0(A,Q){return A==="guard"&&(Q==="actor_ready_timeout"||Q==="actor_runner_failed")}function ZY5(A,Q,B,$){return new R5(A,Q,`Actor failed to start (${B}): ${JSON.stringify($)}`,{metadata:{actorId:B,details:$}})}function FY5(A,Q){return new R5("rivetkit",za,A,{cause:Q==null?void 0:Q.cause})}var fF=i6({});function Qx(A){return aN(A)}function Bx(A,Q){oN(A,Q)}function XY5(A){return{actorId:YA(A),connectionId:YA(A),connectionToken:YA(A)}}function DY5(A,Q){ZA(A,Q.actorId),ZA(A,Q.connectionId),ZA(A,Q.connectionToken)}function NS4(A){return Q8(A)?Qx(A):null}function IS4(A,Q){if(B8(A,Q!=null),Q!=null)Bx(A,Q)}function GY5(A){return Q8(A)?AQ(A):null}function VY5(A,Q){if(B8(A,Q!=null),Q!=null)QQ(A,Q)}function UY5(A){return{group:YA(A),code:YA(A),message:YA(A),metadata:NS4(A),actionId:GY5(A)}}function KY5(A,Q){ZA(A,Q.group),ZA(A,Q.code),ZA(A,Q.message),IS4(A,Q.metadata),VY5(A,Q.actionId)}function EY5(A){return{id:AQ(A),output:Qx(A)}}function zY5(A,Q){QQ(A,Q.id),Bx(A,Q.output)}function WY5(A){return{name:YA(A),args:Qx(A)}}function HY5(A,Q){ZA(A,Q.name),Bx(A,Q.args)}function qY5(A){let Q=A.offset;switch(P9(A)){case 0:return{tag:"Init",val:XY5(A)};case 1:return{tag:"Error",val:UY5(A)};case 2:return{tag:"ActionResponse",val:EY5(A)};case 3:return{tag:"Event",val:WY5(A)};default:throw A.offset=Q,new wA(Q,"invalid tag")}}function NY5(A,Q){switch(Q.tag){case"Init":{W5(A,0),DY5(A,Q.val);break}case"Error":{W5(A,1),KY5(A,Q.val);break}case"ActionResponse":{W5(A,2),zY5(A,Q.val);break}case"Event":{W5(A,3),HY5(A,Q.val);break}}}function IY5(A){return{body:qY5(A)}}function wY5(A,Q){NY5(A,Q.body)}function CY5(A,Q){let B=Q!=null?i6(Q):fF,$=new s4(new Uint8Array(B.initialBufferLength),B);return wY5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function MY5(A){let Q=new s4(A,fF),B=IY5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function LY5(A){return{id:AQ(A),name:YA(A),args:Qx(A)}}function OY5(A,Q){QQ(A,Q.id),ZA(A,Q.name),Bx(A,Q.args)}function jY5(A){return{eventName:YA(A),subscribe:Q8(A)}}function RY5(A,Q){ZA(A,Q.eventName),B8(A,Q.subscribe)}function PY5(A){let Q=A.offset;switch(P9(A)){case 0:return{tag:"ActionRequest",val:LY5(A)};case 1:return{tag:"SubscriptionRequest",val:jY5(A)};default:throw A.offset=Q,new wA(Q,"invalid tag")}}function _Y5(A,Q){switch(Q.tag){case"ActionRequest":{W5(A,0),OY5(A,Q.val);break}case"SubscriptionRequest":{W5(A,1),RY5(A,Q.val);break}}}function TY5(A){return{body:PY5(A)}}function kY5(A,Q){_Y5(A,Q.body)}function SY5(A,Q){let B=Q!=null?i6(Q):fF,$=new s4(new Uint8Array(B.initialBufferLength),B);return kY5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function vY5(A){let Q=new s4(A,fF),B=TY5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function yY5(A){return{args:Qx(A)}}function xY5(A,Q){Bx(A,Q.args)}function fY5(A,Q){let B=Q!=null?i6(Q):fF,$=new s4(new Uint8Array(B.initialBufferLength),B);return xY5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function bY5(A){let Q=new s4(A,fF),B=yY5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function uY5(A){return{output:Qx(A)}}function hY5(A,Q){Bx(A,Q.output)}function gY5(A,Q){let B=Q!=null?i6(Q):fF,$=new s4(new Uint8Array(B.initialBufferLength),B);return hY5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function mY5(A){let Q=new s4(A,fF),B=uY5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function pY5(A){return{group:YA(A),code:YA(A),message:YA(A),metadata:NS4(A)}}function dY5(A,Q){ZA(A,Q.group),ZA(A,Q.code),ZA(A,Q.message),IS4(A,Q.metadata)}function cY5(A,Q){let B=Q!=null?i6(Q):fF,$=new s4(new Uint8Array(B.initialBufferLength),B);return dY5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function lY5(A){let Q=new s4(A,fF),B=pY5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function iY5(A){return{actorId:YA(A)}}function nY5(A,Q){ZA(A,Q.actorId)}function aY5(A,Q){let B=Q!=null?i6(Q):fF,$=new s4(new Uint8Array(B.initialBufferLength),B);return nY5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function oY5(A){let Q=new s4(A,fF),B=iY5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}var bF=i6({});function $x(A){return aN(A)}function Jx(A,Q){oN(A,Q)}function rY5(A){return{actorId:YA(A),connectionId:YA(A)}}function sY5(A,Q){ZA(A,Q.actorId),ZA(A,Q.connectionId)}function wS4(A){return Q8(A)?$x(A):null}function CS4(A,Q){if(B8(A,Q!=null),Q!=null)Jx(A,Q)}function tY5(A){return Q8(A)?AQ(A):null}function eY5(A,Q){if(B8(A,Q!=null),Q!=null)QQ(A,Q)}function AZ5(A){return{group:YA(A),code:YA(A),message:YA(A),metadata:wS4(A),actionId:tY5(A)}}function QZ5(A,Q){ZA(A,Q.group),ZA(A,Q.code),ZA(A,Q.message),CS4(A,Q.metadata),eY5(A,Q.actionId)}function BZ5(A){return{id:AQ(A),output:$x(A)}}function $Z5(A,Q){QQ(A,Q.id),Jx(A,Q.output)}function JZ5(A){return{name:YA(A),args:$x(A)}}function YZ5(A,Q){ZA(A,Q.name),Jx(A,Q.args)}function ZZ5(A){let Q=A.offset;switch(P9(A)){case 0:return{tag:"Init",val:rY5(A)};case 1:return{tag:"Error",val:AZ5(A)};case 2:return{tag:"ActionResponse",val:BZ5(A)};case 3:return{tag:"Event",val:JZ5(A)};default:throw A.offset=Q,new wA(Q,"invalid tag")}}function FZ5(A,Q){switch(Q.tag){case"Init":{W5(A,0),sY5(A,Q.val);break}case"Error":{W5(A,1),QZ5(A,Q.val);break}case"ActionResponse":{W5(A,2),$Z5(A,Q.val);break}case"Event":{W5(A,3),YZ5(A,Q.val);break}}}function XZ5(A){return{body:ZZ5(A)}}function DZ5(A,Q){FZ5(A,Q.body)}function GZ5(A,Q){let B=Q!=null?i6(Q):bF,$=new s4(new Uint8Array(B.initialBufferLength),B);return DZ5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function VZ5(A){let Q=new s4(A,bF),B=XZ5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function UZ5(A){return{id:AQ(A),name:YA(A),args:$x(A)}}function KZ5(A,Q){QQ(A,Q.id),ZA(A,Q.name),Jx(A,Q.args)}function EZ5(A){return{eventName:YA(A),subscribe:Q8(A)}}function zZ5(A,Q){ZA(A,Q.eventName),B8(A,Q.subscribe)}function WZ5(A){let Q=A.offset;switch(P9(A)){case 0:return{tag:"ActionRequest",val:UZ5(A)};case 1:return{tag:"SubscriptionRequest",val:EZ5(A)};default:throw A.offset=Q,new wA(Q,"invalid tag")}}function HZ5(A,Q){switch(Q.tag){case"ActionRequest":{W5(A,0),KZ5(A,Q.val);break}case"SubscriptionRequest":{W5(A,1),zZ5(A,Q.val);break}}}function qZ5(A){return{body:WZ5(A)}}function NZ5(A,Q){HZ5(A,Q.body)}function IZ5(A,Q){let B=Q!=null?i6(Q):bF,$=new s4(new Uint8Array(B.initialBufferLength),B);return NZ5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function wZ5(A){let Q=new s4(A,bF),B=qZ5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function CZ5(A){return{args:$x(A)}}function MZ5(A,Q){Jx(A,Q.args)}function LZ5(A,Q){let B=Q!=null?i6(Q):bF,$=new s4(new Uint8Array(B.initialBufferLength),B);return MZ5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function OZ5(A){let Q=new s4(A,bF),B=CZ5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function jZ5(A){return{output:$x(A)}}function RZ5(A,Q){Jx(A,Q.output)}function PZ5(A,Q){let B=Q!=null?i6(Q):bF,$=new s4(new Uint8Array(B.initialBufferLength),B);return RZ5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function _Z5(A){let Q=new s4(A,bF),B=jZ5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function TZ5(A){return{group:YA(A),code:YA(A),message:YA(A),metadata:wS4(A)}}function kZ5(A,Q){ZA(A,Q.group),ZA(A,Q.code),ZA(A,Q.message),CS4(A,Q.metadata)}function SZ5(A,Q){let B=Q!=null?i6(Q):bF,$=new s4(new Uint8Array(B.initialBufferLength),B);return kZ5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function vZ5(A){let Q=new s4(A,bF),B=TZ5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function yZ5(A){return{actorId:YA(A)}}function xZ5(A,Q){ZA(A,Q.actorId)}function fZ5(A,Q){let B=Q!=null?i6(Q):bF,$=new s4(new Uint8Array(B.initialBufferLength),B);return xZ5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function bZ5(A){let Q=new s4(A,bF),B=yZ5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}var cQ=i6({});function Uj(A){return aN(A)}function Kj(A,Q){oN(A,Q)}function uZ5(A){return{actorId:YA(A),connectionId:YA(A)}}function hZ5(A,Q){ZA(A,Q.actorId),ZA(A,Q.connectionId)}function Pr0(A){return Q8(A)?Uj(A):null}function _r0(A,Q){if(B8(A,Q!=null),Q!=null)Kj(A,Q)}function gZ5(A){return Q8(A)?AQ(A):null}function mZ5(A,Q){if(B8(A,Q!=null),Q!=null)QQ(A,Q)}function pZ5(A){return{group:YA(A),code:YA(A),message:YA(A),metadata:Pr0(A),actionId:gZ5(A)}}function dZ5(A,Q){ZA(A,Q.group),ZA(A,Q.code),ZA(A,Q.message),_r0(A,Q.metadata),mZ5(A,Q.actionId)}function cZ5(A){return{id:AQ(A),output:Uj(A)}}function lZ5(A,Q){QQ(A,Q.id),Kj(A,Q.output)}function iZ5(A){return{name:YA(A),args:Uj(A)}}function nZ5(A,Q){ZA(A,Q.name),Kj(A,Q.args)}function aZ5(A){let Q=A.offset;switch(P9(A)){case 0:return{tag:"Init",val:uZ5(A)};case 1:return{tag:"Error",val:pZ5(A)};case 2:return{tag:"ActionResponse",val:cZ5(A)};case 3:return{tag:"Event",val:iZ5(A)};default:throw A.offset=Q,new wA(Q,"invalid tag")}}function oZ5(A,Q){switch(Q.tag){case"Init":{W5(A,0),hZ5(A,Q.val);break}case"Error":{W5(A,1),dZ5(A,Q.val);break}case"ActionResponse":{W5(A,2),lZ5(A,Q.val);break}case"Event":{W5(A,3),nZ5(A,Q.val);break}}}function rZ5(A){return{body:aZ5(A)}}function sZ5(A,Q){oZ5(A,Q.body)}function tZ5(A,Q){let B=Q!=null?i6(Q):cQ,$=new s4(new Uint8Array(B.initialBufferLength),B);return sZ5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function eZ5(A){let Q=new s4(A,cQ),B=rZ5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function AF5(A){return{id:AQ(A),name:YA(A),args:Uj(A)}}function QF5(A,Q){QQ(A,Q.id),ZA(A,Q.name),Kj(A,Q.args)}function BF5(A){return{eventName:YA(A),subscribe:Q8(A)}}function $F5(A,Q){ZA(A,Q.eventName),B8(A,Q.subscribe)}function JF5(A){let Q=A.offset;switch(P9(A)){case 0:return{tag:"ActionRequest",val:AF5(A)};case 1:return{tag:"SubscriptionRequest",val:BF5(A)};default:throw A.offset=Q,new wA(Q,"invalid tag")}}function YF5(A,Q){switch(Q.tag){case"ActionRequest":{W5(A,0),QF5(A,Q.val);break}case"SubscriptionRequest":{W5(A,1),$F5(A,Q.val);break}}}function ZF5(A){return{body:JF5(A)}}function FF5(A,Q){YF5(A,Q.body)}function XF5(A,Q){let B=Q!=null?i6(Q):cQ,$=new s4(new Uint8Array(B.initialBufferLength),B);return FF5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function DF5(A){let Q=new s4(A,cQ),B=ZF5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function GF5(A){return{args:Uj(A)}}function VF5(A,Q){Kj(A,Q.args)}function UF5(A,Q){let B=Q!=null?i6(Q):cQ,$=new s4(new Uint8Array(B.initialBufferLength),B);return VF5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function KF5(A){let Q=new s4(A,cQ),B=GF5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function EF5(A){return{output:Uj(A)}}function zF5(A,Q){Kj(A,Q.output)}function WF5(A,Q){let B=Q!=null?i6(Q):cQ,$=new s4(new Uint8Array(B.initialBufferLength),B);return zF5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function HF5(A){let Q=new s4(A,cQ),B=EF5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function qF5(A){return Q8(A)?YA(A):null}function NF5(A,Q){if(B8(A,Q!=null),Q!=null)ZA(A,Q)}function IF5(A){return Q8(A)?Q8(A):null}function wF5(A,Q){if(B8(A,Q!=null),Q!=null)B8(A,Q)}function CF5(A){return Q8(A)?sZ0(A):null}function MF5(A,Q){if(B8(A,Q!=null),Q!=null)tZ0(A,Q)}function LF5(A){return{body:Uj(A),name:qF5(A),wait:IF5(A),timeout:CF5(A)}}function OF5(A,Q){Kj(A,Q.body),NF5(A,Q.name),wF5(A,Q.wait),MF5(A,Q.timeout)}function jF5(A,Q){let B=Q!=null?i6(Q):cQ,$=new s4(new Uint8Array(B.initialBufferLength),B);return OF5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function RF5(A){let Q=new s4(A,cQ),B=LF5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function PF5(A){return{status:YA(A),response:Pr0(A)}}function _F5(A,Q){ZA(A,Q.status),_r0(A,Q.response)}function TF5(A,Q){let B=Q!=null?i6(Q):cQ,$=new s4(new Uint8Array(B.initialBufferLength),B);return _F5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function kF5(A){let Q=new s4(A,cQ),B=PF5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function SF5(A){return{group:YA(A),code:YA(A),message:YA(A),metadata:Pr0(A)}}function vF5(A,Q){ZA(A,Q.group),ZA(A,Q.code),ZA(A,Q.message),_r0(A,Q.metadata)}function yF5(A,Q){let B=Q!=null?i6(Q):cQ,$=new s4(new Uint8Array(B.initialBufferLength),B);return vF5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function xF5(A){let Q=new s4(A,cQ),B=SF5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function fF5(A){return{actorId:YA(A)}}function bF5(A,Q){ZA(A,Q.actorId)}function uF5(A,Q){let B=Q!=null?i6(Q):cQ,$=new s4(new Uint8Array(B.initialBufferLength),B);return bF5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function hF5(A){let Q=new s4(A,cQ),B=fF5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}var lQ=i6({});function Ej(A){return aN(A)}function zj(A,Q){oN(A,Q)}function MS4(A){return Q8(A)?YA(A):null}function LS4(A,Q){if(B8(A,Q!=null),Q!=null)ZA(A,Q)}function gF5(A){return{actorId:YA(A),generation:AQ(A),key:MS4(A)}}function mF5(A,Q){ZA(A,Q.actorId),QQ(A,Q.generation),LS4(A,Q.key)}function pF5(A){return{actorId:YA(A),connectionId:YA(A)}}function dF5(A,Q){ZA(A,Q.actorId),ZA(A,Q.connectionId)}function Tr0(A){return Q8(A)?Ej(A):null}function kr0(A,Q){if(B8(A,Q!=null),Q!=null)zj(A,Q)}function cF5(A){return Q8(A)?AQ(A):null}function lF5(A,Q){if(B8(A,Q!=null),Q!=null)QQ(A,Q)}function OS4(A){return Q8(A)?gF5(A):null}function jS4(A,Q){if(B8(A,Q!=null),Q!=null)mF5(A,Q)}function iF5(A){return{group:YA(A),code:YA(A),message:YA(A),metadata:Tr0(A),actionId:cF5(A),actor:OS4(A)}}function nF5(A,Q){ZA(A,Q.group),ZA(A,Q.code),ZA(A,Q.message),kr0(A,Q.metadata),lF5(A,Q.actionId),jS4(A,Q.actor)}function aF5(A){return{id:AQ(A),output:Ej(A)}}function oF5(A,Q){QQ(A,Q.id),zj(A,Q.output)}function rF5(A){return{name:YA(A),args:Ej(A)}}function sF5(A,Q){ZA(A,Q.name),zj(A,Q.args)}function tF5(A){let Q=A.offset;switch(P9(A)){case 0:return{tag:"Init",val:pF5(A)};case 1:return{tag:"Error",val:iF5(A)};case 2:return{tag:"ActionResponse",val:aF5(A)};case 3:return{tag:"Event",val:rF5(A)};default:throw A.offset=Q,new wA(Q,"invalid tag")}}function eF5(A,Q){switch(Q.tag){case"Init":{W5(A,0),dF5(A,Q.val);break}case"Error":{W5(A,1),nF5(A,Q.val);break}case"ActionResponse":{W5(A,2),oF5(A,Q.val);break}case"Event":{W5(A,3),sF5(A,Q.val);break}}}function AX5(A){return{body:tF5(A)}}function QX5(A,Q){eF5(A,Q.body)}function BX5(A,Q){let B=Q!=null?i6(Q):lQ,$=new s4(new Uint8Array(B.initialBufferLength),B);return QX5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function $X5(A){let Q=new s4(A,lQ),B=AX5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function JX5(A){return{id:AQ(A),name:YA(A),args:Ej(A)}}function YX5(A,Q){QQ(A,Q.id),ZA(A,Q.name),zj(A,Q.args)}function ZX5(A){return{eventName:YA(A),subscribe:Q8(A)}}function FX5(A,Q){ZA(A,Q.eventName),B8(A,Q.subscribe)}function XX5(A){let Q=A.offset;switch(P9(A)){case 0:return{tag:"ActionRequest",val:JX5(A)};case 1:return{tag:"SubscriptionRequest",val:ZX5(A)};default:throw A.offset=Q,new wA(Q,"invalid tag")}}function DX5(A,Q){switch(Q.tag){case"ActionRequest":{W5(A,0),YX5(A,Q.val);break}case"SubscriptionRequest":{W5(A,1),FX5(A,Q.val);break}}}function GX5(A){return{body:XX5(A)}}function VX5(A,Q){DX5(A,Q.body)}function UX5(A,Q){let B=Q!=null?i6(Q):lQ,$=new s4(new Uint8Array(B.initialBufferLength),B);return VX5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function KX5(A){let Q=new s4(A,lQ),B=GX5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function EX5(A){return{args:Ej(A)}}function zX5(A,Q){zj(A,Q.args)}function WX5(A,Q){let B=Q!=null?i6(Q):lQ,$=new s4(new Uint8Array(B.initialBufferLength),B);return zX5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function HX5(A){let Q=new s4(A,lQ),B=EX5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function qX5(A){return{output:Ej(A)}}function NX5(A,Q){zj(A,Q.output)}function IX5(A,Q){let B=Q!=null?i6(Q):lQ,$=new s4(new Uint8Array(B.initialBufferLength),B);return NX5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function wX5(A){let Q=new s4(A,lQ),B=qX5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function CX5(A){return Q8(A)?Q8(A):null}function MX5(A,Q){if(B8(A,Q!=null),Q!=null)B8(A,Q)}function LX5(A){return Q8(A)?sZ0(A):null}function OX5(A,Q){if(B8(A,Q!=null),Q!=null)tZ0(A,Q)}function jX5(A){return{body:Ej(A),name:MS4(A),wait:CX5(A),timeout:LX5(A)}}function RX5(A,Q){zj(A,Q.body),LS4(A,Q.name),MX5(A,Q.wait),OX5(A,Q.timeout)}function PX5(A,Q){let B=Q!=null?i6(Q):lQ,$=new s4(new Uint8Array(B.initialBufferLength),B);return RX5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function _X5(A){let Q=new s4(A,lQ),B=jX5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function TX5(A){return{status:YA(A),response:Tr0(A)}}function kX5(A,Q){ZA(A,Q.status),kr0(A,Q.response)}function SX5(A,Q){let B=Q!=null?i6(Q):lQ,$=new s4(new Uint8Array(B.initialBufferLength),B);return kX5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function vX5(A){let Q=new s4(A,lQ),B=TX5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function yX5(A){return{group:YA(A),code:YA(A),message:YA(A),metadata:Tr0(A),actor:OS4(A)}}function xX5(A,Q){ZA(A,Q.group),ZA(A,Q.code),ZA(A,Q.message),kr0(A,Q.metadata),jS4(A,Q.actor)}function fX5(A,Q){let B=Q!=null?i6(Q):lQ,$=new s4(new Uint8Array(B.initialBufferLength),B);return xX5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function bX5(A){let Q=new s4(A,lQ),B=yX5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}function uX5(A){return{actorId:YA(A)}}function hX5(A,Q){ZA(A,Q.actorId)}function gX5(A,Q){let B=Q!=null?i6(Q):lQ,$=new s4(new Uint8Array(B.initialBufferLength),B);return hX5($,A),new Uint8Array($.view.buffer,$.view.byteOffset,$.offset)}function mX5(A){let Q=new s4(A,lQ),B=uX5(Q);if(Q.offset<Q.view.byteLength)throw new wA(Q.offset,"remaining bytes");return B}var ma=4,pX5=(A)=>{if(A.body.tag==="Init"){let{actorId:Q,connectionId:B}=A.body.val;return{body:{tag:"Init",val:{actorId:Q,connectionId:B}}}}return A},dX5=(A)=>{if(A.body.tag==="Init"){let{actorId:Q,connectionId:B}=A.body.val;return{body:{tag:"Init",val:{actorId:Q,connectionId:B,connectionToken:""}}}}return A},cX5=(A)=>{return A},lX5=(A)=>{if(A.body.tag==="Error")return{body:{tag:"Error",val:{...A.body.val,actor:null}}};return A},iX5=(A)=>{if(A.body.tag==="Error"){let{actor:Q,...B}=A.body.val;return{body:{tag:"Error",val:B}}}return A},nX5=(A)=>{return A},aX5=(A)=>{return A},oX5=(A)=>{return A},rX5=(A)=>{return A},sX5=(A)=>{return A},tX5=(A)=>{return A},eX5=(A)=>{return A},AD5=(A)=>({...A,actor:null}),QD5=(A)=>{let{actor:Q,...B}=A;return B},BD5=Oz({deserializeVersion:(A,Q)=>{switch(Q){case 1:return vY5(A);case 2:return wZ5(A);case 3:return DF5(A);case 4:return KX5(A);default:throw Error(`Unknown version ${Q}`)}},serializeVersion:(A,Q)=>{switch(Q){case 1:return SY5(A);case 2:return IZ5(A);case 3:return XF5(A);case 4:return UX5(A);default:throw Error(`Unknown version ${Q}`)}},deserializeConverters:()=>[aX5,oX5,rX5],serializeConverters:()=>[sX5,tX5,eX5]}),$D5=Oz({deserializeVersion:(A,Q)=>{switch(Q){case 1:return MY5(A);case 2:return VZ5(A);case 3:return eZ5(A);case 4:return $X5(A);default:throw Error(`Unknown version ${Q}`)}},serializeVersion:(A,Q)=>{switch(Q){case 1:return CY5(A);case 2:return GZ5(A);case 3:return tZ5(A);case 4:return BX5(A);default:throw Error(`Unknown version ${Q}`)}},deserializeConverters:()=>[pX5,cX5,lX5],serializeConverters:()=>[iX5,nX5,dX5]}),JD5=Oz({deserializeVersion:(A,Q)=>{switch(Q){case 1:return bY5(A);case 2:return OZ5(A);case 3:return KF5(A);case 4:return HX5(A);default:throw Error(`Unknown version ${Q}`)}},serializeVersion:(A,Q)=>{switch(Q){case 1:return fY5(A);case 2:return LZ5(A);case 3:return UF5(A);case 4:return WX5(A);default:throw Error(`Unknown version ${Q}`)}},deserializeConverters:()=>[],serializeConverters:()=>[]}),YD5=Oz({deserializeVersion:(A,Q)=>{switch(Q){case 1:return mY5(A);case 2:return _Z5(A);case 3:return HF5(A);case 4:return wX5(A);default:throw Error(`Unknown version ${Q}`)}},serializeVersion:(A,Q)=>{switch(Q){case 1:return gY5(A);case 2:return PZ5(A);case 3:return WF5(A);case 4:return IX5(A);default:throw Error(`Unknown version ${Q}`)}},deserializeConverters:()=>[],serializeConverters:()=>[]}),ZD5=Oz({deserializeVersion:(A,Q)=>{switch(Q){case 3:return RF5(A);case 4:return _X5(A);default:throw Error(`HttpQueueSendRequest only exists in version 3+, got version ${Q}`)}},serializeVersion:(A,Q)=>{switch(Q){case 3:return jF5(A);case 4:return PX5(A);default:throw Error(`HttpQueueSendRequest only exists in version 3+, got version ${Q}`)}},deserializeConverters:()=>[],serializeConverters:()=>[]}),FD5=Oz({deserializeVersion:(A,Q)=>{switch(Q){case 3:return kF5(A);case 4:return vX5(A);default:throw Error(`HttpQueueSendResponse only exists in version 3+, got version ${Q}`)}},serializeVersion:(A,Q)=>{switch(Q){case 3:return TF5(A);case 4:return SX5(A);default:throw Error(`HttpQueueSendResponse only exists in version 3+, got version ${Q}`)}},deserializeConverters:()=>[],serializeConverters:()=>[]}),RS4=Oz({deserializeVersion:(A,Q)=>{switch(Q){case 1:return lY5(A);case 2:return vZ5(A);case 3:return xF5(A);case 4:return bX5(A);default:throw Error(`Unknown version ${Q}`)}},serializeVersion:(A,Q)=>{switch(Q){case 1:return cY5(A);case 2:return SZ5(A);case 3:return yF5(A);case 4:return fX5(A);default:throw Error(`Unknown version ${Q}`)}},deserializeConverters:()=>[(A)=>A,(A)=>A,AD5],serializeConverters:()=>[QD5,(A)=>A,(A)=>A]}),gD8=Oz({deserializeVersion:(A,Q)=>{switch(Q){case 1:return oY5(A);case 2:return bZ5(A);case 3:return hF5(A);case 4:return mX5(A);default:throw Error(`Unknown version ${Q}`)}},serializeVersion:(A,Q)=>{switch(Q){case 1:return aY5(A);case 2:return fZ5(A);case 3:return uF5(A);case 4:return gX5(A);default:throw Error(`Unknown version ${Q}`)}},deserializeConverters:()=>[],serializeConverters:()=>[]}),Sr0=b.bigint(),XD5=Sr0.nullable(),PS4=b.object({actorId:b.string(),generation:b.union([b.number(),b.bigint()]),key:b.string().optional()}),DD5=b.object({actorId:b.string(),connectionId:b.string()}),GD5=b.object({group:b.string(),code:b.string(),message:b.string(),metadata:b.unknown().optional(),actionId:XD5,actor:PS4.optional()}),VD5=b.object({id:Sr0,output:b.unknown()}),UD5=b.object({name:b.string(),args:b.unknown()}),KD5=b.discriminatedUnion("tag",[b.object({tag:b.literal("Init"),val:DD5}),b.object({tag:b.literal("Error"),val:GD5}),b.object({tag:b.literal("ActionResponse"),val:VD5}),b.object({tag:b.literal("Event"),val:UD5})]),ED5=b.object({body:KD5}),zD5=b.object({id:Sr0,name:b.string(),args:b.unknown()}),WD5=b.object({eventName:b.string(),subscribe:b.boolean()}),HD5=b.discriminatedUnion("tag",[b.object({tag:b.literal("ActionRequest"),val:zD5}),b.object({tag:b.literal("SubscriptionRequest"),val:WD5})]),qD5=b.object({body:HD5}),ND5=b.object({args:b.unknown()}),ID5=b.object({output:b.unknown()}),wD5=b.object({body:b.unknown(),name:b.string().optional(),wait:b.boolean().optional(),timeout:b.number().optional()}),CD5=b.object({status:b.enum(["completed","timedOut"]),response:b.unknown().optional()}),_S4=b.object({group:b.string(),code:b.string(),message:b.string(),metadata:b.unknown().optional(),actor:PS4.optional()}),pD8=b.null(),dD8=b.object({actorId:b.string()});function ey(A={},Q){return{skipReadyWait:(Q==null?void 0:Q.skipReadyWait)??A.skipReadyWait??!1}}function TS4(A){if("getForId"in A)return A.getForId.name;if("getForKey"in A)return A.getForKey.name;if("getOrCreateForKey"in A)return A.getOrCreateForKey.name;if("create"in A)return A.create.name;throw VZ0("Invalid query format")}function rN(A){return"getForKey"in A||"getOrCreateForKey"in A}function Vj(A){if("getForId"in A)return{directId:A.getForId.actorId};if("create"in A)throw VZ0("create queries cannot be used as gateway targets. Resolve to an actor ID first.");return A}function Lr0(A,Q){return A==="actor"&&(Q==="not_found"||Q==="starting"||Q==="stopping"||Q==="not_configured"||Q==="dropped_reply"||Q.startsWith("destroyed_"))}async function Or0(A,Q,B,$,J){let Y=TS4($);try{let Z=await J.getForId({name:Y,actorId:B});if(Z==null?void 0:Z.error)return g4().info({msg:"found actor scheduling error",actorId:B,error:Z.error}),ZY5(A,Q,B,Z.error)}catch(Z){g4().warn({msg:"failed to fetch actor details for scheduling error check",actorId:B,error:j9(Z)})}return null}function*MD5(A,Q=8){let B=A,$=0;while(B!==void 0&&B!==null&&$<Q){if(yield B,typeof B==="object"&&"cause"in B&&B.cause!==B){B=B.cause,$+=1;continue}break}}function sN(A,Q,B,$){return{kind:A,source:Q,group:$==null?void 0:$.group,code:$==null?void 0:$.code,message:B,legacy:($==null?void 0:$.legacy)??!1}}function LD5(A){if(A.group==="actor"&&A.code==="stopping"&&A.message.includes("database accessed after actor stopped"))return;if(A.group==="actor"&&A.code==="restarting")return sN("request_retry","actor_error",A.message,{group:A.group,code:A.code});if(A.group==="guard"&&OD5(A.code))return sN("request_retry","actor_error",A.message,{group:A.group,code:A.code});if(A.group==="actor"&&A.code==="internal_error"&&A.message==="Actor is stopping")return sN("request_retry","actor_error",A.message,{group:A.group,code:A.code,legacy:!0});if(A.group==="actor"&&A.code==="stopping"&&A.message==="Actor stopping: Cannot accept new connections while actor is stopping")return sN("request_retry","actor_error",A.message,{group:A.group,code:A.code,legacy:!0});if(A.group==="actor"&&A.code==="stopped")return sN("reconnect_only","actor_error",A.message,{group:A.group,code:A.code,legacy:!0});if(A.group==="ws"&&A.code==="going_away")return sN("reconnect_only","actor_error",A.message,{group:A.group,code:A.code,legacy:!0});return}function OD5(A){return A==="service_unavailable"||A==="actor_stopped_while_waiting"||A==="tunnel_request_aborted"||A==="tunnel_message_timeout"||A==="tunnel_response_closed"||A==="gateway_response_start_timeout"}function jD5(A){if(A.message.includes("database accessed after actor stopped"))return;if(/^Actor [A-Za-z0-9-]+ stopped$/.test(A.message))return sN("request_retry","transport_error",A.message,{legacy:!0});if(A.message==="WebSocket connection closed during shutdown"||A.message==="envoy shut down"||A.message==="envoy shutting down")return sN("reconnect_only","transport_error",A.message,{legacy:!0});return}function kS4(A){for(let Q of MD5(A)){if(Q instanceof R5){let B=LD5(Q);if(B)return B;continue}if(Q instanceof ga||Q instanceof Error){let B=jD5(Q);if(B)return B}}return}function RD5(A){var Q;return((Q=kS4(A))==null?void 0:Q.kind)==="request_retry"}function PD5(A){let Q=kS4(A);return(Q==null?void 0:Q.kind)==="reconnect_only"||(Q==null?void 0:Q.kind)==="request_retry"}function SS4(A){if(A==null?void 0:A.aborted)throw A.reason??Error("Operation aborted")}async function _D5(A,Q){SS4(Q),await new Promise((B,$)=>{let J=setTimeout(()=>{Z(),B()},A),Y=()=>{clearTimeout(J),Z(),$((Q==null?void 0:Q.reason)??Error("Operation aborted"))},Z=()=>{Q==null||Q.removeEventListener("abort",Y)};Q==null||Q.addEventListener("abort",Y,{once:!0})})}async function TD5(A,Q){let B=(Q==null?void 0:Q.maxAttempts)??5,$=(Q==null?void 0:Q.initialDelayMs)??25,J=(Q==null?void 0:Q.maxDelayMs)??200,Y;for(let Z=0;Z<B;Z+=1){SS4(Q==null?void 0:Q.signal);try{return await A()}catch(F){if(!RD5(F))throw F;if(Y=F,Z===B-1)break;let X=Math.min($*2**Z,J);await _D5(X,Q==null?void 0:Q.signal)}}throw Y}function kD5(A){let[Q,B]=A.split("#"),[$,J]=Q.split(".");if(!$||!J){g4().warn({msg:"failed to parse close reason",reason:A});return}return{group:$,code:J,rayId:B}}function SD5(A){if(A instanceof Blob)return A.size;if(A instanceof ArrayBuffer)return A.byteLength;if(A instanceof Uint8Array)return A.byteLength;if(typeof A==="string")return A.length;Bj(A)}async function vr0(A){var Q,B,$;g4().debug({msg:"sending http request",url:A.url,encoding:A.encoding});let J,Y;if(A.method==="POST"||A.method==="PUT")vS4.default(A.body!==void 0,"missing body"),J=ak4(A.encoding),Y=Gr0(A.encoding,A.body,A.requestVersionedDataHandler,A.requestVersion,A.requestZodSchema,A.requestToJson,A.requestToBare);let Z;try{Z=await(A.customFetch??fetch)(new globalThis.Request(A.url,{method:A.method,headers:{...A.headers,...J?{"Content-Type":J}:{},"User-Agent":wT4()},body:Y,credentials:"include",signal:A.signal}))}catch(F){throw new ga(`Request failed: ${F}`,{cause:F})}if(!Z.ok){let F=await Z.arrayBuffer(),X=Z.headers.get("content-type"),D=Z.headers.get("x-rivet-ray-id"),G=(X==null?void 0:X.includes("application/json"))?"json":A.encoding;try{let V=ya(G,new Uint8Array(F),RS4,_S4,(U)=>({...U,actor:U.actor?{...U.actor,generation:Number(U.actor.generation)}:void 0}),(U)=>({group:U.group,code:U.code,message:U.message,metadata:U.metadata?Lz(new Uint8Array(U.metadata)):void 0,actor:U.actor?{actorId:U.actor.actorId,generation:Number(U.actor.generation),key:U.actor.key??void 0}:void 0}));throw g4().warn({msg:"http error response",group:V.group,code:V.code,message:V.message,metadata:V.metadata,actorId:(Q=V.actor)==null?void 0:Q.actorId,generation:(B=V.actor)==null?void 0:B.generation,actorKey:($=V.actor)==null?void 0:$.key}),new R5(V.group,V.code,V.message,{metadata:V.metadata,actor:V.actor})}catch(V){if(V instanceof R5)throw V;let U=new TextDecoder("utf-8",{fatal:!1}).decode(F);if(D)throw new ga(`${Z.statusText} (${Z.status}) (Ray ID: ${D}):
4622
4622
  ${U}`);else throw new ga(`${Z.statusText} (${Z.status}):
4623
- ${U}`)}}if(A.skipParseResponse)return;try{let F=new Uint8Array(await Z.arrayBuffer());return ya(A.encoding,F,A.responseVersionedDataHandler,A.responseZodSchema,A.responseFromJson,A.responseFromBare)}catch(F){throw new ga(`Failed to parse response: ${F}`,{cause:F})}}function yS4(A){async function Q(B,$,J){let Y=(J==null?void 0:J.wait)??!1,Z=J==null?void 0:J.timeout,F=await vr0({url:`http://actor/queue/${encodeURIComponent(B)}`,method:"POST",headers:{[HS4]:A.encoding,...A.params!==void 0?{[Rr0]:JSON.stringify(A.params)}:{}},body:{body:$,wait:Y,timeout:Z},encoding:A.encoding,customFetch:A.customFetch,signal:J==null?void 0:J.signal,requestVersion:ma,requestVersionedDataHandler:ZD5,responseVersion:ma,responseVersionedDataHandler:FD5,requestZodSchema:wD5,responseZodSchema:CD5,requestToJson:(X)=>({...X,name:B}),requestToBare:(X)=>({name:X.name??B,body:xZ0(Xj(X.body)),wait:X.wait??!1,timeout:X.timeout!==void 0?BigInt(X.timeout):null}),responseFromJson:(X)=>{if(X.response===void 0)return{status:X.status};return{status:X.status,response:X.response}},responseFromBare:(X)=>{if(X.response===null||X.response===void 0)return{status:X.status};return{status:X.status,response:Lz(new Uint8Array(X.response))}}});if(Y)return F;return}return{send:Q}}async function vD5(A,Q,B,$,J,Y={}){let Z,F=J||{};if(typeof $==="string")Z=$;else if($ instanceof URL)Z=$.pathname+$.search;else if($ instanceof Request){let X=new URL($.url);Z=X.pathname+X.search;let D=new Headers($.headers),G=new Headers((J==null?void 0:J.headers)||{}),V=new Headers(D);if(G.forEach((U,K)=>{V.set(K,U)}),F={method:$.method,body:$.body,mode:$.mode,credentials:$.credentials,redirect:$.redirect,referrer:$.referrer,referrerPolicy:$.referrerPolicy,integrity:$.integrity,keepalive:$.keepalive,signal:$.signal,...F,headers:V},F.body)F.duplex="half"}else throw TypeError("Invalid input type for fetch");try{g4().debug("directId"in Q?{msg:"sending raw http request to actor",actorId:Q.directId}:{msg:"sending raw http request with actor query",query:Q});let X=Z.startsWith("/")?Z.slice(1):Z,D=new URL(`http://actor/request/${X}`),G=new Headers(F.headers);if(B)G.set(Rr0,JSON.stringify(B));let V=new Request(D,{...F,headers:G});return A.sendRequest(Q,V,Y)}catch(X){let{group:D,code:G,message:V,metadata:U,actor:K}=Na(X,!0);throw new R5(D,G,V,{metadata:U,actor:K})}}async function yD5(A,Q,B,$,J,Y={}){let F="",X="";if($){let V=$.indexOf("?");if(V!==-1)F=$.substring(0,V),X=$.substring(V);else F=$;if(F.startsWith("/"))F=F.slice(1)}let D=`${WS4}${F}${X}`;return g4().debug({msg:"opening websocket",target:Q,encoding:"bare",path:D}),await A.openWebSocket(D,Q,"bare",B,Y)}async function xS4(A,Q){if("directId"in Q)return Q.directId;if("getForId"in Q)return Q.getForId.actorId;if("getForKey"in Q){let B=await A.getWithKey({name:Q.getForKey.name,key:Q.getForKey.key});if(!B)throw XP4(`${Q.getForKey.name}:${JSON.stringify(Q.getForKey.key)}`);return B.actorId}if("getOrCreateForKey"in Q)return(await A.getOrCreateWithKey({name:Q.getOrCreateForKey.name,key:Q.getOrCreateForKey.key,input:Q.getOrCreateForKey.input,region:Q.getOrCreateForKey.region})).actorId;if("create"in Q)return(await A.createActor({name:Q.create.name,key:Q.create.key,input:Q.create.input,region:Q.create.region})).actorId;throw VZ0("Invalid query format")}var xD5=class{#A;#Q;#B;#$;#Y;#J;#F;#Z;#X;#D=new ok4;constructor(A,Q,B,$,J,Y,Z={}){this.#A=A,this.#Q=Q,this.#B=J,this.#$=Y,this.#Y=Z,this.#J=B,this.#F=$}async#U(){if(this.#F)return await this.#F();return this.#J}send(A,Q,B){return this.#K(A,Q,B)}async#K(A,Q,B){return await this.#D.run(async()=>{let $=this.#H(),J=!1;for(let Y=0;Y<$;Y++){let Z;try{let F=ey(this.#Y),X=await this.#w(J,F);return Z="directId"in X?X.directId:void 0,await yS4({encoding:this.#B,params:this.#J,customFetch:async(D)=>{return await this.#Q.sendRequest(X,D,F)}}).send(A,Q,B)}catch(F){let{group:X,code:D,message:G,metadata:V,actor:U}=Na(F,!0);if(this.#E(X,D,V,Y,$)){await this.#V();continue}if(await this.#C(X,D,Z,Y,$)){J=!0,await this.#V();continue}if(this.#W(X,D,Y,$)){this.#G(),J=!0,await this.#V();continue}if(this.#q(X,D)&&Y<$-1){if(J=D==="starting"||D==="stopping"||D.startsWith("destroyed_"),J)await this.#V();continue}throw new R5(X,D,G,{metadata:V,actor:U})}}throw Error("unreachable queue retry state")})}async action(A){if(typeof A==="string"||typeof A!=="object"||A===null||!("name"in A))throw Error(`Invalid action call: expected an options object { name, args }, got ${typeof A}. Use handle.actionName(...args) for the shorthand API.`);let Q=async()=>await this.#z(A);if(A.name==="destroy")return await Q();return await TD5(Q,{signal:A.signal})}async#z(A){let Q=this.#H(),B=!1,$=ey(this.#Y,A);for(let J=0;J<Q;J++){let Y;try{let Z=await this.#w(B,$);Y="directId"in Z?Z.directId:void 0,g4().debug(Y?{msg:"using direct actor gateway target",actorId:Y}:{msg:"using query gateway target for action",query:this.#$}),g4().debug({msg:"handling action",name:A.name,encoding:this.#B});let F=await vr0({url:`http://actor/action/${encodeURIComponent(A.name)}`,method:"POST",headers:{[HS4]:this.#B,...this.#J!==void 0?{[Rr0]:JSON.stringify(this.#J)}:{}},body:A.args,encoding:this.#B,customFetch:async(X)=>await this.#Q.sendRequest(Z,X,$),signal:A==null?void 0:A.signal,requestVersion:ma,requestVersionedDataHandler:JD5,responseVersion:ma,responseVersionedDataHandler:YD5,requestZodSchema:ND5,responseZodSchema:ID5,requestToJson:(X)=>({args:X}),requestToBare:(X)=>({args:xZ0(Xj(X))}),responseFromJson:(X)=>X.output,responseFromBare:(X)=>Lz(new Uint8Array(X.output))});if(A.name==="destroy"&&Y)await this.#N(Y);return F}catch(Z){let{group:F,code:X,message:D,metadata:G,actor:V}=Na(Z,!0);if(await this.#C(F,X,Y,J,Q)){B=!0,await this.#V();continue}if(A.name!=="destroy"&&this.#W(F,X,J,Q)){this.#G(),B=!0,await this.#V();continue}if(F==="actor"&&X==="destroyed_while_waiting_for_ready"&&"getForId"in this.#$)throw new R5("actor","not_found","The actor does not exist or was destroyed.",{metadata:G,actor:V});if(this.#q(F,X)&&J<Q-1){if(F==="actor"&&(X==="starting"||X==="stopping"))B=!0,await new Promise((K)=>setTimeout(K,100));continue}throw new R5(F,X,D,{metadata:G,actor:V})}}throw Error("unreachable action retry state")}async#N(A){let Q=TS4(this.#$),B=Date.now()+1000;while(Date.now()<B){if(!await this.#Q.getForId({name:Q,actorId:A}))return;await new Promise((J)=>setTimeout(J,25))}}async#V(){await new Promise((A)=>setTimeout(A,100))}#H(){if(!rN(this.#$))return 1;return"getOrCreateForKey"in this.#$?60:24}#W(A,Q,B,$){if(!rN(this.#$)||B>=$-1||A!=="actor")return!1;return Q==="not_found"||Q==="starting"||Q==="stopping"||Q==="not_configured"||Q==="dropped_reply"||Q==="destroying"||Q.startsWith("destroyed_")}#E(A,Q,B,$,J){if(!rN(this.#$)||$>=J-1||A!=="actor"||Q!=="overloaded"||B===null||typeof B!=="object")return!1;let Y=B;return Y.channel==="dispatch_inbox"&&Y.operation==="dispatch_queue_send"}#G(){this.#Z=void 0,this.#X=void 0}async#C(A,Q,B,$,J){if(!rN(this.#$)||!Cr0(A,Q)||$>=J-1)return!1;if(B){let Y=await Or0(A,Q,B,this.#$,this.#Q);if(Y)throw Y}return this.#G(),!0}#q(A,Q){if(!rN(this.#$)||!Lr0(A,Q))return!1;return this.#G(),!0}async#L(A){if("getForId"in this.#$)return Vj(this.#$);if(A)return Vj(this.#$);if(this.#Z)return{directId:this.#Z};if(!this.#X)this.#X=xS4(this.#Q,this.#$).then((Q)=>{return this.#Z=Q,Q});try{return{directId:await this.#X}}finally{this.#X=void 0}}async#w(A,Q){if(Q.skipReadyWait)return Vj(this.#$);return await this.#L(A)}connect(A,Q={}){g4().debug({msg:"establishing connection from handle",query:this.#$});let B=A===void 0?this.#J:A,$=A===void 0?this.#F:void 0,J=new bD5(this.#A,this.#Q,B,$,this.#B,this.#$,ey(this.#Y,Q));return this.#A[fS4](J)}fetch(A,Q){return this.#M(A,Q)}async#M(A,Q){let B=this.#H(),$=!1,{skipReadyWait:J,...Y}=Q??{},Z=ey(this.#Y,{skipReadyWait:J});for(let F=0;F<B;F++){let X;try{let D=await this.#w($,Z);X="directId"in D?D.directId:void 0;let G=await vD5(this.#Q,D,this.#J,A,Y,Z),V=await this.#I(G,X,F,B);if(V){if($=V.useQueryTarget,V.waitForRetryWindow)await this.#V();continue}return G}catch(D){let{group:G,code:V,message:U,metadata:K,actor:E}=Na(D,!0);if(await this.#C(G,V,X,F,B)){$=!0,await this.#V();continue}if(this.#W(G,V,F,B)){this.#G(),$=!0,await this.#V();continue}if(this.#q(G,V)&&F<B-1){if($=V==="starting"||V==="stopping"||V.startsWith("destroyed_"),$)await this.#V();continue}throw new R5(G,V,U,{metadata:K,actor:E})}}throw Error("unreachable fetch retry state")}async#I(A,Q,B,$){if(A.ok||!rN(this.#$))return null;let J=await this.#O(A);if(!J)return null;let{group:Y,code:Z}=J;if(await this.#C(Y,Z,Q,B,$))return{useQueryTarget:!0,waitForRetryWindow:!0};if(this.#W(Y,Z,B,$))return this.#G(),{useQueryTarget:!0,waitForRetryWindow:!0};if(this.#q(Y,Z)&&B<$-1){let X=Z==="starting"||Z==="stopping"||Z.startsWith("destroyed_");return{useQueryTarget:X,waitForRetryWindow:X}}return null}async#O(A){if(A.ok)return null;let Q=A.headers.get("content-type"),B=(Q==null?void 0:Q.includes("application/json"))?"json":this.#B;try{return ya(B,new Uint8Array(await A.clone().arrayBuffer()),RS4,_S4,($)=>({...$,actor:$.actor?{...$.actor,generation:Number($.actor.generation)}:void 0}),($)=>({group:$.group,code:$.code,message:$.message,metadata:$.metadata?Lz(new Uint8Array($.metadata)):void 0,actor:$.actor?{actorId:$.actor.actorId,generation:Number($.actor.generation),key:$.actor.key??void 0}:void 0}))}catch{return null}}async webSocket(A,Q,B={}){let $=await this.#U(),J=ey(this.#Y,B),Y=await this.#w(!1,J);return await yD5(this.#Q,Y,$,A,Q,J)}async resolve(){if("getForId"in this.#$)return this.#$.getForId.actorId;let A=await this.#L(!1);if("directId"in A)return A.directId;throw Error("dynamic actor resolution did not produce a direct actor id")}async getGatewayUrl(){return await this.#Q.buildGatewayUrl(Vj(this.#$),this.#Y)}async reload(){let A=Vj(this.#$),Q=new Request("http://actor/dynamic/reload",{method:"PUT"}),B=await this.#Q.sendRequest(A,Q);if(!B.ok){let $=await B.text().catch(()=>"");throw new R5("actor","reload_failed",`reload failed with status ${B.status}: ${$}`,{})}}},BF0=Symbol("actorConns"),fS4=Symbol("createActorConnProxy"),fD5=class{#A=!1;[BF0]=new Set;#Q;#B;#$;constructor(A,Q,B={}){this.#Q=A,this.#B=Q??"bare",this.#$=B}getForId(A,Q,B){g4().debug({msg:"get handle to actor with id",name:A,actorId:Q,params:B==null?void 0:B.params});let $={getForId:{name:A,actorId:Q}},J=this.#Y(B==null?void 0:B.params,B==null?void 0:B.getParams,$);return ua(J)}get(A,Q,B){let $=typeof Q==="string"?[Q]:Q||[];g4().debug({msg:"get handle to actor",name:A,key:$,parameters:B==null?void 0:B.params});let J={getForKey:{name:A,key:$}},Y=this.#Y(B==null?void 0:B.params,B==null?void 0:B.getParams,J);return ua(Y)}getOrCreate(A,Q,B){let $=typeof Q==="string"?[Q]:Q||[];g4().debug({msg:"get or create handle to actor",name:A,key:$,parameters:B==null?void 0:B.params,createInRegion:B==null?void 0:B.createInRegion});let J={getOrCreateForKey:{name:A,key:$,input:B==null?void 0:B.createWithInput,region:B==null?void 0:B.createInRegion}},Y=this.#Y(B==null?void 0:B.params,B==null?void 0:B.getParams,J);return ua(Y)}async create(A,Q,B){let $=typeof Q==="string"?[Q]:Q||[],J={create:{...B,name:A,key:$}};g4().debug({msg:"create actor handle",name:A,key:$,parameters:B==null?void 0:B.params,create:J.create});let Y=await xS4(this.#Q,J);g4().debug({msg:"created actor with ID",name:A,key:$,actorId:Y});let Z={getForId:{name:A,actorId:Y}},F=this.#Y(B==null?void 0:B.params,B==null?void 0:B.getParams,Z);return ua(F)}#Y(A,Q,B){return new xD5(this,this.#Q,A,Q,this.#B,B,this.#$)}[fS4](A){return this[BF0].add(A),A[uS4](),ua(A)}async dispose(){if(this.#A){g4().warn({msg:"client already disconnected"});return}this.#A=!0,g4().debug({msg:"disposing client"});let A=[];for(let Q of this[BF0].values())A.push(Q.dispose());await Promise.all(A)}};function bS4(A,Q={}){let B=new fD5(A,Q.encoding,Q.gateway);return new Proxy(B,{get:($,J,Y)=>{if(typeof J==="symbol"||J in $){let Z=Reflect.get($,J,Y);if(typeof Z==="function")return Z.bind($);return Z}if(typeof J==="string")return{get:(Z,F)=>{return $.get(J,Z,F)},getOrCreate:(Z,F)=>{return $.getOrCreate(J,Z,F)},getForId:(Z,F)=>{return $.getForId(J,Z,F)},create:async(Z,F={})=>{return await $.create(J,Z,F)}};return}})}function ua(A){let Q=new Map;return new Proxy(A,{get(B,$,J){if(typeof $==="symbol")return Reflect.get(B,$,J);if($==="constructor"||$ in B){let Y=Reflect.get(B,$,B);if(typeof Y==="function")return Y.bind(B);return Y}if(typeof $==="string"){if($==="then")return;let Y=Q.get($);if(!Y)Y=(...Z)=>B.action({name:$,args:Z}),Q.set($,Y);return Y}},has(B,$){if(typeof $==="string")return!0;return Reflect.has(B,$)},getPrototypeOf(B){return Reflect.getPrototypeOf(B)},ownKeys(B){return Reflect.ownKeys(B)},getOwnPropertyDescriptor(B,$){let J=Reflect.getOwnPropertyDescriptor(B,$);if(J)return J;if(typeof $==="string")return{configurable:!0,enumerable:!1,writable:!1,value:(...Y)=>B.action({name:$,args:Y})};return}})}var Nr0=65536,uS4=Symbol("connect"),bD5=class{#A=!1;#Q=new AbortController;#B="idle";#$;#Y;#J=[];#F=new Map;#Z=new Map;#X=new Set;#D=new Set;#U=!1;#K=new Set;#z=new Set;#N=0;#V;#H;#W;#E;#G;#C;#q;#L;#w;#M;#I;#O;constructor(A,Q,B,$,J,Y,Z={}){this.#C=A,this.#q=Q,this.#L=B,this.#w=$,this.#M=J,this.#I=Y,this.#O=ey(Z),this.#H=ly((F)=>g4().warn({msg:"unhandled ready promise rejection",reason:F})),this.#V=yS4({encoding:this.#M,params:this.#L,customFetch:async(F)=>{return await this.#q.sendRequest(Vj(this.#I),F,this.#O)}}),this.#W=setInterval(()=>60000)}#_(){this.#$=void 0,this.#Y=void 0}#T(A,Q){if(!rN(this.#I)||!Lr0(A,Q))return!1;return this.#_(),!0}#k(A,Q){return rN(this.#I)&&Lr0(A,Q)&&this.#E!==void 0&&this.#B!=="connected"}send(A,Q,B){return this.#h(A,Q,B)}async#h(A,Q,B){return await this.#V.send(A,Q,B)}async action(A){if(typeof A==="string"||typeof A!=="object"||A===null||!("name"in A))throw Error(`Invalid action call: expected an options object { name, args }, got ${typeof A}. Use conn.actionName(...args) for the shorthand API.`);g4().debug({msg:"action",name:A.name,args:A.args});let Q=this.#N;this.#N+=1;let{promise:B,resolve:$,reject:J}=ly((F)=>g4().warn({msg:"unhandled action promise rejection",reason:F}));this.#F.set(Q,{name:A.name,resolve:$,reject:J}),g4().debug({msg:"added action to in-flight map",actionId:Q,actionName:A.name,inFlightCount:this.#F.size}),this.#v({body:{tag:"ActionRequest",val:{id:BigInt(Q),name:A.name,args:A.args}}});let{id:Y,output:Z}=await B;if(Y!==BigInt(Q))throw Error(`Request ID ${Q} does not match response ID ${Y}`);return Z}[uS4](){this.#x()}#j(A){let Q=this.#B;if(Q===A)return;this.#B=A;for(let B of[...this.#z])try{B(A)}catch($){g4().error({msg:"error in status change handler",error:j9($)})}if(A==="connected"){this.#H.resolve(void 0);for(let B of[...this.#D])try{B()}catch($){g4().error({msg:"error in open handler",error:j9($)})}}if((A==="disconnected"||A==="idle")&&Q==="connected")for(let B of[...this.#K])try{B()}catch($){g4().error({msg:"error in close handler",error:j9($)})}}#x(){this.#j("connecting"),fa(this.#g.bind(this),{forever:!0,minTimeout:250,maxTimeout:30000,onFailedAttempt:(A)=>{g4().warn({msg:"failed to reconnect",attempt:A.attemptNumber,error:j9(A)})},signal:this.#Q.signal}).catch((A)=>{if(A instanceof xa||A.name==="AbortError"||!this.#f(A))g4().info({msg:"connection retry aborted"});else g4().error({msg:"unexpected error in connection retry",error:j9(A)})})}async#g(){try{if(this.#E)throw Error("#onOpenPromise already defined");this.#E=ly((A)=>g4().warn({msg:"unhandled open promise rejection",reason:A})),await this.#p(),await this.#E.promise}catch(A){if(this.#f(A))throw A;let Q=A instanceof R5?A:new R5("client","connection_open_failed",`Failed to open connection: ${j9(A)}`,{error:j9(A)});throw this.#b(),this.#R(Q,!1),this.#P(Q),this.#j("idle"),new xa(A instanceof Error?A:Error(j9(A)))}finally{this.#E=void 0}}#f(A){if(A instanceof QF0)return!1;if(A instanceof R5&&this.#k(A.group,A.code))return!0;if(A instanceof R5&&A.group==="client"&&A.code==="get_params_failed")return!0;return PD5(A)}#b(){if(this.#J.length===0)return;g4().debug({msg:"clearing queued connection messages",queueLength:this.#J.length}),this.#J=[]}async#m(){if(!this.#w)return this.#L;try{return await this.#w()}catch(A){let Q=j9(A),B=new R5("client","get_params_failed",`Failed to resolve connection params: ${Q}`,{error:Q});throw this.#b(),this.#R(B,!1),this.#P(B),B}}async#p(){let A=await this.#m(),Q=Vj(this.#I),B=await this.#q.openWebSocket(zS4,Q,this.#M,A,this.#O);Mr0.default(B,"websocket should have been created"),g4().debug({msg:"opened websocket",connId:this.#Y,readyState:B.readyState,messageQueueLength:this.#J.length}),this.#G=B,B.addEventListener("open",()=>{g4().debug({msg:"client websocket open",connId:this.#Y})}),B.addEventListener("message",async($)=>{try{await this.#c($.data)}catch(J){g4().error({msg:"error in websocket message handler",error:j9(J)})}}),B.addEventListener("close",async($)=>{try{await this.#l($)}catch(J){g4().error({msg:"error in websocket close handler",error:j9(J)})}}),B.addEventListener("error",()=>{try{this.#i()}catch($){g4().error({msg:"error in websocket error handler",error:j9($)})}})}#d(){if(this.#A){if(g4().debug({msg:"handleOnOpen called after dispose, closing websocket"}),this.#G)this.#G.close(1000,"Disposed"),this.#G=void 0;return}if(this.#B==="connected"||this.#U)return;this.#U=!0,queueMicrotask(()=>{if(this.#U=!1,this.#A){if(g4().debug({msg:"handleOnOpen scheduled after dispose, closing websocket"}),this.#G)this.#G.close(1000,"Disposed"),this.#G=void 0;return}if(g4().debug({msg:"socket open",messageQueueLength:this.#J.length,connId:this.#Y}),this.#j("connected"),this.#E)this.#E.resolve(void 0);else g4().warn({msg:"#onOpenPromise is undefined"});for(let Q of this.#Z.keys())this.#y(Q,!0);let A=this.#J;this.#J=[],g4().debug({msg:"flushing message queue",queueLength:A.length});for(let Q of A)this.#v(Q)})}async#c(A){var Q;g4().trace({msg:"received message",dataType:typeof A,isBlob:A instanceof Blob,isArrayBuffer:A instanceof ArrayBuffer});let B=await this.#a(A);if(g4().trace(ET4()?{msg:"parsed message",message:Dr0(B).substring(0,100)+"..."}:{msg:"parsed message"}),B.body.tag==="Init")this.#$=B.body.val.actorId,this.#Y=B.body.val.connectionId,g4().trace({msg:"received init message",actorId:this.#$,connId:this.#Y}),this.#d();else if(B.body.tag==="Error"){let{group:$,code:J,message:Y,metadata:Z,actionId:F,actor:X}=B.body.val;if(F!==null){let D=this.#S(Number(F));this.#T($,J),g4().warn({msg:"action error",actionId:F,actionName:D==null?void 0:D.name,group:$,code:J,message:Y,metadata:Z,actorId:X==null?void 0:X.actorId,generation:X==null?void 0:X.generation,actorKey:X==null?void 0:X.key}),D.reject(new R5($,J,Y,{metadata:Z,actor:X}))}else{if(g4().warn({msg:"connection error",group:$,code:J,message:Y,metadata:Z,actorId:X==null?void 0:X.actorId,generation:X==null?void 0:X.generation,actorKey:X==null?void 0:X.key}),this.#k($,J)){this.#_(),(Q=this.#E)==null||Q.reject(new R5($,J,Y,{metadata:Z,actor:X}));return}let D=new R5($,J,Y,{metadata:Z,actor:X});if(Cr0($,J)&&this.#$){let G=await Or0($,J,this.#$,this.#I,this.#q);if(G)D=G}if(this.#E)this.#E.reject(D);this.#T($,J);for(let[G,V]of this.#F.entries())V.reject(D),this.#F.delete(G);this.#P(D)}}else if(B.body.tag==="ActionResponse"){let{id:$}=B.body.val;g4().debug({msg:"received action response",actionId:Number($),inFlightCount:this.#F.size,inFlightIds:Array.from(this.#F.keys())});let J=this.#S(Number($));g4().trace({msg:"resolving action promise",actionId:$,actionName:J==null?void 0:J.name}),J.resolve(B.body.val)}else if(B.body.tag==="Event")g4().trace({msg:"received event",name:B.body.val.name}),this.#n(B.body.val);else Bj(B.body)}async#l(A){var Q;let B=A,$=B.wasClean,J=this.#B==="connected";if(g4().info({msg:"socket closed",code:B.code,reason:B.reason,wasClean:$,disposed:this.#A,connId:this.#Y}),this.#G=void 0,this.#A)this.#R(new QF0,!0);else{this.#j("disconnected");let Y,Z=B.reason||"",F=kD5(Z);if(F){let{group:X,code:D}=F;if(this.#k(X,D)){this.#_(),(Q=this.#E)==null||Q.reject(new R5(X,D,`Connection closed: ${Z}`,void 0));return}if(Cr0(X,D)&&this.#$){let G=await Or0(X,D,this.#$,this.#I,this.#q);if(G)Y=G;else Y=new R5(X,D,`Connection closed: ${Z}`,void 0)}else Y=new R5(X,D,`Connection closed: ${Z}`,void 0);this.#T(X,D)}else Y=Error(`${$?"Connection closed":"Connection lost"} (code: ${B.code}, reason: ${Z})`);if(this.#R(Y,!1),Y instanceof R5)this.#P(Y);if(J)g4().debug({msg:"triggering reconnect",connId:this.#Y}),this.#x()}}#R(A,Q){if(this.#E){if(Q)this.#E.promise.catch(()=>{});this.#E.reject(A)}for(let B of this.#F.values())B.reject(A);this.#F.clear()}#i(){if(this.#A)return;g4().warn("socket error")}#S(A){let Q=this.#F.get(A);if(!Q)throw g4().error({msg:"action not found in in-flight map",lookupId:A,inFlightCount:this.#F.size,inFlightIds:Array.from(this.#F.keys()),inFlightActions:Array.from(this.#F.entries()).map(([B,$])=>({id:B,name:$.name}))}),FY5(`No in flight response for ${A}`);return this.#F.delete(A),g4().debug({msg:"removed action from in-flight map",actionId:A,actionName:Q.name,inFlightCount:this.#F.size}),Q}#n(A){let{name:Q,args:B}=A,$=this.#Z.get(Q);if(!$)return;for(let J of[...$])if(J.callback(...B),J.once)$.delete(J);if($.size===0)this.#Z.delete(Q)}#P(A){for(let Q of[...this.#X])try{Q(A)}catch(B){g4().error({msg:"error in connection error handler",error:j9(B)})}}#u(A,Q,B){let $={callback:Q,once:B},J=this.#Z.get(A);if(J===void 0)J=new Set,this.#Z.set(A,J),this.#y(A,!0);return J.add($),()=>{let Y=this.#Z.get(A);if(Y){if(Y.delete($),Y.size===0)this.#Z.delete(A),this.#y(A,!1)}}}on(A,Q){return this.#u(A,Q,!1)}once(A,Q){return this.#u(A,Q,!0)}onError(A){return this.#X.add(A),()=>{this.#X.delete(A)}}get connStatus(){return this.#B}get isConnected(){return this.#B==="connected"}get ready(){return this.#H.promise}onOpen(A){if(this.#D.add(A),this.#B==="connected")queueMicrotask(()=>{if(!this.#D.has(A))return;try{A()}catch(Q){g4().error({msg:"error in open handler",error:j9(Q)})}});return()=>{this.#D.delete(A)}}onClose(A){return this.#K.add(A),()=>{this.#K.delete(A)}}onStatusChange(A){return this.#z.add(A),()=>{this.#z.delete(A)}}#v(A,Q){var B,$;if(this.#A)if(Q==null?void 0:Q.ephemeral)return;else throw new QF0;let J=!1;if(this.#G){let Y=this.#G.readyState;if(g4().debug({msg:"websocket send attempt",readyState:Y,readyStateString:Y===0?"CONNECTING":Y===1?"OPEN":Y===2?"CLOSING":"CLOSED",connId:this.#Y,messageType:A.body.tag,actionName:(B=A.body.val)==null?void 0:B.name}),this.#B!=="connected")g4().debug({msg:"websocket init pending, queueing message",connStatus:this.#B,messageType:A.body.tag}),J=!0;else if(Y===1)try{let Z=Gr0(this.#M,A,BD5,ma,qD5,(X)=>X,(X)=>{if(X.body.tag==="ActionRequest")return{body:{tag:"ActionRequest",val:{id:X.body.val.id,name:X.body.val.name,args:xZ0(Xj(X.body.val.args))}}};else return X}),F=SD5(Z);if(F>Nr0&&A.body.tag==="ActionRequest"){let X=Number(A.body.val.id),D=this.#S(X),G=new R5("message","incoming_too_long","Incoming message too long",{maxSize:Nr0,actualSize:F});g4().warn({msg:"rejecting oversized connection action request",actionId:X,actionName:D.name,actualSize:F,maxSize:Nr0}),D.reject(G),this.#P(G);return}this.#G.send(Z),g4().trace({msg:"sent websocket message",len:F})}catch(Z){g4().warn({msg:"failed to send message, added to queue",error:Z,connId:this.#Y}),J=!0}else g4().debug({msg:"websocket not open, queueing message",readyState:Y}),J=!0}else g4().debug({msg:"no websocket, queueing message"}),J=!0;if(!(Q==null?void 0:Q.ephemeral)&&J)this.#J.push(A),g4().debug({msg:"queued connection message",queueLength:this.#J.length,connId:this.#Y,messageType:A.body.tag,actionName:($=A.body.val)==null?void 0:$.name})}async#a(A){Mr0.default(this.#G,"websocket must be defined");let Q=await ck4(A);return ya(this.#M,Q,$D5,ED5,(B)=>{if(B.body.tag!=="Error"||!B.body.val.actor)return B;return{body:{tag:"Error",val:{...B.body.val,actor:{...B.body.val.actor,generation:Number(B.body.val.actor.generation)}}}}},(B)=>{if(B.body.tag==="Error")return{body:{tag:"Error",val:{group:B.body.val.group,code:B.body.val.code,message:B.body.val.message,metadata:B.body.val.metadata?Lz(new Uint8Array(B.body.val.metadata)):null,actionId:B.body.val.actionId,actor:B.body.val.actor?{actorId:B.body.val.actor.actorId,generation:Number(B.body.val.actor.generation),key:B.body.val.actor.key??void 0}:void 0}}};else if(B.body.tag==="ActionResponse")return{body:{tag:"ActionResponse",val:{id:B.body.val.id,output:Lz(new Uint8Array(B.body.val.output))}}};else if(B.body.tag==="Event")return{body:{tag:"Event",val:{name:B.body.val.name,args:Lz(new Uint8Array(B.body.val.args))}}};else return B})}get actorId(){return this.#$}get connId(){return this.#Y}get connectionId(){return this.#Y}async dispose(){if(this.#A){g4().warn({msg:"connection already disconnected"});return}if(this.#A=!0,g4().debug({msg:"disposing actor conn"}),this.#j("idle"),clearInterval(this.#W),this.#Q.abort(),this.#C[BF0].delete(this),this.#G){let A=this.#G;if(A.readyState!==2&&A.readyState!==3){let{promise:Q,resolve:B}=ly(($)=>g4().warn({msg:"unhandled websocket close promise rejection",reason:$}));A.addEventListener("close",()=>B(void 0)),A.close(1000,"Disposed"),await Q}}else this.#R(new QF0,!0);this.#G=void 0}#y(A,Q){this.#v({body:{tag:"SubscriptionRequest",val:{eventName:A,subscribe:Q}}},{ephemeral:!0})}};function uD5(A,Q){let{endpoint:B,path:$=["endpoint"],namespace:J,token:Y}=Q,Z;try{Z=new URL(B)}catch{A.addIssue({code:"custom",message:`invalid URL: ${B}`,path:$});return}if(Z.search){A.addIssue({code:"custom",message:"endpoint cannot contain a query string",path:$});return}if(Z.hash){A.addIssue({code:"custom",message:"endpoint cannot contain a fragment",path:$});return}let F=Z.username?decodeURIComponent(Z.username):void 0,X=Z.password?decodeURIComponent(Z.password):void 0;if(X&&!F){A.addIssue({code:"custom",message:"endpoint cannot have a token without a namespace",path:$});return}if(F&&J)A.addIssue({code:"custom",message:"cannot specify namespace both in endpoint URL and as a separate config option",path:["namespace"]});if(X&&Y)A.addIssue({code:"custom",message:"cannot specify token both in endpoint URL and as a separate config option",path:["token"]});return Z.username="",Z.password="",{endpoint:Z.toString(),namespace:F,token:X}}var ZS4="http://localhost:6420",hS4=4096,FS4=!1,hD5=_B.object({endpoint:_B.string().optional().transform((A)=>{let Q=A??DT4()??GT4();if(!Q&&!FS4)FS4=!0,console.warn(`[rivetkit] No endpoint provided to client. Defaulting to ${ZS4}. Starting in 2.2.0, an explicit endpoint will be required. Pass an endpoint to createClient() or createRivetKit(), or set the RIVET_ENDPOINT environment variable.`);return Q??ZS4}),token:_B.string().optional().transform((A)=>A??VT4()),namespace:_B.string().optional().transform((A)=>A??UT4()),poolName:_B.string().default(()=>KT4()??"default"),encoding:dk4.default("bare"),headers:_B.record(_B.string(),_B.string()).optional().default(()=>({})),gateway:_B.object({skipReadyWait:_B.boolean().optional().default(!1)}).optional().default(()=>({skipReadyWait:!1})),getUpgradeWebSocket:_B.custom().optional(),disableMetadataLookup:_B.boolean().optional().default(!1),maxInputSize:_B.number().int().positive().default(hS4),devtools:_B.boolean().default(()=>{var A,Q;return typeof window<"u"&&(((A=window==null?void 0:window.location)==null?void 0:A.hostname)==="127.0.0.1"||((Q=window.location)==null?void 0:Q.hostname)==="localhost")})}),gS4=hD5.transform((A,Q)=>gD5(A,Q));function gD5(A,Q){let B=uD5(Q,{endpoint:A.endpoint,path:["endpoint"],namespace:A.namespace,token:A.token});return{...A,endpoint:B==null?void 0:B.endpoint,namespace:(B==null?void 0:B.namespace)??A.namespace??"default",token:(B==null?void 0:B.token)??A.token}}function b5(){return cN("engine-client")}function $F0(A){return A.endpoint??"http://127.0.0.1:6420"}async function tN(A,Q,B,$){let J=$F0(A),Y=iy(J,B,{namespace:A.namespace});b5().debug({msg:"making api call",method:Q,url:Y});let Z={...A.headers};if(A.token)Z.Authorization=`Bearer ${A.token}`;return await vr0({method:Q,url:Y,headers:Z,body:$,encoding:"json",skipParseResponse:!1,requestVersionedDataHandler:void 0,requestVersion:void 0,responseVersionedDataHandler:void 0,responseVersion:void 0,requestZodSchema:b.any(),responseZodSchema:b.any(),requestToJson:(F)=>F,requestToBare:(F)=>F,responseFromJson:(F)=>F,responseFromBare:(F)=>F})}async function mD5(A,Q,B){return tN(A,"GET",`/actors?actor_ids=${encodeURIComponent(B)}`)}async function pD5(A,Q,B){let $=uZ0(B);return tN(A,"GET",`/actors?name=${encodeURIComponent(Q)}&key=${encodeURIComponent($)}`)}async function dD5(A,Q){return tN(A,"GET",`/actors?name=${encodeURIComponent(Q)}`)}async function cD5(A,Q){return tN(A,"PUT","/actors",Q)}async function lD5(A,Q){return tN(A,"POST","/actors",Q)}async function iD5(A,Q){return tN(A,"DELETE",`/actors/${encodeURIComponent(Q)}`)}async function nD5(A){return tN(A,"GET","/metadata")}async function aD5(A,Q,B){return tN(A,"GET",`/actors/${encodeURIComponent(Q)}/kv/keys/${encodeURIComponent(B)}`)}function Ax(A={}){return A.skipReadyWait===!0}async function XS4(A,Q,B,$={}){let J=null,Y=rD5(A,B,$);if(B.method!=="GET"&&B.method!=="HEAD"){if(B.bodyUsed)throw Error("Request body has already been consumed");let F=await B.arrayBuffer();if(F.byteLength!==0)J=F,Y.delete("transfer-encoding"),Y.set("content-length",String(J.byteLength))}let Z=new Request(Q,{method:B.method,headers:Y,body:J,signal:B.signal});return oD5(await fetch(Z))}function oD5(A){return new Response(A.body,A)}function rD5(A,Q,B){let $=new Headers;Q.headers.forEach((J,Y)=>{$.set(Y,J)});for(let[J,Y]of Object.entries(A.headers))$.set(J,Y);if(A.token)$.set(aJ5,A.token);if(B.directActorId!==void 0)$.set(oJ5,"actor"),$.set(rJ5,B.directActorId);if(Ax(B))$.set(sJ5,"1");return $}var DS4=new Map;function sD5(A,Q,B){if(!B)return;let $=A;$.__rivetGetHibernatableAckState=Q.getState,$.__rivetWaitForHibernatableAck=Q.waitForAck}function tD5(A,Q,B){if(!B)return;sD5(A,{getState:()=>{let $=DS4.get(Q);if(!$)throw Error(`remote hibernatable websocket ack hooks are unavailable for token ${Q}`);return $.getState()},waitForAck:async($)=>{let J=DS4.get(Q);if(!J)throw Error(`remote hibernatable websocket ack hooks are unavailable for token ${Q}`);await J.waitForAck($)}},B)}var eD5=class{CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;#A;#Q=new Map;#B=[];#$=null;#Y=null;#J=null;#F=null;constructor(A){this.#A=A;for(let Q of["open","message","close","error"])this.#A.addEventListener(Q,(B)=>{this.#Z(Q,B)})}get readyState(){return this.#A.readyState}get binaryType(){return this.#A.binaryType}set binaryType(A){this.#A.binaryType=A}get bufferedAmount(){return this.#A.bufferedAmount}get extensions(){return this.#A.extensions}get protocol(){return this.#A.protocol}get url(){return this.#A.url}get onopen(){return this.#$}set onopen(A){this.#$=A,this.#X()}get onclose(){return this.#Y}set onclose(A){this.#Y=A,this.#X()}get onerror(){return this.#J}set onerror(A){this.#J=A,this.#X()}get onmessage(){return this.#F}set onmessage(A){this.#F=A,this.#X()}send(A){this.#A.send(A)}close(A,Q){this.#A.close(A,Q)}addEventListener(A,Q){let B=this.#Q.get(A)??new Set;B.add(Q),this.#Q.set(A,B),this.#X()}removeEventListener(A,Q){var B;(B=this.#Q.get(A))==null||B.delete(Q)}dispatchEvent(A){return this.#U(A.type,A)}#Z(A,Q){if(this.#D(A)){this.#U(A,Q);return}this.#B.push({type:A,event:Q})}#X(){if(this.#B.length===0)return;let A=this.#B;this.#B=[];for(let Q of A){if(this.#D(Q.type)){this.#U(Q.type,Q.event);continue}this.#B.push(Q)}}#D(A){var Q;let B=A==="open"?this.#$:A==="close"?this.#Y:A==="error"?this.#J:A==="message"?this.#F:null;return Boolean(B)||(((Q=this.#Q.get(A))==null?void 0:Q.size)??0)>0}#U(A,Q){let B=this.#Q.get(A);if(B)for(let J of B)J(Q);let $=A==="open"?this.#$:A==="close"?this.#Y:A==="error"?this.#J:A==="message"?this.#F:null;return $==null||$(Q),!0}};function GS4(A,Q,B,$=""){let J=B!==void 0?`@${encodeURIComponent(B)}`:"",Y=`/gateway/${encodeURIComponent(Q)}${J}${$}`;return iy(A,Y)}function AG5(A,Q,B,$,J="",Y=hS4,Z=void 0,F,X={}){if(Q.length===0)throw Error("actor query namespace must not be empty");let D,G=new URLSearchParams;if(G.append("rvt-namespace",Q),"getForKey"in B){if(D=B.getForKey.name,G.append("rvt-method","get"),VS4(G,B.getForKey.key),Z!==void 0)throw Error("Actor query method=get does not support crashPolicy.");if(F!==void 0)throw Error("Actor query method=get does not support runnerName.")}else if("getOrCreateForKey"in B){if(D=B.getOrCreateForKey.name,G.append("rvt-method","getOrCreate"),F===void 0)throw Error("Actor query method=getOrCreate requires runnerName.");if(G.append("rvt-runner",F),VS4(G,B.getOrCreateForKey.key),QG5(G,B.getOrCreateForKey.input,Y),B.getOrCreateForKey.region!==void 0)G.append("rvt-region",B.getOrCreateForKey.region);G.append("rvt-crash-policy",Z??"sleep")}else throw Error("Actor query gateway URLs only support get and getOrCreate.");if(D.length===0)throw Error("actor query name must not be empty");if($!==void 0)G.append("rvt-token",$);if(Ax(X))G.append("rvt-skip-ready-wait","true");let V=G.toString(),U;if(J.endsWith("?")||J.endsWith("&"))U="";else if(J.includes("?"))U="&";else U="?";let K=`/gateway/${encodeURIComponent(D)}${J}${U}${V}`;return iy(A,K)}function VS4(A,Q){if(Q.length>0)A.append("rvt-key",Q.join(","))}function QG5(A,Q,B){if(Q===void 0)return;let $=Xj(Q);if($.byteLength>B)throw Error(`Actor query input exceeds maxInputSize (${$.byteLength} > ${B} bytes). Increase client maxInputSize to allow larger query payloads.`);A.append("rvt-input",BG5($))}function BG5(A){return oZ0(A).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function $G5(A,Q,B,$,J={}){let Y=await Vr0(),Z=typeof process<"u"&&process.env.VITEST?crypto.randomUUID():void 0;b5().debug({msg:"opening websocket to actor via guard",gatewayUrl:Q});let F=new Y(Q,pS4(A,B,$,Z,J.directActorId?{target:"actor",actorId:J.directActorId}:void 0,J));F.binaryType="arraybuffer";let X=new eD5(F);if(Z)tD5(X,Z,!0);return X}function pS4(A,Q,B,$,J,Y={}){let Z=[];if(Z.push(tJ5),Z.push(`${QY5}${Q}`),J){if(Z.push(`${eJ5}${J.target}`),Z.push(`${AY5}${J.actorId}`),A.token)Z.push(`${$Y5}${A.token}`)}if(Ax(Y))Z.push(JY5);if(B)Z.push(`${BY5}${encodeURIComponent(JSON.stringify(B))}`);if($)Z.push(`${YY5}${encodeURIComponent($)}`);return Z}var US4=new Map;async function JG5(A){let Q=$F0(A),B=US4.get(Q);if(B)return B;let $=fa(async()=>{b5().debug({msg:"fetching metadata",endpoint:Q});let J=await nD5(A);return b5().debug({msg:"received metadata",endpoint:Q,clientEndpoint:J.clientEndpoint}),J},{forever:!0,minTimeout:500,maxTimeout:15000,onFailedAttempt:(J)=>{if(J.attemptNumber>1)b5().warn({msg:"failed to fetch metadata, retrying",endpoint:Q,attempt:J.attemptNumber,error:j9(J)})}});return US4.set(Q,$),$}async function YG5(A,Q,B){let $=await Vr0(),J={};return{onOpen:async(Y,Z)=>{if(b5().debug({msg:"client websocket connected",targetUrl:Q}),Z.readyState!==1){b5().warn({msg:"client websocket not open on connection",targetUrl:Q,readyState:Z.readyState});return}let F=new $(Q,B);J.targetWs=F,J.connectPromise=new Promise((X,D)=>{F.addEventListener("open",()=>{if(b5().debug({msg:"target websocket connected",targetUrl:Q}),Z.readyState!==1){b5().warn({msg:"client websocket closed before target connected",targetUrl:Q,clientReadyState:Z.readyState}),F.close(1001,"Client disconnected"),D(Error("Client disconnected"));return}X()}),F.addEventListener("error",(G)=>{b5().warn({msg:"target websocket error during connection",targetUrl:Q}),D(G)})}),J.targetWs.addEventListener("message",(X)=>{if(typeof X.data==="string"||X.data instanceof ArrayBuffer)Z.send(X.data);else if(X.data instanceof Blob)X.data.arrayBuffer().then((D)=>{Z.send(D)})}),J.targetWs.addEventListener("close",(X)=>{b5().debug({msg:"target websocket closed",targetUrl:Q,code:X.code,reason:X.reason}),Ir0(Z,X.code,X.reason)}),J.targetWs.addEventListener("error",(X)=>{b5().error({msg:"target websocket error",targetUrl:Q,error:j9(X)}),Ir0(Z,1011,"Target WebSocket error")})},onMessage:async(Y,Z)=>{if(!J.targetWs||!J.connectPromise){b5().error({msg:"websocket state not initialized",targetUrl:Q});return}try{if(await J.connectPromise,J.targetWs.readyState===$.OPEN)J.targetWs.send(Y.data);else b5().warn({msg:"target websocket not open",targetUrl:Q,readyState:J.targetWs.readyState})}catch(F){b5().error({msg:"failed to connect to target websocket",targetUrl:Q,error:F}),Ir0(Z,1011,"Failed to connect to target")}},onClose:(Y,Z)=>{if(b5().debug({msg:"client websocket closed",targetUrl:Q,code:Y.code,reason:Y.reason,wasClean:Y.wasClean}),J.targetWs){if(J.targetWs.readyState===$.OPEN||J.targetWs.readyState===$.CONNECTING)J.targetWs.close(1000,Y.reason||"Client disconnected")}},onError:(Y,Z)=>{if(b5().error({msg:"client websocket error",targetUrl:Q,event:Y}),J.targetWs){if(J.targetWs.readyState===$.OPEN)J.targetWs.close(1011,"Client WebSocket error");else if(J.targetWs.readyState===$.CONNECTING)J.targetWs.close()}}}}function Ir0(A,Q,B){if(A.readyState===1)A.close(Q,B);else if("close"in A&&A.readyState===WebSocket.OPEN)A.close(Q,B)}var dS4=class{#A;#Q;constructor(A){if(zT4()==="phase-production-build")b5().info("detected next.js build phase, disabling health check"),A.disableMetadataLookup=!0;if(this.#A={...A},!A.disableMetadataLookup)this.#Q=JG5(this.#A).then((Q)=>{if(Q.clientEndpoint){if(this.#A.endpoint=Q.clientEndpoint,Q.clientNamespace)this.#A.namespace=Q.clientNamespace;if(Q.clientToken)this.#A.token=Q.clientToken;b5().info({msg:"overriding client endpoint",endpoint:Q.clientEndpoint,namespace:Q.clientNamespace,token:Q.clientToken})}b5().info({msg:"connected to rivetkit runtime",runtime:Q.runtime,version:Q.version,envoy:Q.envoy})})}async getForId({name:A,actorId:Q}){await this.#Q;let $=(await mD5(this.#A,A,Q)).actors[0];if(!$)return;if($.name!==A){b5().debug({msg:"actor name mismatch from api",actorId:Q,apiName:$.name,requestedName:A});return}return ha($)}async getWithKey({name:A,key:Q}){await this.#Q,b5().debug({msg:"getWithKey: searching for actor",name:A,key:Q});try{let $=(await pD5(this.#A,A,Q)).actors[0];if(!$)return;return b5().debug({msg:"getWithKey: found actor via api",actorId:$.actor_id,name:A,key:Q}),ha($)}catch(B){if(B instanceof R5&&B.group==="actor"&&B.code==="not_found")return;throw B}}async getOrCreateWithKey(A){await this.#Q;let{name:Q,key:B,input:$,region:J,crashPolicy:Y}=A;b5().info({msg:"getOrCreateWithKey: getting or creating actor via engine api",name:Q,key:B});let{actor:Z,created:F}=await cD5(this.#A,{datacenter:J,name:Q,key:uZ0(B),runner_name_selector:this.#A.poolName,input:$?oZ0(Xj($)):void 0,crash_policy:Y??"sleep"});return b5().info({msg:"getOrCreateWithKey: actor ready",actorId:Z.actor_id,name:Q,key:B,created:F}),ha(Z)}async createActor({name:A,key:Q,input:B,region:$,crashPolicy:J}){await this.#Q,b5().info({msg:"creating actor via engine api",name:A,key:Q});let Y=await lD5(this.#A,{datacenter:$,name:A,runner_name_selector:this.#A.poolName,key:uZ0(Q),input:B?oZ0(Xj(B)):void 0,crash_policy:J??"sleep"});return b5().info({msg:"actor created",actorId:Y.actor.actor_id,name:A,key:Q}),ha(Y.actor)}async listActors({name:A}){return await this.#Q,b5().debug({msg:"listing actors via engine api",name:A}),(await dD5(this.#A,A)).actors.map(ha)}async destroyActor(A){await this.#Q,b5().info({msg:"destroying actor via engine api",actorId:A}),await iD5(this.#A,A),b5().info({msg:"actor destroyed",actorId:A})}async sendRequest(A,Q,B={}){await this.#Q;let $=ES4(Q),J=this.#B(A,$,B),Y={...B,directActorId:Ax(B)?wr0(A):void 0};return XS4(this.#A,J,Q,Y)}async openWebSocket(A,Q,B,$,J={}){await this.#Q;let Y=this.#B(Q,A,J);return $G5(this.#A,Y,B,$,{...J,directActorId:Ax(J)?wr0(Q):void 0})}async buildGatewayUrl(A,Q={}){return await this.#Q,this.#B(A,"",Q)}async proxyRequest(A,Q,B){await this.#Q;let $=this.#B({directId:B},ES4(Q));return XS4(this.#A,$,Q)}async proxyWebSocket(A,Q,B,$,J){var Y,Z;await this.#Q;let F=(Z=(Y=this.#A).getUpgradeWebSocket)==null?void 0:Z.call(Y);mS4.default(F,"missing getUpgradeWebSocket");let X=$F0(this.#A),D=iy(X,Q),G=D.replace("http://","ws://");b5().debug({msg:"forwarding websocket to actor via guard",actorId:B,path:Q,guardUrl:D});let V=pS4(this.#A,$,J,void 0,{target:"actor",actorId:B}),U=await YG5(A,G,V);return await F(()=>U)(A,WT4())}async kvGet(A,Q){return await this.#Q,b5().debug({msg:"getting kv value via engine api",key:Q}),(await aD5(this.#A,A,new TextDecoder("utf8").decode(Q))).value}async kvBatchGet(A,Q){throw Error("kvBatchGet not supported on remote engine client")}async kvBatchPut(A,Q){throw Error("kvBatchPut not supported on remote engine client")}async kvBatchDelete(A,Q){throw Error("kvBatchDelete not supported on remote engine client")}async kvDeleteRange(A,Q,B){throw Error("kvDeleteRange not supported on remote engine client")}displayInformation(){return{properties:{}}}setGetUpgradeWebSocket(A){this.#A.getUpgradeWebSocket=A}#B(A,Q,B={}){let $=$F0(this.#A);if(Ax(B)&&wr0(A)&&ZG5(Q))return iy($,Q);if("directId"in A)return GS4($,A.directId,this.#A.token,Q);if("getForId"in A)return GS4($,A.getForId.actorId,this.#A.token,Q);if("getForKey"in A||"getOrCreateForKey"in A)return AG5($,this.#A.namespace,A,this.#A.token,Q,this.#A.maxInputSize,void 0,"getOrCreateForKey"in A?this.#A.poolName:void 0,B);if("create"in A)throw Error("Gateway URLs only support direct actor IDs, get, and getOrCreate targets.");throw Error("unreachable: unknown gateway target type")}};function ZG5(A){return FG5(A)||KS4(A,zS4)||KS4(A,nJ5)||A.startsWith(WS4)}function KS4(A,Q){return A===Q||A.startsWith(`${Q}?`)}function FG5(A){let Q=A.slice(8);return A.startsWith("/request")&&(Q.length===0||Q.startsWith("/")||Q.startsWith("?"))}function wr0(A){if("directId"in A)return A.directId;if("getForId"in A)return A.getForId.actorId;return}function ES4(A){let Q=new URL(A.url);return`${Q.pathname}${Q.search}`}function ha(A){return{actorId:A.actor_id,name:A.name,key:xT4(A.key),createTs:A.create_ts,startTs:A.start_ts??null,connectableTs:A.connectable_ts??null,sleepTs:A.sleep_ts??null,destroyTs:A.destroy_ts??null,error:A.error??void 0}}function XG5(){return cN("devtools")}var DG5=(A=jo0)=>`https://releases.rivet.dev/rivet/latest/devtools/mod.js?v=${A}`,cS4="rivetkit-devtools-script";function GG5(A){if(!window){XG5().warn("devtools not available outside browser environment");return}if(!document.getElementById(cS4)){let Q=document.createElement("script");Q.id=cS4,Q.src=DG5(),Q.async=!0,document.head.appendChild(Q)}window.__rivetkit=window.__rivetkit||[],window.__rivetkit.push(A)}function yr0(A){let Q=A===void 0?{}:typeof A==="string"?{endpoint:A}:A,B=gS4.parse(Q),$=new dS4(B);if(B.devtools)GG5(B);return bS4($,B)}function OU(A){return yr0(A)}var VG5="https://default:uScL4UEKjZsetHm4U495exBWa1WOTmus2UWwhBfo4XJMUuhL6DZIQ8nwx8MACPvV@actors.ampcode.com",UG5="https://default:bvUhSEyRuaUZjf68K05GVMaLRUFRa8ZUIQkcUP9MvOTmkXrS8tYZJ5eFmJOSmO0v@actors.staging.ampcodedev.org";function xr0(A,Q){try{return new URL(A).hostname===Q}catch{return A.includes(Q)}}function KG5(A){return xr0(A,"localhost")||xr0(A,"127.0.0.1")}function EG5(A){return xr0(A,"staging.ampcodedev.org")}function uF(A){if(KG5(A))return $04(process.cwd());if(EG5(A))return UG5;return VG5}async function Yx(A){let Q=uF(A.ampURL),B=OU({endpoint:Q}),$=await A.configService.getLatest(A.signal),J=await $.secrets.getToken("apiKey",$.settings.url);if(!J)throw Error("API key required. Please run `amp login` first.");let Y=await B.threadActor.get([A.threadID]).fetch("/context-analysis",{method:"GET",headers:{Authorization:`Bearer ${J}`},signal:A.signal,skipReadyWait:!0});if(!Y.ok){let F=await Y.text();throw Error(`Context analysis request failed (${Y.status}): ${F}`)}let Z=await Y.json();if(!Z.ok||!Z.analysis)throw Error(Z.error??"Invalid context analysis response from thread actor");return Z.analysis}var{stderr:zG5,stdout:_9}=process;function kD(A,Q=!1){if(Q||A<1000)return A.toLocaleString();return`${(A/1000).toFixed(1)}k`}function lS4(A,Q,B,$,J,Y,Z){return}async function WG5(A,Q,B,$,J,Y,Z,F,X){Y(J,A);let D=await Z(Q,A);try{let G=$.v2===!0;zG5.write(n0.dim(G?`Analyzing context tokens via v2 thread actor...
4623
+ ${U}`)}}if(A.skipParseResponse)return;try{let F=new Uint8Array(await Z.arrayBuffer());return ya(A.encoding,F,A.responseVersionedDataHandler,A.responseZodSchema,A.responseFromJson,A.responseFromBare)}catch(F){throw new ga(`Failed to parse response: ${F}`,{cause:F})}}function yS4(A){async function Q(B,$,J){let Y=(J==null?void 0:J.wait)??!1,Z=J==null?void 0:J.timeout,F=await vr0({url:`http://actor/queue/${encodeURIComponent(B)}`,method:"POST",headers:{[HS4]:A.encoding,...A.params!==void 0?{[Rr0]:JSON.stringify(A.params)}:{}},body:{body:$,wait:Y,timeout:Z},encoding:A.encoding,customFetch:A.customFetch,signal:J==null?void 0:J.signal,requestVersion:ma,requestVersionedDataHandler:ZD5,responseVersion:ma,responseVersionedDataHandler:FD5,requestZodSchema:wD5,responseZodSchema:CD5,requestToJson:(X)=>({...X,name:B}),requestToBare:(X)=>({name:X.name??B,body:xZ0(Xj(X.body)),wait:X.wait??!1,timeout:X.timeout!==void 0?BigInt(X.timeout):null}),responseFromJson:(X)=>{if(X.response===void 0)return{status:X.status};return{status:X.status,response:X.response}},responseFromBare:(X)=>{if(X.response===null||X.response===void 0)return{status:X.status};return{status:X.status,response:Lz(new Uint8Array(X.response))}}});if(Y)return F;return}return{send:Q}}async function vD5(A,Q,B,$,J,Y={}){let Z,F=J||{};if(typeof $==="string")Z=$;else if($ instanceof URL)Z=$.pathname+$.search;else if($ instanceof Request){let X=new URL($.url);Z=X.pathname+X.search;let D=new Headers($.headers),G=new Headers((J==null?void 0:J.headers)||{}),V=new Headers(D);if(G.forEach((U,K)=>{V.set(K,U)}),F={method:$.method,body:$.body,mode:$.mode,credentials:$.credentials,redirect:$.redirect,referrer:$.referrer,referrerPolicy:$.referrerPolicy,integrity:$.integrity,keepalive:$.keepalive,signal:$.signal,...F,headers:V},F.body)F.duplex="half"}else throw TypeError("Invalid input type for fetch");try{g4().debug("directId"in Q?{msg:"sending raw http request to actor",actorId:Q.directId}:{msg:"sending raw http request with actor query",query:Q});let X=Z.startsWith("/")?Z.slice(1):Z,D=new URL(`http://actor/request/${X}`),G=new Headers(F.headers);if(B)G.set(Rr0,JSON.stringify(B));let V=new Request(D,{...F,headers:G});return A.sendRequest(Q,V,Y)}catch(X){let{group:D,code:G,message:V,metadata:U,actor:K}=Na(X,!0);throw new R5(D,G,V,{metadata:U,actor:K})}}async function yD5(A,Q,B,$,J,Y={}){let F="",X="";if($){let V=$.indexOf("?");if(V!==-1)F=$.substring(0,V),X=$.substring(V);else F=$;if(F.startsWith("/"))F=F.slice(1)}let D=`${WS4}${F}${X}`;return g4().debug({msg:"opening websocket",target:Q,encoding:"bare",path:D}),await A.openWebSocket(D,Q,"bare",B,Y)}async function xS4(A,Q){if("directId"in Q)return Q.directId;if("getForId"in Q)return Q.getForId.actorId;if("getForKey"in Q){let B=await A.getWithKey({name:Q.getForKey.name,key:Q.getForKey.key});if(!B)throw XP4(`${Q.getForKey.name}:${JSON.stringify(Q.getForKey.key)}`);return B.actorId}if("getOrCreateForKey"in Q)return(await A.getOrCreateWithKey({name:Q.getOrCreateForKey.name,key:Q.getOrCreateForKey.key,input:Q.getOrCreateForKey.input,region:Q.getOrCreateForKey.region})).actorId;if("create"in Q)return(await A.createActor({name:Q.create.name,key:Q.create.key,input:Q.create.input,region:Q.create.region})).actorId;throw VZ0("Invalid query format")}var xD5=class{#A;#Q;#B;#$;#Y;#J;#F;#Z;#X;#D=new ok4;constructor(A,Q,B,$,J,Y,Z={}){this.#A=A,this.#Q=Q,this.#B=J,this.#$=Y,this.#Y=Z,this.#J=B,this.#F=$}async#U(){if(this.#F)return await this.#F();return this.#J}send(A,Q,B){return this.#K(A,Q,B)}async#K(A,Q,B){return await this.#D.run(async()=>{let $=this.#H(),J=!1;for(let Y=0;Y<$;Y++){let Z;try{let F=ey(this.#Y),X=await this.#w(J,F);return Z="directId"in X?X.directId:void 0,await yS4({encoding:this.#B,params:this.#J,customFetch:async(D)=>{return await this.#Q.sendRequest(X,D,F)}}).send(A,Q,B)}catch(F){let{group:X,code:D,message:G,metadata:V,actor:U}=Na(F,!0);if(this.#E(X,D,V,Y,$)){await this.#V();continue}if(await this.#C(X,D,Z,Y,$)){J=!0,await this.#V();continue}if(this.#W(X,D,Y,$)){this.#G(),J=!0,await this.#V();continue}if(this.#q(X,D)&&Y<$-1){if(J=D==="starting"||D==="stopping"||D.startsWith("destroyed_"),J)await this.#V();continue}throw new R5(X,D,G,{metadata:V,actor:U})}}throw Error("unreachable queue retry state")})}async action(A){if(typeof A==="string"||typeof A!=="object"||A===null||!("name"in A))throw Error(`Invalid action call: expected an options object { name, args }, got ${typeof A}. Use handle.actionName(...args) for the shorthand API.`);let Q=async()=>await this.#z(A);if(A.name==="destroy")return await Q();return await TD5(Q,{signal:A.signal})}async#z(A){let Q=this.#H(),B=!1,$=ey(this.#Y,A);for(let J=0;J<Q;J++){let Y;try{let Z=await this.#w(B,$);Y="directId"in Z?Z.directId:void 0,g4().debug(Y?{msg:"using direct actor gateway target",actorId:Y}:{msg:"using query gateway target for action",query:this.#$}),g4().debug({msg:"handling action",name:A.name,encoding:this.#B});let F=await vr0({url:`http://actor/action/${encodeURIComponent(A.name)}`,method:"POST",headers:{[HS4]:this.#B,...this.#J!==void 0?{[Rr0]:JSON.stringify(this.#J)}:{}},body:A.args,encoding:this.#B,customFetch:async(X)=>await this.#Q.sendRequest(Z,X,$),signal:A==null?void 0:A.signal,requestVersion:ma,requestVersionedDataHandler:JD5,responseVersion:ma,responseVersionedDataHandler:YD5,requestZodSchema:ND5,responseZodSchema:ID5,requestToJson:(X)=>({args:X}),requestToBare:(X)=>({args:xZ0(Xj(X))}),responseFromJson:(X)=>X.output,responseFromBare:(X)=>Lz(new Uint8Array(X.output))});if(A.name==="destroy"&&Y)await this.#N(Y);return F}catch(Z){let{group:F,code:X,message:D,metadata:G,actor:V}=Na(Z,!0);if(await this.#C(F,X,Y,J,Q)){B=!0,await this.#V();continue}if(A.name!=="destroy"&&this.#W(F,X,J,Q)){this.#G(),B=!0,await this.#V();continue}if(F==="actor"&&X==="destroyed_while_waiting_for_ready"&&"getForId"in this.#$)throw new R5("actor","not_found","The actor does not exist or was destroyed.",{metadata:G,actor:V});if(this.#q(F,X)&&J<Q-1){if(F==="actor"&&(X==="starting"||X==="stopping"))B=!0,await new Promise((K)=>setTimeout(K,100));continue}throw new R5(F,X,D,{metadata:G,actor:V})}}throw Error("unreachable action retry state")}async#N(A){let Q=TS4(this.#$),B=Date.now()+1000;while(Date.now()<B){if(!await this.#Q.getForId({name:Q,actorId:A}))return;await new Promise((J)=>setTimeout(J,25))}}async#V(){await new Promise((A)=>setTimeout(A,100))}#H(){if(!rN(this.#$))return 1;return"getOrCreateForKey"in this.#$?60:24}#W(A,Q,B,$){if(!rN(this.#$)||B>=$-1||A!=="actor")return!1;return Q==="not_found"||Q==="starting"||Q==="stopping"||Q==="not_configured"||Q==="dropped_reply"||Q==="destroying"||Q.startsWith("destroyed_")}#E(A,Q,B,$,J){if(!rN(this.#$)||$>=J-1||A!=="actor"||Q!=="overloaded"||B===null||typeof B!=="object")return!1;let Y=B;return Y.channel==="dispatch_inbox"&&Y.operation==="dispatch_queue_send"}#G(){this.#Z=void 0,this.#X=void 0}async#C(A,Q,B,$,J){if(!rN(this.#$)||!Cr0(A,Q)||$>=J-1)return!1;if(B){let Y=await Or0(A,Q,B,this.#$,this.#Q);if(Y)throw Y}return this.#G(),!0}#q(A,Q){if(!rN(this.#$)||!Lr0(A,Q))return!1;return this.#G(),!0}async#L(A){if("getForId"in this.#$)return Vj(this.#$);if(A)return Vj(this.#$);if(this.#Z)return{directId:this.#Z};if(!this.#X)this.#X=xS4(this.#Q,this.#$).then((Q)=>{return this.#Z=Q,Q});try{return{directId:await this.#X}}finally{this.#X=void 0}}async#w(A,Q){if(Q.skipReadyWait)return Vj(this.#$);return await this.#L(A)}connect(A,Q={}){g4().debug({msg:"establishing connection from handle",query:this.#$});let B=A===void 0?this.#J:A,$=A===void 0?this.#F:void 0,J=new bD5(this.#A,this.#Q,B,$,this.#B,this.#$,ey(this.#Y,Q));return this.#A[fS4](J)}fetch(A,Q){return this.#M(A,Q)}async#M(A,Q){let B=this.#H(),$=!1,{skipReadyWait:J,...Y}=Q??{},Z=ey(this.#Y,{skipReadyWait:J});for(let F=0;F<B;F++){let X;try{let D=await this.#w($,Z);X="directId"in D?D.directId:void 0;let G=await vD5(this.#Q,D,this.#J,A,Y,Z),V=await this.#I(G,X,F,B);if(V){if($=V.useQueryTarget,V.waitForRetryWindow)await this.#V();continue}return G}catch(D){let{group:G,code:V,message:U,metadata:K,actor:E}=Na(D,!0);if(await this.#C(G,V,X,F,B)){$=!0,await this.#V();continue}if(this.#W(G,V,F,B)){this.#G(),$=!0,await this.#V();continue}if(this.#q(G,V)&&F<B-1){if($=V==="starting"||V==="stopping"||V.startsWith("destroyed_"),$)await this.#V();continue}throw new R5(G,V,U,{metadata:K,actor:E})}}throw Error("unreachable fetch retry state")}async#I(A,Q,B,$){if(A.ok||!rN(this.#$))return null;let J=await this.#O(A);if(!J)return null;let{group:Y,code:Z}=J;if(await this.#C(Y,Z,Q,B,$))return{useQueryTarget:!0,waitForRetryWindow:!0};if(this.#W(Y,Z,B,$))return this.#G(),{useQueryTarget:!0,waitForRetryWindow:!0};if(this.#q(Y,Z)&&B<$-1){let X=Z==="starting"||Z==="stopping"||Z.startsWith("destroyed_");return{useQueryTarget:X,waitForRetryWindow:X}}return null}async#O(A){if(A.ok)return null;let Q=A.headers.get("content-type"),B=(Q==null?void 0:Q.includes("application/json"))?"json":this.#B;try{return ya(B,new Uint8Array(await A.clone().arrayBuffer()),RS4,_S4,($)=>({...$,actor:$.actor?{...$.actor,generation:Number($.actor.generation)}:void 0}),($)=>({group:$.group,code:$.code,message:$.message,metadata:$.metadata?Lz(new Uint8Array($.metadata)):void 0,actor:$.actor?{actorId:$.actor.actorId,generation:Number($.actor.generation),key:$.actor.key??void 0}:void 0}))}catch{return null}}async webSocket(A,Q,B={}){let $=await this.#U(),J=ey(this.#Y,B),Y=await this.#w(!1,J);return await yD5(this.#Q,Y,$,A,Q,J)}async resolve(){if("getForId"in this.#$)return this.#$.getForId.actorId;let A=await this.#L(!1);if("directId"in A)return A.directId;throw Error("dynamic actor resolution did not produce a direct actor id")}async getGatewayUrl(){return await this.#Q.buildGatewayUrl(Vj(this.#$),this.#Y)}async reload(){let A=Vj(this.#$),Q=new Request("http://actor/dynamic/reload",{method:"PUT"}),B=await this.#Q.sendRequest(A,Q);if(!B.ok){let $=await B.text().catch(()=>"");throw new R5("actor","reload_failed",`reload failed with status ${B.status}: ${$}`,{})}}},BF0=Symbol("actorConns"),fS4=Symbol("createActorConnProxy"),fD5=class{#A=!1;[BF0]=new Set;#Q;#B;#$;constructor(A,Q,B={}){this.#Q=A,this.#B=Q??"bare",this.#$=B}getForId(A,Q,B){g4().debug({msg:"get handle to actor with id",name:A,actorId:Q,params:B==null?void 0:B.params});let $={getForId:{name:A,actorId:Q}},J=this.#Y(B==null?void 0:B.params,B==null?void 0:B.getParams,$);return ua(J)}get(A,Q,B){let $=typeof Q==="string"?[Q]:Q||[];g4().debug({msg:"get handle to actor",name:A,key:$,parameters:B==null?void 0:B.params});let J={getForKey:{name:A,key:$}},Y=this.#Y(B==null?void 0:B.params,B==null?void 0:B.getParams,J);return ua(Y)}getOrCreate(A,Q,B){let $=typeof Q==="string"?[Q]:Q||[];g4().debug({msg:"get or create handle to actor",name:A,key:$,parameters:B==null?void 0:B.params,createInRegion:B==null?void 0:B.createInRegion});let J={getOrCreateForKey:{name:A,key:$,input:B==null?void 0:B.createWithInput,region:B==null?void 0:B.createInRegion}},Y=this.#Y(B==null?void 0:B.params,B==null?void 0:B.getParams,J);return ua(Y)}async create(A,Q,B){let $=typeof Q==="string"?[Q]:Q||[],J={create:{...B,name:A,key:$}};g4().debug({msg:"create actor handle",name:A,key:$,parameters:B==null?void 0:B.params,create:J.create});let Y=await xS4(this.#Q,J);g4().debug({msg:"created actor with ID",name:A,key:$,actorId:Y});let Z={getForId:{name:A,actorId:Y}},F=this.#Y(B==null?void 0:B.params,B==null?void 0:B.getParams,Z);return ua(F)}#Y(A,Q,B){return new xD5(this,this.#Q,A,Q,this.#B,B,this.#$)}[fS4](A){return this[BF0].add(A),A[uS4](),ua(A)}async dispose(){if(this.#A){g4().warn({msg:"client already disconnected"});return}this.#A=!0,g4().debug({msg:"disposing client"});let A=[];for(let Q of this[BF0].values())A.push(Q.dispose());await Promise.all(A)}};function bS4(A,Q={}){let B=new fD5(A,Q.encoding,Q.gateway);return new Proxy(B,{get:($,J,Y)=>{if(typeof J==="symbol"||J in $){let Z=Reflect.get($,J,Y);if(typeof Z==="function")return Z.bind($);return Z}if(typeof J==="string")return{get:(Z,F)=>{return $.get(J,Z,F)},getOrCreate:(Z,F)=>{return $.getOrCreate(J,Z,F)},getForId:(Z,F)=>{return $.getForId(J,Z,F)},create:async(Z,F={})=>{return await $.create(J,Z,F)}};return}})}function ua(A){let Q=new Map;return new Proxy(A,{get(B,$,J){if(typeof $==="symbol")return Reflect.get(B,$,J);if($==="constructor"||$ in B){let Y=Reflect.get(B,$,B);if(typeof Y==="function")return Y.bind(B);return Y}if(typeof $==="string"){if($==="then")return;let Y=Q.get($);if(!Y)Y=(...Z)=>B.action({name:$,args:Z}),Q.set($,Y);return Y}},has(B,$){if(typeof $==="string")return!0;return Reflect.has(B,$)},getPrototypeOf(B){return Reflect.getPrototypeOf(B)},ownKeys(B){return Reflect.ownKeys(B)},getOwnPropertyDescriptor(B,$){let J=Reflect.getOwnPropertyDescriptor(B,$);if(J)return J;if(typeof $==="string")return{configurable:!0,enumerable:!1,writable:!1,value:(...Y)=>B.action({name:$,args:Y})};return}})}var Nr0=65536,uS4=Symbol("connect"),bD5=class{#A=!1;#Q=new AbortController;#B="idle";#$;#Y;#J=[];#F=new Map;#Z=new Map;#X=new Set;#D=new Set;#U=!1;#K=new Set;#z=new Set;#N=0;#V;#H;#W;#E;#G;#C;#q;#L;#w;#M;#I;#O;constructor(A,Q,B,$,J,Y,Z={}){this.#C=A,this.#q=Q,this.#L=B,this.#w=$,this.#M=J,this.#I=Y,this.#O=ey(Z),this.#H=ly((F)=>g4().warn({msg:"unhandled ready promise rejection",reason:F})),this.#V=yS4({encoding:this.#M,params:this.#L,customFetch:async(F)=>{return await this.#q.sendRequest(Vj(this.#I),F,this.#O)}}),this.#W=setInterval(()=>60000)}#_(){this.#$=void 0,this.#Y=void 0}#T(A,Q){if(!rN(this.#I)||!Lr0(A,Q))return!1;return this.#_(),!0}#k(A,Q){return rN(this.#I)&&Lr0(A,Q)&&this.#E!==void 0&&this.#B!=="connected"}send(A,Q,B){return this.#h(A,Q,B)}async#h(A,Q,B){return await this.#V.send(A,Q,B)}async action(A){if(typeof A==="string"||typeof A!=="object"||A===null||!("name"in A))throw Error(`Invalid action call: expected an options object { name, args }, got ${typeof A}. Use conn.actionName(...args) for the shorthand API.`);g4().debug({msg:"action",name:A.name,args:A.args});let Q=this.#N;this.#N+=1;let{promise:B,resolve:$,reject:J}=ly((F)=>g4().warn({msg:"unhandled action promise rejection",reason:F}));this.#F.set(Q,{name:A.name,resolve:$,reject:J}),g4().debug({msg:"added action to in-flight map",actionId:Q,actionName:A.name,inFlightCount:this.#F.size}),this.#v({body:{tag:"ActionRequest",val:{id:BigInt(Q),name:A.name,args:A.args}}});let{id:Y,output:Z}=await B;if(Y!==BigInt(Q))throw Error(`Request ID ${Q} does not match response ID ${Y}`);return Z}[uS4](){this.#x()}#j(A){let Q=this.#B;if(Q===A)return;this.#B=A;for(let B of[...this.#z])try{B(A)}catch($){g4().error({msg:"error in status change handler",error:j9($)})}if(A==="connected"){this.#H.resolve(void 0);for(let B of[...this.#D])try{B()}catch($){g4().error({msg:"error in open handler",error:j9($)})}}if((A==="disconnected"||A==="idle")&&Q==="connected")for(let B of[...this.#K])try{B()}catch($){g4().error({msg:"error in close handler",error:j9($)})}}#x(){this.#j("connecting"),fa(this.#g.bind(this),{forever:!0,minTimeout:250,maxTimeout:30000,onFailedAttempt:(A)=>{g4().warn({msg:"failed to reconnect",attempt:A.attemptNumber,error:j9(A)})},signal:this.#Q.signal}).catch((A)=>{if(A instanceof xa||A.name==="AbortError"||!this.#f(A))g4().info({msg:"connection retry aborted"});else g4().error({msg:"unexpected error in connection retry",error:j9(A)})})}async#g(){try{if(this.#E)throw Error("#onOpenPromise already defined");this.#E=ly((A)=>g4().warn({msg:"unhandled open promise rejection",reason:A})),await this.#p(),await this.#E.promise}catch(A){if(this.#f(A))throw A;let Q=A instanceof R5?A:new R5("client","connection_open_failed",`Failed to open connection: ${j9(A)}`,{error:j9(A)});throw this.#b(),this.#R(Q,!1),this.#P(Q),this.#j("idle"),new xa(A instanceof Error?A:Error(j9(A)))}finally{this.#E=void 0}}#f(A){if(A instanceof QF0)return!1;if(A instanceof R5&&this.#k(A.group,A.code))return!0;if(A instanceof R5&&A.group==="client"&&A.code==="get_params_failed")return!0;return PD5(A)}#b(){if(this.#J.length===0)return;g4().debug({msg:"clearing queued connection messages",queueLength:this.#J.length}),this.#J=[]}async#m(){if(!this.#w)return this.#L;try{return await this.#w()}catch(A){let Q=j9(A),B=new R5("client","get_params_failed",`Failed to resolve connection params: ${Q}`,{error:Q});throw this.#b(),this.#R(B,!1),this.#P(B),B}}async#p(){let A=await this.#m(),Q=Vj(this.#I),B=await this.#q.openWebSocket(zS4,Q,this.#M,A,this.#O);Mr0.default(B,"websocket should have been created"),g4().debug({msg:"opened websocket",connId:this.#Y,readyState:B.readyState,messageQueueLength:this.#J.length}),this.#G=B,B.addEventListener("open",()=>{g4().debug({msg:"client websocket open",connId:this.#Y})}),B.addEventListener("message",async($)=>{try{await this.#c($.data)}catch(J){g4().error({msg:"error in websocket message handler",error:j9(J)})}}),B.addEventListener("close",async($)=>{try{await this.#l($)}catch(J){g4().error({msg:"error in websocket close handler",error:j9(J)})}}),B.addEventListener("error",()=>{try{this.#i()}catch($){g4().error({msg:"error in websocket error handler",error:j9($)})}})}#d(){if(this.#A){if(g4().debug({msg:"handleOnOpen called after dispose, closing websocket"}),this.#G)this.#G.close(1000,"Disposed"),this.#G=void 0;return}if(this.#B==="connected"||this.#U)return;this.#U=!0,queueMicrotask(()=>{if(this.#U=!1,this.#A){if(g4().debug({msg:"handleOnOpen scheduled after dispose, closing websocket"}),this.#G)this.#G.close(1000,"Disposed"),this.#G=void 0;return}if(g4().debug({msg:"socket open",messageQueueLength:this.#J.length,connId:this.#Y}),this.#j("connected"),this.#E)this.#E.resolve(void 0);else g4().warn({msg:"#onOpenPromise is undefined"});for(let Q of this.#Z.keys())this.#y(Q,!0);let A=this.#J;this.#J=[],g4().debug({msg:"flushing message queue",queueLength:A.length});for(let Q of A)this.#v(Q)})}async#c(A){var Q;g4().trace({msg:"received message",dataType:typeof A,isBlob:A instanceof Blob,isArrayBuffer:A instanceof ArrayBuffer});let B=await this.#a(A);if(g4().trace(ET4()?{msg:"parsed message",message:Dr0(B).substring(0,100)+"..."}:{msg:"parsed message"}),B.body.tag==="Init")this.#$=B.body.val.actorId,this.#Y=B.body.val.connectionId,g4().trace({msg:"received init message",actorId:this.#$,connId:this.#Y}),this.#d();else if(B.body.tag==="Error"){let{group:$,code:J,message:Y,metadata:Z,actionId:F,actor:X}=B.body.val;if(F!==null){let D=this.#S(Number(F));this.#T($,J),g4().warn({msg:"action error",actionId:F,actionName:D==null?void 0:D.name,group:$,code:J,message:Y,metadata:Z,actorId:X==null?void 0:X.actorId,generation:X==null?void 0:X.generation,actorKey:X==null?void 0:X.key}),D.reject(new R5($,J,Y,{metadata:Z,actor:X}))}else{if(g4().warn({msg:"connection error",group:$,code:J,message:Y,metadata:Z,actorId:X==null?void 0:X.actorId,generation:X==null?void 0:X.generation,actorKey:X==null?void 0:X.key}),this.#k($,J)){this.#_(),(Q=this.#E)==null||Q.reject(new R5($,J,Y,{metadata:Z,actor:X}));return}let D=new R5($,J,Y,{metadata:Z,actor:X});if(Cr0($,J)&&this.#$){let G=await Or0($,J,this.#$,this.#I,this.#q);if(G)D=G}if(this.#E)this.#E.reject(D);this.#T($,J);for(let[G,V]of this.#F.entries())V.reject(D),this.#F.delete(G);this.#P(D)}}else if(B.body.tag==="ActionResponse"){let{id:$}=B.body.val;g4().debug({msg:"received action response",actionId:Number($),inFlightCount:this.#F.size,inFlightIds:Array.from(this.#F.keys())});let J=this.#S(Number($));g4().trace({msg:"resolving action promise",actionId:$,actionName:J==null?void 0:J.name}),J.resolve(B.body.val)}else if(B.body.tag==="Event")g4().trace({msg:"received event",name:B.body.val.name}),this.#n(B.body.val);else Bj(B.body)}async#l(A){var Q;let B=A,$=B.wasClean,J=this.#B==="connected";if(g4().info({msg:"socket closed",code:B.code,reason:B.reason,wasClean:$,disposed:this.#A,connId:this.#Y}),this.#G=void 0,this.#A)this.#R(new QF0,!0);else{this.#j("disconnected");let Y,Z=B.reason||"",F=kD5(Z);if(F){let{group:X,code:D}=F;if(this.#k(X,D)){this.#_(),(Q=this.#E)==null||Q.reject(new R5(X,D,`Connection closed: ${Z}`,void 0));return}if(Cr0(X,D)&&this.#$){let G=await Or0(X,D,this.#$,this.#I,this.#q);if(G)Y=G;else Y=new R5(X,D,`Connection closed: ${Z}`,void 0)}else Y=new R5(X,D,`Connection closed: ${Z}`,void 0);this.#T(X,D)}else Y=Error(`${$?"Connection closed":"Connection lost"} (code: ${B.code}, reason: ${Z})`);if(this.#R(Y,!1),Y instanceof R5)this.#P(Y);if(J)g4().debug({msg:"triggering reconnect",connId:this.#Y}),this.#x()}}#R(A,Q){if(this.#E){if(Q)this.#E.promise.catch(()=>{});this.#E.reject(A)}for(let B of this.#F.values())B.reject(A);this.#F.clear()}#i(){if(this.#A)return;g4().warn("socket error")}#S(A){let Q=this.#F.get(A);if(!Q)throw g4().error({msg:"action not found in in-flight map",lookupId:A,inFlightCount:this.#F.size,inFlightIds:Array.from(this.#F.keys()),inFlightActions:Array.from(this.#F.entries()).map(([B,$])=>({id:B,name:$.name}))}),FY5(`No in flight response for ${A}`);return this.#F.delete(A),g4().debug({msg:"removed action from in-flight map",actionId:A,actionName:Q.name,inFlightCount:this.#F.size}),Q}#n(A){let{name:Q,args:B}=A,$=this.#Z.get(Q);if(!$)return;for(let J of[...$])if(J.callback(...B),J.once)$.delete(J);if($.size===0)this.#Z.delete(Q)}#P(A){for(let Q of[...this.#X])try{Q(A)}catch(B){g4().error({msg:"error in connection error handler",error:j9(B)})}}#u(A,Q,B){let $={callback:Q,once:B},J=this.#Z.get(A);if(J===void 0)J=new Set,this.#Z.set(A,J),this.#y(A,!0);return J.add($),()=>{let Y=this.#Z.get(A);if(Y){if(Y.delete($),Y.size===0)this.#Z.delete(A),this.#y(A,!1)}}}on(A,Q){return this.#u(A,Q,!1)}once(A,Q){return this.#u(A,Q,!0)}onError(A){return this.#X.add(A),()=>{this.#X.delete(A)}}get connStatus(){return this.#B}get isConnected(){return this.#B==="connected"}get ready(){return this.#H.promise}onOpen(A){if(this.#D.add(A),this.#B==="connected")queueMicrotask(()=>{if(!this.#D.has(A))return;try{A()}catch(Q){g4().error({msg:"error in open handler",error:j9(Q)})}});return()=>{this.#D.delete(A)}}onClose(A){return this.#K.add(A),()=>{this.#K.delete(A)}}onStatusChange(A){return this.#z.add(A),()=>{this.#z.delete(A)}}#v(A,Q){var B,$;if(this.#A)if(Q==null?void 0:Q.ephemeral)return;else throw new QF0;let J=!1;if(this.#G){let Y=this.#G.readyState;if(g4().debug({msg:"websocket send attempt",readyState:Y,readyStateString:Y===0?"CONNECTING":Y===1?"OPEN":Y===2?"CLOSING":"CLOSED",connId:this.#Y,messageType:A.body.tag,actionName:(B=A.body.val)==null?void 0:B.name}),this.#B!=="connected")g4().debug({msg:"websocket init pending, queueing message",connStatus:this.#B,messageType:A.body.tag}),J=!0;else if(Y===1)try{let Z=Gr0(this.#M,A,BD5,ma,qD5,(X)=>X,(X)=>{if(X.body.tag==="ActionRequest")return{body:{tag:"ActionRequest",val:{id:X.body.val.id,name:X.body.val.name,args:xZ0(Xj(X.body.val.args))}}};else return X}),F=SD5(Z);if(F>Nr0&&A.body.tag==="ActionRequest"){let X=Number(A.body.val.id),D=this.#S(X),G=new R5("message","incoming_too_long","Incoming message too long",{maxSize:Nr0,actualSize:F});g4().warn({msg:"rejecting oversized connection action request",actionId:X,actionName:D.name,actualSize:F,maxSize:Nr0}),D.reject(G),this.#P(G);return}this.#G.send(Z),g4().trace({msg:"sent websocket message",len:F})}catch(Z){g4().warn({msg:"failed to send message, added to queue",error:Z,connId:this.#Y}),J=!0}else g4().debug({msg:"websocket not open, queueing message",readyState:Y}),J=!0}else g4().debug({msg:"no websocket, queueing message"}),J=!0;if(!(Q==null?void 0:Q.ephemeral)&&J)this.#J.push(A),g4().debug({msg:"queued connection message",queueLength:this.#J.length,connId:this.#Y,messageType:A.body.tag,actionName:($=A.body.val)==null?void 0:$.name})}async#a(A){Mr0.default(this.#G,"websocket must be defined");let Q=await ck4(A);return ya(this.#M,Q,$D5,ED5,(B)=>{if(B.body.tag!=="Error"||!B.body.val.actor)return B;return{body:{tag:"Error",val:{...B.body.val,actor:{...B.body.val.actor,generation:Number(B.body.val.actor.generation)}}}}},(B)=>{if(B.body.tag==="Error")return{body:{tag:"Error",val:{group:B.body.val.group,code:B.body.val.code,message:B.body.val.message,metadata:B.body.val.metadata?Lz(new Uint8Array(B.body.val.metadata)):null,actionId:B.body.val.actionId,actor:B.body.val.actor?{actorId:B.body.val.actor.actorId,generation:Number(B.body.val.actor.generation),key:B.body.val.actor.key??void 0}:void 0}}};else if(B.body.tag==="ActionResponse")return{body:{tag:"ActionResponse",val:{id:B.body.val.id,output:Lz(new Uint8Array(B.body.val.output))}}};else if(B.body.tag==="Event")return{body:{tag:"Event",val:{name:B.body.val.name,args:Lz(new Uint8Array(B.body.val.args))}}};else return B})}get actorId(){return this.#$}get connId(){return this.#Y}get connectionId(){return this.#Y}async dispose(){if(this.#A){g4().warn({msg:"connection already disconnected"});return}if(this.#A=!0,g4().debug({msg:"disposing actor conn"}),this.#j("idle"),clearInterval(this.#W),this.#Q.abort(),this.#C[BF0].delete(this),this.#G){let A=this.#G;if(A.readyState!==2&&A.readyState!==3){let{promise:Q,resolve:B}=ly(($)=>g4().warn({msg:"unhandled websocket close promise rejection",reason:$}));A.addEventListener("close",()=>B(void 0)),A.close(1000,"Disposed"),await Q}}else this.#R(new QF0,!0);this.#G=void 0}#y(A,Q){this.#v({body:{tag:"SubscriptionRequest",val:{eventName:A,subscribe:Q}}},{ephemeral:!0})}};function uD5(A,Q){let{endpoint:B,path:$=["endpoint"],namespace:J,token:Y}=Q,Z;try{Z=new URL(B)}catch{A.addIssue({code:"custom",message:`invalid URL: ${B}`,path:$});return}if(Z.search){A.addIssue({code:"custom",message:"endpoint cannot contain a query string",path:$});return}if(Z.hash){A.addIssue({code:"custom",message:"endpoint cannot contain a fragment",path:$});return}let F=Z.username?decodeURIComponent(Z.username):void 0,X=Z.password?decodeURIComponent(Z.password):void 0;if(X&&!F){A.addIssue({code:"custom",message:"endpoint cannot have a token without a namespace",path:$});return}if(F&&J)A.addIssue({code:"custom",message:"cannot specify namespace both in endpoint URL and as a separate config option",path:["namespace"]});if(X&&Y)A.addIssue({code:"custom",message:"cannot specify token both in endpoint URL and as a separate config option",path:["token"]});return Z.username="",Z.password="",{endpoint:Z.toString(),namespace:F,token:X}}var ZS4="http://localhost:6420",hS4=4096,FS4=!1,hD5=_B.object({endpoint:_B.string().optional().transform((A)=>{let Q=A??DT4()??GT4();if(!Q&&!FS4)FS4=!0,console.warn(`[rivetkit] No endpoint provided to client. Defaulting to ${ZS4}. Starting in 2.2.0, an explicit endpoint will be required. Pass an endpoint to createClient() or createRivetKit(), or set the RIVET_ENDPOINT environment variable.`);return Q??ZS4}),token:_B.string().optional().transform((A)=>A??VT4()),namespace:_B.string().optional().transform((A)=>A??UT4()),poolName:_B.string().default(()=>KT4()??"default"),encoding:dk4.default("bare"),headers:_B.record(_B.string(),_B.string()).optional().default(()=>({})),gateway:_B.object({skipReadyWait:_B.boolean().optional().default(!1)}).optional().default(()=>({skipReadyWait:!1})),getUpgradeWebSocket:_B.custom().optional(),disableMetadataLookup:_B.boolean().optional().default(!1),maxInputSize:_B.number().int().positive().default(hS4),devtools:_B.boolean().default(()=>{var A,Q;return typeof window<"u"&&(((A=window==null?void 0:window.location)==null?void 0:A.hostname)==="127.0.0.1"||((Q=window.location)==null?void 0:Q.hostname)==="localhost")})}),gS4=hD5.transform((A,Q)=>gD5(A,Q));function gD5(A,Q){let B=uD5(Q,{endpoint:A.endpoint,path:["endpoint"],namespace:A.namespace,token:A.token});return{...A,endpoint:B==null?void 0:B.endpoint,namespace:(B==null?void 0:B.namespace)??A.namespace??"default",token:(B==null?void 0:B.token)??A.token}}function b5(){return cN("engine-client")}function $F0(A){return A.endpoint??"http://127.0.0.1:6420"}async function tN(A,Q,B,$){let J=$F0(A),Y=iy(J,B,{namespace:A.namespace});b5().debug({msg:"making api call",method:Q,url:Y});let Z={...A.headers};if(A.token)Z.Authorization=`Bearer ${A.token}`;return await vr0({method:Q,url:Y,headers:Z,body:$,encoding:"json",skipParseResponse:!1,requestVersionedDataHandler:void 0,requestVersion:void 0,responseVersionedDataHandler:void 0,responseVersion:void 0,requestZodSchema:b.any(),responseZodSchema:b.any(),requestToJson:(F)=>F,requestToBare:(F)=>F,responseFromJson:(F)=>F,responseFromBare:(F)=>F})}async function mD5(A,Q,B){return tN(A,"GET",`/actors?actor_ids=${encodeURIComponent(B)}`)}async function pD5(A,Q,B){let $=uZ0(B);return tN(A,"GET",`/actors?name=${encodeURIComponent(Q)}&key=${encodeURIComponent($)}`)}async function dD5(A,Q){return tN(A,"GET",`/actors?name=${encodeURIComponent(Q)}`)}async function cD5(A,Q){return tN(A,"PUT","/actors",Q)}async function lD5(A,Q){return tN(A,"POST","/actors",Q)}async function iD5(A,Q){return tN(A,"DELETE",`/actors/${encodeURIComponent(Q)}`)}async function nD5(A){return tN(A,"GET","/metadata")}async function aD5(A,Q,B){return tN(A,"GET",`/actors/${encodeURIComponent(Q)}/kv/keys/${encodeURIComponent(B)}`)}function Ax(A={}){return A.skipReadyWait===!0}async function XS4(A,Q,B,$={}){let J=null,Y=rD5(A,B,$);if(B.method!=="GET"&&B.method!=="HEAD"){if(B.bodyUsed)throw Error("Request body has already been consumed");let F=await B.arrayBuffer();if(F.byteLength!==0)J=F,Y.delete("transfer-encoding"),Y.set("content-length",String(J.byteLength))}let Z=new Request(Q,{method:B.method,headers:Y,body:J,signal:B.signal});return oD5(await fetch(Z))}function oD5(A){return new Response(A.body,A)}function rD5(A,Q,B){let $=new Headers;Q.headers.forEach((J,Y)=>{$.set(Y,J)});for(let[J,Y]of Object.entries(A.headers))$.set(J,Y);if(A.token)$.set(aJ5,A.token);if(B.directActorId!==void 0)$.set(oJ5,"actor"),$.set(rJ5,B.directActorId);if(Ax(B))$.set(sJ5,"1");return $}var DS4=new Map;function sD5(A,Q,B){if(!B)return;let $=A;$.__rivetGetHibernatableAckState=Q.getState,$.__rivetWaitForHibernatableAck=Q.waitForAck}function tD5(A,Q,B){if(!B)return;sD5(A,{getState:()=>{let $=DS4.get(Q);if(!$)throw Error(`remote hibernatable websocket ack hooks are unavailable for token ${Q}`);return $.getState()},waitForAck:async($)=>{let J=DS4.get(Q);if(!J)throw Error(`remote hibernatable websocket ack hooks are unavailable for token ${Q}`);await J.waitForAck($)}},B)}var eD5=class{CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;#A;#Q=new Map;#B=[];#$=null;#Y=null;#J=null;#F=null;constructor(A){this.#A=A;for(let Q of["open","message","close","error"])this.#A.addEventListener(Q,(B)=>{this.#Z(Q,B)})}get readyState(){return this.#A.readyState}get binaryType(){return this.#A.binaryType}set binaryType(A){this.#A.binaryType=A}get bufferedAmount(){return this.#A.bufferedAmount}get extensions(){return this.#A.extensions}get protocol(){return this.#A.protocol}get url(){return this.#A.url}get onopen(){return this.#$}set onopen(A){this.#$=A,this.#X()}get onclose(){return this.#Y}set onclose(A){this.#Y=A,this.#X()}get onerror(){return this.#J}set onerror(A){this.#J=A,this.#X()}get onmessage(){return this.#F}set onmessage(A){this.#F=A,this.#X()}send(A){this.#A.send(A)}close(A,Q){this.#A.close(A,Q)}addEventListener(A,Q){let B=this.#Q.get(A)??new Set;B.add(Q),this.#Q.set(A,B),this.#X()}removeEventListener(A,Q){var B;(B=this.#Q.get(A))==null||B.delete(Q)}dispatchEvent(A){return this.#U(A.type,A)}#Z(A,Q){if(this.#D(A)){this.#U(A,Q);return}this.#B.push({type:A,event:Q})}#X(){if(this.#B.length===0)return;let A=this.#B;this.#B=[];for(let Q of A){if(this.#D(Q.type)){this.#U(Q.type,Q.event);continue}this.#B.push(Q)}}#D(A){var Q;let B=A==="open"?this.#$:A==="close"?this.#Y:A==="error"?this.#J:A==="message"?this.#F:null;return Boolean(B)||(((Q=this.#Q.get(A))==null?void 0:Q.size)??0)>0}#U(A,Q){let B=this.#Q.get(A);if(B)for(let J of B)J(Q);let $=A==="open"?this.#$:A==="close"?this.#Y:A==="error"?this.#J:A==="message"?this.#F:null;return $==null||$(Q),!0}};function GS4(A,Q,B,$=""){let J=B!==void 0?`@${encodeURIComponent(B)}`:"",Y=`/gateway/${encodeURIComponent(Q)}${J}${$}`;return iy(A,Y)}function AG5(A,Q,B,$,J="",Y=hS4,Z=void 0,F,X={}){if(Q.length===0)throw Error("actor query namespace must not be empty");let D,G=new URLSearchParams;if(G.append("rvt-namespace",Q),"getForKey"in B){if(D=B.getForKey.name,G.append("rvt-method","get"),VS4(G,B.getForKey.key),Z!==void 0)throw Error("Actor query method=get does not support crashPolicy.");if(F!==void 0)throw Error("Actor query method=get does not support runnerName.")}else if("getOrCreateForKey"in B){if(D=B.getOrCreateForKey.name,G.append("rvt-method","getOrCreate"),F===void 0)throw Error("Actor query method=getOrCreate requires runnerName.");if(G.append("rvt-runner",F),VS4(G,B.getOrCreateForKey.key),QG5(G,B.getOrCreateForKey.input,Y),B.getOrCreateForKey.region!==void 0)G.append("rvt-region",B.getOrCreateForKey.region);G.append("rvt-crash-policy",Z??"sleep")}else throw Error("Actor query gateway URLs only support get and getOrCreate.");if(D.length===0)throw Error("actor query name must not be empty");if($!==void 0)G.append("rvt-token",$);if(Ax(X))G.append("rvt-skip-ready-wait","true");let V=G.toString(),U;if(J.endsWith("?")||J.endsWith("&"))U="";else if(J.includes("?"))U="&";else U="?";let K=`/gateway/${encodeURIComponent(D)}${J}${U}${V}`;return iy(A,K)}function VS4(A,Q){if(Q.length>0)A.append("rvt-key",Q.join(","))}function QG5(A,Q,B){if(Q===void 0)return;let $=Xj(Q);if($.byteLength>B)throw Error(`Actor query input exceeds maxInputSize (${$.byteLength} > ${B} bytes). Increase client maxInputSize to allow larger query payloads.`);A.append("rvt-input",BG5($))}function BG5(A){return oZ0(A).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function $G5(A,Q,B,$,J={}){let Y=await Vr0(),Z=typeof process<"u"&&process.env.VITEST?crypto.randomUUID():void 0;b5().debug({msg:"opening websocket to actor via guard",gatewayUrl:Q});let F=new Y(Q,pS4(A,B,$,Z,J.directActorId?{target:"actor",actorId:J.directActorId}:void 0,J));F.binaryType="arraybuffer";let X=new eD5(F);if(Z)tD5(X,Z,!0);return X}function pS4(A,Q,B,$,J,Y={}){let Z=[];if(Z.push(tJ5),Z.push(`${QY5}${Q}`),J){if(Z.push(`${eJ5}${J.target}`),Z.push(`${AY5}${J.actorId}`),A.token)Z.push(`${$Y5}${A.token}`)}if(Ax(Y))Z.push(JY5);if(B)Z.push(`${BY5}${encodeURIComponent(JSON.stringify(B))}`);if($)Z.push(`${YY5}${encodeURIComponent($)}`);return Z}var US4=new Map;async function JG5(A){let Q=$F0(A),B=US4.get(Q);if(B)return B;let $=fa(async()=>{b5().debug({msg:"fetching metadata",endpoint:Q});let J=await nD5(A);return b5().debug({msg:"received metadata",endpoint:Q,clientEndpoint:J.clientEndpoint}),J},{forever:!0,minTimeout:500,maxTimeout:15000,onFailedAttempt:(J)=>{if(J.attemptNumber>1)b5().warn({msg:"failed to fetch metadata, retrying",endpoint:Q,attempt:J.attemptNumber,error:j9(J)})}});return US4.set(Q,$),$}async function YG5(A,Q,B){let $=await Vr0(),J={};return{onOpen:async(Y,Z)=>{if(b5().debug({msg:"client websocket connected",targetUrl:Q}),Z.readyState!==1){b5().warn({msg:"client websocket not open on connection",targetUrl:Q,readyState:Z.readyState});return}let F=new $(Q,B);J.targetWs=F,J.connectPromise=new Promise((X,D)=>{F.addEventListener("open",()=>{if(b5().debug({msg:"target websocket connected",targetUrl:Q}),Z.readyState!==1){b5().warn({msg:"client websocket closed before target connected",targetUrl:Q,clientReadyState:Z.readyState}),F.close(1001,"Client disconnected"),D(Error("Client disconnected"));return}X()}),F.addEventListener("error",(G)=>{b5().warn({msg:"target websocket error during connection",targetUrl:Q}),D(G)})}),J.targetWs.addEventListener("message",(X)=>{if(typeof X.data==="string"||X.data instanceof ArrayBuffer)Z.send(X.data);else if(X.data instanceof Blob)X.data.arrayBuffer().then((D)=>{Z.send(D)})}),J.targetWs.addEventListener("close",(X)=>{b5().debug({msg:"target websocket closed",targetUrl:Q,code:X.code,reason:X.reason}),Ir0(Z,X.code,X.reason)}),J.targetWs.addEventListener("error",(X)=>{b5().error({msg:"target websocket error",targetUrl:Q,error:j9(X)}),Ir0(Z,1011,"Target WebSocket error")})},onMessage:async(Y,Z)=>{if(!J.targetWs||!J.connectPromise){b5().error({msg:"websocket state not initialized",targetUrl:Q});return}try{if(await J.connectPromise,J.targetWs.readyState===$.OPEN)J.targetWs.send(Y.data);else b5().warn({msg:"target websocket not open",targetUrl:Q,readyState:J.targetWs.readyState})}catch(F){b5().error({msg:"failed to connect to target websocket",targetUrl:Q,error:F}),Ir0(Z,1011,"Failed to connect to target")}},onClose:(Y,Z)=>{if(b5().debug({msg:"client websocket closed",targetUrl:Q,code:Y.code,reason:Y.reason,wasClean:Y.wasClean}),J.targetWs){if(J.targetWs.readyState===$.OPEN||J.targetWs.readyState===$.CONNECTING)J.targetWs.close(1000,Y.reason||"Client disconnected")}},onError:(Y,Z)=>{if(b5().error({msg:"client websocket error",targetUrl:Q,event:Y}),J.targetWs){if(J.targetWs.readyState===$.OPEN)J.targetWs.close(1011,"Client WebSocket error");else if(J.targetWs.readyState===$.CONNECTING)J.targetWs.close()}}}}function Ir0(A,Q,B){if(A.readyState===1)A.close(Q,B);else if("close"in A&&A.readyState===WebSocket.OPEN)A.close(Q,B)}var dS4=class{#A;#Q;constructor(A){if(zT4()==="phase-production-build")b5().info("detected next.js build phase, disabling health check"),A.disableMetadataLookup=!0;if(this.#A={...A},!A.disableMetadataLookup)this.#Q=JG5(this.#A).then((Q)=>{if(Q.clientEndpoint){if(this.#A.endpoint=Q.clientEndpoint,Q.clientNamespace)this.#A.namespace=Q.clientNamespace;if(Q.clientToken)this.#A.token=Q.clientToken;b5().info({msg:"overriding client endpoint",endpoint:Q.clientEndpoint,namespace:Q.clientNamespace,token:Q.clientToken})}b5().info({msg:"connected to rivetkit runtime",runtime:Q.runtime,version:Q.version,envoy:Q.envoy})})}async getForId({name:A,actorId:Q}){await this.#Q;let $=(await mD5(this.#A,A,Q)).actors[0];if(!$)return;if($.name!==A){b5().debug({msg:"actor name mismatch from api",actorId:Q,apiName:$.name,requestedName:A});return}return ha($)}async getWithKey({name:A,key:Q}){await this.#Q,b5().debug({msg:"getWithKey: searching for actor",name:A,key:Q});try{let $=(await pD5(this.#A,A,Q)).actors[0];if(!$)return;return b5().debug({msg:"getWithKey: found actor via api",actorId:$.actor_id,name:A,key:Q}),ha($)}catch(B){if(B instanceof R5&&B.group==="actor"&&B.code==="not_found")return;throw B}}async getOrCreateWithKey(A){await this.#Q;let{name:Q,key:B,input:$,region:J,crashPolicy:Y}=A;b5().info({msg:"getOrCreateWithKey: getting or creating actor via engine api",name:Q,key:B});let{actor:Z,created:F}=await cD5(this.#A,{datacenter:J,name:Q,key:uZ0(B),runner_name_selector:this.#A.poolName,input:$?oZ0(Xj($)):void 0,crash_policy:Y??"sleep"});return b5().info({msg:"getOrCreateWithKey: actor ready",actorId:Z.actor_id,name:Q,key:B,created:F}),ha(Z)}async createActor({name:A,key:Q,input:B,region:$,crashPolicy:J}){await this.#Q,b5().info({msg:"creating actor via engine api",name:A,key:Q});let Y=await lD5(this.#A,{datacenter:$,name:A,runner_name_selector:this.#A.poolName,key:uZ0(Q),input:B?oZ0(Xj(B)):void 0,crash_policy:J??"sleep"});return b5().info({msg:"actor created",actorId:Y.actor.actor_id,name:A,key:Q}),ha(Y.actor)}async listActors({name:A}){return await this.#Q,b5().debug({msg:"listing actors via engine api",name:A}),(await dD5(this.#A,A)).actors.map(ha)}async destroyActor(A){await this.#Q,b5().info({msg:"destroying actor via engine api",actorId:A}),await iD5(this.#A,A),b5().info({msg:"actor destroyed",actorId:A})}async sendRequest(A,Q,B={}){await this.#Q;let $=ES4(Q),J=this.#B(A,$,B),Y={...B,directActorId:Ax(B)?wr0(A):void 0};return XS4(this.#A,J,Q,Y)}async openWebSocket(A,Q,B,$,J={}){await this.#Q;let Y=this.#B(Q,A,J);return $G5(this.#A,Y,B,$,{...J,directActorId:Ax(J)?wr0(Q):void 0})}async buildGatewayUrl(A,Q={}){return await this.#Q,this.#B(A,"",Q)}async proxyRequest(A,Q,B){await this.#Q;let $=this.#B({directId:B},ES4(Q));return XS4(this.#A,$,Q)}async proxyWebSocket(A,Q,B,$,J){var Y,Z;await this.#Q;let F=(Z=(Y=this.#A).getUpgradeWebSocket)==null?void 0:Z.call(Y);mS4.default(F,"missing getUpgradeWebSocket");let X=$F0(this.#A),D=iy(X,Q),G=D.replace("http://","ws://");b5().debug({msg:"forwarding websocket to actor via guard",actorId:B,path:Q,guardUrl:D});let V=pS4(this.#A,$,J,void 0,{target:"actor",actorId:B}),U=await YG5(A,G,V);return await F(()=>U)(A,WT4())}async kvGet(A,Q){return await this.#Q,b5().debug({msg:"getting kv value via engine api",key:Q}),(await aD5(this.#A,A,new TextDecoder("utf8").decode(Q))).value}async kvBatchGet(A,Q){throw Error("kvBatchGet not supported on remote engine client")}async kvBatchPut(A,Q){throw Error("kvBatchPut not supported on remote engine client")}async kvBatchDelete(A,Q){throw Error("kvBatchDelete not supported on remote engine client")}async kvDeleteRange(A,Q,B){throw Error("kvDeleteRange not supported on remote engine client")}displayInformation(){return{properties:{}}}setGetUpgradeWebSocket(A){this.#A.getUpgradeWebSocket=A}#B(A,Q,B={}){let $=$F0(this.#A);if(Ax(B)&&wr0(A)&&ZG5(Q))return iy($,Q);if("directId"in A)return GS4($,A.directId,this.#A.token,Q);if("getForId"in A)return GS4($,A.getForId.actorId,this.#A.token,Q);if("getForKey"in A||"getOrCreateForKey"in A)return AG5($,this.#A.namespace,A,this.#A.token,Q,this.#A.maxInputSize,void 0,"getOrCreateForKey"in A?this.#A.poolName:void 0,B);if("create"in A)throw Error("Gateway URLs only support direct actor IDs, get, and getOrCreate targets.");throw Error("unreachable: unknown gateway target type")}};function ZG5(A){return FG5(A)||KS4(A,zS4)||KS4(A,nJ5)||A.startsWith(WS4)}function KS4(A,Q){return A===Q||A.startsWith(`${Q}?`)}function FG5(A){let Q=A.slice(8);return A.startsWith("/request")&&(Q.length===0||Q.startsWith("/")||Q.startsWith("?"))}function wr0(A){if("directId"in A)return A.directId;if("getForId"in A)return A.getForId.actorId;return}function ES4(A){let Q=new URL(A.url);return`${Q.pathname}${Q.search}`}function ha(A){return{actorId:A.actor_id,name:A.name,key:xT4(A.key),createTs:A.create_ts,startTs:A.start_ts??null,connectableTs:A.connectable_ts??null,sleepTs:A.sleep_ts??null,destroyTs:A.destroy_ts??null,error:A.error??void 0}}function XG5(){return cN("devtools")}var DG5=(A=jo0)=>`https://releases.rivet.dev/rivet/latest/devtools/mod.js?v=${A}`,cS4="rivetkit-devtools-script";function GG5(A){if(!window){XG5().warn("devtools not available outside browser environment");return}if(!document.getElementById(cS4)){let Q=document.createElement("script");Q.id=cS4,Q.src=DG5(),Q.async=!0,document.head.appendChild(Q)}window.__rivetkit=window.__rivetkit||[],window.__rivetkit.push(A)}function yr0(A){let Q=A===void 0?{}:typeof A==="string"?{endpoint:A}:A,B=gS4.parse(Q),$=new dS4(B);if(B.devtools)GG5(B);return bS4($,B)}function OU(A){return yr0(VG5(A))}function VG5(A){let Q=UG5();if(!Q)return A;if(A===void 0)return{poolName:Q};if(typeof A==="string")return{endpoint:A,poolName:Q};return{...A,poolName:A.poolName??Q}}function UG5(){if(typeof process>"u")return;let A=process.env.RIVET_POOL_NAME?.trim();return A&&A.length>0?A:void 0}var KG5="https://default:uScL4UEKjZsetHm4U495exBWa1WOTmus2UWwhBfo4XJMUuhL6DZIQ8nwx8MACPvV@actors.ampcode.com",EG5="https://default:bvUhSEyRuaUZjf68K05GVMaLRUFRa8ZUIQkcUP9MvOTmkXrS8tYZJ5eFmJOSmO0v@actors.staging.ampcodedev.org";function xr0(A,Q){try{return new URL(A).hostname===Q}catch{return A.includes(Q)}}function zG5(A){return xr0(A,"localhost")||xr0(A,"127.0.0.1")}function WG5(A){return xr0(A,"staging.ampcodedev.org")}function uF(A){if(zG5(A))return $04(process.cwd());if(WG5(A))return EG5;return KG5}async function Yx(A){let Q=uF(A.ampURL),B=OU({endpoint:Q}),$=await A.configService.getLatest(A.signal),J=await $.secrets.getToken("apiKey",$.settings.url);if(!J)throw Error("API key required. Please run `amp login` first.");let Y=await B.threadActor.get([A.threadID]).fetch("/context-analysis",{method:"GET",headers:{Authorization:`Bearer ${J}`},signal:A.signal,skipReadyWait:!0});if(!Y.ok){let F=await Y.text();throw Error(`Context analysis request failed (${Y.status}): ${F}`)}let Z=await Y.json();if(!Z.ok||!Z.analysis)throw Error(Z.error??"Invalid context analysis response from thread actor");return Z.analysis}var{stderr:HG5,stdout:_9}=process;function kD(A,Q=!1){if(Q||A<1000)return A.toLocaleString();return`${(A/1000).toFixed(1)}k`}function lS4(A,Q,B,$,J,Y,Z){return}async function qG5(A,Q,B,$,J,Y,Z,F,X){Y(J,A);let D=await Z(Q,A);try{let G=$.v2===!0;HG5.write(n0.dim(G?`Analyzing context tokens via v2 thread actor...
4624
4624
  `:`Analyzing context tokens...
4625
4625
  `));let V=G?await Yx({ampURL:Q.ampURL,configService:D.configService,threadID:B}):await(async()=>{let q=await F(B,D),N=await T1(jQ(D.configService).pipe(t6((I)=>I!=="pending")));return fZ0({configService:D.configService,buildSystemPromptDeps:{configService:D.configService,toolService:D.toolService,filesystem:j3,skillService:D.skillService,getThreadEnvironment:Iz,getEnvironmentData:(I,w)=>$D({filesystem:j3},I,w),threadService:D.threadService,serverStatus:mA(N)?N:void 0},mcpInitialized:D.mcpService.initialized},q)})();if(_9.write(`
4626
4626
  `),_9.write(n0.bold(`Context Usage Analysis
@@ -4642,20 +4642,20 @@ ${U}`)}}if(A.skipParseResponse)return;try{let F=new Uint8Array(await Z.arrayBuff
4642
4642
  `));_9.write(n0.dim(` Current analysis: ${kD(V.totalTokens,!0).padStart(8)} tokens
4643
4643
  `));let I=N>=0?"+":"-";if(_9.write(n0.dim(` Difference: ${I}${kD(Math.abs(N),!0).padStart(7)} tokens
4644
4644
  `)),Math.abs(N)>100)_9.write(n0.dim(` (Analysis regenerates context; differences expected due to dynamic content)
4645
- `))}await D.asyncDispose(),process.exit(0)}catch(G){await D.asyncDispose();let V=`Failed to analyze thread context: ${G instanceof Error?G.message:String(G)}`;X(V)}}var iS4=process.hrtime.bigint(),fr0=null;function nS4(){fr0=process.hrtime.bigint()}function br0(){if(fr0===null)return null;return Number(process.hrtime.bigint()-fr0)/1e6}import Fx from"node:fs";import Xx from"node:path";_50();function ur0(A,Q){let B=Q.formatter??M50,$=Q.encoder??new TextEncoder,J=Q.maxSize??1048576,Y=Q.maxFiles??5,Z=Q.bufferSize??8192,F=Q.flushInterval??5000,X=0;try{X=Q.statSync(A).size}catch{}let D=Q.openSync(A),G=Date.now(),V="";function U(O){return X+O.length>J}function K(){Q.closeSync(D);for(let O=Y-1;O>0;O--){let L=`${A}.${O}`,P=`${A}.${O+1}`;try{Q.renameSync(L,P)}catch(T){}}Q.renameSync(A,`${A}.1`),X=0,D=Q.openSync(A)}if(!Q.nonBlocking){let O=function(){if(V.length>0){let P=$.encode(V);if(V="",U(P))K();Q.writeSync(D,P),Q.flushSync(D),X+=P.length,G=Date.now()}},L=(P)=>{V+=B(P);let T=V.length>=Z,k=F>0&&P.timestamp-G>=F;if(T||k)O()};return L[Symbol.dispose]=()=>{O(),Q.closeSync(D)},L}let E=Q,z=!1,W=null,H=null;async function q(){if(V.length===0)return;let O=V;V="";try{let L=$.encode(O);if(U(L))K();E.writeSync(D,L),await E.flush(D),X+=L.length,G=Date.now()}catch{}}function N(){if(W||z)return;W=q().finally(()=>{W=null})}function I(){if(H!==null||z)return;H=setInterval(()=>{N()},F)}let w=(O)=>{if(z)return;V+=B(O);let L=V.length>=Z,P=F>0&&O.timestamp-G>=F;if(L||P)N();else if(H===null&&F>0)I()};return w[Symbol.asyncDispose]=async()=>{if(z=!0,H!==null)clearInterval(H),H=null;await q();try{await E.close(D)}catch{}},w}import X7 from"node:fs";import{join as aS4}from"node:path";import{promisify as JF0}from"node:util";var hr0={openSync(A){return X7.openSync(A,"a")},writeSync:X7.writeSync,writeManySync(A,Q){if(Q.length===0)return;if(Q.length===1){X7.writeSync(A,Q[0]);return}X7.writevSync(A,Q)},flushSync:X7.fsyncSync,closeSync:X7.closeSync,statSync:X7.statSync,renameSync:X7.renameSync},oS4={...hr0,async writeMany(A,Q){if(Q.length===0)return;if(Q.length===1){await JF0(X7.write)(A,Q[0]);return}await JF0(X7.writev)(A,Q)},flush:JF0(X7.fsync),close:JF0(X7.close)},aG8={...hr0,readdirSync:X7.readdirSync,unlinkSync:X7.unlinkSync,mkdirSync:X7.mkdirSync,joinPath:aS4},oG8={...oS4,readdirSync:X7.readdirSync,unlinkSync:X7.unlinkSync,mkdirSync:X7.mkdirSync,joinPath:aS4};function gr0(A,Q={}){if(Q.nonBlocking)return ur0(A,{...Q,...oS4});return ur0(A,{...Q,...hr0})}_50();pZ();d0();var mr0=v4(w4(),1);import{inspect as HG5}from"node:util";function YF0(A,...Q){if(Q.length===0)return A;return(B)=>{let $=B;for(let J of Q)$=J($);A($)}}var ZF0=(A)=>{let Q=mr0.trace.getActiveSpan();if(!Q)return A;let{traceId:B,spanId:$}=Q.spanContext();return{...A,properties:{...A.properties,traceId:B,spanId:$}}},FF0=(A)=>{let Q=null;for(let B of Object.keys(A.properties)){let $=A.properties[B];if($ instanceof Error)Q??={...A.properties},Q[B]=rS4($)}return Q===null?A:{...A,properties:Q}},rS4=(A)=>({name:A.name,message:A.message,stack:A.stack,cause:A.cause instanceof Error?rS4(A.cause):A.cause}),pr0=(A)=>({...A,properties:{...A.properties,pid:process.pid}});var sS4=(A)=>{let Q=mr0.trace.getActiveSpan();if(!Q)return;Q.addEvent(qG5(A.message),A.properties)};var Zx={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m"};var JV8={trace:Zx.magenta,debug:Zx.blue,info:Zx.green,warning:Zx.yellow,error:Zx.red,fatal:Zx.red};function qG5(A,Q){let B="";for(let $=0;$<A.length;$++){let J=A[$];if($%2===0)B+=typeof J==="string"?J:String(J);else B+=typeof J==="string"?J:HG5(J,Q)}return B}var tS4=Xx.join(x$,"logs"),NG5=604800000,XF0=Xx.join(tS4,"threads"),da=Xx.join(tS4,"cli.log"),IG5=Number(process.env.AMP_MAX_LOG_FILE_SIZE)||10485760,wG5={error:"error",warn:"warning",info:"info",debug:"debug"},dr0=!1,pa=null,cr0=!1;function GF0(){cr0=!0}function Dx(A){return Xx.join(XF0,`${A}.log`)}function eS4(A=Date.now()){let Q;try{Q=Fx.readdirSync(XF0)}catch{return}let B=A-NG5;for(let $ of Q){if(!$.endsWith(".log"))continue;let J=Xx.join(XF0,$);try{let Y=Fx.statSync(J);if(Y.isFile()&&Y.mtimeMs<B)Fx.rmSync(J,{force:!0})}catch{}}}function Av4(A){pa=null,cr0=!1;let{logFile:Q,logLevel:B}=A,$=wG5[hr1.catch("info").parse(B)],J=L50({properties:"flatten"});return Fx.mkdirSync(Xx.dirname(Q),{recursive:!0}),CT(),vm({sinks:{file:YF0(gr0(Q,{maxSize:IG5,maxFiles:2,formatter:J}),pr0,ZF0,FF0),otel:YF0(sS4,ZF0,FF0),thread:YF0(CG5(XF0,J),pr0,ZF0,FF0)},loggers:[{category:["logtape","meta"],sinks:["file"],lowestLevel:"warning"},{category:[],sinks:["file","otel","thread"],lowestLevel:$}]}),dr0=!0,Q}var DF0=new Map;function CG5(A,Q){return(B)=>{if(!cr0)return;let $=B.properties.threadId;if(typeof $!=="string"||$.length===0)return;try{let J=DF0.get($);if(!J)Fx.mkdirSync(A,{recursive:!0}),J=Fx.createWriteStream(Dx($),{flags:"a"}),DF0.set($,J);J.write(Q(B))}catch{}}}function jz(){if(pa)return pa;if(!dr0)return Promise.resolve();return pa=MG5(),pa}async function MG5(){await new Promise((J)=>{setImmediate(J)});let A=Array.from(DF0.values());DF0.clear();let Q=Promise.all(A.map((J)=>new Promise((Y)=>J.end(()=>Y())))),B,$=new Promise((J)=>{B=setTimeout(J,500)});try{await Promise.race([Promise.all([Q,R50()]),$])}finally{if(B)clearTimeout(B)}try{CT()}catch{}dr0=!1}d0();import{execFile as LG5}from"node:child_process";import{promisify as OG5}from"node:util";var jG5=OG5(LG5),RG5=["private","public","workspace"];function lr0(A){return A.endsWith("/")?A.slice(0,-1):A}function PG5(A){let Q=bZ0(A);try{let J=new URL(Q);return lr0(`${J.host}${J.pathname}`).replace(/^\//,"")}catch{}let B=Q.match(/^[^@]+@([^:/]+)[:/](.+)$/);if(B?.[1]&&B[2])return lr0(`${B[1]}/${B[2]}`).replace(/\.git$/,"");let $=Q.match(/^([^:]+):(.+)$/);if($?.[1]&&$[2])return lr0(`${$[1]}/${$[2]}`).replace(/\.git$/,"");return null}async function Bv4(A){try{let{stdout:Q}=await jG5("git",["remote","get-url","origin"],{cwd:A}),B=Q.trim();if(!B)return null;return PG5(B)}catch{return null}}function _G5(A){let Q=[...RG5];if(A?.team?.disablePrivateThreads){let B=Q.indexOf("private");if(B!==-1)Q.splice(B,1)}if(A?.team?.groups&&A.team.groups.length>0)Q.push("group");return Q}function TG5(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.
4645
+ `))}await D.asyncDispose(),process.exit(0)}catch(G){await D.asyncDispose();let V=`Failed to analyze thread context: ${G instanceof Error?G.message:String(G)}`;X(V)}}var iS4=process.hrtime.bigint(),fr0=null;function nS4(){fr0=process.hrtime.bigint()}function br0(){if(fr0===null)return null;return Number(process.hrtime.bigint()-fr0)/1e6}import Fx from"node:fs";import Xx from"node:path";_50();function ur0(A,Q){let B=Q.formatter??M50,$=Q.encoder??new TextEncoder,J=Q.maxSize??1048576,Y=Q.maxFiles??5,Z=Q.bufferSize??8192,F=Q.flushInterval??5000,X=0;try{X=Q.statSync(A).size}catch{}let D=Q.openSync(A),G=Date.now(),V="";function U(O){return X+O.length>J}function K(){Q.closeSync(D);for(let O=Y-1;O>0;O--){let L=`${A}.${O}`,P=`${A}.${O+1}`;try{Q.renameSync(L,P)}catch(T){}}Q.renameSync(A,`${A}.1`),X=0,D=Q.openSync(A)}if(!Q.nonBlocking){let O=function(){if(V.length>0){let P=$.encode(V);if(V="",U(P))K();Q.writeSync(D,P),Q.flushSync(D),X+=P.length,G=Date.now()}},L=(P)=>{V+=B(P);let T=V.length>=Z,k=F>0&&P.timestamp-G>=F;if(T||k)O()};return L[Symbol.dispose]=()=>{O(),Q.closeSync(D)},L}let E=Q,z=!1,W=null,H=null;async function q(){if(V.length===0)return;let O=V;V="";try{let L=$.encode(O);if(U(L))K();E.writeSync(D,L),await E.flush(D),X+=L.length,G=Date.now()}catch{}}function N(){if(W||z)return;W=q().finally(()=>{W=null})}function I(){if(H!==null||z)return;H=setInterval(()=>{N()},F)}let w=(O)=>{if(z)return;V+=B(O);let L=V.length>=Z,P=F>0&&O.timestamp-G>=F;if(L||P)N();else if(H===null&&F>0)I()};return w[Symbol.asyncDispose]=async()=>{if(z=!0,H!==null)clearInterval(H),H=null;await q();try{await E.close(D)}catch{}},w}import X7 from"node:fs";import{join as aS4}from"node:path";import{promisify as JF0}from"node:util";var hr0={openSync(A){return X7.openSync(A,"a")},writeSync:X7.writeSync,writeManySync(A,Q){if(Q.length===0)return;if(Q.length===1){X7.writeSync(A,Q[0]);return}X7.writevSync(A,Q)},flushSync:X7.fsyncSync,closeSync:X7.closeSync,statSync:X7.statSync,renameSync:X7.renameSync},oS4={...hr0,async writeMany(A,Q){if(Q.length===0)return;if(Q.length===1){await JF0(X7.write)(A,Q[0]);return}await JF0(X7.writev)(A,Q)},flush:JF0(X7.fsync),close:JF0(X7.close)},aG8={...hr0,readdirSync:X7.readdirSync,unlinkSync:X7.unlinkSync,mkdirSync:X7.mkdirSync,joinPath:aS4},oG8={...oS4,readdirSync:X7.readdirSync,unlinkSync:X7.unlinkSync,mkdirSync:X7.mkdirSync,joinPath:aS4};function gr0(A,Q={}){if(Q.nonBlocking)return ur0(A,{...Q,...oS4});return ur0(A,{...Q,...hr0})}_50();pZ();d0();var mr0=v4(w4(),1);import{inspect as NG5}from"node:util";function YF0(A,...Q){if(Q.length===0)return A;return(B)=>{let $=B;for(let J of Q)$=J($);A($)}}var ZF0=(A)=>{let Q=mr0.trace.getActiveSpan();if(!Q)return A;let{traceId:B,spanId:$}=Q.spanContext();return{...A,properties:{...A.properties,traceId:B,spanId:$}}},FF0=(A)=>{let Q=null;for(let B of Object.keys(A.properties)){let $=A.properties[B];if($ instanceof Error)Q??={...A.properties},Q[B]=rS4($)}return Q===null?A:{...A,properties:Q}},rS4=(A)=>({name:A.name,message:A.message,stack:A.stack,cause:A.cause instanceof Error?rS4(A.cause):A.cause}),pr0=(A)=>({...A,properties:{...A.properties,pid:process.pid}});var sS4=(A)=>{let Q=mr0.trace.getActiveSpan();if(!Q)return;Q.addEvent(IG5(A.message),A.properties)};var Zx={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m"};var JV8={trace:Zx.magenta,debug:Zx.blue,info:Zx.green,warning:Zx.yellow,error:Zx.red,fatal:Zx.red};function IG5(A,Q){let B="";for(let $=0;$<A.length;$++){let J=A[$];if($%2===0)B+=typeof J==="string"?J:String(J);else B+=typeof J==="string"?J:NG5(J,Q)}return B}var tS4=Xx.join(x$,"logs"),wG5=604800000,XF0=Xx.join(tS4,"threads"),da=Xx.join(tS4,"cli.log"),CG5=Number(process.env.AMP_MAX_LOG_FILE_SIZE)||10485760,MG5={error:"error",warn:"warning",info:"info",debug:"debug"},dr0=!1,pa=null,cr0=!1;function GF0(){cr0=!0}function Dx(A){return Xx.join(XF0,`${A}.log`)}function eS4(A=Date.now()){let Q;try{Q=Fx.readdirSync(XF0)}catch{return}let B=A-wG5;for(let $ of Q){if(!$.endsWith(".log"))continue;let J=Xx.join(XF0,$);try{let Y=Fx.statSync(J);if(Y.isFile()&&Y.mtimeMs<B)Fx.rmSync(J,{force:!0})}catch{}}}function Av4(A){pa=null,cr0=!1;let{logFile:Q,logLevel:B}=A,$=MG5[hr1.catch("info").parse(B)],J=L50({properties:"flatten"});return Fx.mkdirSync(Xx.dirname(Q),{recursive:!0}),CT(),vm({sinks:{file:YF0(gr0(Q,{maxSize:CG5,maxFiles:2,formatter:J}),pr0,ZF0,FF0),otel:YF0(sS4,ZF0,FF0),thread:YF0(LG5(XF0,J),pr0,ZF0,FF0)},loggers:[{category:["logtape","meta"],sinks:["file"],lowestLevel:"warning"},{category:[],sinks:["file","otel","thread"],lowestLevel:$}]}),dr0=!0,Q}var DF0=new Map;function LG5(A,Q){return(B)=>{if(!cr0)return;let $=B.properties.threadId;if(typeof $!=="string"||$.length===0)return;try{let J=DF0.get($);if(!J)Fx.mkdirSync(A,{recursive:!0}),J=Fx.createWriteStream(Dx($),{flags:"a"}),DF0.set($,J);J.write(Q(B))}catch{}}}function jz(){if(pa)return pa;if(!dr0)return Promise.resolve();return pa=OG5(),pa}async function OG5(){await new Promise((J)=>{setImmediate(J)});let A=Array.from(DF0.values());DF0.clear();let Q=Promise.all(A.map((J)=>new Promise((Y)=>J.end(()=>Y())))),B,$=new Promise((J)=>{B=setTimeout(J,500)});try{await Promise.race([Promise.all([Q,R50()]),$])}finally{if(B)clearTimeout(B)}try{CT()}catch{}dr0=!1}d0();import{execFile as jG5}from"node:child_process";import{promisify as RG5}from"node:util";var PG5=RG5(jG5),_G5=["private","public","workspace"];function lr0(A){return A.endsWith("/")?A.slice(0,-1):A}function TG5(A){let Q=bZ0(A);try{let J=new URL(Q);return lr0(`${J.host}${J.pathname}`).replace(/^\//,"")}catch{}let B=Q.match(/^[^@]+@([^:/]+)[:/](.+)$/);if(B?.[1]&&B[2])return lr0(`${B[1]}/${B[2]}`).replace(/\.git$/,"");let $=Q.match(/^([^:]+):(.+)$/);if($?.[1]&&$[2])return lr0(`${$[1]}/${$[2]}`).replace(/\.git$/,"");return null}async function Bv4(A){try{let{stdout:Q}=await PG5("git",["remote","get-url","origin"],{cwd:A}),B=Q.trim();if(!B)return null;return TG5(B)}catch{return null}}function kG5(A){let Q=[..._G5];if(A?.team?.disablePrivateThreads){let B=Q.indexOf("private");if(B!==-1)Q.splice(B,1)}if(A?.team?.groups&&A.team.groups.length>0)Q.push("group");return Q}function SG5(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.
4646
4646
  `].join(""));return Error(`Group visibility is not available.
4647
4647
  `)}function Qv4(A,Q){let $=[`Invalid ${A?`visibility for amp.defaultVisibility.${A}`:"visibility"}. `,`Must be one of: ${Q.join(", ")}.
4648
- `].join("");return Error($)}function kG5(A,Q){return Q.includes(A)}function SG5(A){return A?.team?.billingMode==="enterprise"||A?.team?.billingMode==="enterprise.selfserve"}function $v4(A,Q,B){if(A===void 0||A===null)return;let $=_G5(Q);if(typeof A!=="string")return Qv4(B,$);if(A==="group"&&!$.includes("group"))return TG5(Q);if(kG5(A,$))return A;return Qv4(B,$)}async function vG5(A,Q,B){let $=await Bv4(Q);if(!$)return;let J;try{J=await A.get("defaultVisibility")}catch(Z){j.warn("Failed to read defaultVisibility setting",{error:Z});return}let Y=J?.[$];return $v4(Y,B,$)}async function ca(A,Q,B,$){if($)return $;if(!SG5(B))return;let J=await vG5(A,Q,B);if(J instanceof Error)return J;return J}function Jv4(A,Q){return $v4(A,Q)}async function Yv4(A,Q,B){let $=await Bv4(Q);if(!$)return Error("No git origin remote found for this repository.");let Y={...await A.get("defaultVisibility","global")??{},[$]:B};return await A.set("defaultVisibility",Y,"global"),{repoKey:$}}import{spawn as yG5}from"node:child_process";async function xG5(A,Q,B){let $=Q.split("/");if($.length!==2||!$[0]||!$[1])throw new $4("Drive must be specified as <workspace-or-user>/<drive-name>",1);let J=B??$[1],Y=await A.secrets.get("apiKey",A.ampURL);if(!Y)throw new $4("API key required. Please run `amp login` first.",1);let Z=new URL(`/drive/${encodeURIComponent($[0])}/${encodeURIComponent($[1])}`,A.ampURL);Z.username="x-amp-user",Z.password=Y;let F=yG5("git",["clone",Z.toString(),J],{stdio:"inherit"}),X=await new Promise((D,G)=>{F.once("error",G),F.once("close",(V)=>D(V??1))});if(X!==0)throw new $4(`git clone failed with exit code ${X}`,X)}function Zv4(A,Q){A.command("drive",{hidden:!0}).description("Drive commands").command("clone <drive> [target-dir]",{hidden:!0}).description("Clone a workspace drive").action(async($,J,Y,Z)=>{let F=Z.optsWithGlobals(),X=await Q(F);await xG5(X,$,J),process.exit(process.exitCode??0)})}import{stderr as eN}from"node:process";d0();var CV8=Buffer.from([1]),MV8=Buffer.from([2]),LV8=Buffer.from([3]),OV8=Buffer.from([4]),jV8=Buffer.from([5]),RV8=Buffer.from([6]),PV8=Buffer.from([8]),_V8=Buffer.from([11]),TV8=Buffer.from([12]),kV8=Buffer.from([14]),SV8=Buffer.from([16]),vV8=Buffer.from([21]),yV8=Buffer.from([23]),xV8=Buffer.from([25]),fV8=Buffer.from([7]),bV8=Buffer.from([15]),uV8=Buffer.from([17]),hV8=Buffer.from([18]),gV8=Buffer.from([19]),mV8=Buffer.from([20]),pV8=Buffer.from([22]),dV8=Buffer.from([24]),cV8=Buffer.from([26]),lV8=Buffer.from([27]),iV8=Buffer.from([13]),nV8=Buffer.from([10]),aV8=Buffer.from([127]),oV8=Buffer.from([9]),rV8=Buffer.from([27,91,90]),sV8=Buffer.from([27,91,65]),tV8=Buffer.from([27,91,66]),eV8=Buffer.from([27,91,67]),AU8=Buffer.from([27,91,68]),QU8=Buffer.from([27,91,49,59,50,65]),BU8=Buffer.from([27,91,49,59,50,66]),$U8=Buffer.from([27,91,49,59,50,67]),JU8=Buffer.from([27,91,49,59,50,68]),YU8=Buffer.from([27,91,53,126]),ZU8=Buffer.from([27,91,54,126]),FU8=Buffer.from([27,91,72]),XU8=Buffer.from([27,91,70]),DU8=Buffer.from([27,91,49,126]),GU8=Buffer.from([27,91,52,126]),VU8=Buffer.from([27,91,55,126]),UU8=Buffer.from([27,91,56,126]),KU8=Buffer.from([27,91,51,126]),EU8=Buffer.from([27,91,50,126]),zU8=Buffer.from([27,91,71]),WU8=Buffer.from([27,91,49,48,126]),HU8=Buffer.from([27,91,49,49,126]),qU8=Buffer.from([27,91,49,50,126]),NU8=Buffer.from([27,91,49,51,126]),IU8=Buffer.from([27,91,49,52,126]),wU8=Buffer.from([27,91,49,53,126]),CU8=Buffer.from([27,91,49,55,126]),MU8=Buffer.from([27,91,49,56,126]),LU8=Buffer.from([27,91,49,57,126]),OU8=Buffer.from([27,91,50,48,126]),jU8=Buffer.from([27,91,50,49,126]),RU8=Buffer.from([27,91,50,51,126]),PU8=Buffer.from([27,91,50,52,126]),_U8=Buffer.from([27,91,50,53,126]),TU8=Buffer.from([27,91,50,54,126]),kU8=Buffer.from([27,91,50,56,126]),SU8=Buffer.from([27,91,50,57,126]),vU8=Buffer.from([27,91,51,49,126]),yU8=Buffer.from([27,91,51,50,126]),xU8=Buffer.from([27,91,51,51,126]),fU8=Buffer.from([27,91,51,52,126]),bU8=Buffer.from([27,79,80]),uU8=Buffer.from([27,79,81]),hU8=Buffer.from([27,79,82]),gU8=Buffer.from([27,79,83]),mU8=Buffer.from([27,91,49,80]),pU8=Buffer.from([27,91,49,81]),dU8=Buffer.from([27,91,49,82]),cU8=Buffer.from([27,91,49,83]),lU8=Buffer.from([27,102]),iU8=Buffer.from([27,98]),nU8=Buffer.from([27,100]),aU8=Buffer.from([27,127]),oU8=Buffer.from([27,91,49,59,51,65]),rU8=Buffer.from([27,91,49,59,51,66]),sU8=Buffer.from([27,91,49,59,53,65]),tU8=Buffer.from([27,91,49,59,53,66]),eU8=Buffer.from([27,91,49,59,53,68]),AK8=Buffer.from([27,91,49,59,53,67]),QK8=Buffer.from([27,91,49,50,55,59,53,117]),BK8=Buffer.from([27,91,50,55,59,50,59,49,51,126]),$K8=Buffer.from([27,91,50,55,59,53,59,49,51,126]),JK8=Buffer.from([27,91,50,55,59,56,59,49,51,126]),Fv4={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 fG5=process.env.AMP_DEBUG!==void 0&&process.env.AMP_DEBUG!=="0"&&!!process.env.AMP_DEBUG,D7={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.",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.${fG5?" Run with AMP_DEBUG=1 to see detailed logs.":""}`,nodeVersion:(A)=>`Amp CLI requires Node.js v20+. Current version: ${A}`};function zJ(A){throw new $4(`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 bG5(A){if(!(A instanceof Error))return!1;let Q=(A.message??"").toLowerCase()+(A.stack??"").toLowerCase();return["thread","threadservice","threadsync","threadworker","threadhistory","threadsummary","thread-"].some(($)=>Q.includes($))}function Wj(){try{j.debug("cleanupTerminal() called"),Fv4.disable(),eN.write("\x1B[?25h")}catch(A){}}function ir0(A){if(A instanceof $4)return{message:A.userMessage,suggestion:A.suggestion};if(A instanceof JP4)return{message:A.message};if(A instanceof Error){let Q=(A.message??"").toLowerCase();if(Q.includes("401")||Q.includes("unauthorized"))return{message:D7.invalidAPIKey};if(Q.includes("403")||Q.includes("forbidden"))return{message:D7.authExpired};if(Q.includes("timeout")||Q.includes("etimedout"))return{message:D7.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:D7.webSocketConnectionFailed};if(Q.includes("enotfound")||Q.includes("econnrefused")||Q.includes("unable to connect"))return{message:D7.networkOffline};if(/api request .* failed: 5\d\d/.test(Q))return{message:D7.serverError};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:D7.networkOffline}}return{message:D7.internalBug}}function Xv4(A,Q){let B=process.env.AMP_DEBUG==="1"||process.argv.includes("--debug");j.error("CLI Error",A);let{message:$,suggestion:J}=ir0(A);if(eN.write(n0.red.bold("Error: ")+$+`
4648
+ `].join("");return Error($)}function vG5(A,Q){return Q.includes(A)}function yG5(A){return A?.team?.billingMode==="enterprise"||A?.team?.billingMode==="enterprise.selfserve"}function $v4(A,Q,B){if(A===void 0||A===null)return;let $=kG5(Q);if(typeof A!=="string")return Qv4(B,$);if(A==="group"&&!$.includes("group"))return SG5(Q);if(vG5(A,$))return A;return Qv4(B,$)}async function xG5(A,Q,B){let $=await Bv4(Q);if(!$)return;let J;try{J=await A.get("defaultVisibility")}catch(Z){j.warn("Failed to read defaultVisibility setting",{error:Z});return}let Y=J?.[$];return $v4(Y,B,$)}async function ca(A,Q,B,$){if($)return $;if(!yG5(B))return;let J=await xG5(A,Q,B);if(J instanceof Error)return J;return J}function Jv4(A,Q){return $v4(A,Q)}async function Yv4(A,Q,B){let $=await Bv4(Q);if(!$)return Error("No git origin remote found for this repository.");let Y={...await A.get("defaultVisibility","global")??{},[$]:B};return await A.set("defaultVisibility",Y,"global"),{repoKey:$}}import{spawn as fG5}from"node:child_process";async function bG5(A,Q,B){let $=Q.split("/");if($.length!==2||!$[0]||!$[1])throw new $4("Drive must be specified as <workspace-or-user>/<drive-name>",1);let J=B??$[1],Y=await A.secrets.get("apiKey",A.ampURL);if(!Y)throw new $4("API key required. Please run `amp login` first.",1);let Z=new URL(`/drive/${encodeURIComponent($[0])}/${encodeURIComponent($[1])}`,A.ampURL);Z.username="x-amp-user",Z.password=Y;let F=fG5("git",["clone",Z.toString(),J],{stdio:"inherit"}),X=await new Promise((D,G)=>{F.once("error",G),F.once("close",(V)=>D(V??1))});if(X!==0)throw new $4(`git clone failed with exit code ${X}`,X)}function Zv4(A,Q){A.command("drive",{hidden:!0}).description("Drive commands").command("clone <drive> [target-dir]",{hidden:!0}).description("Clone a workspace drive").action(async($,J,Y,Z)=>{let F=Z.optsWithGlobals(),X=await Q(F);await bG5(X,$,J),process.exit(process.exitCode??0)})}import{stderr as eN}from"node:process";d0();var CV8=Buffer.from([1]),MV8=Buffer.from([2]),LV8=Buffer.from([3]),OV8=Buffer.from([4]),jV8=Buffer.from([5]),RV8=Buffer.from([6]),PV8=Buffer.from([8]),_V8=Buffer.from([11]),TV8=Buffer.from([12]),kV8=Buffer.from([14]),SV8=Buffer.from([16]),vV8=Buffer.from([21]),yV8=Buffer.from([23]),xV8=Buffer.from([25]),fV8=Buffer.from([7]),bV8=Buffer.from([15]),uV8=Buffer.from([17]),hV8=Buffer.from([18]),gV8=Buffer.from([19]),mV8=Buffer.from([20]),pV8=Buffer.from([22]),dV8=Buffer.from([24]),cV8=Buffer.from([26]),lV8=Buffer.from([27]),iV8=Buffer.from([13]),nV8=Buffer.from([10]),aV8=Buffer.from([127]),oV8=Buffer.from([9]),rV8=Buffer.from([27,91,90]),sV8=Buffer.from([27,91,65]),tV8=Buffer.from([27,91,66]),eV8=Buffer.from([27,91,67]),AU8=Buffer.from([27,91,68]),QU8=Buffer.from([27,91,49,59,50,65]),BU8=Buffer.from([27,91,49,59,50,66]),$U8=Buffer.from([27,91,49,59,50,67]),JU8=Buffer.from([27,91,49,59,50,68]),YU8=Buffer.from([27,91,53,126]),ZU8=Buffer.from([27,91,54,126]),FU8=Buffer.from([27,91,72]),XU8=Buffer.from([27,91,70]),DU8=Buffer.from([27,91,49,126]),GU8=Buffer.from([27,91,52,126]),VU8=Buffer.from([27,91,55,126]),UU8=Buffer.from([27,91,56,126]),KU8=Buffer.from([27,91,51,126]),EU8=Buffer.from([27,91,50,126]),zU8=Buffer.from([27,91,71]),WU8=Buffer.from([27,91,49,48,126]),HU8=Buffer.from([27,91,49,49,126]),qU8=Buffer.from([27,91,49,50,126]),NU8=Buffer.from([27,91,49,51,126]),IU8=Buffer.from([27,91,49,52,126]),wU8=Buffer.from([27,91,49,53,126]),CU8=Buffer.from([27,91,49,55,126]),MU8=Buffer.from([27,91,49,56,126]),LU8=Buffer.from([27,91,49,57,126]),OU8=Buffer.from([27,91,50,48,126]),jU8=Buffer.from([27,91,50,49,126]),RU8=Buffer.from([27,91,50,51,126]),PU8=Buffer.from([27,91,50,52,126]),_U8=Buffer.from([27,91,50,53,126]),TU8=Buffer.from([27,91,50,54,126]),kU8=Buffer.from([27,91,50,56,126]),SU8=Buffer.from([27,91,50,57,126]),vU8=Buffer.from([27,91,51,49,126]),yU8=Buffer.from([27,91,51,50,126]),xU8=Buffer.from([27,91,51,51,126]),fU8=Buffer.from([27,91,51,52,126]),bU8=Buffer.from([27,79,80]),uU8=Buffer.from([27,79,81]),hU8=Buffer.from([27,79,82]),gU8=Buffer.from([27,79,83]),mU8=Buffer.from([27,91,49,80]),pU8=Buffer.from([27,91,49,81]),dU8=Buffer.from([27,91,49,82]),cU8=Buffer.from([27,91,49,83]),lU8=Buffer.from([27,102]),iU8=Buffer.from([27,98]),nU8=Buffer.from([27,100]),aU8=Buffer.from([27,127]),oU8=Buffer.from([27,91,49,59,51,65]),rU8=Buffer.from([27,91,49,59,51,66]),sU8=Buffer.from([27,91,49,59,53,65]),tU8=Buffer.from([27,91,49,59,53,66]),eU8=Buffer.from([27,91,49,59,53,68]),AK8=Buffer.from([27,91,49,59,53,67]),QK8=Buffer.from([27,91,49,50,55,59,53,117]),BK8=Buffer.from([27,91,50,55,59,50,59,49,51,126]),$K8=Buffer.from([27,91,50,55,59,53,59,49,51,126]),JK8=Buffer.from([27,91,50,55,59,56,59,49,51,126]),Fv4={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 uG5=process.env.AMP_DEBUG!==void 0&&process.env.AMP_DEBUG!=="0"&&!!process.env.AMP_DEBUG,D7={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.",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.${uG5?" Run with AMP_DEBUG=1 to see detailed logs.":""}`,nodeVersion:(A)=>`Amp CLI requires Node.js v20+. Current version: ${A}`};function zJ(A){throw new $4(`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 hG5(A){if(!(A instanceof Error))return!1;let Q=(A.message??"").toLowerCase()+(A.stack??"").toLowerCase();return["thread","threadservice","threadsync","threadworker","threadhistory","threadsummary","thread-"].some(($)=>Q.includes($))}function Wj(){try{j.debug("cleanupTerminal() called"),Fv4.disable(),eN.write("\x1B[?25h")}catch(A){}}function ir0(A){if(A instanceof $4)return{message:A.userMessage,suggestion:A.suggestion};if(A instanceof JP4)return{message:A.message};if(A instanceof Error){let Q=(A.message??"").toLowerCase();if(Q.includes("401")||Q.includes("unauthorized"))return{message:D7.invalidAPIKey};if(Q.includes("403")||Q.includes("forbidden"))return{message:D7.authExpired};if(Q.includes("timeout")||Q.includes("etimedout"))return{message:D7.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:D7.webSocketConnectionFailed};if(Q.includes("enotfound")||Q.includes("econnrefused")||Q.includes("unable to connect"))return{message:D7.networkOffline};if(/api request .* failed: 5\d\d/.test(Q))return{message:D7.serverError};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:D7.networkOffline}}return{message:D7.internalBug}}function Xv4(A,Q){let B=process.env.AMP_DEBUG==="1"||process.argv.includes("--debug");j.error("CLI Error",A);let{message:$,suggestion:J}=ir0(A);if(eN.write(n0.red.bold("Error: ")+$+`
4649
4649
  `),J){eN.write(`
4650
4650
  `);let Y=J.split(`
4651
4651
  `);for(let Z of Y)eN.write(n0.blue(Z)+`
4652
- `)}if(!(A instanceof $4)&&$===D7.internalBug&&(Q!==void 0||bG5(A))){let Y=Q?` ${Q}`:"";eN.write(`Use 'amp threads share${Y} --support' to share this with the Amp team.
4652
+ `)}if(!(A instanceof $4)&&$===D7.internalBug&&(Q!==void 0||hG5(A))){let Y=Q?` ${Q}`:"";eN.write(`Use 'amp threads share${Y} --support' to share this with the Amp team.
4653
4653
  `)}if(B&&A instanceof Error)if(eN.write(`
4654
4654
  `+n0.grey("Debug details:")+`
4655
4655
  `),A.stack)eN.write(A.stack+`
4656
4656
  `);else eN.write(String(A)+`
4657
- `);return Wj(),A instanceof $4?A.exitCode:1}function Dv4(A,Q){let B=Xv4(A,Q);process.exit(B)}async function Rz(A,Q){let B=Xv4(A,Q);await jz(),process.exit(B)}d0();HD();i4();x4();M1();var Gx=(A)=>{let Q=!1;return{install:()=>{if(!Q)process.on("SIGINT",A),process.on("SIGTERM",A),Q=!0},remove:()=>{if(Q)process.off("SIGINT",A),process.off("SIGTERM",A),Q=!1},get installed(){return Q}}};d0();i4();M1();import{once as dG5}from"node:events";import{createInterface as cG5}from"node:readline";d0();HD();kB();RQ();function VF0(A){return{type:"text",text:A.text}}function Gv4(A){return{type:"tool_use",id:A.id,name:A.name,input:A.input}}function Vv4(A){let Q="",B=!1;switch(A.run.status){case"done":Q=typeof A.run.result==="string"?A.run.result:JSON.stringify(A.run.result),B=!1;break;case"error":Q=typeof A.run.error==="string"?A.run.error:A.run.error?.message||"Tool execution error",B=!0;break;case"cancelled":Q=`Tool execution cancelled: ${A.run.reason||"Unknown reason"}`,B=!0;break;case"rejected-by-user":Q=`Tool execution rejected by user: ${A.run.reason||"User declined permission"}`,B=!0;break;default:Q=`Tool status: ${A.run.status}`,B=!1}return{type:"tool_result",tool_use_id:A.toolUseID,content:Q,is_error:B}}function Uv4(A){return{type:"thinking",thinking:A.thinking}}function Kv4(A){return{type:"redacted_thinking",data:A.data}}function Ev4(A,Q,B,$){let J=[],Y=$?.includeThinking??!1;for(let Z of A.content)if(Z.type==="text")J.push(VF0(Z));else if(Z.type==="tool_use")J.push(Gv4(Z));else if(Y&&Z.type==="thinking")J.push(Uv4(Z));else if(Y&&Z.type==="redacted_thinking")J.push(Kv4(Z));return{type:"assistant",message:{type:"message",role:"assistant",content:J,stop_reason:A.state.type==="complete"?A.state.stopReason:null,usage:A.usage?qv4(A.usage):void 0},parent_tool_use_id:B??null,session_id:Q}}function zv4(A,Q,B){let $=[];for(let J of A.content)if(J.type==="text")$.push(VF0(J));else if(J.type==="tool_result")$.push(Vv4(J));return{type:"user",message:{role:"user",content:$},parent_tool_use_id:B??null,session_id:Q}}function Wv4(A,Q,B,$){let J=[];for(let Z of A.content)if(Z.type==="text")J.push(VF0(Z));else if(Z.type==="tool_use")J.push(Gv4(Z));else if($.includeThinking&&Z.type==="thinking")J.push(Uv4(Z));else if($.includeThinking&&Z.type==="redacted_thinking")J.push(Kv4(Z));let Y=(()=>{if(A.state?.type!=="complete")return null;return A.content.some((F)=>F.type==="tool_use")?"tool_use":"end_turn"})();return{type:"assistant",message:{type:"message",role:"assistant",content:J,stop_reason:Y,usage:A.usage?qv4(A.usage):void 0},parent_tool_use_id:B,session_id:Q}}function Hv4(A,Q,B){let $=[];for(let J of A.content)if(J.type==="text")$.push(VF0(J));else if(J.type==="tool_result")$.push(Vv4(J));return{type:"user",message:{role:"user",content:$},parent_tool_use_id:B,session_id:Q}}function qv4(A){if(!A)return;return{input_tokens:A.inputTokens||0,cache_creation_input_tokens:A.cacheCreationInputTokens??void 0,cache_read_input_tokens:A.cacheReadInputTokens??void 0,output_tokens:A.outputTokens||0,max_tokens:A.maxInputTokens,service_tier:"standard"}}var uG5=b.object({type:b.literal("text"),text:b.string()}),hG5=b.object({type:b.literal("base64"),media_type:b.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:b.string()}),gG5=b.object({type:b.literal("image"),source:hG5,source_path:b.string().optional()}),mG5=b.union([uG5,gG5]),pG5=b.object({role:b.literal("user"),content:b.array(mG5)}),Nv4=b.object({type:b.literal("user"),steer:b.boolean().optional(),message:pG5});async function hF(A){let Q=JSON.stringify(A)+`
4658
- `;try{if(!process.stdout.write(Q))await dG5(process.stdout,"drain")}catch(B){throw j.error("Failed to emit JSON message",{error:B,messageType:A.type}),B}}function UF0(A){let Q=Promise.resolve();return(B)=>{let $=Q.then(()=>A(B));return Q=$.catch(()=>{}),$}}function jU(A){let Q;if(A&&typeof A==="object"&&"message"in A&&typeof A.message==="string"){if(Q=Error(A.message),"stack"in A&&typeof A.stack==="string")Q.stack=A.stack}else if(A instanceof Error)Q=A;if(Q&&(tv(Q)||rV(Q)||UO(Q)||KO(Q)||sv(Q))){let B=uN(Q,{freeTierEnabled:!1});return B.description?`${B.title} ${B.description}`:B.title}if(Q)return Q.message;return String(A)}async function*KF0(A){let Q=cG5({input:A,crlfDelay:Number.POSITIVE_INFINITY}),B=0;try{for await(let $ of Q){if(B++,$.trim()==="")continue;let J;try{J=JSON.parse($)}catch(X){throw new $4(`Invalid JSON on stdin line ${B}: ${X instanceof Error?X.message:String(X)}`,1,`Line content: ${$.slice(0,100)}${$.length>100?"...":""}`)}let Y=Nv4.safeParse(J);if(!Y.success){let X=Y.error.issues.map((D)=>`${D.path.join(".")}: ${D.message}`).join(", ");throw new $4(`Invalid message format on stdin line ${B}: ${X}`,1,'Expected format: {"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}')}let Z=Y.data,F={contentBlocks:Iv4(Z.message.content,B)};if(Z.steer!==void 0)F.steer=Z.steer;yield F}}finally{Q.close()}}function Iv4(A,Q){let B=0;return A.map(($)=>{if($.type==="text")return{type:"text",text:$.text};if(B++,B>s9)throw new $4(`Too many images on stdin line ${Q}: ${B} (max ${s9})`,1);let J=$.source_path??`stream-json://stdin/line-${Q}/image-${B}`,Y=Buffer.from($.source.data,"base64"),Z=HV(Y);if(!Z)throw new $4(`Invalid image on stdin line ${Q}: could not decode image bytes`,1);if(Z!==$.source.media_type)throw new $4(`Invalid image on stdin line ${Q}: declared media type ${$.source.media_type} does not match detected type ${Z}`,1);let F=TB({source:{type:"base64",data:$.source.data}});if(F)throw new $4(`Invalid image on stdin line ${Q}: ${F}`,1);return{type:"image",sourcePath:J,source:{type:"base64",mediaType:$.source.media_type,data:$.source.data}}})}d0();L2();function lG5(A,Q){switch(Q.code){case"auth-required":return"Authentication required to label threads";case"thread-not-found":return`Thread ${A} not found`;case"permission-denied":return`Permission denied to label thread ${A}`;case"rate-limit-exceeded":return"Rate limit exceeded while labeling thread";case"invalid-argument":return Q.message??"Invalid labels";default:return Q.message||`Failed to label thread ${A}`}}async function nr0(A,Q,B){if(Q.length===0)return[];let $=await DA.addThreadLabels({thread:A,labels:Q},{config:B});if(!$.ok)throw new $4(lG5(A,$.error));return $.result.map((J)=>J.name)}async function Hj(A,Q,B){if(Q.length===0)return;try{await nr0(A,Q,B)}catch($){j.error("Failed to label thread",{error:$})}}var wv4=1048576;function iG5(A){return A!==void 0}function nG5(A){for(let Q of A)if(Q.type==="tool_result"&&!S5(Q.run.status))return!1;return!0}function Lv4(A){return A.parentToolUseId===void 0}function Ov4(A){return A.role==="assistant"&&Lv4(A)}function Cv4(A){return A.filter((Q)=>Ov4(Q)&&Q.state.type!=="streaming").length}function Mv4(A){return A.messages.findLast(Ov4)}function aG5(A){return A.protocolMessageID??(A.messageId!==void 0?`${A.role}:${A.parentToolUseId??"top-level"}:${A.messageId}`:void 0)}function oG5(A){if(!Lv4(A))return 1;switch(A.role){case"user":return nG5(A.content)?0:2;case"assistant":return A.state.type!=="streaming"?0:2;default:return 1}}async function jv4({handle:A,threadID:Q,initialThread:B,userInput:$,stdinInput:J,dependencies:Y,streamJsonInput:Z=!1,streamJsonThinking:F=!1,stdin:X=process.stdin,ampURL:D="https://ampcode.com",isInternalUser:G=!1,agentMode:V,reasoningEffort:U,labels:K}){let E=B??await T1(A.thread$.pipe(w2(1),MB(5000))),z=V??E.agentMode??"smart",W=Q,H=Date.now(),q=0,N=!1,I=E,w=null;if(J&&J.length>wv4)throw Error(`Stdin input too large: ${J.length} bytes (max ${wv4})`);let O,P=Gx(()=>{if(!N)O("User cancelled (SIGINT/SIGTERM)")});try{P.install();let k=(await T1(Y.toolService.getTools(z).pipe(w2(1),MB(5000)))).map((H0)=>H0.spec.name),x=[];try{x=(await T1(Y.mcpService.servers.pipe(w2(1),MB(5000)))).map((V0)=>({name:V0.name,status:V0.status.type}))}catch(H0){j.warn("Unable to obtain MCP server list for system init message",{err:H0})}let h={type:"system",subtype:"init",cwd:process.cwd(),session_id:W,tools:k,mcp_servers:x,agent_mode:z};if(U!==void 0)h.reasoning_effort=U;await hF(h);let f=Cv4(E.messages),S=E.messages.length,u=new Set,d=[],c=!Z,g=!1,l=[],A0=UF0(async(H0)=>{while(S<H0.messages.length){let V0=H0.messages[S],w0=oG5(V0);if(w0===1){S++;continue}if(w0===2)break;let Z0=aG5(V0);if(!Z0||!u.has(Z0)){if(V0.role==="user")await hF(zv4(V0,W,null));else if(V0.role==="assistant"){if(V0.content.length>0){let R0=Ev4(V0,W,null,{includeThinking:F});await hF(R0)}q++}if(Z0)u.add(Z0)}S++}});return new Promise((H0,V0)=>{O=async(N0)=>{if(N){j.debug("Complete called multiple times, ignoring",{error:N0});return}N=!0,P.remove();try{try{let n=await T1(A.thread$.pipe(w2(1),MB(1000)));I=n,await A0(n)}catch(n){j.debug("Unable to flush pending thread messages before completion",{error:n})}if(N0){let n={type:"result",subtype:"error_during_execution",duration_ms:Date.now()-H,is_error:!0,num_turns:q,error:N0,session_id:W};await hF(n)}else{let n=I?Mv4(I):null,o=n?E8(n.content):"",r={type:"result",subtype:"success",duration_ms:Date.now()-H,is_error:!1,num_turns:q,result:o,session_id:W};await hF(r)}if(w0.unsubscribe(),Z0.unsubscribe(),d.forEach((n)=>n.unsubscribe()),await A.postExecuteMode?.(),K&&K.length>0)await Hj(Q,K,Y.configService);H0()}catch(n){j.error("Error during completion",{error:n}),V0(n)}};let w0=A.threadViewState$.subscribe(async(N0)=>{try{if(w=N0,N0.state==="active"&&N0.ephemeralError){await O(jU(N0.ephemeralError));return}if(l.length>0){let n=[...new Set(l.map((r)=>r.toolName))],o=n.length>0?`The following tools require user approval, which is not supported in stream JSON mode: ${n.join(", ")}`:"A tool requires user approval, which is not supported in stream JSON mode";await O(o);return}if(N0.state==="active"&&N0.inferenceState==="idle"&&I){let n=I.messages.flatMap((o)=>o.content.map((r)=>{if(r.type==="tool_result"&&r.run.status==="blocked-on-user")return a9(I,r.toolUseID)}).filter(iG5));if(n.length>0){j.warn("Tools require user consent - exiting stream JSON mode",{blockedTools:n.map((e)=>({name:e.name,id:e.id}))});let r=`The following tools require user approval, which is not supported in stream JSON mode: ${n.map((e)=>e.name).join(", ")}`;await O(r);return}}if(c&&g&&N0.state==="active"&&N0.inferenceState==="idle")await O()}catch(n){j.error("Error in status subscription",{error:n}),await O(jU(n))}}),Z0=A.thread$.subscribe(async(N0)=>{try{I=N0,await A0(N0);let n=Cv4(N0.messages),o=Mv4(N0);if(g=n>f&&o!==void 0&&o.state.type!=="streaming"&&Ak(o)&&!o.content.some((r)=>r.type==="tool_use"),c&&g&&w?.state==="active"&&w.inferenceState==="idle")await O()}catch(n){j.error("Error in thread subscription",{error:n}),await O(jU(n))}}),R0=A.pendingApprovals$.subscribe((N0)=>{if(l=N0,N0.length>0){let n=[...new Set(N0.map((r)=>r.toolName))],o=n.length>0?`The following tools require user approval, which is not supported in stream JSON mode: ${n.join(", ")}`:"A tool requires user approval, which is not supported in stream JSON mode";O(o)}});d.push(R0);let B0=A.inferenceErrors$?.subscribe((N0)=>{O(jU(N0))});if(B0)d.push(B0);if(Z)(async()=>{try{for await(let N0 of KF0(X)){if(N)break;await A.sendMessage({content:N0.contentBlocks,agentMode:z})}if(c=!0,g&&w?.state==="active"&&w.inferenceState==="idle")await O()}catch(N0){j.error("Error processing streaming input",{error:N0}),await O(jU(N0))}})();else(async()=>{try{let N0=[{type:"text",text:$}];if(J)N0.unshift({type:"text",text:`Input received on stdin:
4657
+ `);return Wj(),A instanceof $4?A.exitCode:1}function Dv4(A,Q){let B=Xv4(A,Q);process.exit(B)}async function Rz(A,Q){let B=Xv4(A,Q);await jz(),process.exit(B)}d0();HD();i4();x4();M1();var Gx=(A)=>{let Q=!1;return{install:()=>{if(!Q)process.on("SIGINT",A),process.on("SIGTERM",A),Q=!0},remove:()=>{if(Q)process.off("SIGINT",A),process.off("SIGTERM",A),Q=!1},get installed(){return Q}}};d0();i4();M1();import{once as lG5}from"node:events";import{createInterface as iG5}from"node:readline";d0();HD();kB();RQ();function VF0(A){return{type:"text",text:A.text}}function Gv4(A){return{type:"tool_use",id:A.id,name:A.name,input:A.input}}function Vv4(A){let Q="",B=!1;switch(A.run.status){case"done":Q=typeof A.run.result==="string"?A.run.result:JSON.stringify(A.run.result),B=!1;break;case"error":Q=typeof A.run.error==="string"?A.run.error:A.run.error?.message||"Tool execution error",B=!0;break;case"cancelled":Q=`Tool execution cancelled: ${A.run.reason||"Unknown reason"}`,B=!0;break;case"rejected-by-user":Q=`Tool execution rejected by user: ${A.run.reason||"User declined permission"}`,B=!0;break;default:Q=`Tool status: ${A.run.status}`,B=!1}return{type:"tool_result",tool_use_id:A.toolUseID,content:Q,is_error:B}}function Uv4(A){return{type:"thinking",thinking:A.thinking}}function Kv4(A){return{type:"redacted_thinking",data:A.data}}function Ev4(A,Q,B,$){let J=[],Y=$?.includeThinking??!1;for(let Z of A.content)if(Z.type==="text")J.push(VF0(Z));else if(Z.type==="tool_use")J.push(Gv4(Z));else if(Y&&Z.type==="thinking")J.push(Uv4(Z));else if(Y&&Z.type==="redacted_thinking")J.push(Kv4(Z));return{type:"assistant",message:{type:"message",role:"assistant",content:J,stop_reason:A.state.type==="complete"?A.state.stopReason:null,usage:A.usage?qv4(A.usage):void 0},parent_tool_use_id:B??null,session_id:Q}}function zv4(A,Q,B){let $=[];for(let J of A.content)if(J.type==="text")$.push(VF0(J));else if(J.type==="tool_result")$.push(Vv4(J));return{type:"user",message:{role:"user",content:$},parent_tool_use_id:B??null,session_id:Q}}function Wv4(A,Q,B,$){let J=[];for(let Z of A.content)if(Z.type==="text")J.push(VF0(Z));else if(Z.type==="tool_use")J.push(Gv4(Z));else if($.includeThinking&&Z.type==="thinking")J.push(Uv4(Z));else if($.includeThinking&&Z.type==="redacted_thinking")J.push(Kv4(Z));let Y=(()=>{if(A.state?.type!=="complete")return null;return A.content.some((F)=>F.type==="tool_use")?"tool_use":"end_turn"})();return{type:"assistant",message:{type:"message",role:"assistant",content:J,stop_reason:Y,usage:A.usage?qv4(A.usage):void 0},parent_tool_use_id:B,session_id:Q}}function Hv4(A,Q,B){let $=[];for(let J of A.content)if(J.type==="text")$.push(VF0(J));else if(J.type==="tool_result")$.push(Vv4(J));return{type:"user",message:{role:"user",content:$},parent_tool_use_id:B,session_id:Q}}function qv4(A){if(!A)return;return{input_tokens:A.inputTokens||0,cache_creation_input_tokens:A.cacheCreationInputTokens??void 0,cache_read_input_tokens:A.cacheReadInputTokens??void 0,output_tokens:A.outputTokens||0,max_tokens:A.maxInputTokens,service_tier:"standard"}}var gG5=b.object({type:b.literal("text"),text:b.string()}),mG5=b.object({type:b.literal("base64"),media_type:b.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:b.string()}),pG5=b.object({type:b.literal("image"),source:mG5,source_path:b.string().optional()}),dG5=b.union([gG5,pG5]),cG5=b.object({role:b.literal("user"),content:b.array(dG5)}),Nv4=b.object({type:b.literal("user"),steer:b.boolean().optional(),message:cG5});async function hF(A){let Q=JSON.stringify(A)+`
4658
+ `;try{if(!process.stdout.write(Q))await lG5(process.stdout,"drain")}catch(B){throw j.error("Failed to emit JSON message",{error:B,messageType:A.type}),B}}function UF0(A){let Q=Promise.resolve();return(B)=>{let $=Q.then(()=>A(B));return Q=$.catch(()=>{}),$}}function jU(A){let Q;if(A&&typeof A==="object"&&"message"in A&&typeof A.message==="string"){if(Q=Error(A.message),"stack"in A&&typeof A.stack==="string")Q.stack=A.stack}else if(A instanceof Error)Q=A;if(Q&&(tv(Q)||rV(Q)||UO(Q)||KO(Q)||sv(Q))){let B=uN(Q,{freeTierEnabled:!1});return B.description?`${B.title} ${B.description}`:B.title}if(Q)return Q.message;return String(A)}async function*KF0(A){let Q=iG5({input:A,crlfDelay:Number.POSITIVE_INFINITY}),B=0;try{for await(let $ of Q){if(B++,$.trim()==="")continue;let J;try{J=JSON.parse($)}catch(X){throw new $4(`Invalid JSON on stdin line ${B}: ${X instanceof Error?X.message:String(X)}`,1,`Line content: ${$.slice(0,100)}${$.length>100?"...":""}`)}let Y=Nv4.safeParse(J);if(!Y.success){let X=Y.error.issues.map((D)=>`${D.path.join(".")}: ${D.message}`).join(", ");throw new $4(`Invalid message format on stdin line ${B}: ${X}`,1,'Expected format: {"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}')}let Z=Y.data,F={contentBlocks:Iv4(Z.message.content,B)};if(Z.steer!==void 0)F.steer=Z.steer;yield F}}finally{Q.close()}}function Iv4(A,Q){let B=0;return A.map(($)=>{if($.type==="text")return{type:"text",text:$.text};if(B++,B>s9)throw new $4(`Too many images on stdin line ${Q}: ${B} (max ${s9})`,1);let J=$.source_path??`stream-json://stdin/line-${Q}/image-${B}`,Y=Buffer.from($.source.data,"base64"),Z=HV(Y);if(!Z)throw new $4(`Invalid image on stdin line ${Q}: could not decode image bytes`,1);if(Z!==$.source.media_type)throw new $4(`Invalid image on stdin line ${Q}: declared media type ${$.source.media_type} does not match detected type ${Z}`,1);let F=TB({source:{type:"base64",data:$.source.data}});if(F)throw new $4(`Invalid image on stdin line ${Q}: ${F}`,1);return{type:"image",sourcePath:J,source:{type:"base64",mediaType:$.source.media_type,data:$.source.data}}})}d0();L2();function nG5(A,Q){switch(Q.code){case"auth-required":return"Authentication required to label threads";case"thread-not-found":return`Thread ${A} not found`;case"permission-denied":return`Permission denied to label thread ${A}`;case"rate-limit-exceeded":return"Rate limit exceeded while labeling thread";case"invalid-argument":return Q.message??"Invalid labels";default:return Q.message||`Failed to label thread ${A}`}}async function nr0(A,Q,B){if(Q.length===0)return[];let $=await DA.addThreadLabels({thread:A,labels:Q},{config:B});if(!$.ok)throw new $4(nG5(A,$.error));return $.result.map((J)=>J.name)}async function Hj(A,Q,B){if(Q.length===0)return;try{await nr0(A,Q,B)}catch($){j.error("Failed to label thread",{error:$})}}var wv4=1048576;function aG5(A){return A!==void 0}function oG5(A){for(let Q of A)if(Q.type==="tool_result"&&!S5(Q.run.status))return!1;return!0}function Lv4(A){return A.parentToolUseId===void 0}function Ov4(A){return A.role==="assistant"&&Lv4(A)}function Cv4(A){return A.filter((Q)=>Ov4(Q)&&Q.state.type!=="streaming").length}function Mv4(A){return A.messages.findLast(Ov4)}function rG5(A){return A.protocolMessageID??(A.messageId!==void 0?`${A.role}:${A.parentToolUseId??"top-level"}:${A.messageId}`:void 0)}function sG5(A){if(!Lv4(A))return 1;switch(A.role){case"user":return oG5(A.content)?0:2;case"assistant":return A.state.type!=="streaming"?0:2;default:return 1}}async function jv4({handle:A,threadID:Q,initialThread:B,userInput:$,stdinInput:J,dependencies:Y,streamJsonInput:Z=!1,streamJsonThinking:F=!1,stdin:X=process.stdin,ampURL:D="https://ampcode.com",isInternalUser:G=!1,agentMode:V,reasoningEffort:U,labels:K}){let E=B??await T1(A.thread$.pipe(w2(1),MB(5000))),z=V??E.agentMode??"smart",W=Q,H=Date.now(),q=0,N=!1,I=E,w=null;if(J&&J.length>wv4)throw Error(`Stdin input too large: ${J.length} bytes (max ${wv4})`);let O,P=Gx(()=>{if(!N)O("User cancelled (SIGINT/SIGTERM)")});try{P.install();let k=(await T1(Y.toolService.getTools(z).pipe(w2(1),MB(5000)))).map((H0)=>H0.spec.name),x=[];try{x=(await T1(Y.mcpService.servers.pipe(w2(1),MB(5000)))).map((V0)=>({name:V0.name,status:V0.status.type}))}catch(H0){j.warn("Unable to obtain MCP server list for system init message",{err:H0})}let h={type:"system",subtype:"init",cwd:process.cwd(),session_id:W,tools:k,mcp_servers:x,agent_mode:z};if(U!==void 0)h.reasoning_effort=U;await hF(h);let f=Cv4(E.messages),S=E.messages.length,u=new Set,d=[],c=!Z,g=!1,l=[],A0=UF0(async(H0)=>{while(S<H0.messages.length){let V0=H0.messages[S],w0=sG5(V0);if(w0===1){S++;continue}if(w0===2)break;let Z0=rG5(V0);if(!Z0||!u.has(Z0)){if(V0.role==="user")await hF(zv4(V0,W,null));else if(V0.role==="assistant"){if(V0.content.length>0){let R0=Ev4(V0,W,null,{includeThinking:F});await hF(R0)}q++}if(Z0)u.add(Z0)}S++}});return new Promise((H0,V0)=>{O=async(N0)=>{if(N){j.debug("Complete called multiple times, ignoring",{error:N0});return}N=!0,P.remove();try{try{let n=await T1(A.thread$.pipe(w2(1),MB(1000)));I=n,await A0(n)}catch(n){j.debug("Unable to flush pending thread messages before completion",{error:n})}if(N0){let n={type:"result",subtype:"error_during_execution",duration_ms:Date.now()-H,is_error:!0,num_turns:q,error:N0,session_id:W};await hF(n)}else{let n=I?Mv4(I):null,o=n?E8(n.content):"",r={type:"result",subtype:"success",duration_ms:Date.now()-H,is_error:!1,num_turns:q,result:o,session_id:W};await hF(r)}if(w0.unsubscribe(),Z0.unsubscribe(),d.forEach((n)=>n.unsubscribe()),await A.postExecuteMode?.(),K&&K.length>0)await Hj(Q,K,Y.configService);H0()}catch(n){j.error("Error during completion",{error:n}),V0(n)}};let w0=A.threadViewState$.subscribe(async(N0)=>{try{if(w=N0,N0.state==="active"&&N0.ephemeralError){await O(jU(N0.ephemeralError));return}if(l.length>0){let n=[...new Set(l.map((r)=>r.toolName))],o=n.length>0?`The following tools require user approval, which is not supported in stream JSON mode: ${n.join(", ")}`:"A tool requires user approval, which is not supported in stream JSON mode";await O(o);return}if(N0.state==="active"&&N0.inferenceState==="idle"&&I){let n=I.messages.flatMap((o)=>o.content.map((r)=>{if(r.type==="tool_result"&&r.run.status==="blocked-on-user")return a9(I,r.toolUseID)}).filter(aG5));if(n.length>0){j.warn("Tools require user consent - exiting stream JSON mode",{blockedTools:n.map((e)=>({name:e.name,id:e.id}))});let r=`The following tools require user approval, which is not supported in stream JSON mode: ${n.map((e)=>e.name).join(", ")}`;await O(r);return}}if(c&&g&&N0.state==="active"&&N0.inferenceState==="idle")await O()}catch(n){j.error("Error in status subscription",{error:n}),await O(jU(n))}}),Z0=A.thread$.subscribe(async(N0)=>{try{I=N0,await A0(N0);let n=Cv4(N0.messages),o=Mv4(N0);if(g=n>f&&o!==void 0&&o.state.type!=="streaming"&&Ak(o)&&!o.content.some((r)=>r.type==="tool_use"),c&&g&&w?.state==="active"&&w.inferenceState==="idle")await O()}catch(n){j.error("Error in thread subscription",{error:n}),await O(jU(n))}}),R0=A.pendingApprovals$.subscribe((N0)=>{if(l=N0,N0.length>0){let n=[...new Set(N0.map((r)=>r.toolName))],o=n.length>0?`The following tools require user approval, which is not supported in stream JSON mode: ${n.join(", ")}`:"A tool requires user approval, which is not supported in stream JSON mode";O(o)}});d.push(R0);let B0=A.inferenceErrors$?.subscribe((N0)=>{O(jU(N0))});if(B0)d.push(B0);if(Z)(async()=>{try{for await(let N0 of KF0(X)){if(N)break;await A.sendMessage({content:N0.contentBlocks,agentMode:z})}if(c=!0,g&&w?.state==="active"&&w.inferenceState==="idle")await O()}catch(N0){j.error("Error processing streaming input",{error:N0}),await O(jU(N0))}})();else(async()=>{try{let N0=[{type:"text",text:$}];if(J)N0.unshift({type:"text",text:`Input received on stdin:
4659
4659
  \`\`\`
4660
4660
  ${J}
4661
4661
  \`\`\``});if(await A.sendMessage({content:N0,agentMode:z}),c=!0,g&&w?.state==="active"&&w.inferenceState==="idle")await O()}catch(N0){j.error("Error processing input",{error:N0}),await O(jU(N0))}})()})}catch(T){throw P.remove(),T}}async function Tv4(A){let{threadPool:Q,userInput:B,stdinInput:$,dependencies:J,streamJson:Y,streamJsonInput:Z,streamJsonThinking:F,stats:X,ampURL:D,isInternalUser:G,agentMode:V,reasoningEffort:U,labels:K}=A,E=await T1(Q.threadHandles$.pipe(t6((N)=>N!==null),w2(1),MB(5000))),z=await T1(E.thread$.pipe(w2(1),MB(5000))),W=z.id;if(await E.preExecuteMode?.(),E.setReasoningEffortOverride?.(U),Y)return await jv4({handle:E,threadID:W,initialThread:z,userInput:B,stdinInput:$,dependencies:J,streamJsonInput:Z,streamJsonThinking:F,ampURL:D,isInternalUser:G,agentMode:V,reasoningEffort:U,labels:K}),W;let H=Rv4(z.messages),q=[{type:"text",text:B}];if($)q.unshift({type:"text",text:`Input received on stdin:
@@ -4680,9 +4680,9 @@ ${_v4("\t",l??"(unknown)")}
4680
4680
  `)}else if(l)process.stdout.write(l+`
4681
4681
  `);await x()}}})})}function Rv4(A){return A.filter((Q)=>Q.role==="assistant"&&Q.state.type!=="streaming").length}function Pv4(A){if(A instanceof Error)if(tv(A))return"Unauthorized. Check your access token.";else if(rV(A))return"Context window limit reached.";else if(UO(A))return"Model provider overloaded. Try again in a few seconds.";else if(KO(A))return"Model stream timed out. Try again in a few seconds.";else if(sv(A))return"Insufficient credit balance.";else return A.message;if(typeof A==="object"&&A&&"message"in A&&typeof A.message==="string")return A.message;return String(A)}function _v4(A,Q){if(!Q)return Q;return A+Q.split(`
4682
4682
  `).join(`
4683
- `+A)}d0();import{randomUUID as kH5}from"node:crypto";x4();M1();class EF0 extends Error{constructor(A){super(A);this.name="ThreadClientError"}}class c3 extends EF0{cause;constructor(A,Q){super(A);this.cause=Q;this.name="NetworkError"}}class J9 extends EF0{cause;constructor(A,Q){super(A);this.cause=Q;this.name="ThreadClientConnectionError"}}r1();RH();M3();v5();x4();pH();d0();x4();var rG5=0,kv4=0,ar0=0,Vx=new Map,Sv4=typeof FinalizationRegistry>"u"?void 0:new FinalizationRegistry(({boundaryRef:A,threadID:Q})=>{if(Vx.get(Q)?.boundaryRef===A)Vx.delete(Q)});function fv4(A,Q,B,$){let J=typeof process<"u"&&process.env.AMP_BUILD_TRANSCRIPT_PERF_LOG!==void 0,Y=++rG5,Z=J?performance.now():0,F=J?vv4():void 0,X=!1,D=A.length,G=0,{threadID:V,...U}=Q,K=typeof process<"u"&&process.env.AMP_BUILD_TRANSCRIPT_CACHE==="0",E={activityGroups:Q.activityGroups,aggman:Q.aggman,compactionCutMessageIDs:Q.compactionCutMessageIDs,isWorking:!1},z;if(K)z=B(A,E);else{let H=JSON.stringify({activityGroups:E.activityGroups??!0,aggman:E.aggman??!1,compactionCutMessageIDs:Array.from(new Set(E.compactionCutMessageIDs??[])).sort()}),q=eG5(A);if(q===-1)ar0+=1,z=B(A,E);else{let N=A[q],I=tG5(V,A,q,H);if(I){X=!0,kv4+=1,G=I.cachedPrefix.messageCount,D=A.length-I.cachedPrefix.messageCount;let w=q+1,O=I.cachedPrefix.entries.concat(B(A.slice(I.cachedPrefix.messageCount,w),E));if(w!==I.cachedPrefix.messageCount)yv4(V,N,H,{messageCount:w,entries:O});z=O.concat(B(A.slice(w),E))}else{ar0+=1;let w=q+1,O=B(A.slice(0,w),E);yv4(V,N,H,{messageCount:w,entries:O}),G=w,z=O.concat(B(A.slice(w),E))}}}let W=$(z,U);if(J){let H=vv4(),q=sG5(F,H);j.debug("buildTranscript completed",{callCount:Y,durationUs:Math.round((performance.now()-Z)*1000),threadID:V,messageCount:A.length,cachedPrefixMessageCount:G,cachePartialHit:X&&D>0,cacheProcessedMessageCount:D,cacheHit:X,cacheDisabled:K,cacheHits:kv4,cacheMisses:ar0,memoryUsageAvailable:q!==void 0,heapUsedBeforeBytes:F?.heapUsedBytes,heapUsedAfterBytes:H?.heapUsedBytes,heapUsedDeltaBytes:q?.heapUsedBytes,heapTotalDeltaBytes:q?.heapTotalBytes,rssDeltaBytes:q?.rssBytes,externalDeltaBytes:q?.externalBytes,arrayBuffersDeltaBytes:q?.arrayBuffersBytes})}return W}function vv4(){if(typeof process>"u"||typeof process.memoryUsage!=="function")return;let A=process.memoryUsage();return{arrayBuffersBytes:A.arrayBuffers,externalBytes:A.external,heapTotalBytes:A.heapTotal,heapUsedBytes:A.heapUsed,rssBytes:A.rss}}function sG5(A,Q){if(!A||!Q)return;return{arrayBuffersBytes:Q.arrayBuffersBytes-A.arrayBuffersBytes,externalBytes:Q.externalBytes-A.externalBytes,heapTotalBytes:Q.heapTotalBytes-A.heapTotalBytes,heapUsedBytes:Q.heapUsedBytes-A.heapUsedBytes,rssBytes:Q.rssBytes-A.rssBytes}}function tG5(A,Q,B,$){let J=Vx.get(A);if(!J)return;if(J.cacheKey!==$)return;let Y=J.boundaryRef.deref();if(!Y){Vx.delete(A);return}let Z=J.messageCount-1;if(Z>B)return;if(Q[Z]!==Y)return;return{cachedPrefix:J}}function yv4(A,Q,B,$){let J=Vx.get(A);if(J)Sv4?.unregister(J.boundaryRef);let Y=new WeakRef(Q);Vx.set(A,{...$,boundaryRef:Y,cacheKey:B}),Sv4?.register(Q,{boundaryRef:Y,threadID:A},Y)}function eG5(A){let Q=-1,B=new Set,$=new Set;for(let[J,Y]of A.entries()){if(Y.role==="assistant"){for(let Z of Y.content){if(Z.type!=="tool_use")continue;if(Z.name!==void 0&&w30(Z.name)){if(Z.id!==void 0)$.add(Z.id);continue}if(Z.id!==void 0)B.add(Z.id)}if(xv4(Y)&&AV5(Y,J,A.length))Q=J;continue}if(Y.role==="user"){for(let Z of Y.content){if(Z.type!=="tool_result"||Z.toolUseID===void 0)continue;if($.has(Z.toolUseID))continue;B.delete(Z.toolUseID)}if(xv4(Y)){Q=J;continue}if(B.size===0&&QV5(A,J))Q=J}}return Q}function AV5(A,Q,B){if(A.state===void 0)return Q<B-1;return A.state.type==="complete"||A.state.type==="cancelled"||A.state.type==="error"}function xv4(A){return A.content.length===1&&bv4(A.content[0])}function QV5(A,Q){let B=A[Q+1];if(B?.role!=="assistant")return!1;let $=B.content.find((J)=>J.type!=="thinking"&&J.type!=="redacted_thinking");return $!==void 0&&bv4($)}function bv4(A){return A?.type==="text"&&!A.hidden&&(A.text??"").trim()!==""}function WF0(A){return A.type==="compaction"||A.parentToolUseID===void 0}function Bs0(A){let Q=new Map;for(let B of A){if(B.type==="compaction"||B.parentToolUseID===void 0)continue;let $=er0(B.parentToolUseID),J=Q.get($)??[];J.push(B),Q.set($,J)}return Q}function $s0(A,Q){if(A===void 0)return[];return Q.get(A)??[]}function HF0(A,Q){switch(A.type){case"message":return A.role==="assistant"&&A.text.trim()!=="";case"tool":return!0;case"activity-group":return A.actions.length>0||A.label!==void 0||A.detail!==void 0||A.error!==void 0||Q(A.rowID).some((B)=>HF0(B,Q));case"compaction":case"thinking":return!1}}function gv4(A,Q){if(A.label!==void 0||A.detail!==void 0||A.error!==void 0||A.actions.length===0)return!1;return!Q(A.rowID).some((B)=>HF0(B,Q))}function BV5(A){let Q=[...A];for(let B=0;B<A.length;B++){let $=Bs0(Q),J=!1,Y=Q.map((Z)=>{let F=$V5(Z,$);if(F!==Z)J=!0;return F});if(!J)return Y;Q=Y}return Q}function $V5(A,Q){if(A.type!=="activity-group"||A.rowID===void 0)return A;let B=$s0(A.rowID,Q);if(B.some(mv4))return A.hasInProgress?A:{...A,hasInProgress:!0};if(!A.hasInProgress)return A;if(!YV5(B))return A;let $={...A,actions:JV5(A.actions),hasInProgress:!1};if($.status!==void 0&&vM($.status))$.status="done";return $}function JV5(A){return A.map((Q)=>{if(Q.status==="queued"||Q.status==="in-progress")return{...Q,status:"done"};return Q})}function YV5(A){return!A.some(mv4)&&A.some(ZV5)}function mv4(A){if(A.type==="activity-group")return A.hasInProgress;if(pv4(A))return!0;return A.type==="tool"&&vM(A.tool.status)}function ZV5(A){return A.type==="message"&&A.role==="assistant"&&A.text.trim()!==""&&!pv4(A)}function pv4(A){return A.type==="message"&&A.role==="assistant"&&A.isStreaming===!0}function FV5(A){if(A.isStreaming===!0)return!0;if(A.state?.type==="streaming")return!0;return A.state?.type==="complete"&&"stopReason"in A.state&&A.state.stopReason===null}function dv4(A){return{activityGroups:!XV5.has(A)}}var XV5=new Set(["rush","large"]);function er0(A,Q){return Q===void 0?`tool:${A}`:`tool:${A}:${Q}`}function DV5(A,Q){return`manual-bash:${A}:${Q}`}function or0(A){return A==="done"||A==="in-progress"||A==="queued"||A==="blocked-on-user"||A==="cancellation-requested"||A==="error"||A==="cancelled"||A==="rejected-by-user"}function GV5(A){if(A.message.content.length===0&&A.message.images.length===0)return;let{message:Q}=A,$={type:"message",text:Q.content.map((J)=>(J.text??"").trim()).join(`
4683
+ `+A)}d0();import{randomUUID as SH5}from"node:crypto";x4();M1();class EF0 extends Error{constructor(A){super(A);this.name="ThreadClientError"}}class c3 extends EF0{cause;constructor(A,Q){super(A);this.cause=Q;this.name="NetworkError"}}class J9 extends EF0{cause;constructor(A,Q){super(A);this.cause=Q;this.name="ThreadClientConnectionError"}}r1();RH();M3();v5();x4();pH();d0();x4();var tG5=0,kv4=0,ar0=0,Vx=new Map,Sv4=typeof FinalizationRegistry>"u"?void 0:new FinalizationRegistry(({boundaryRef:A,threadID:Q})=>{if(Vx.get(Q)?.boundaryRef===A)Vx.delete(Q)});function fv4(A,Q,B,$){let J=typeof process<"u"&&process.env.AMP_BUILD_TRANSCRIPT_PERF_LOG!==void 0,Y=++tG5,Z=J?performance.now():0,F=J?vv4():void 0,X=!1,D=A.length,G=0,{threadID:V,...U}=Q,K=typeof process<"u"&&process.env.AMP_BUILD_TRANSCRIPT_CACHE==="0",E={activityGroups:Q.activityGroups,aggman:Q.aggman,compactionCutMessageIDs:Q.compactionCutMessageIDs,isWorking:!1},z;if(K)z=B(A,E);else{let H=JSON.stringify({activityGroups:E.activityGroups??!0,aggman:E.aggman??!1,compactionCutMessageIDs:Array.from(new Set(E.compactionCutMessageIDs??[])).sort()}),q=QV5(A);if(q===-1)ar0+=1,z=B(A,E);else{let N=A[q],I=AV5(V,A,q,H);if(I){X=!0,kv4+=1,G=I.cachedPrefix.messageCount,D=A.length-I.cachedPrefix.messageCount;let w=q+1,O=I.cachedPrefix.entries.concat(B(A.slice(I.cachedPrefix.messageCount,w),E));if(w!==I.cachedPrefix.messageCount)yv4(V,N,H,{messageCount:w,entries:O});z=O.concat(B(A.slice(w),E))}else{ar0+=1;let w=q+1,O=B(A.slice(0,w),E);yv4(V,N,H,{messageCount:w,entries:O}),G=w,z=O.concat(B(A.slice(w),E))}}}let W=$(z,U);if(J){let H=vv4(),q=eG5(F,H);j.debug("buildTranscript completed",{callCount:Y,durationUs:Math.round((performance.now()-Z)*1000),threadID:V,messageCount:A.length,cachedPrefixMessageCount:G,cachePartialHit:X&&D>0,cacheProcessedMessageCount:D,cacheHit:X,cacheDisabled:K,cacheHits:kv4,cacheMisses:ar0,memoryUsageAvailable:q!==void 0,heapUsedBeforeBytes:F?.heapUsedBytes,heapUsedAfterBytes:H?.heapUsedBytes,heapUsedDeltaBytes:q?.heapUsedBytes,heapTotalDeltaBytes:q?.heapTotalBytes,rssDeltaBytes:q?.rssBytes,externalDeltaBytes:q?.externalBytes,arrayBuffersDeltaBytes:q?.arrayBuffersBytes})}return W}function vv4(){if(typeof process>"u"||typeof process.memoryUsage!=="function")return;let A=process.memoryUsage();return{arrayBuffersBytes:A.arrayBuffers,externalBytes:A.external,heapTotalBytes:A.heapTotal,heapUsedBytes:A.heapUsed,rssBytes:A.rss}}function eG5(A,Q){if(!A||!Q)return;return{arrayBuffersBytes:Q.arrayBuffersBytes-A.arrayBuffersBytes,externalBytes:Q.externalBytes-A.externalBytes,heapTotalBytes:Q.heapTotalBytes-A.heapTotalBytes,heapUsedBytes:Q.heapUsedBytes-A.heapUsedBytes,rssBytes:Q.rssBytes-A.rssBytes}}function AV5(A,Q,B,$){let J=Vx.get(A);if(!J)return;if(J.cacheKey!==$)return;let Y=J.boundaryRef.deref();if(!Y){Vx.delete(A);return}let Z=J.messageCount-1;if(Z>B)return;if(Q[Z]!==Y)return;return{cachedPrefix:J}}function yv4(A,Q,B,$){let J=Vx.get(A);if(J)Sv4?.unregister(J.boundaryRef);let Y=new WeakRef(Q);Vx.set(A,{...$,boundaryRef:Y,cacheKey:B}),Sv4?.register(Q,{boundaryRef:Y,threadID:A},Y)}function QV5(A){let Q=-1,B=new Set,$=new Set;for(let[J,Y]of A.entries()){if(Y.role==="assistant"){for(let Z of Y.content){if(Z.type!=="tool_use")continue;if(Z.name!==void 0&&w30(Z.name)){if(Z.id!==void 0)$.add(Z.id);continue}if(Z.id!==void 0)B.add(Z.id)}if(B.size===0&&xv4(Y)&&BV5(Y,J,A.length))Q=J;continue}if(Y.role==="user"){for(let Z of Y.content){if(Z.type!=="tool_result"||Z.toolUseID===void 0)continue;if($.has(Z.toolUseID))continue;B.delete(Z.toolUseID)}if(xv4(Y)){Q=J;continue}if(B.size===0&&$V5(A,J))Q=J}}return Q}function BV5(A,Q,B){if(A.state===void 0)return Q<B-1;return A.state.type==="complete"||A.state.type==="cancelled"||A.state.type==="error"}function xv4(A){return A.content.length===1&&bv4(A.content[0])}function $V5(A,Q){let B=A[Q+1];if(B?.role!=="assistant")return!1;let $=B.content.find((J)=>J.type!=="thinking"&&J.type!=="redacted_thinking");return $!==void 0&&bv4($)}function bv4(A){return A?.type==="text"&&!A.hidden&&(A.text??"").trim()!==""}function WF0(A){return A.type==="compaction"||A.parentToolUseID===void 0}function Bs0(A){let Q=new Map;for(let B of A){if(B.type==="compaction"||B.parentToolUseID===void 0)continue;let $=er0(B.parentToolUseID),J=Q.get($)??[];J.push(B),Q.set($,J)}return Q}function $s0(A,Q){if(A===void 0)return[];return Q.get(A)??[]}function HF0(A,Q){switch(A.type){case"message":return A.role==="assistant"&&A.text.trim()!=="";case"tool":return!0;case"activity-group":return A.actions.length>0||A.label!==void 0||A.detail!==void 0||A.error!==void 0||Q(A.rowID).some((B)=>HF0(B,Q));case"compaction":case"thinking":return!1}}function gv4(A,Q){if(A.label!==void 0||A.detail!==void 0||A.error!==void 0||A.actions.length===0)return!1;return!Q(A.rowID).some((B)=>HF0(B,Q))}function JV5(A){let Q=[...A];for(let B=0;B<A.length;B++){let $=Bs0(Q),J=!1,Y=Q.map((Z)=>{let F=YV5(Z,$);if(F!==Z)J=!0;return F});if(!J)return Y;Q=Y}return Q}function YV5(A,Q){if(A.type!=="activity-group"||A.rowID===void 0)return A;let B=$s0(A.rowID,Q);if(B.some(mv4))return A.hasInProgress?A:{...A,hasInProgress:!0};if(!A.hasInProgress)return A;if(!ZV5(B))return A;let $={...A,hasInProgress:!1};if($.status!==void 0&&vM($.status))$.status="done";return $}function ZV5(A){return!A.some(mv4)&&A.some(FV5)}function mv4(A){if(A.type==="activity-group")return A.hasInProgress;if(pv4(A))return!0;return A.type==="tool"&&vM(A.tool.status)}function FV5(A){return A.type==="message"&&A.role==="assistant"&&A.text.trim()!==""&&!pv4(A)}function pv4(A){return A.type==="message"&&A.role==="assistant"&&A.isStreaming===!0}function XV5(A){if(A.isStreaming===!0)return!0;if(A.state?.type==="streaming")return!0;return A.state?.type==="complete"&&"stopReason"in A.state&&A.state.stopReason===null}function dv4(A){return{activityGroups:!DV5.has(A)}}var DV5=new Set(["rush","large"]);function er0(A,Q){return Q===void 0?`tool:${A}`:`tool:${A}:${Q}`}function GV5(A,Q){return`manual-bash:${A}:${Q}`}function or0(A){return A==="done"||A==="in-progress"||A==="queued"||A==="blocked-on-user"||A==="cancellation-requested"||A==="error"||A==="cancelled"||A==="rejected-by-user"}function VV5(A){if(A.message.content.length===0&&A.message.images.length===0)return;let{message:Q}=A,$={type:"message",text:Q.content.map((J)=>(J.text??"").trim()).join(`
4684
4684
 
4685
- `),images:Q.images,timestampLookupID:A.timestampLookupID,parentToolUseID:A.parentToolUseID,role:Q.role};if(A.sourceMessageID!==void 0)$.sourceMessageID=A.sourceMessageID;if(Q.role==="user")$.fromAggman=Q.fromAggman,$.fromExecutorThreadID=Q.fromExecutorThreadID;else if(Q.isStreaming)$.isStreaming=!0;return $}function VV5(A){let Q=A.manualBashInvocation.toolRun;return{type:"tool",timestampLookupID:A.timestampLookupID,parentToolUseID:A.parentToolUseID,tool:{kind:"bash",rowID:A.rowID,command:A.manualBashInvocation.args.cmd,status:Q.status,output:Ys0(Q),exitCode:By4(Q),error:$8(Q)}}}function UV5(A,Q={}){return _V5(RV5(A,Q.compactionCutMessageIDs),Q).filter(zV5)}function cv4(A,Q){return fv4(A,Q,UV5,KV5)}function KV5(A,Q){let B=BV5(A);if(!Q.isWorking)return B;return EV5(B)}function EV5(A){for(let Q=A.length-1;Q>=0;Q--){let B=A[Q];if(B.type==="thinking"||!WF0(B))continue;if(B.type==="activity-group"){if(!Dy4(B))break;let $=A.slice();return $[Q]={...B,hasInProgress:!0},$}break}return A}function zV5(A){if(A.type==="thinking"&&A.text.trim()==="")return!1;if(A.type==="message"&&A.text===""&&A.images.length===0)return!1;return!0}function WV5(A){if(A.protocolMessageID!==void 0)return A.protocolMessageID;if(typeof A.messageId==="string"&&A.messageId.startsWith("M-"))return A.messageId;return}function lv4(A,Q){return{kind:"bash",command:A,status:Q.status,output:Ys0(Q),exitCode:By4(Q),error:$8(Q)}}function iv4(A,Q){let B=AI(A.path);if(B===void 0)return;let $=Q.status==="done"&&typeof Q.result==="object"&&Q.result&&"diff"in Q.result?Q.result.diff:void 0,J=Q.status==="done"?VV(A.old_str,A.new_str):{added:0,deleted:0,changed:0};return{kind:"edit",uri:B,status:Q.status,diff:$,linesAdded:J.added,linesDeleted:J.deleted,error:$8(Q)}}function AI(A){return typeof A==="string"&&A.trim()!==""?b1(o0.file(A)):void 0}function nv4(A,Q){let B=AI(A.path);if(B===void 0)return;let $=typeof A.content==="string"?A.content:void 0,J=UV($);return{kind:"create-file",uri:B,status:Q.status,content:$,linesAdded:J.added,error:$8(Q)}}function HV5(A,Q){let B=AI(A.path);if(B===void 0)return;let $=A.read_range,J=Array.isArray($)&&$.length===2&&typeof $[0]==="number"&&typeof $[1]==="number"?[$[0],$[1]]:void 0,Y={kind:"read",uri:B,status:Q.status,error:$8(Q)};if(J)return{...Y,readRange:J};return Y}function av4(A,Q){let B=AI(A.path);if(B===void 0)return;let $=typeof A.objective==="string"&&A.objective.trim()!==""?A.objective.trim():void 0,J=typeof A.context==="string"&&A.context.trim()!==""?A.context.trim():void 0,Y=Array.isArray(A.referenceFiles)?A.referenceFiles.filter((F)=>typeof F==="string"):[],Z={kind:"look-at",uri:B,referenceFiles:Y,status:Q.status,error:$8(Q)};if($)Z.objective=$;if(J)Z.context=J;return Z}function qV5(A,Q){let B=typeof A.threadID==="string"&&A.threadID.trim()!==""?A.threadID.trim():void 0,$=typeof A.goal==="string"&&A.goal.trim()!==""?A.goal.trim():void 0,J=Q.status==="done"&&typeof Q.result==="string"&&Q.result.length>0?Q.result:void 0,Z=(Q.status==="in-progress"?Q.progress:void 0)?.statusMessage,F={kind:"read-thread",status:Q.status,error:$8(Q)};if(B)F.threadID=B;if($)F.goal=$;if(J)F.markdownResult=J;if(Z)F.statusMessage=Z;return F}function ov4(A,Q){return{kind:"edit",uri:A.uri,status:Q.status,diff:A.diff||void 0,linesAdded:A.additions,linesDeleted:A.deletions,error:$8(Q)}}function rv4(A,Q){return{kind:"read-web-page",url:Zy4(A),status:Q.status,error:$8(Q)}}function NV5(A,Q){let B=OV5(Q);return{kind:"find-thread",query:(typeof A.query==="string"?A.query.trim():void 0)||void 0,status:Q.status,threads:B?.threads??[],hasMore:B?.hasMore??!1,error:$8(Q)}}function sv4(A,Q,B){let $=typeof Q.prompt==="string"?Q.prompt.trim():void 0,J=vV5(B);return{kind:"painter",title:A==="render_agg_man"?"Render Agg Man":void 0,prompt:$,status:B.status,images:J?.images??[],error:$8(B)}}function IV5(A,Q,B){if(Js0(A)){let J=Ay4(Q);if(J)return lv4(J,B)}if(A==="edit_file")return iv4(Q,B);if(A==="create_file")return nv4(Q,B);if(A==="Read")return HV5(Q,B);if(A==="look_at")return av4(Q,B);if(A==="read_thread")return qV5(Q,B);if(A==="apply_patch"){if(B.status==="error")return{kind:"generic",name:A,detail:gF(Q),status:B.status,error:$8(B)};let J=$y4(B);if(J&&J.length>0)return ov4(J[0],B);let Y=Jy4(Q),Z=Y?Yy4(Y):[],F=AI(Z[0]?.path);if(F===void 0)return;let X={kind:"edit",uri:F,status:B.status,diff:Z[0]?.diff,linesAdded:Z[0]?.additions??0,linesDeleted:Z[0]?.deletions??0,error:$8(B)};if(Z[0]?.path)X.displayPath=Z[0].path;return X}if(A==="read_web_page")return rv4(Q,B);if(A==="find_thread")return NV5(Q,B);if(A==="painter"||A==="render_agg_man")return sv4(A,Q,B);let $=ev4(B);return{kind:"generic",name:A,detail:gF(Q),status:B.status,error:$8(B),...$.length>0?{images:$}:{}}}function tv4(A){switch(A.kind){case"bash":return{action:GV("Bash"),detail:A.command};case"edit":return{action:rr0(A.status,"Edited","Editing"),detail:A.displayPath??o0.parse(A.uri).fsPath};case"create-file":return{action:rr0(A.status,"Created","Creating"),detail:o0.parse(A.uri).fsPath};case"read":return{action:GV("Read"),detail:o0.parse(A.uri).fsPath};case"look-at":return{action:GV("look_at"),detail:o0.parse(A.uri).fsPath};case"read-thread":return{action:GV("read_thread"),detail:A.threadID};case"painter":return{action:A.title??GV("painter"),detail:A.prompt};case"read-web-page":return{action:GV("Read"),detail:A.url};case"find-thread":return{action:GV("find_thread"),detail:A.query};case"generic":if(CV5(A))return{action:rr0(A.status,"Ran tool","Running tool"),detail:A.name};return{action:A.name,detail:A.detail}}}function rr0(A,Q,B){switch(A){case"in-progress":case"queued":case"blocked-on-user":case"cancellation-requested":return B;case"done":case"error":case"cancelled":case"rejected-by-user":return Q}}function wV5(A){return A.kind==="generic"&&MV5.has(A.name)}function CV5(A){return A.kind==="generic"&&!wV5(A)&&typeof A.markdownResponse!=="string"&&!LV5.has(A.name)}var MV5=new Set(["Web Search"]),LV5=new Set(["Slack"]);function ev4(A){if(A.status!=="done"||!Array.isArray(A.result))return[];return A.result.filter(PQ0).filter((Q)=>Q.type==="image").map((Q)=>({mimeType:Q.mimeType,data:Q.data}))}function OV5(A){if(A.status!=="done"||!aB(A.result))return;return{threads:Array.isArray(A.result.threads)?A.result.threads.filter(jV5):[],hasMore:A.result.hasMore===!0}}function jV5(A){return aB(A)&&typeof A.id==="string"&&typeof A.creatorUserID==="string"&&typeof A.created==="number"&&typeof A.updatedAt==="string"&&typeof A.messageCount==="number"&&(A.title===void 0||typeof A.title==="string")&&(A.matchedSearchText===void 0||typeof A.matchedSearchText==="string")}function Js0(A){return A==="Bash"||A==="shell_command"||A==="run_terminal_command"}function RV5(A,Q){let B=[],$=new Map,J=new Set,Y=new Set(Q??[]),Z=[];for(let[F,X]of A.entries()){let D=X.parentToolUseId,G=WV5(X);if(G!==void 0&&Y.has(G))Z.push({cutMessageID:G,messageIndex:F});if(X.role==="assistant"){let V=FV5(X),U=X.content.filter((E)=>E.type==="text"&&!E.hidden&&(E.text??"").trim()!==""),K=X.content.some((E)=>E.type!=="thinking"&&E.type!=="redacted_thinking");for(let E of X.content)if(E.type==="thinking"&&E.thinking.trim()!=="")B.push({type:"thinking",parentToolUseID:D,startMessageIndex:F,endMessageIndex:F,timestampLookupID:X.messageId,text:E.thinking,isStreaming:!K});if(U.length>0)B.push({type:"message",parentToolUseID:D,startMessageIndex:F,endMessageIndex:F,sourceMessageID:X.messageId,timestampLookupID:X.messageId,message:{role:"assistant",content:U,images:[],isStreaming:V}});for(let E of X.content)if(E.type==="tool_use"){if(w30(E.name)){J.add(E.id);continue}if(!E.complete&&Js0(E.normalizedName??E.name)){J.add(E.id);continue}let z=B.push({type:"toolResult",parentToolUseID:D,startMessageIndex:F,endMessageIndex:F,timestampLookupID:X.messageId,toolUse:E})-1;$.set(E.id,{itemIndex:z,messageIndex:F,isStreaming:V,parentToolUseID:D})}}else if(X.role==="user"){for(let z of X.content)if(z.type==="tool_result"){if(J.has(z.toolUseID))continue;let W=$.get(z.toolUseID);if(W){let H=B[W.itemIndex];if(H?.type==="toolResult")H.toolResult=z,H.endMessageIndex=F;$.delete(z.toolUseID)}}let V=X.content.filter((z)=>z.type==="text"&&!z.hidden&&(z.text??"").trim()!==""),U=X.content.filter((z)=>z.type==="image"),K=X.meta?.fromAggman===!0,E=X.meta?.fromExecutorThreadID;if(V.length>0||U.length>0)B.push({type:"message",parentToolUseID:D,startMessageIndex:F,endMessageIndex:F,sourceMessageID:X.messageId,timestampLookupID:X.messageId,message:{role:"user",content:V,images:U,...K?{fromAggman:!0}:{},...E?{fromExecutorThreadID:E}:{}}})}else if(X.role==="info"){for(let[V,U]of X.content.entries())if(U.type==="manual_bash_invocation")B.push({type:"manualBashInvocation",parentToolUseID:D,startMessageIndex:F,endMessageIndex:F,rowID:DV5(X.messageId,V),manualBashInvocation:U})}}for(let[F,X]of $){let D=B[X.itemIndex];if(D?.type!=="toolResult")continue;let V=A.slice(X.messageIndex+1).some((K)=>{if(K.parentToolUseId!==X.parentToolUseID)return!1;if(K.role==="assistant")return!0;return K.content.some((E)=>E.type!=="tool_result")})?"cancelled":X.isStreaming?"in-progress":"queued",U={type:"tool_result",toolUseID:F,run:{status:V}};D.toolResult=U}if(Z.length===0)return B;return PV5(B,Z)}function PV5(A,Q){let B=[],$=[...Q].sort((Y,Z)=>Y.messageIndex-Z.messageIndex),J=0;for(let[Y,Z]of A.entries()){while(J<$.length){let X=$[J];if(X.messageIndex<Z.startMessageIndex){B.push({type:"compaction",cutMessageID:X.cutMessageID}),J++;continue}break}B.push(Z);let F=A[Y+1];while(J<$.length){let X=$[J];if(X.messageIndex<=Z.endMessageIndex&&(F===void 0||X.messageIndex<F.startMessageIndex)){B.push({type:"compaction",cutMessageID:X.cutMessageID}),J++;continue}break}}for(;J<$.length;J++)B.push({type:"compaction",cutMessageID:$[J].cutMessageID});return B}function _V5(A,Q){let B=[],$=Q.activityGroups??!0,J=Q.aggman??!1,Y=[],Z=[],F,X=new Set,D=!1,G,V,U=(I,w,O,L,P)=>{if(Y.length>0&&V!==P)q();if(Y.length===0)V=P;if(Y.push(Xy4(I,w)),L!==void 0&&F===void 0)F=L;if(O!==void 0&&G===void 0)G=O;if(w==="in-progress"||w==="queued")D=!0},K=(I,w,O,L)=>{for(let P of Gy4(I)){let T=`${P.kind}:${P.title}`;if(X.has(T))continue;X.add(T),U(P,I.status,w,O,L)}},E=(I,w,O,L,P)=>{U(I,w.status,O,L,P),K(w,O,L,P)},z=(I,w,O)=>{B.push({type:"tool",tool:I,timestampLookupID:w,parentToolUseID:O})},W=(I)=>{B.push({type:"thinking",text:I.text,isStreaming:I.isStreaming,timestampLookupID:I.timestampLookupID,parentToolUseID:I.parentToolUseID})},H=(I,w,O)=>{if(I.actions.length===0&&I.label===void 0&&I.detail===void 0&&I.error===void 0)return;B.push({type:"activity-group",...I,timestampLookupID:w,parentToolUseID:O})},q=()=>{if(Y.length===0){Z=[];return}let I={rowID:F,actions:D?Y:Y.map(oV5),summary:Qs0(Y),hasInProgress:D};if(Z.length>0)I.thinkings=Z;if(J)I.aggman=!0;H(I,G,V),Y=[],Z=[],F=void 0,X=new Set,D=!1,G=void 0,V=void 0};for(let I of A){if(I.type==="compaction"){q(),B.push(I);continue}if(I.type==="message"){let w=GV5(I);if(w)q(),B.push(w);continue}if(I.type==="manualBashInvocation"){q(),B.push(VV5(I));continue}if(I.type==="thinking"){if($&&Y.length>0)Z.push({type:"thinking",text:I.text,isStreaming:I.isStreaming,timestampLookupID:I.timestampLookupID,parentToolUseID:I.parentToolUseID});else q(),W(I);continue}if(I.type==="toolResult"&&I.toolResult){let w=I.toolUse.normalizedName??I.toolUse.name,O=xV5(I.toolUse),L=I.toolResult.run,P=I.timestampLookupID,T=er0(I.toolUse.id),k=(S,u)=>{if(S===void 0)return;z({...S,rowID:er0(I.toolUse.id,u?.index)},u?.timestampLookupID??P,I.parentToolUseID)},x=()=>{k(IV5(w,O,L))};if($){let S=gV5(w,O);if(S){E(S,L,P,T,I.parentToolUseID);continue}}if(Js0(w)){let S=Ay4(O);if(S){let u=dn0(S),d=u[0]??lO(S),c=u.some((l)=>l.kind==="command");if(u.length===1&&d.isWriteLike&&(d.program==="sed"||d.program==="perl")){if(!or0(L.status))continue;let l=AI(d.path??S);if(l===void 0)continue;q(),k({kind:"edit",uri:l,status:L.status,linesAdded:0,linesDeleted:0,error:$8(L)});continue}let g=u.filter((l)=>l.kind!=="command");if(g.length>0&&!c){if(!$){q(),x();continue}let l=Ys0(L),s=!1;for(let[A0,H0]of g.entries()){let V0=AU5(H0);if(!V0)continue;E({kind:H0.kind,title:V0,...A0===g.length-1&&l?{detail:l}:{}},L,P,T,I.parentToolUseID),s=!0}if(s)continue}q(),k(lv4(S,L));continue}}if(w==="edit_file"){if(!or0(L.status))continue;q(),k(iv4(O,L));continue}if(w==="create_file"){q(),k(nv4(O,L));continue}if(w==="apply_patch"){if(!or0(L.status))continue;if(q(),L.status==="error"){x();continue}let S=$y4(L);if(S&&S.length>0)for(let[u,d]of S.entries())k(ov4(d,L),{index:u});else{let u=Jy4(O),d=u?Yy4(u):[];for(let[c,g]of d.entries()){let l=AI(g.path);if(l===void 0)continue;k({kind:"edit",uri:l,displayPath:g.path,status:L.status,diff:g.diff,linesAdded:g.additions,linesDeleted:g.deletions,error:$8(L)},{index:c})}}continue}if(w==="Read"){if(AI(O.path)===void 0)continue;if(!$){q(),x();continue}let S=zF0(w,O);E({kind:"read",title:S},L,P,T,I.parentToolUseID);continue}if(w==="file_tree"){if(!$){q(),x();continue}let S=zF0(w,O);E({kind:"list",title:S},L,P,T,I.parentToolUseID);continue}if(w==="glob"||w==="Grep"){if(!$){q(),x();continue}let S=zF0(w,O);E({kind:"search",title:S},L,P,T,I.parentToolUseID);continue}if(w==="finder"){q();let S=typeof O.query==="string"?O.query.trim():void 0,u=Zs0([],L),d={rowID:T,label:{active:"Searching codebase",complete:"Searched codebase"},actions:u,summary:Qs0(u),hasInProgress:vM(L.status),status:L.status};if(S!==void 0)d.detail=S;let c=$8(L);if(c!==void 0)d.error=c;H(d,P,I.parentToolUseID);continue}let h=sV5(w,O,L);if(h){q(),H({rowID:T,...h},P,I.parentToolUseID);continue}if(w==="web_search"){q();let S=Fy4(O);k({kind:"generic",name:"Web Search",detail:S,status:L.status,error:$8(L)});continue}if(w==="read_web_page"){q(),k(rv4(O,L));continue}if(w==="read_thread"){if(!$){q(),x();continue}let S=typeof O.threadID==="string"?O.threadID.trim():void 0,u=typeof O.goal==="string"?O.goal.trim():void 0,d=u?`Read thread: ${u}`:S?`Read thread ${S}`:"Read thread";E({kind:"thread",title:d,icon:"threads"},L,P,T,I.parentToolUseID);continue}if(w==="find_thread"){if(!$){q(),x();continue}let S=typeof O.query==="string"?O.query.trim():void 0,u=S?`Searched threads: ${S}`:"Searched threads";E({kind:"search",title:u},L,P,T,I.parentToolUseID);continue}if(w==="skill"){if(!$){q(),x();continue}let S=O.name;E({kind:"read",title:`Read skill ${S}`},L,P,T,I.parentToolUseID);continue}if(w==="get_diagnostics"){if(!$){q(),x();continue}let S=zF0(w,O);E({kind:"read",title:S},L,P,T,I.parentToolUseID);continue}if(w==="look_at"){q(),k(av4(O,L));continue}if(w==="task_list"){q();let S=typeof O.action==="string"?O.action.trim():void 0,u=typeof O.title==="string"?O.title.trim():void 0,d=S&&u?`Task list: ${S} "${u}"`:S?`Task list: ${S}`:"Task list";k({kind:"generic",name:"task_list",detail:d,status:L.status,error:$8(L)});continue}if(w==="painter"||w==="render_agg_man"){q(),k(sv4(w,O,L));continue}if(w==="slack_write"){q();let S=L.status==="done"?"sent message":"sending message…";k({kind:"generic",name:"Slack",detail:S,status:L.status,error:$8(L)});continue}if(w==="slack_read"){q();let S=typeof O.type==="string"?O.type:void 0,u;if(S==="channels")u="searched channels";else if(S==="users")u="searched users";else if(S==="thread")u="read thread";else u="read";k({kind:"generic",name:"Slack",detail:u,status:L.status,error:$8(L)});continue}q();let f=ev4(L);k({kind:"generic",name:w,detail:gF(O),args:aV5(O),status:L.status,error:$8(L),...f.length>0?{images:f}:{}})}}q();let N=kV5(B);if(Q.isWorking)TV5(N);return N}function TV5(A){for(let Q=A.length-1;Q>=0;Q--){let B=A[Q];if(B.type==="thinking"||!WF0(B))continue;if(B.type==="activity-group"){if(!Dy4(B))break;B.hasInProgress=!0}break}}function kV5(A){let Q=[];for(let B of A){let $=Q[Q.length-1];if($&&$.type==="tool"&&B.type==="tool"&&$.parentToolUseID===B.parentToolUseID){let J=$.tool,Y=B.tool,Z=$.timestampLookupID??B.timestampLookupID;if(J.kind==="edit"&&Y.kind==="edit"&&J.uri===Y.uri&&sr0(J.status)&&sr0(Y.status)){let F=J.diff&&Y.diff?`${J.diff}
4685
+ `),images:Q.images,timestampLookupID:A.timestampLookupID,parentToolUseID:A.parentToolUseID,role:Q.role};if(A.sourceMessageID!==void 0)$.sourceMessageID=A.sourceMessageID;if(Q.role==="user")$.fromAggman=Q.fromAggman,$.fromExecutorThreadID=Q.fromExecutorThreadID;else if(Q.isStreaming)$.isStreaming=!0;return $}function UV5(A){let Q=A.manualBashInvocation.toolRun;return{type:"tool",timestampLookupID:A.timestampLookupID,parentToolUseID:A.parentToolUseID,tool:{kind:"bash",rowID:A.rowID,command:A.manualBashInvocation.args.cmd,status:Q.status,output:Ys0(Q),exitCode:By4(Q),error:$8(Q)}}}function KV5(A,Q={}){return TV5(PV5(A,Q.compactionCutMessageIDs),Q).filter(WV5)}function cv4(A,Q){return fv4(A,Q,KV5,EV5)}function EV5(A,Q){let B=JV5(A);if(!Q.isWorking)return B;return zV5(B)}function zV5(A){for(let Q=A.length-1;Q>=0;Q--){let B=A[Q];if(B.type==="thinking"||!WF0(B))continue;if(B.type==="activity-group"){if(!Dy4(B))break;let $=A.slice();return $[Q]={...B,hasInProgress:!0},$}break}return A}function WV5(A){if(A.type==="thinking"&&A.text.trim()==="")return!1;if(A.type==="message"&&A.text===""&&A.images.length===0)return!1;return!0}function HV5(A){if(A.protocolMessageID!==void 0)return A.protocolMessageID;if(typeof A.messageId==="string"&&A.messageId.startsWith("M-"))return A.messageId;return}function lv4(A,Q){return{kind:"bash",command:A,status:Q.status,output:Ys0(Q),exitCode:By4(Q),error:$8(Q)}}function iv4(A,Q){let B=AI(A.path);if(B===void 0)return;let $=Q.status==="done"&&typeof Q.result==="object"&&Q.result&&"diff"in Q.result?Q.result.diff:void 0,J=Q.status==="done"?VV(A.old_str,A.new_str):{added:0,deleted:0,changed:0};return{kind:"edit",uri:B,status:Q.status,diff:$,linesAdded:J.added,linesDeleted:J.deleted,error:$8(Q)}}function AI(A){return typeof A==="string"&&A.trim()!==""?b1(o0.file(A)):void 0}function nv4(A,Q){let B=AI(A.path);if(B===void 0)return;let $=typeof A.content==="string"?A.content:void 0,J=UV($);return{kind:"create-file",uri:B,status:Q.status,content:$,linesAdded:J.added,error:$8(Q)}}function qV5(A,Q){let B=AI(A.path);if(B===void 0)return;let $=A.read_range,J=Array.isArray($)&&$.length===2&&typeof $[0]==="number"&&typeof $[1]==="number"?[$[0],$[1]]:void 0,Y={kind:"read",uri:B,status:Q.status,error:$8(Q)};if(J)return{...Y,readRange:J};return Y}function av4(A,Q){let B=AI(A.path);if(B===void 0)return;let $=typeof A.objective==="string"&&A.objective.trim()!==""?A.objective.trim():void 0,J=typeof A.context==="string"&&A.context.trim()!==""?A.context.trim():void 0,Y=Array.isArray(A.referenceFiles)?A.referenceFiles.filter((F)=>typeof F==="string"):[],Z={kind:"look-at",uri:B,referenceFiles:Y,status:Q.status,error:$8(Q)};if($)Z.objective=$;if(J)Z.context=J;return Z}function NV5(A,Q){let B=typeof A.threadID==="string"&&A.threadID.trim()!==""?A.threadID.trim():void 0,$=typeof A.goal==="string"&&A.goal.trim()!==""?A.goal.trim():void 0,J=Q.status==="done"&&typeof Q.result==="string"&&Q.result.length>0?Q.result:void 0,Z=(Q.status==="in-progress"?Q.progress:void 0)?.statusMessage,F={kind:"read-thread",status:Q.status,error:$8(Q)};if(B)F.threadID=B;if($)F.goal=$;if(J)F.markdownResult=J;if(Z)F.statusMessage=Z;return F}function ov4(A,Q){return{kind:"edit",uri:A.uri,status:Q.status,diff:A.diff||void 0,linesAdded:A.additions,linesDeleted:A.deletions,error:$8(Q)}}function rv4(A,Q){return{kind:"read-web-page",url:Zy4(A),status:Q.status,error:$8(Q)}}function IV5(A,Q){let B=jV5(Q);return{kind:"find-thread",query:(typeof A.query==="string"?A.query.trim():void 0)||void 0,status:Q.status,threads:B?.threads??[],hasMore:B?.hasMore??!1,error:$8(Q)}}function sv4(A,Q,B){let $=typeof Q.prompt==="string"?Q.prompt.trim():void 0,J=yV5(B);return{kind:"painter",title:A==="render_agg_man"?"Render Agg Man":void 0,prompt:$,status:B.status,images:J?.images??[],error:$8(B)}}function wV5(A,Q,B){if(Js0(A)){let J=Ay4(Q);if(J)return lv4(J,B)}if(A==="edit_file")return iv4(Q,B);if(A==="create_file")return nv4(Q,B);if(A==="Read")return qV5(Q,B);if(A==="look_at")return av4(Q,B);if(A==="read_thread")return NV5(Q,B);if(A==="apply_patch"){if(B.status==="error")return{kind:"generic",name:A,detail:gF(Q),status:B.status,error:$8(B)};let J=$y4(B);if(J&&J.length>0)return ov4(J[0],B);let Y=Jy4(Q),Z=Y?Yy4(Y):[],F=AI(Z[0]?.path);if(F===void 0)return;let X={kind:"edit",uri:F,status:B.status,diff:Z[0]?.diff,linesAdded:Z[0]?.additions??0,linesDeleted:Z[0]?.deletions??0,error:$8(B)};if(Z[0]?.path)X.displayPath=Z[0].path;return X}if(A==="read_web_page")return rv4(Q,B);if(A==="find_thread")return IV5(Q,B);if(A==="painter"||A==="render_agg_man")return sv4(A,Q,B);let $=ev4(B);return{kind:"generic",name:A,detail:gF(Q),status:B.status,error:$8(B),...$.length>0?{images:$}:{}}}function tv4(A){switch(A.kind){case"bash":return{action:GV("Bash"),detail:A.command};case"edit":return{action:rr0(A.status,"Edited","Editing"),detail:A.displayPath??o0.parse(A.uri).fsPath};case"create-file":return{action:rr0(A.status,"Created","Creating"),detail:o0.parse(A.uri).fsPath};case"read":return{action:GV("Read"),detail:o0.parse(A.uri).fsPath};case"look-at":return{action:GV("look_at"),detail:o0.parse(A.uri).fsPath};case"read-thread":return{action:GV("read_thread"),detail:A.threadID};case"painter":return{action:A.title??GV("painter"),detail:A.prompt};case"read-web-page":return{action:GV("Read"),detail:A.url};case"find-thread":return{action:GV("find_thread"),detail:A.query};case"generic":if(MV5(A))return{action:rr0(A.status,"Ran tool","Running tool"),detail:A.name};return{action:A.name,detail:A.detail}}}function rr0(A,Q,B){switch(A){case"in-progress":case"queued":case"blocked-on-user":case"cancellation-requested":return B;case"done":case"error":case"cancelled":case"rejected-by-user":return Q}}function CV5(A){return A.kind==="generic"&&LV5.has(A.name)}function MV5(A){return A.kind==="generic"&&!CV5(A)&&typeof A.markdownResponse!=="string"&&!OV5.has(A.name)}var LV5=new Set(["Web Search"]),OV5=new Set(["Slack"]);function ev4(A){if(A.status!=="done"||!Array.isArray(A.result))return[];return A.result.filter(PQ0).filter((Q)=>Q.type==="image").map((Q)=>({mimeType:Q.mimeType,data:Q.data}))}function jV5(A){if(A.status!=="done"||!aB(A.result))return;return{threads:Array.isArray(A.result.threads)?A.result.threads.filter(RV5):[],hasMore:A.result.hasMore===!0}}function RV5(A){return aB(A)&&typeof A.id==="string"&&typeof A.creatorUserID==="string"&&typeof A.created==="number"&&typeof A.updatedAt==="string"&&typeof A.messageCount==="number"&&(A.title===void 0||typeof A.title==="string")&&(A.matchedSearchText===void 0||typeof A.matchedSearchText==="string")}function Js0(A){return A==="Bash"||A==="shell_command"||A==="run_terminal_command"}function PV5(A,Q){let B=[],$=new Map,J=new Set,Y=new Set(Q??[]),Z=[];for(let[F,X]of A.entries()){let D=X.parentToolUseId,G=HV5(X);if(G!==void 0&&Y.has(G))Z.push({cutMessageID:G,messageIndex:F});if(X.role==="assistant"){let V=XV5(X),U=X.content.filter((E)=>E.type==="text"&&!E.hidden&&(E.text??"").trim()!==""),K=X.content.some((E)=>E.type!=="thinking"&&E.type!=="redacted_thinking");for(let E of X.content)if(E.type==="thinking"&&E.thinking.trim()!=="")B.push({type:"thinking",parentToolUseID:D,startMessageIndex:F,endMessageIndex:F,timestampLookupID:X.messageId,text:E.thinking,isStreaming:!K});if(U.length>0)B.push({type:"message",parentToolUseID:D,startMessageIndex:F,endMessageIndex:F,sourceMessageID:X.messageId,timestampLookupID:X.messageId,message:{role:"assistant",content:U,images:[],isStreaming:V}});for(let E of X.content)if(E.type==="tool_use"){if(w30(E.name)){J.add(E.id);continue}if(!E.complete&&Js0(E.normalizedName??E.name)){J.add(E.id);continue}let z=B.push({type:"toolResult",parentToolUseID:D,startMessageIndex:F,endMessageIndex:F,timestampLookupID:X.messageId,toolUse:E})-1;$.set(E.id,{itemIndex:z,messageIndex:F,isStreaming:V,parentToolUseID:D})}}else if(X.role==="user"){for(let z of X.content)if(z.type==="tool_result"){if(J.has(z.toolUseID))continue;let W=$.get(z.toolUseID);if(W){let H=B[W.itemIndex];if(H?.type==="toolResult")H.toolResult=z,H.endMessageIndex=F;$.delete(z.toolUseID)}}let V=X.content.filter((z)=>z.type==="text"&&!z.hidden&&(z.text??"").trim()!==""),U=X.content.filter((z)=>z.type==="image"),K=X.meta?.fromAggman===!0,E=X.meta?.fromExecutorThreadID;if(V.length>0||U.length>0)B.push({type:"message",parentToolUseID:D,startMessageIndex:F,endMessageIndex:F,sourceMessageID:X.messageId,timestampLookupID:X.messageId,message:{role:"user",content:V,images:U,...K?{fromAggman:!0}:{},...E?{fromExecutorThreadID:E}:{}}})}else if(X.role==="info"){for(let[V,U]of X.content.entries())if(U.type==="manual_bash_invocation")B.push({type:"manualBashInvocation",parentToolUseID:D,startMessageIndex:F,endMessageIndex:F,rowID:GV5(X.messageId,V),manualBashInvocation:U})}}for(let[F,X]of $){let D=B[X.itemIndex];if(D?.type!=="toolResult")continue;let V=A.slice(X.messageIndex+1).some((K)=>{if(K.parentToolUseId!==X.parentToolUseID)return!1;if(K.role==="assistant")return!0;return K.content.some((E)=>E.type!=="tool_result")})?"cancelled":X.isStreaming?"in-progress":"queued",U={type:"tool_result",toolUseID:F,run:{status:V}};D.toolResult=U}if(Z.length===0)return B;return _V5(B,Z)}function _V5(A,Q){let B=[],$=[...Q].sort((Y,Z)=>Y.messageIndex-Z.messageIndex),J=0;for(let[Y,Z]of A.entries()){while(J<$.length){let X=$[J];if(X.messageIndex<Z.startMessageIndex){B.push({type:"compaction",cutMessageID:X.cutMessageID}),J++;continue}break}B.push(Z);let F=A[Y+1];while(J<$.length){let X=$[J];if(X.messageIndex<=Z.endMessageIndex&&(F===void 0||X.messageIndex<F.startMessageIndex)){B.push({type:"compaction",cutMessageID:X.cutMessageID}),J++;continue}break}}for(;J<$.length;J++)B.push({type:"compaction",cutMessageID:$[J].cutMessageID});return B}function TV5(A,Q){let B=[],$=Q.activityGroups??!0,J=Q.aggman??!1,Y=[],Z=[],F,X=new Set,D=!1,G,V,U=(I,w,O,L,P)=>{if(Y.length>0&&V!==P)q();if(Y.length===0)V=P;if(Y.push(Xy4(I,w)),L!==void 0&&F===void 0)F=L;if(O!==void 0&&G===void 0)G=O;if(w==="in-progress"||w==="queued")D=!0},K=(I,w,O,L)=>{for(let P of Gy4(I)){let T=`${P.kind}:${P.title}`;if(X.has(T))continue;X.add(T),U(P,I.status,w,O,L)}},E=(I,w,O,L,P)=>{U(I,w.status,O,L,P),K(w,O,L,P)},z=(I,w,O)=>{B.push({type:"tool",tool:I,timestampLookupID:w,parentToolUseID:O})},W=(I)=>{B.push({type:"thinking",text:I.text,isStreaming:I.isStreaming,timestampLookupID:I.timestampLookupID,parentToolUseID:I.parentToolUseID})},H=(I,w,O)=>{if(I.actions.length===0&&I.label===void 0&&I.detail===void 0&&I.error===void 0)return;B.push({type:"activity-group",...I,timestampLookupID:w,parentToolUseID:O})},q=()=>{if(Y.length===0){Z=[];return}let I={rowID:F,actions:D?Y:Y.map(rV5),summary:Qs0(Y),hasInProgress:D};if(Z.length>0)I.thinkings=Z;if(J)I.aggman=!0;H(I,G,V),Y=[],Z=[],F=void 0,X=new Set,D=!1,G=void 0,V=void 0};for(let I of A){if(I.type==="compaction"){q(),B.push(I);continue}if(I.type==="message"){let w=VV5(I);if(w)q(),B.push(w);continue}if(I.type==="manualBashInvocation"){q(),B.push(UV5(I));continue}if(I.type==="thinking"){if($&&Y.length>0)Z.push({type:"thinking",text:I.text,isStreaming:I.isStreaming,timestampLookupID:I.timestampLookupID,parentToolUseID:I.parentToolUseID});else q(),W(I);continue}if(I.type==="toolResult"&&I.toolResult){let w=I.toolUse.normalizedName??I.toolUse.name,O=fV5(I.toolUse),L=I.toolResult.run,P=I.timestampLookupID,T=er0(I.toolUse.id),k=(S,u)=>{if(S===void 0)return;z({...S,rowID:er0(I.toolUse.id,u?.index)},u?.timestampLookupID??P,I.parentToolUseID)},x=()=>{k(wV5(w,O,L))};if($){let S=mV5(w,O);if(S){E(S,L,P,T,I.parentToolUseID);continue}}if(Js0(w)){let S=Ay4(O);if(S){let u=dn0(S),d=u[0]??lO(S),c=u.some((l)=>l.kind==="command");if(u.length===1&&d.isWriteLike&&(d.program==="sed"||d.program==="perl")){if(!or0(L.status))continue;let l=AI(d.path??S);if(l===void 0)continue;q(),k({kind:"edit",uri:l,status:L.status,linesAdded:0,linesDeleted:0,error:$8(L)});continue}let g=u.filter((l)=>l.kind!=="command");if(g.length>0&&!c){if(!$){q(),x();continue}let l=Ys0(L),s=!1;for(let[A0,H0]of g.entries()){let V0=QU5(H0);if(!V0)continue;E({kind:H0.kind,title:V0,...A0===g.length-1&&l?{detail:l}:{}},L,P,T,I.parentToolUseID),s=!0}if(s)continue}q(),k(lv4(S,L));continue}}if(w==="edit_file"){if(!or0(L.status))continue;q(),k(iv4(O,L));continue}if(w==="create_file"){q(),k(nv4(O,L));continue}if(w==="apply_patch"){if(!or0(L.status))continue;if(q(),L.status==="error"){x();continue}let S=$y4(L);if(S&&S.length>0)for(let[u,d]of S.entries())k(ov4(d,L),{index:u});else{let u=Jy4(O),d=u?Yy4(u):[];for(let[c,g]of d.entries()){let l=AI(g.path);if(l===void 0)continue;k({kind:"edit",uri:l,displayPath:g.path,status:L.status,diff:g.diff,linesAdded:g.additions,linesDeleted:g.deletions,error:$8(L)},{index:c})}}continue}if(w==="Read"){if(AI(O.path)===void 0)continue;if(!$){q(),x();continue}let S=zF0(w,O);E({kind:"read",title:S},L,P,T,I.parentToolUseID);continue}if(w==="file_tree"){if(!$){q(),x();continue}let S=zF0(w,O);E({kind:"list",title:S},L,P,T,I.parentToolUseID);continue}if(w==="glob"||w==="Grep"){if(!$){q(),x();continue}let S=zF0(w,O);E({kind:"search",title:S},L,P,T,I.parentToolUseID);continue}if(w==="finder"){q();let S=typeof O.query==="string"?O.query.trim():void 0,u=Zs0([],L),d={rowID:T,label:{active:"Searching codebase",complete:"Searched codebase"},actions:u,summary:Qs0(u),hasInProgress:vM(L.status),status:L.status};if(S!==void 0)d.detail=S;let c=$8(L);if(c!==void 0)d.error=c;H(d,P,I.parentToolUseID);continue}let h=tV5(w,O,L);if(h){q(),H({rowID:T,...h},P,I.parentToolUseID);continue}if(w==="web_search"){q();let S=Fy4(O);k({kind:"generic",name:"Web Search",detail:S,status:L.status,error:$8(L)});continue}if(w==="read_web_page"){q(),k(rv4(O,L));continue}if(w==="read_thread"){if(!$){q(),x();continue}let S=typeof O.threadID==="string"?O.threadID.trim():void 0,u=typeof O.goal==="string"?O.goal.trim():void 0,d=u?`Read thread: ${u}`:S?`Read thread ${S}`:"Read thread";E({kind:"thread",title:d,icon:"threads"},L,P,T,I.parentToolUseID);continue}if(w==="find_thread"){if(!$){q(),x();continue}let S=typeof O.query==="string"?O.query.trim():void 0,u=S?`Searched threads: ${S}`:"Searched threads";E({kind:"search",title:u},L,P,T,I.parentToolUseID);continue}if(w==="skill"){if(!$){q(),x();continue}let S=O.name;E({kind:"read",title:`Read skill ${S}`},L,P,T,I.parentToolUseID);continue}if(w==="get_diagnostics"){if(!$){q(),x();continue}let S=zF0(w,O);E({kind:"read",title:S},L,P,T,I.parentToolUseID);continue}if(w==="look_at"){q(),k(av4(O,L));continue}if(w==="task_list"){q();let S=typeof O.action==="string"?O.action.trim():void 0,u=typeof O.title==="string"?O.title.trim():void 0,d=S&&u?`Task list: ${S} "${u}"`:S?`Task list: ${S}`:"Task list";k({kind:"generic",name:"task_list",detail:d,status:L.status,error:$8(L)});continue}if(w==="painter"||w==="render_agg_man"){q(),k(sv4(w,O,L));continue}if(w==="slack_write"){q();let S=L.status==="done"?"sent message":"sending message…";k({kind:"generic",name:"Slack",detail:S,status:L.status,error:$8(L)});continue}if(w==="slack_read"){q();let S=typeof O.type==="string"?O.type:void 0,u;if(S==="channels")u="searched channels";else if(S==="users")u="searched users";else if(S==="thread")u="read thread";else u="read";k({kind:"generic",name:"Slack",detail:u,status:L.status,error:$8(L)});continue}q();let f=ev4(L);k({kind:"generic",name:w,detail:gF(O),args:oV5(O),status:L.status,error:$8(L),...f.length>0?{images:f}:{}})}}q();let N=SV5(B);if(Q.isWorking)kV5(N);return N}function kV5(A){for(let Q=A.length-1;Q>=0;Q--){let B=A[Q];if(B.type==="thinking"||!WF0(B))continue;if(B.type==="activity-group"){if(!Dy4(B))break;B.hasInProgress=!0}break}}function SV5(A){let Q=[];for(let B of A){let $=Q[Q.length-1];if($&&$.type==="tool"&&B.type==="tool"&&$.parentToolUseID===B.parentToolUseID){let J=$.tool,Y=B.tool,Z=$.timestampLookupID??B.timestampLookupID;if(J.kind==="edit"&&Y.kind==="edit"&&J.uri===Y.uri&&sr0(J.status)&&sr0(Y.status)){let F=J.diff&&Y.diff?`${J.diff}
4686
4686
  ${Y.diff}`:Y.diff??J.diff,X=Y.status==="error"?0:J.linesAdded+Y.linesAdded,D=Y.status==="error"?0:J.linesDeleted+Y.linesDeleted;Q[Q.length-1]={type:"tool",tool:{kind:"edit",rowID:J.rowID??Y.rowID,uri:J.uri,displayPath:J.displayPath??Y.displayPath??o0.parse(J.uri).fsPath,status:Y.status,diff:F,linesAdded:X,linesDeleted:D,error:Y.error??J.error},timestampLookupID:Z,parentToolUseID:$.parentToolUseID};continue}if(J.kind==="create-file"&&Y.kind==="create-file"&&J.uri===Y.uri){Q[Q.length-1]={type:"tool",tool:{...Y,rowID:J.rowID??Y.rowID},timestampLookupID:Z,parentToolUseID:$.parentToolUseID};continue}if(J.kind==="create-file"&&Y.kind==="edit"&&J.uri===Y.uri&&sr0(Y.status)){let F=o0.parse(J.uri).fsPath,X=J.content&&Y.diff?`${As0(J.content,la(F))}
4687
4687
  ${Y.diff}`:Y.diff??(J.content?As0(J.content,la(F)):void 0),D=Y.status==="error"?0:J.linesAdded+Y.linesAdded,G=Y.status==="error"?0:Y.linesDeleted;Q[Q.length-1]={type:"tool",tool:{kind:"edit",rowID:J.rowID??Y.rowID,uri:J.uri,displayPath:Y.displayPath??o0.parse(J.uri).fsPath,status:Y.status,diff:X,linesAdded:D,linesDeleted:G,error:Y.error??J.error},timestampLookupID:Z,parentToolUseID:$.parentToolUseID};continue}}Q.push(B)}return Q}function sr0(A){return A!=="error"&&A!=="cancelled"&&A!=="rejected-by-user"}function As0(A,Q){let B=A.split(`
4688
4688
  `),$=B.map((J)=>`+${J}`).join(`
@@ -4690,43 +4690,43 @@ ${Y.diff}`:Y.diff??(J.content?As0(J.content,la(F)):void 0),D=Y.status==="error"?
4690
4690
  +++ b/${Q}
4691
4691
  @@ -0,0 +1,${B.length} @@
4692
4692
  ${$}`}function la(A){let Q=A.lastIndexOf("/");return Q===-1?A:A.slice(Q+1)}function Ay4(A){if(typeof A.cmd==="string")return A.cmd;if(typeof A.command==="string")return A.command;return}function Ys0(A){if(A.status==="in-progress"||A.status==="cancelled"||A.status==="error"){let Q=Qy4(A.progress),B=Q&&typeof Q==="object"&&"output"in Q?Q.output:Q;return typeof B==="string"?B:void 0}if(A.status==="done"&&typeof A.result==="object"&&A.result&&"output"in A.result){let Q=A.result,B=typeof Q.output==="string"?Q.output:void 0;if(B&&Q.truncation?.prefixLinesOmitted){let $=Q.truncation.prefixLinesOmitted;B=`--- Truncated ${$} ${V4($,"line")} above this point ---
4693
- `+B}return B}return}function Qy4(A){if(!A||typeof A!=="object"||!("type"in A))return A;let Q=A;if(Q.type==="snapshot"&&"value"in Q)return Array.isArray(Q.value)?uv4(Q.value):Q.value;if(Q.type==="delta"&&Array.isArray(Q.blocks)){let B=uv4(Q.blocks);if(B===void 0)return;try{return JSON.parse(B)}catch{return B}}return A}function uv4(A){let Q=A.map((B)=>{if(!B||typeof B!=="object"||!("type"in B)||B.type!=="text"||!("text"in B)||typeof B.text!=="string")return"";return B.text}).join("");return Q.length>0?Q:void 0}function By4(A){if(A.status==="done"&&typeof A.result==="object"&&A.result){let Q=A.result.exitCode;return typeof Q==="number"?Q:void 0}return}function $y4(A){if(A.status!=="done")return;if(typeof A.result!=="object"||A.result===null)return;if(!("files"in A.result)||!Array.isArray(A.result.files))return;return A.result.files.flatMap((Q)=>{if(typeof Q.uri!=="string")return[];return[{uri:JY.parse(Q.uri),type:SV5(Q.type)?Q.type:"update",additions:typeof Q.additions==="number"?Q.additions:0,deletions:typeof Q.deletions==="number"?Q.deletions:0,diff:typeof Q.diff==="string"?Q.diff:""}]})}function SV5(A){return A==="add"||A==="update"||A==="delete"||A==="move"}function vV5(A){if(A.status!=="done"||!Array.isArray(A.result))return;let Q=A.result.flatMap((B)=>{let $=yV5(B);return $?[$]:[]});if(Q.length===0)return;return{images:Q}}function yV5(A){if(!aB(A)||A.type!=="image"||typeof A.mimeType!=="string")return null;let Q=typeof A.savedPath==="string"?A.savedPath:void 0,B=hv4(A.url);if(B){let Y={mimeType:A.mimeType,url:B};if(Q!==void 0)Y.savedPath=Q;return Y}let $=hv4(A.data);if(!$)return null;let J={mimeType:A.mimeType,data:$};if(Q!==void 0)J.savedPath=Q;return J}function hv4(A){return typeof A==="string"&&A.length>0?A:void 0}function Jy4(A){if(typeof A.patchText==="string")return{patchText:A.patchText};if(typeof A.patch==="string")return{patchText:A.patch};return}function xV5(A){return A.complete?A.normalizedInput??A.input:A.normalizedInput??A.inputIncomplete??A.input}function Yy4(A){let Q=bV5(A.patchText);if(Q.length>0)return Q;return fV5(A).map((B)=>({path:B,additions:0,deletions:0}))}function fV5(A){try{let Q=[],B=new Set;for(let $ of FV(A.patchText).hunks){let J=$.type==="update"&&$.movePath?$.movePath:$.path;if(B.has(J))continue;B.add(J),Q.push(J)}return Q}catch{return hV5(A.patchText)}}function bV5(A){let Q=[],B=new Set,$=A.split(`
4694
- `),J,Y=()=>{if(!J||B.has(J.path)){J=void 0;return}B.add(J.path),Q.push(uV5(J)),J=void 0};for(let Z=0;Z<$.length;Z++){let F=$[Z],X=F.match(/^\*\*\* (Add|Delete|Update) File: (.+)$/);if(X){Y(),J={type:X[1].toLowerCase(),path:X[2],lines:[]};continue}let D=F.match(/^\*\*\* Move to: (.+)$/);if(D&&J?.type==="update"){J.path=D[1];continue}if(F.trim()==="*** End Patch"){Y();continue}J?.lines.push(F)}return Y(),Q}function uV5(A){if(A.type==="add"){let J=A.lines.filter((Y)=>Y.startsWith("+")).map((Y)=>Y.slice(1));return{path:A.path,additions:J.length,deletions:0,diff:J.length>0?As0(J.join(`
4693
+ `+B}return B}return}function Qy4(A){if(!A||typeof A!=="object"||!("type"in A))return A;let Q=A;if(Q.type==="snapshot"&&"value"in Q)return Array.isArray(Q.value)?uv4(Q.value):Q.value;if(Q.type==="delta"&&Array.isArray(Q.blocks)){let B=uv4(Q.blocks);if(B===void 0)return;try{return JSON.parse(B)}catch{return B}}return A}function uv4(A){let Q=A.map((B)=>{if(!B||typeof B!=="object"||!("type"in B)||B.type!=="text"||!("text"in B)||typeof B.text!=="string")return"";return B.text}).join("");return Q.length>0?Q:void 0}function By4(A){if(A.status==="done"&&typeof A.result==="object"&&A.result){let Q=A.result.exitCode;return typeof Q==="number"?Q:void 0}return}function $y4(A){if(A.status!=="done")return;if(typeof A.result!=="object"||A.result===null)return;if(!("files"in A.result)||!Array.isArray(A.result.files))return;return A.result.files.flatMap((Q)=>{if(typeof Q.uri!=="string")return[];return[{uri:JY.parse(Q.uri),type:vV5(Q.type)?Q.type:"update",additions:typeof Q.additions==="number"?Q.additions:0,deletions:typeof Q.deletions==="number"?Q.deletions:0,diff:typeof Q.diff==="string"?Q.diff:""}]})}function vV5(A){return A==="add"||A==="update"||A==="delete"||A==="move"}function yV5(A){if(A.status!=="done"||!Array.isArray(A.result))return;let Q=A.result.flatMap((B)=>{let $=xV5(B);return $?[$]:[]});if(Q.length===0)return;return{images:Q}}function xV5(A){if(!aB(A)||A.type!=="image"||typeof A.mimeType!=="string")return null;let Q=typeof A.savedPath==="string"?A.savedPath:void 0,B=hv4(A.url);if(B){let Y={mimeType:A.mimeType,url:B};if(Q!==void 0)Y.savedPath=Q;return Y}let $=hv4(A.data);if(!$)return null;let J={mimeType:A.mimeType,data:$};if(Q!==void 0)J.savedPath=Q;return J}function hv4(A){return typeof A==="string"&&A.length>0?A:void 0}function Jy4(A){if(typeof A.patchText==="string")return{patchText:A.patchText};if(typeof A.patch==="string")return{patchText:A.patch};return}function fV5(A){return A.complete?A.normalizedInput??A.input:A.normalizedInput??A.inputIncomplete??A.input}function Yy4(A){let Q=uV5(A.patchText);if(Q.length>0)return Q;return bV5(A).map((B)=>({path:B,additions:0,deletions:0}))}function bV5(A){try{let Q=[],B=new Set;for(let $ of FV(A.patchText).hunks){let J=$.type==="update"&&$.movePath?$.movePath:$.path;if(B.has(J))continue;B.add(J),Q.push(J)}return Q}catch{return gV5(A.patchText)}}function uV5(A){let Q=[],B=new Set,$=A.split(`
4694
+ `),J,Y=()=>{if(!J||B.has(J.path)){J=void 0;return}B.add(J.path),Q.push(hV5(J)),J=void 0};for(let Z=0;Z<$.length;Z++){let F=$[Z],X=F.match(/^\*\*\* (Add|Delete|Update) File: (.+)$/);if(X){Y(),J={type:X[1].toLowerCase(),path:X[2],lines:[]};continue}let D=F.match(/^\*\*\* Move to: (.+)$/);if(D&&J?.type==="update"){J.path=D[1];continue}if(F.trim()==="*** End Patch"){Y();continue}J?.lines.push(F)}return Y(),Q}function hV5(A){if(A.type==="add"){let J=A.lines.filter((Y)=>Y.startsWith("+")).map((Y)=>Y.slice(1));return{path:A.path,additions:J.length,deletions:0,diff:J.length>0?As0(J.join(`
4695
4695
  `),la(A.path)):void 0}}let Q=A.lines.filter((J)=>J.startsWith("+")||J.startsWith("-")||J.startsWith(" ")),B=Q.filter((J)=>J.startsWith("+")).length,$=Q.filter((J)=>J.startsWith("-")).length;return{path:A.path,additions:B,deletions:$,diff:Q.length>0?`--- a/${la(A.path)}
4696
4696
  +++ b/${la(A.path)}
4697
4697
  @@ -1,1 +1,1 @@
4698
4698
  ${Q.join(`
4699
- `)}`:void 0}}function hV5(A){let Q=[],B=new Set,$=A.split(`
4700
- `);for(let J=0;J<$.length;J++){let Z=$[J].match(/^\*\*\* (?:Add|Delete|Update) File: (.+)$/);if(!Z)continue;let F=Z[1],X=$[J+1]?.match(/^\*\*\* Move to: (.+)$/);if(X)F=X[1];if(B.has(F))continue;B.add(F),Q.push(F)}return Q}function $8(A){if(A.status!=="error"||!A.error)return;if(typeof A.error==="object"&&"message"in A.error){let Q=A.error.message;if(typeof Q==="string"&&Q.trim())return Q}return String(A.error)}function gV5(A,Q){if(A==="find_thread"){let B=typeof Q.query==="string"?Q.query.trim():void 0;return{kind:"search",title:B?`Searched threads: ${B}`:"Searched threads",icon:"search"}}if(A==="read_thread"){let B=typeof Q.threadID==="string"?Q.threadID.trim():void 0,$=typeof Q.goal==="string"?Q.goal.trim():void 0;return{kind:"thread",title:$?`Read thread: ${$}`:B?`Read thread ${B}`:"Read thread",icon:"threads"}}if(A==="slack_read"){let B=typeof Q.type==="string"?Q.type:void 0,$=typeof Q.query==="string"?Q.query.trim():void 0,J=$?`: ${$}`:"";if(B==="users")return{kind:"search",title:`Slack searched users${J}`,icon:"slack"};if(B==="channels")return{kind:"search",title:`Slack searched channels${J}`,icon:"slack"};if(B==="messages")return{kind:"read",title:`Slack read messages${J}`,icon:"slack"};if(B==="thread")return{kind:"read",title:"Slack read thread",icon:"slack"};return{kind:"read",title:$?`Slack read: ${$}`:"Slack read",icon:"slack"}}if(A==="docs_list"){let B=gF(Q);return{kind:"list",title:B?`Listed docs: ${B}`:"Listed docs",icon:"docs"}}if(A==="docs_read"){let B=gF(Q);return{kind:"read",title:B?`Read docs: ${B}`:"Read docs",icon:"docs"}}if(A==="github_repo_ci_status"){let B=gF(Q);return{kind:"read",title:B?`Read CI status: ${B}`:"Read CI status",icon:"github"}}if(A==="web_search"){let B=gF(Q);return{kind:"search",title:B?`Searched web: ${B}`:"Searched web",icon:"web"}}if(A==="read_web_page"){let B=gF(Q);return{kind:"web-page",title:B?`Read web page: ${B}`:"Read web page",icon:"web"}}if(A==="search_github"||A==="commit_search"||A==="glob_github"){let B=gF(Q);return{kind:"search",title:B?`Searched GitHub: ${B}`:"Searched GitHub",icon:"github"}}if(A==="list_directory_github"||A==="list_repositories"){let B=gF(Q);return{kind:"list",title:B?`Listed GitHub content: ${B}`:"Listed GitHub content",icon:"github"}}if(A==="read_github"||A==="diff"){let B=gF(Q);return{kind:"read",title:B?`Read GitHub content: ${B}`:"Read GitHub content",icon:"github"}}return}function zF0(A,Q){if(A==="Read"){let J=mV5(Q);if(J)return J}if(A==="read_thread"){let J=typeof Q.goal==="string"?Q.goal.trim():void 0;if(J)return`Read thread: ${J}`;let Y=typeof Q.threadID==="string"?Q.threadID.trim():void 0;return Y?`Read thread ${Y}`:"Read thread"}if(A==="find_thread"){let J=typeof Q.query==="string"?Q.query.trim():void 0;return J?`Searched threads: ${J}`:"Searched threads"}if(A==="skill")return`Read skill ${Q.name}`;if(A==="file_tree")return pV5(Q);if(A==="web_search"){let J=Fy4(Q);return J?`Web Search ${J}`:"Web Search"}if(A==="read_web_page"){let J=Zy4(Q);return J?`Read ${J}`:"Read"}if(A.toLowerCase()==="Grep".toLowerCase())return cV5(Q);let B=gF(Q);if(!B)return A;let $=B.includes("/")?YY(B):B;return`${A} ${$}`}function mV5(A){let Q=typeof A.path==="string"?A.path.trim():void 0,B=dV5(A.read_range);if(!Q)return B?`Read ${B}`:void 0;let $=YY(Q);return B?`Read ${$} ${B}`:`Read ${$}`}function pV5(A){let Q=typeof A.path==="string"?A.path.trim():void 0;if(!Q)return"List";let B=Q==="/"?Q:Q.replace(/\/+$/,"");return`List ${B.includes("/")?YY(B)||B:B}`}function dV5(A){if(!Array.isArray(A)||A.length!==2)return;let[Q,B]=A;if(typeof Q!=="number"||typeof B!=="number"||!Number.isInteger(Q)||!Number.isInteger(B))return;if(Q<1||B===-1||B<Q)return;if(Q===B)return`L${Q}`;return`L${Q}-${B}`}function cV5(A){let Q=A.path?.trim(),B=A.pattern?.trim();if(Q&&B)return`Grep ${Q} "${B}"`;if(B)return`Grep "${B}"`;if(Q)return`Grep ${Q}`;return"Grep"}function gF(A){for(let Q of["path","filePattern","pattern","query","url","objective","description","prompt"])if(typeof A[Q]==="string"&&A[Q].trim())return A[Q].trim();return}function Zy4(A){if(typeof A.url!=="string")return;return A.url.trim()||void 0}function Fy4(A){let Q=typeof A.query==="string"?A.query:void 0,B=typeof A.objective==="string"?A.objective:void 0;return(Q??B)?.trim()||void 0}function lV5(A){let Q=A.replace(/\/+$/,""),B=Q.lastIndexOf("/");return(B===-1?Q:Q.slice(B+1)).replace(/\.md$/i,"")||A}function iV5(A,Q){let B=aB(Q.result)?Q.result:void 0,$=aB(B?.check)?B.check:void 0;return typeof $?.name==="string"?$.name:lV5(A)}function nV5(A){if(A.status!=="done")return;let Q=aB(A.result)?A.result:void 0;return Array.isArray(Q?.issues)?Q.issues.length:void 0}function aV5(A){let Q=Object.entries(A).filter(([,B])=>B!==void 0&&B!==null&&B!=="");if(Q.length===0)return;return Q.map(([B,$])=>{let J=typeof $==="string"?$:JSON.stringify($);return`${B}: ${J}`}).join(`
4701
- `)}function Zs0(A,Q){let B=[...A],$=new Set(B.map((J)=>`${J.kind}:${J.title}`));for(let J of Gy4(Q)){let Y=`${J.kind}:${J.title}`;if($.has(Y))continue;$.add(Y),B.push(Xy4(J,Q.status))}return B}function Xy4(A,Q){return{...A,status:Q}}function oV5(A){let{status:Q,...B}=A;return B}function Dy4(A){return A.activityKind!=="subagent"||A.status===void 0||vM(A.status)}function Gy4(A){return rV5(A).map((Q)=>({kind:"read",title:`Read ${QJ(Q.uri)}`,...typeof Q.content==="string"?{detail:Q.content}:{},icon:"docs"}))}function rV5(A){if(A.status!=="done"||!aB(A.result))return[];let{discoveredGuidanceFiles:Q}=A.result;if(!Array.isArray(Q))return[];return Q.flatMap((B)=>{if(!aB(B)||typeof B.uri!=="string"||typeof B.lineCount!=="number"||!Number.isFinite(B.lineCount))return[];return[{uri:B.uri,lineCount:B.lineCount,...typeof B.content==="string"?{content:B.content}:{}}]})}function sV5(A,Q,B){if(A==="oracle"){let $=typeof Q.task==="string"?Q.task.trim():void 0;return tr0({label:{active:"Oracle exploring",complete:"Oracle has spoken"},detail:$,run:B})}if(A==="librarian"){let $=typeof Q.query==="string"?Q.query.trim():void 0;return tr0({label:{active:"Librarian researching",complete:"Librarian researched"},detail:$,run:B})}if(A==="Task"){let $=typeof Q.description==="string"?Q.description.trim():void 0,J=typeof Q.prompt==="string"?Q.prompt.trim():void 0;return tr0({label:{active:"Subagent working",complete:"Subagent finished"},detail:$??J,run:B})}if(A==="code_review"){let $=eV5(B,Q),J=Zs0($.actions,B),Y={label:{active:"Reviewing code",complete:"Reviewed code"},activityKind:"subagent",actions:J,summary:$.summary,hasInProgress:vM(B.status),status:B.status},Z=typeof Q.diff_description==="string"?Q.diff_description.trim():void 0;if(Z!==void 0)Y.detail=Z;let F=$8(B);if(F!==void 0)Y.error=F;return Y}return}function tr0(A){let Q=Zs0([],A.run),B={label:A.label,activityKind:"subagent",actions:Q,summary:Qs0(Q),hasInProgress:vM(A.run.status),status:A.run.status};if(A.detail!==void 0)B.detail=A.detail;let $=$8(A.run);if($!==void 0)B.error=$;return B}function tV5(A){let Q="result"in A&&aB(A.result)?A.result:void 0,B=Qy4("progress"in A?A.progress:void 0),$=aB(B)?B:void 0;return{main:(aB(Q?.main)?Q.main:void 0)??(aB($?.main)?$.main:void 0),checks:(aB(Q?.checks)?Q.checks:void 0)??(aB($?.checks)?$.checks:void 0)}}function eV5(A,Q){let B=[],$=new Set,J=(G)=>{let V=`${G.kind}:${G.title}`;if($.has(V))return;$.add(V),B.push(G)},{main:Y,checks:Z}=tV5(A);if(A.status==="queued")J({kind:"review",title:"Code review queued"});if(A.status==="error"){let G=$8(A)??"Unknown error";J({kind:"review",title:`Code review failed: ${G}`})}let F=0,X=0;for(let[G,V]of Object.entries(Z??{})){if(!aB(V))continue;X+=1;let U=iV5(G,V);if(V.status==="done"){F+=1;let K=nV5(V);if(K===void 0)J({kind:"review",title:`Check ${U}: complete`});else if(K===0)J({kind:"review",title:`Check ${U}: ok`});else J({kind:"review",title:`Check ${U}: ${K} ${V4(K,"issue")} found`});continue}if(V.status==="error"){F+=1;let K=typeof V.error==="string"&&V.error.trim()?V.error.trim():"Unknown error";J({kind:"review",title:`Check ${U}: error (${K})`});continue}if(V.status==="in-progress"){let K=typeof V.message==="string"&&V.message.trim()?V.message.trim():"Running check...";J({kind:"review",title:`Check ${U}: ${K}`})}}if(Y?.status==="done"&&X>0&&F<X)J({kind:"review",title:"Main review complete, running checks..."});if(A.status==="done")J({kind:"review",title:"Code review complete"});if(B.length===0)J({kind:"review",title:A.status==="queued"?"Code review queued":"Reviewing code changes..."});let D=Q.thinking==="low"?"quick code review":"code review";return{actions:B,summary:X>0?`${F}/${X} checks · ${D}`:D}}function Qs0(A,Q=""){let B=0,$=0,J=new Map;for(let Z of A){if(Z.icon==="docs"&&(Z.title.startsWith("Read ")||Z.title.startsWith("Load "))){B++;continue}if(Z.title.startsWith("Read skill ")){$++;continue}J.set(Z.kind,(J.get(Z.kind)??0)+1)}let Y=[];for(let[Z,F,X]of[["read","file",void 0],["web-page","web page","web pages"],["thread","thread",void 0],["skill","skill",void 0],["guidance","guidance file","guidance files"],["search","search","searches"],["web","web search","web searches"],["review","review","reviews"],["list","list",void 0]]){let D=Z==="guidance"?B:Z==="skill"?$:J.get(Z);if(!D)continue;Y.push(`${D} ${V4(D,F,X)}`)}if(Y.length>0)return Y.join(", ");return Q}function AU5(A){if(A.kind==="search"&&QU5(A.program)&&A.query){if(A.path)return`Grep ${A.path} "${A.query}"`;return`Grep "${A.query}"`}return kY0(A)}function QU5(A){if(!A)return!1;return new Set(["rg","ripgrep","grep","egrep","fgrep","ag","ack","pt","git grep"]).has(A)}function aB(A){return typeof A==="object"&&A!==null}CB();function Fs0(A){let Q=A.replace(/-/g,"");if(Q.length!==32)throw Error(`Invalid UUID hex length: ${Q.length}`);let B=BigInt("0x"+Q),$="";while(B>0n)$="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[Number(B%62n)]+$,B=B/62n;return $.padStart(22,"0")}A3();MS();r1();kk0();CB();var z3=b.string().min(1),QI=z3.brand(),Ds0=b.string().regex(/^[0-9A-Za-z]{22}$/),BU5=b.templateLiteral([b.string().regex(/^[0-9a-f]{8}$/),"-",b.string().regex(/^[0-9a-f]{4}$/),"-",b.string().regex(/^[0-9a-f]{4}$/),"-",b.string().regex(/^[0-9a-f]{4}$/),"-",b.string().regex(/^[0-9a-f]{12}$/)]),ia=b.templateLiteral(["T-",BU5]),Gs0=b.enum(["fork","handoff","mention"]),Vs0=b.enum(["parent","child"]),Vy4=b.object({threadID:ia,type:Gs0,role:Vs0,messageIndex:b.number().int().nonnegative().optional(),blockIndex:b.number().int().nonnegative().optional(),createdAt:b.number().int().nonnegative(),comment:b.string().optional()}),f6=b.templateLiteral(["M-",Ds0]);function qF0(){return`M-${Fs0(cT())}`}var l3=b.templateLiteral(["TU-",Ds0]);var Uy4=b.templateLiteral(["E-",Ds0]);function Ky4(){return`E-${Fs0(cT())}`}var $U5=b.looseObject({type:b.literal("object"),properties:b.record(b.string(),b.unknown()),required:b.array(b.string()).optional(),additionalProperties:b.boolean().optional()}),JU5=b.union([b.literal("builtin"),b.object({toolbox:z3}).strict(),b.object({mcp:z3,target:b.enum(["global","workspace","flag","default"]).optional()}).strict(),b.object({plugin:z3}).strict(),b.object({remote:z3}).strict()]),YU5=b.object({serial:b.boolean().optional(),deferred:b.boolean().optional(),skillNames:b.array(z3).optional()}),Ey4=b.looseObject({name:z3,description:b.string(),inputSchema:$U5,source:JU5,meta:YU5.optional()}),NE8=b.object({id:z3,category:z3,title:z3,description:b.string().optional(),pluginName:z3}),BI=b.enum(["none","minimal","low","medium","high","xhigh","max"]),Us0=b.enum(["anthropic","vertex"]),Ks0=b.enum(["standard","fast"]),Es0=b.enum(["gemini-3-pro-image","gpt-image-2"]),zs0=b.enum(["none","minimal","low","medium","high","xhigh"]),Ws0=b.enum(["minimal","low","medium","high"]),NF0=b.object({"agent.skipTitleGenerationIfMessageContains":b.array(b.string()).optional(),"anthropic.thinking.enabled":b.boolean().optional(),"anthropic.interleavedThinking.enabled":b.boolean().optional(),"anthropic.temperature":b.number().optional(),"anthropic.provider":Us0.optional(),"openai.speed":Ks0.optional(),"painter.model":Es0.optional(),"reasoning.effort":BI.optional(),"internal.compactionThresholdPercent":b.number().min(0).max(100).optional(),"internal.model":b.union([b.string(),b.record(b.string(),b.string())]).optional(),"internal.oracleReasoningEffort":zs0.optional(),"gemini.thinkingLevel":Ws0.optional(),"tools.disable":b.array(b.string()).optional(),"tools.enable":b.array(b.string()).optional()}),zy4=b.object({workspaceId:b.string(),workingDirectory:b.string(),environment:b.object({os:b.enum(["darwin","linux","windows"]),hasDocker:b.boolean().optional(),hasBrowser:b.boolean().optional()}).strict(),tags:b.array(b.string())}).strict(),Wy4=b.enum(["sandbox","local-client"]),na=b.any().and(b.object({status:b.string()})),Hy4=b.discriminatedUnion("type",[b.object({type:b.literal("delta"),blocks:b.array(b.unknown()).optional(),state:b.enum(["start","generating","tool_use","complete","error","aborted"])}),b.object({type:b.literal("snapshot"),value:b.unknown()})]),RU=z3,qy4=30000,Kx=JY,ZU5=b.enum(["file","directory"]),FU5=b.object({mtimeMs:b.number().nonnegative().optional()}),aa=b.tuple([b.string(),ZU5,FU5.nullish()]),XU5=b.enum(["INVALID_URI","EXECUTOR_NOT_CONNECTED","NOT_FOUND","NOT_DIRECTORY","IS_DIRECTORY","ACCESS_DENIED","INTERNAL_ERROR"]),$I=b.object({code:XU5,message:b.string()}),DU5=b.object({ok:b.literal(!0),entries:b.array(aa)}),GU5=b.object({ok:b.literal(!1),error:$I}),IE8=b.discriminatedUnion("ok",[DU5,GU5]),VU5=b.object({ok:b.literal(!0),contentBase64:b.string()}),UU5=b.object({ok:b.literal(!1),error:$I}),wE8=b.discriminatedUnion("ok",[VU5,UU5]),KU5=z3,Hs0=b.object({key:z3,dataType:KU5,contentBase64:b.string()}),qs0=Hs0.extend({toolCallId:l3.optional(),updatedAt:b.string()}),Ns0=b.looseObject({uri:JY,content:b.string().optional(),lineCount:b.int().optional(),hash:b.string().optional()}),EU5=b.enum(KJ4),Ny4=b.object({path:JY,error:b.string(),hint:b.string().optional()}),Iy4=b.object({uri:JY,hash:b.string(),lineCount:b.int().optional()}),wy4=b.object({name:z3,description:b.string(),baseDir:JY,frontmatter:b.object({name:z3,description:b.string()}).catchall(b.unknown()),files:b.array(b.string()).optional(),source:EU5.optional()}),zU5=b.enum(["start","streaming","complete"]),oa=b.object({blockState:zU5.optional()}),Is0=b.object({type:b.literal("text"),text:b.string(),hidden:b.boolean().optional()}).extend(oa.shape),Cy4=b.looseObject({type:b.literal("image"),source:b.discriminatedUnion("type",[b.object({type:b.literal("base64"),mediaType:b.literal(["image/jpeg","image/png","image/gif","image/webp"]),data:b.string()}),b.object({type:b.literal("url"),url:b.string()})]),sourcePath:b.string()}),ra=b.array(b.discriminatedUnion("type",[Is0,Cy4])),Ux=b.record(b.string(),b.unknown()),My4=b.object({type:b.literal("tool_use"),id:b.string().min(1),name:b.string().min(1),normalizedName:b.string().optional(),metadata:b.record(b.string(),b.unknown()).optional()}).extend(oa.shape),WU5=My4.extend({complete:b.literal(!0),input:Ux,normalizedInput:Ux.optional()}),HU5=My4.extend({complete:b.literal(!1),input:Ux,inputIncomplete:Ux,inputPartialJSON:b.object({json:b.string()}),normalizedInput:Ux.optional()}),qU5=b.object({accepted:b.boolean(),askAnswers:b.record(b.string(),b.string()).optional(),denyFeedback:b.string().optional()}),NU5=b.object({type:b.literal("tool_result"),toolUseID:b.string().min(1),run:na,userInput:qU5.optional()}),IU5=b.object({type:b.literal("thinking"),thinking:b.string(),signature:b.string()}).extend(oa.shape),wU5=b.object({type:b.literal("redacted_thinking"),data:b.string()}).extend(oa.shape),CU5=b.object({type:b.literal("server_tool_use"),id:b.string().min(1),name:b.string().min(1),input:Ux}).extend(oa.shape),MU5=b.object({type:b.literal("manual_bash_invocation"),args:b.object({cmd:b.string(),args:b.array(b.string()).readonly().optional(),cwd:b.string().optional()}),toolRun:na,hidden:b.boolean().optional()}),ws0=b.object({sentAt:b.number().int().nonnegative().optional(),fromAggman:b.boolean().optional(),fromExecutorThreadID:ia.optional()}),LU5=b.union([Is0,Cy4,NU5]),OU5=b.union([Is0,IU5,wU5,WU5,HU5,CU5]),sa=b.array(LU5),ta=b.array(OU5),Cs0=b.array(MU5),Xs0=b.looseObject({line:b.number().int(),column:b.number().int()}),jU5=b.looseObject({start:Xs0,end:Xs0}),RU5=b.looseObject({name:b.string(),repositoryURL:b.string()}),PU5=b.looseObject({currentURL:b.string(),availableProjects:b.array(RU5).optional()}),Ms0=b.looseObject({currentlyVisibleFiles:b.array(JY),runningTerminalCommands:b.array(b.string()).optional(),activeEditor:b.any().optional(),cursorLocation:Xs0.optional(),cursorLocationLine:b.string().optional(),selectionRange:jU5.optional(),aggmanContext:PU5.optional()}),Pz=b.custom((A)=>typeof A==="string"&&b3(A)!==void 0),_U5=b.object({threadId:ia,role:b.literal("user"),content:sa,agentMode:Pz.optional(),meta:ws0.optional(),userState:Ms0.optional(),readAt:b.string().nullable().optional(),messageId:f6,createdAt:b.string().optional()}),Ls0=b.object({model:b.string().optional(),maxInputTokens:b.number(),inputTokens:b.number(),outputTokens:b.number(),cacheCreationInputTokens:b.number().nullable(),cacheReadInputTokens:b.number().nullable(),totalInputTokens:b.number(),thinkingBudget:b.number().optional(),timestamp:b.string().optional()}),Os0=b.union([b.object({type:b.literal("complete")}),b.object({type:b.literal("cancelled")})]),TU5=b.object({threadId:ia,role:b.literal("assistant"),content:ta,state:Os0.optional(),usage:Ls0.optional(),readAt:b.string().nullable().optional(),messageId:f6,createdAt:b.string().optional()}),kU5=b.object({threadId:ia,role:b.literal("info"),content:Cs0,messageId:f6,createdAt:b.string().optional()}),js0=b.discriminatedUnion("role",[_U5,TU5,kU5]),ea=b.object({workspaceRoot:JY.optional(),workingDirectory:JY.optional(),rootDirectoryListing:b.string().nullable().optional(),trees:b.array(b.any()).optional(),platform:b.any().optional(),tags:b.array(b.string()).optional(),git:b.object({branch:b.string().optional()}).optional(),updatedAt:b.string().optional()}),SU5=b.object({added:b.number().int().nonnegative(),deleted:b.number().int().nonnegative(),changed:b.number().int().nonnegative()}),vU5=b.object({path:b.string(),previousPath:b.string().optional(),changeType:b.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","untracked"]),created:b.boolean(),diff:b.string(),fullFileDiff:b.string().optional(),oldContent:b.string().optional(),newContent:b.string().optional(),diffStat:SU5}),yU5=b.object({hash:b.string(),shortHash:b.string(),subject:b.string()}),Ly4=b.object({provider:b.literal("git"),capturedAt:b.number(),available:b.boolean(),repositoryRoot:b.string().nullable(),repositoryName:b.string().nullable(),branch:b.string().nullable(),head:b.string().nullable(),baseRef:b.string().nullable().optional(),baseRefHead:b.string().nullable().optional(),aheadCount:b.number().int().nonnegative().optional(),behindCount:b.number().int().nonnegative().optional(),aheadCommits:b.array(yU5).optional(),diffHash:b.string().optional(),files:b.array(vU5),unavailableReason:b.string().optional(),unchanged:b.boolean().optional()}),Rs0=b.enum(["thread","subagent"]),Ps0=b.enum(["user","built-in"]),IF0=b.object({id:b.string(),toolCallId:l3,toolName:b.string(),args:b.record(b.string(),b.unknown()),reason:b.string().optional(),toAllow:b.array(b.string()).optional(),context:Rs0,subagentToolName:b.string().optional(),parentToolCallId:l3.optional(),timestamp:b.number(),matchedRule:b.object({tool:b.string(),action:b.string(),matches:b.record(b.string(),b.unknown()).optional()}).optional(),ruleSource:Ps0.optional()}),xU5=b.object({type:b.literal("request"),id:z3,method:z3,params:b.unknown()}),fU5=b.object({type:b.literal("response"),id:z3,result:b.unknown().optional(),error:b.string().optional()}),bU5=b.object({type:b.literal("event"),event:z3,data:b.unknown(),span:b.string().optional()}),wF0=b.discriminatedUnion("type",[xU5,fU5,bU5]);var uU5=b.object({type:b.literal("executor_connect"),clientId:QI,capabilities:zy4,executorType:Wy4.optional()}),hU5=b.object({type:b.literal("client_update_thread_settings"),settings:NF0}),gU5=b.object({type:b.literal("executor_tools_register"),tools:b.array(Ey4)}),mU5=b.object({type:b.literal("executor_tools_unregister"),toolNames:b.array(z3)}),pU5=b.object({type:b.literal("executor_tools_bootstrap_complete"),ok:b.boolean(),error:b.string().optional()}),dU5=b.object({type:b.literal("executor_tool_lease_ack"),toolCallId:l3}),_s0=b.object({type:b.literal("tool_progress"),toolCallId:l3,progress:b.union([Hy4,b.unknown()]).optional(),parentToolCallId:l3.optional()}),cU5=b.object({type:b.literal("executor_tool_result"),toolCallId:l3,run:na}),lU5=b.object({type:b.literal("executor_guidance_snapshot"),snapshotId:z3,files:b.array(Ns0),isLast:b.boolean(),userConfigDir:b.any().optional()}),iU5=b.object({type:b.literal("executor_guidance_discovery"),toolCallId:l3,files:b.array(Ns0),isLast:b.boolean()}),nU5=b.object({type:b.literal("executor_skill_snapshot"),snapshotId:z3,skills:b.array(wy4),isLast:b.boolean(),errors:b.array(Ny4).optional()}),aU5=b.object({type:b.literal("executor_environment_snapshot"),environment:ea}),oU5=b.object({type:b.literal("executor_environment_update"),environment:ea}),rU5=b.object({type:b.literal("executor_artifact_upsert"),artifact:Hs0,toolCallId:l3.optional()}),sU5=b.object({type:b.literal("executor_artifact_delete"),key:z3}),tU5=b.object({type:b.literal("executor_tool_approval_request"),approval:IF0}),eU5=b.object({type:b.literal("executor_plugin_message"),message:wF0}),AK5=b.object({type:b.literal("client_append_user_msg"),content:ra,userState:Ms0.optional(),agentMode:Pz.optional(),reasoningEffort:BI.optional(),messageId:f6,steer:b.boolean().optional()}),QK5=b.object({type:b.literal("client_remove_queued_msg"),queuedMessageId:f6}),BK5=b.object({type:b.literal("client_steer_queued_msg"),queuedMessageId:f6}),$K5=b.object({type:b.literal("client_edit_message"),messageId:f6,editId:Uy4,content:ra,agentMode:Pz.optional(),reasoningEffort:BI.optional()}),JK5=b.object({type:b.literal("client_mark_message_read"),messageId:f6}),YK5=b.object({type:b.literal("client_mark_message_unread"),messageId:f6}),ZK5=b.object({type:b.literal("client_set_thread_title"),title:b.string().trim().min(1).max(256)}),FK5=b.object({auth:b.string().min(1),p256dh:b.string().min(1)}),XK5=b.object({endpoint:b.string().url(),keys:FK5}),DK5=b.object({type:b.literal("client_upsert_notification_subscription"),subscription:XK5,threadURL:b.string().min(1)}),GK5=b.object({type:b.literal("client_filesystem_read_directory"),requestId:RU,uri:Kx}),VK5=b.object({type:b.literal("client_filesystem_read_file"),requestId:RU,uri:Kx}),UK5=b.object({type:b.literal("executor_filesystem_read_directory_result"),requestId:RU,ok:b.boolean(),entries:b.array(aa).optional(),error:$I.optional()}).superRefine((A,Q)=>{if(A.ok){if(!A.entries)Q.addIssue({code:b.ZodIssueCode.custom,message:"entries is required when ok is true"});if(A.error)Q.addIssue({code:b.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!A.error)Q.addIssue({code:b.ZodIssueCode.custom,message:"error is required when ok is false"});if(A.entries)Q.addIssue({code:b.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),KK5=b.object({type:b.literal("executor_filesystem_read_file_result"),requestId:RU,ok:b.boolean(),contentBase64:b.string().optional(),error:$I.optional()}).superRefine((A,Q)=>{if(A.ok){if(A.contentBase64===void 0)Q.addIssue({code:b.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(A.error)Q.addIssue({code:b.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!A.error)Q.addIssue({code:b.ZodIssueCode.custom,message:"error is required when ok is false"});if(A.contentBase64!==void 0)Q.addIssue({code:b.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),EK5=b.object({type:b.literal("client_resume"),version:b.number()}),zK5=b.object({type:b.literal("client_retry")}),WK5=b.object({type:b.literal("client_dismiss_active_error"),seq:b.number().optional()}),HK5=b.object({type:b.literal("client_cancel")}),qK5=b.object({type:b.literal("client_append_manual_bash_invocation"),args:b.object({cmd:b.string().trim().min(1,"cmd must contain at least one non-whitespace character"),args:b.array(b.string()).optional(),cwd:b.string().optional()}),run:na,hidden:b.boolean().optional()}),NK5=b.object({type:b.literal("client_tool_approval_response"),toolCallId:l3,accepted:b.boolean(),input:b.object({askAnswers:b.record(b.string(),b.string()).optional(),denyFeedback:b.string().optional()}).optional()}),IK5=b.union([b.object({name:b.string(),type:b.literal("git").optional(),url:b.string()}),b.object({driveName:b.string().min(1).describe("Drive name. Must be a single path component."),name:b.string(),namespace:b.string(),type:b.literal("drive")})]),wK5=b.object({type:b.literal("client_spawn_executor"),requestId:b.string().optional(),repositoryURL:b.string().optional(),projectID:b.uuid().optional(),additionalRepositories:b.array(IK5).optional()}),Oy4=b.discriminatedUnion("type",[uU5,hU5,gU5,mU5,pU5,dU5,_s0,cU5,lU5,iU5,nU5,aU5,oU5,rU5,sU5,tU5,eU5,AK5,QK5,BK5,$K5,JK5,YK5,ZK5,DK5,GK5,VK5,UK5,KK5,EK5,zK5,WK5,HK5,qK5,NK5,wK5]);CB();var CF0=(A)=>b.codec(b.string(),A,{decode:(Q,B)=>{try{return JSON.parse(Q)}catch($){return B.issues.push({code:"invalid_format",format:"json",input:Q,message:$.message}),b.NEVER}},encode:(Q)=>JSON.stringify(Q)});CB();CB();var Qo=["idle","working","streaming","tool_use","running_tools","awaiting_approval","error"],PE8=new Set(Qo);var CK5=["working","streaming","tool_use","running_tools"],MK5=new Set(CK5);function BQ(A){if(typeof A!=="string")return!1;return MK5.has(A)}function Ao(A){return typeof A==="object"&&A!==null}function LK5(A){return Ao(A)&&A.type==="text"&&typeof A.text==="string"}function Ts0(A){if(!A)return;let Q=A.filter(LK5).map((B)=>B.text).join("");return Q.length>0?Q:void 0}function ks0(A){if(typeof A==="string")return A;if(Array.isArray(A))return Ts0(A);if(!Ao(A))return;for(let Q of["output","displayMessage","message","reason"]){let B=A[Q];if(typeof B==="string")return B}for(let Q of["result","error","value"])if(Q in A){let B=ks0(A[Q]);if(B!==void 0)return B}return}function jy4(A,Q){if(typeof A==="string")return A+Q;if(Array.isArray(A)){if(!A.every((B)=>Ao(B)&&typeof B.type==="string"))return;return[...A,{type:"text",text:Q}]}if(!Ao(A))return;for(let B of["output","displayMessage","message","reason"]){let $=A[B];if(typeof $==="string")return{...A,[B]:$+Q}}if("value"in A){let B=jy4(A.value,Q);if(B!==void 0)return{...A,value:B}}return}function OK5(A){return Ao(A)&&typeof A.status==="string"}function jK5(A,Q){return{type:"delta",...A?{blocks:[{type:"text",text:A}]}:{},state:Q}}function RK5(A){if(!A)return;if(A.type==="snapshot")return ks0(A.value);return Ts0(A.blocks)}function Ex(A,Q){if(A&&typeof A==="object"&&"type"in A){let $=A;if($.type==="delta"||$.type==="snapshot")return $}if(Q==="snapshot")return{type:"snapshot",value:A};let B=typeof A==="string"?A:A!==void 0?JSON.stringify(A):"";return{type:"delta",blocks:B?[{type:"text",text:B}]:void 0,state:"generating"}}function Ry4(A,Q){if(Q.type!=="snapshot"||OK5(Q.value))return Q;let B=RK5(A),$=ks0(Q.value);if(B===void 0||$===void 0)return Q;if(!$.startsWith(B))return Q;return jK5($.slice(B.length),"generating")}function MF0(A,Q){let B=A===void 0?void 0:Ex(A,"snapshot"),$=Ex(Q,"snapshot");if($.type==="snapshot")return $;if(!B)return $;let J=Ts0($.blocks);if(J===void 0)return B;if(B.type==="snapshot"){let Z=jy4(B.value,J);if(Z!==void 0)return{type:"snapshot",value:Z}}return{type:"delta",blocks:[...B.type==="delta"?B.blocks??[]:Array.isArray(B.value)?B.value:[],...$.blocks??[]],state:$.state}}var PK5=b.enum(Qo),Ss0=b.enum(["start","generating","tool_use","complete","error","aborted"]),_K5=b.object({message:b.string(),code:b.string().optional(),stack:b.string().optional(),retryAt:b.number().optional(),attempt:b.number().optional()}),TK5=b.object({userId:b.string(),name:b.string(),avatarURL:b.string().optional()}),vs0=b.enum(["starting","running","failed"]),ys0=b.enum(["missing","allocating_environment","configuring_workspace","starting_headless","headless_ready","paused","failed"]),xs0=b.enum(["pending","ready","failed"]),kK5=xs0.nullable(),fs0=b.enum(["allocating_environment","configuring_workspace","starting_headless"]),SK5=fs0.nullable(),bs0=b.enum(["idle","creating","recovering"]),us0=b.enum(["unknown","running","paused","missing"]),hs0=b.enum(["spawn_requested","spawn_rejected","environment_recovering","waiting_for_executor_connect","executor_connected","executor_disconnected","connect_timeout","executor_connect_rejected","spawn_failed","restart_failed","environment_missing"]),gs0=b.enum(["ACCESS_DENIED","ACTOR_STOPPING","CONNECTION_ERROR","MAX_RECONNECT_EXCEEDED","MESSAGE_ERROR","LOOP_RUNNING","NO_THREAD_ID","NO_ERROR","INVALID_MESSAGE","PARSE_ERROR","UNKNOWN_TYPE","INTERNAL_ERROR"]),ms0=b.enum(["executor_disconnected","reassigned","user_canceled"]),ps0=b.enum(["NOT_CONNECTED","ACCESS_DENIED","INVALID_MESSAGE","TOOL_NOT_FOUND","LEASE_NOT_FOUND","DUPLICATE_TOOL","INTERNAL_ERROR"]),vK5=b.object({environmentId:b.string().nullable().optional(),stage:ys0.optional(),setupState:kK5.optional(),setupPhase:SK5.optional(),operation:bs0.optional(),providerState:us0.optional(),restartAttempts:b.number().optional()}),yK5=b.object({reasonCode:hs0.optional(),executionEnvironment:vK5.optional()}),xK5=b.object({cutMessageId:f6,createdAt:b.string()}),Py4=b.object({steer:b.boolean(),queuedMessage:b.object({role:b.literal("user"),messageId:f6,content:ra,userState:b.any().optional(),meta:ws0.optional(),createdAt:b.string().optional()})}),fK5=b.object({type:b.literal("agent_state"),state:PK5,messageId:f6.optional(),agentMode:Pz.optional(),reasoningEffort:BI.optional()}),bK5=b.object({type:b.literal("inference_tools"),messageId:f6,agentMode:Pz,tools:b.array(z3),parentToolCallId:l3.optional()}),uK5=b.object({type:b.literal("thread_settings"),settings:NF0}),hK5=b.object({type:b.literal("error"),message:b.string(),code:gs0.optional()}),gK5=b.object({type:b.literal("error_set"),seq:b.number(),error:_K5}),mK5=b.object({type:b.literal("error_cleared"),seq:b.number()}),pK5=b.object({type:b.literal("cancelled"),seq:b.number(),messageId:f6.optional()}),dK5=b.object({type:b.literal("retry_scheduled"),retryAt:b.number(),attempt:b.number(),maxAttempts:b.number(),reason:b.string()}),cK5=b.object({type:b.literal("retry_started")}),lK5=b.object({type:b.literal("retry_cancelled")}),iK5=b.object({type:b.literal("executor_connected"),executorId:QI,registeredToolCount:b.number(),guidanceInventory:b.array(Iy4),resumeBootstrap:b.boolean().optional(),rejectedTools:b.array(b.object({name:b.string(),reason:b.string()})).optional()}),nK5=b.object({type:b.literal("tool_lease"),toolCallId:l3,toolName:b.string(),args:b.unknown(),messageId:f6,parentToolCallId:l3.optional()}),aK5=b.object({type:b.literal("executor_filesystem_read_directory"),requestId:RU,uri:Kx}),oK5=b.object({type:b.literal("executor_filesystem_read_file"),requestId:RU,uri:Kx}),rK5=b.object({type:b.literal("client_filesystem_read_directory_result"),requestId:RU,ok:b.boolean(),entries:b.array(aa).optional(),error:$I.optional()}).superRefine((A,Q)=>{if(A.ok){if(!A.entries)Q.addIssue({code:"custom",message:"entries is required when ok is true"});if(A.error)Q.addIssue({code:"custom",message:"error must not be present when ok is true"});return}if(!A.error)Q.addIssue({code:"custom",message:"error is required when ok is false"});if(A.entries)Q.addIssue({code:"custom",message:"entries must not be present when ok is false"})}),sK5=b.object({type:b.literal("client_filesystem_read_file_result"),requestId:RU,ok:b.boolean(),contentBase64:b.string().optional(),error:$I.optional()}).superRefine((A,Q)=>{if(A.ok){if(A.contentBase64===void 0)Q.addIssue({code:"custom",message:"contentBase64 is required when ok is true"});if(A.error)Q.addIssue({code:"custom",message:"error must not be present when ok is true"});return}if(!A.error)Q.addIssue({code:"custom",message:"error is required when ok is false"});if(A.contentBase64!==void 0)Q.addIssue({code:"custom",message:"contentBase64 must not be present when ok is false"})}),tK5=b.object({type:b.literal("tool_approval_queue"),approvals:b.array(IF0)}),eK5=b.object({type:b.literal("executor_tool_lease_revoked"),toolCallId:l3,reason:ms0}),AE5=b.object({type:b.literal("executor_tool_result_ack"),toolCallId:l3}),QE5=b.object({type:b.literal("plugin_message"),message:wF0}),BE5=b.object({type:b.literal("executor_tool_approval_response"),toolCallId:l3,accepted:b.boolean(),input:b.object({askAnswers:b.record(b.string(),b.string()).optional(),denyFeedback:b.string().optional()}).optional()}),$E5=b.object({type:b.literal("executor_error"),message:b.string(),toolCallId:l3.optional(),code:ps0}),JE5=b.object({type:b.literal("delta"),messageId:f6,role:b.literal("assistant"),blocks:ta.optional(),blockIndex:b.number().int().nonnegative().optional(),state:Ss0,usage:Ls0.optional(),parentToolCallId:l3.optional()}),YE5=b.object({type:b.literal("delta"),messageId:f6,role:b.literal("user"),blocks:sa.optional(),state:b.literal("complete"),parentToolCallId:l3.optional()}),ZE5=b.discriminatedUnion("role",[JE5,YE5]),FE5=b.object({type:b.literal("queued_messages"),messages:b.array(Py4)}),XE5=b.object({type:b.literal("queued_message_added"),message:Py4,seq:b.number()}),DE5=b.object({type:b.literal("queued_message_removed"),queuedMessageId:f6,seq:b.number()}),GE5=b.object({type:b.literal("queued_message_dequeued"),queuedMessageId:f6,seq:b.number()}),VE5=b.object({type:b.literal("message_added"),message:js0,seq:b.number(),parentToolUseId:l3.optional()}),UE5=b.object({type:b.literal("message_updated"),message:js0,seq:b.number()}),KE5=b.object({type:b.literal("edit_rejected"),editId:b.string(),message:b.string()}),EE5=b.object({type:b.literal("thread_truncated"),seq:b.number(),truncateFromMessage:f6}),zE5=b.object({type:b.literal("observers"),count:b.number(),observers:b.array(TK5),hasExecutor:b.boolean().optional()}),WE5=b.object({type:b.literal("executor_status"),spawnId:b.string().optional(),status:vs0,message:b.string().optional(),executorId:b.string().optional(),details:yK5.optional()}),HE5=b.object({type:b.literal("environment_update"),environment:ea}),qE5=b.object({type:b.literal("artifacts_snapshot"),artifacts:b.array(qs0)}),NE5=b.object({type:b.literal("artifact_upserted"),artifact:qs0}),IE5=b.object({type:b.literal("artifact_deleted"),key:z3}),wE5=b.object({type:b.literal("thread_title"),title:b.string().nullable()}),CE5=b.object({type:b.literal("thread_status"),status:b.union([b.literal("merging"),b.literal("merged"),b.null()])}),ME5=b.object({type:b.literal("thread_relationships"),seq:b.number(),relationships:b.array(Vy4)}),LE5=b.object({type:b.literal("compaction_started")}),OE5=b.object({type:b.literal("compaction_complete"),cutMessageId:f6}),jE5=b.object({type:b.literal("compaction_records"),records:b.array(xK5)}),LF0=b.discriminatedUnion("type",[fK5,bK5,uK5,hK5,gK5,mK5,pK5,dK5,cK5,lK5,iK5,nK5,aK5,oK5,rK5,sK5,tK5,eK5,AE5,QE5,BE5,_s0,$E5,ZE5,EE5,FE5,XE5,DE5,GE5,VE5,UE5,KE5,zE5,WE5,HE5,qE5,NE5,IE5,wE5,CE5,ME5,LE5,OE5,jE5]);var _y4=CF0(Oy4),RE5=b.union([LF0,b.array(LF0)]),Ty4=CF0(LF0),hE8=CF0(RE5);r1();function ky4(A,Q={}){let $=(Q.mode??"lenient")==="strict";if(!Array.isArray(A))return $?null:[];let J=[];for(let Y of A){if(typeof Y!=="object"||Y===null){if($)return null;continue}let Z=Y;if(typeof Z.uri!=="string"||Z.uri.length===0){if($)return null;continue}let F;try{F=b1(o0.parse(Z.uri))}catch{if($)return null;continue}let X={uri:F};if(typeof Z.content==="string")X.content=Z.content;if(typeof Z.lineCount==="number"&&Number.isFinite(Z.lineCount))X.lineCount=Z.lineCount;if(typeof Z.hash==="string")X.hash=Z.hash;J.push(X)}return J}function ds0(A){let Q=Number.isFinite(A)?A:0;function B(J=Q){if(Number.isFinite(J))Q=J;return Q}function $(J){if(!Number.isFinite(J)||J<1)return Q;return Q=Math.max(Q,J),Q}return{getVersion:()=>Q,reset:B,advanceFromSeq:$}}function fy4(A,Q,B){let $;switch(Q.type){case"message_added":$=PE5(A,Q);break;case"message_updated":$=_E5(A,Q);break;case"delta":$=kE5(A,Q,B);break;case"tool_progress":$=SE5(A,Q,B);break;case"thread_truncated":$=vE5(A,Q);break}return $}function PE5(A,Q){let B=qj(Q.message,Q.parentToolUseId??Q.message.parentToolUseId);return by4(A,B)}function _E5(A,Q){let B=TE5(A,Q.message);return by4(A,B)}function by4(A,Q){let B=cE5(A,iE5(Q)),$=Bo(B,Q.messageId),J=B.slice();if($>=0)return J[$]=Q,J;return J.push(Q),J}function TE5(A,Q){let B=Bo(A,Q.messageId),$=B>=0?A[B]:void 0;return qj(Q,$?.parentToolUseId)}function qj(A,Q){let B={...A};if(Q!==void 0)B.parentToolUseId=Q;return B}function kE5(A,Q,B){let $=Q.role==="assistant"&&Q.state==="aborted"?hE5(A,Q.messageId):A;if(!Q.blocks||Q.blocks.length===0){if(Q.role==="assistant"&&(Q.state==="complete"||Q.state==="tool_use"))return yy4($,{...Q,blocks:[],blockIndex:Q.blockIndex??0},B);return $.slice()}if(Q.role==="assistant")return yy4($,Q,B);return yE5($,{...Q,blocks:Q.blocks},B)}function SE5(A,Q,B){let $=dE5(Q.progress);if($!==void 0&&$.status!=="in-progress"&&!S5($.status))return A.slice();if(xy4(A,Q.toolCallId,(V)=>S5(V.run.status)))return A.slice();let Y=xy4(A,Q.toolCallId),Z=$!==void 0&&S5($.status)?$:void 0;if(Z!==void 0){let V=Sy4(Q.toolCallId,Z,Y?.block.userInput);return vy4(A,Q,B,Y,V)}let F=Y&&"progress"in Y.block.run?Y.block.run.progress:void 0,X=Q.progress===void 0?F:MF0(F,Q.progress),D=X===void 0?{status:"in-progress"}:{status:"in-progress",progress:X},G=Sy4(Q.toolCallId,D,Y?.block.userInput);return vy4(A,Q,B,Y,G)}function Sy4(A,Q,B){if(B!==void 0)return{type:"tool_result",toolUseID:A,run:Q,userInput:B};return{type:"tool_result",toolUseID:A,run:Q}}function vy4(A,Q,B,$,J){if($)return gE5(A,$,J);return[...A,qj({threadId:B.threadId,messageId:uy4(Q.toolCallId),role:"user",content:[J]},Q.parentToolCallId)]}function vE5(A,Q){let B=Bo(A,Q.truncateFromMessage);return B>=0?A.slice(0,B):A.slice()}function yy4(A,Q,B){let $=Bo(A,Q.messageId),J=$>=0?A[$]:void 0,Y=J?.role==="assistant"?J.content:[],Z=xE5(Y,Q.blocks,Q.blockIndex),F=Q.parentToolCallId??J?.parentToolUseId,X=J?.role==="assistant"?qj({...J,content:Z},F):qj({threadId:B.threadId,messageId:Q.messageId,role:"assistant",content:Z},F);if(Q.usage!==void 0)X.usage=Q.usage;if(Q.state==="aborted")X.state={type:"cancelled"},delete X.isStreaming;else if(Q.state==="complete"||Q.state==="tool_use")X.state={type:"complete"},delete X.isStreaming;else X.isStreaming=!0;return cs0(A,$,X)}function yE5(A,Q,B){let $=Bo(A,Q.messageId),J=$>=0?A[$]:void 0,Y=J?.role==="user"?J.content:[],Z=uE5(Y,Q.blocks),F=Q.parentToolCallId??J?.parentToolUseId,X=J?.role==="user"?qj({...J,content:Z},F):qj({threadId:B.threadId,messageId:Q.messageId,role:"user",content:Z},F);return cs0(A,$,X)}function xE5(A,Q,B){let $=[...A];for(let[J,Y]of Q.entries()){let Z=B+J;fE5($,Z);let F=$[Z];if(bE5(F))$[Z]=Y;else if(F?.type==="text"&&Y.type==="text")$[Z]={...F,...Y,text:F.text+Y.text};else if(F?.type==="thinking"&&Y.type==="thinking")$[Z]={...F,...Y,thinking:F.thinking+Y.thinking};else $[Z]=Y}return $}function fE5(A,Q){while(A.length<Q)A.push({type:"text",text:"",hidden:!0})}function bE5(A){return A?.type==="text"&&A.hidden===!0&&A.text===""}function uE5(A,Q){let B=[...A];for(let $ of Q){let J=B.length-1,Y=B[J];if(Y?.type==="text"&&$.type==="text")B[J]={...Y,text:Y.text+$.text};else B.push($)}return B}function cs0(A,Q,B){let $=A.slice();if(Q>=0)return $[Q]=B,$;return $.push(B),$}function hE5(A,Q){return A.filter((B)=>B.messageId!==Q)}function Bo(A,Q){return A.findIndex((B)=>B.messageId===Q)}function xy4(A,Q,B=()=>!0){for(let[$,J]of A.entries()){if(J.role!=="user")continue;for(let[Y,Z]of J.content.entries())if(Z.type==="tool_result"&&Z.toolUseID===Q&&B(Z))return{messageIndex:$,blockIndex:Y,message:J,block:Z}}return}function gE5(A,Q,B){let $=Q.message.content.slice();return $[Q.blockIndex]=B,cs0(A,Q.messageIndex,{...Q.message,content:$})}var mE5=["queued","blocked-on-user","in-progress","rejected-by-user","cancellation-requested","cancelled","done","error"];function pE5(A){return typeof A==="string"&&mE5.includes(A)}function dE5(A){if(A===void 0||typeof A!=="object"||A===null)return;let Q=A;if(Q.type!=="snapshot")return;let B=Q.value;if(typeof B!=="object"||B===null)return;let $=B;return pE5($.status)?$:void 0}function cE5(A,Q){if(Q.size===0)return A;return A.filter((B)=>!lE5(B,Q))}function lE5(A,Q){if(A.role!=="user"||A.content.length!==1)return!1;let B=A.content[0];return B?.type==="tool_result"&&Q.has(B.toolUseID)&&A.messageId===uy4(B.toolUseID)}function iE5(A){let Q=new Set;if(A.role!=="user")return Q;for(let B of A.content)if(B.type==="tool_result")Q.add(B.toolUseID);return Q}function uy4(A){return`M-${A.replace(/^TU-/,"")}`}class ls0{inProgressMessageID=null;threadMessages=[];messageSeq=new Map;messageOrder=new Map;nextMessageOrder=0;threadID;constructor(A){this.threadID=A}setThreadID(A){this.threadID=A}getThreadID(){return this.threadID}reset(A){if(A!==void 0)this.threadID=A;this.threadMessages=[],this.messageSeq.clear(),this.messageOrder.clear(),this.nextMessageOrder=0,this.inProgressMessageID=null}apply(A){let Q=this.threadMessages;if(A.type==="delta"&&A.parentToolCallId===void 0&&A.state==="aborted"){if(this.applyThreadMessageEvent(A),this.inProgressMessageID===A.messageId)this.inProgressMessageID=null;return this.threadMessages!==Q}let B=nE5(A);if(B!==void 0)this.updateInProgressMessage(B);if(this.applyThreadMessageEvent(A),A.type==="delta"&&(A.state==="complete"||A.state==="tool_use"))this.inProgressMessageID=null;return this.threadMessages!==Q}messages(){return this.threadMessages}sortedMessages(){return this.sortThreadMessages(this.threadMessages)}applyThreadMessageEvent(A){this.recordMessageOrder(A);let Q=A.type==="thread_truncated"?this.sortThreadMessages(this.threadMessages):this.threadMessages;this.threadMessages=fy4(Q,A,{threadId:this.threadID}),this.pruneMessageOrder()}recordMessageOrder(A){if(A.type==="message_added"){this.recordMessage(A.message.messageId,A.seq);return}if(A.type==="message_updated"){this.recordMessage(A.message.messageId,this.messageSeq.has(A.message.messageId)?void 0:A.seq);return}if(A.type==="delta"){this.recordMessage(A.messageId);return}if(A.type==="tool_progress")this.recordMessage(oE5(A.toolCallId))}recordMessage(A,Q){if(!this.messageOrder.has(A))this.messageOrder.set(A,this.nextMessageOrder),this.nextMessageOrder+=1;if(Q!==void 0)this.messageSeq.set(A,Q)}sortThreadMessages(A){return A.slice().sort((Q,B)=>{let $=this.messageSeq.get(Q.messageId),J=this.messageSeq.get(B.messageId),Y=$!==void 0&&J!==void 0?$-J:this.messageSortOrder(Q.messageId)-this.messageSortOrder(B.messageId);if(Y!==0)return Y;return this.messageSortOrder(Q.messageId)-this.messageSortOrder(B.messageId)})}messageSortOrder(A){return this.messageOrder.get(A)??Number.MAX_SAFE_INTEGER}pruneMessageOrder(){let A=new Set(this.threadMessages.map((Q)=>Q.messageId));for(let Q of this.messageSeq.keys())if(!A.has(Q))this.messageSeq.delete(Q);for(let Q of this.messageOrder.keys())if(!A.has(Q))this.messageOrder.delete(Q);if(this.inProgressMessageID!==null&&!A.has(this.inProgressMessageID))this.inProgressMessageID=null}updateInProgressMessage(A){if(this.inProgressMessageID===A)return;if(this.inProgressMessageID!==null)this.markMessageNotInProgress(this.inProgressMessageID);this.inProgressMessageID=A}markMessageNotInProgress(A){this.threadMessages=this.threadMessages.map((Q)=>{if(Q.messageId!==A||Q.role!=="assistant"||Q.state!==void 0)return Q;let B={...Q,state:{type:"complete"}};return delete B.isStreaming,B})}}function nE5(A){if(A.type==="message_added"&&aE5(A)===void 0)return A.message.messageId;if(A.type==="delta"&&A.parentToolCallId===void 0)return A.messageId;return}function aE5(A){return A.parentToolUseId??A.message.parentToolUseId}function oE5(A){return`M-${A.replace(/^TU-/,"")}`}i4();function hy4(A,Q){let B=A.parentToolUseId;if(A.role==="assistant"){let J={role:"assistant",content:A.content,state:A.state?.type==="cancelled"?{type:"cancelled"}:A.isStreaming===!0?{type:"streaming"}:{type:"complete",stopReason:null},usage:A.usage,messageId:Q,protocolMessageID:A.messageId,readAt:A.readAt};if(B===void 0)return J;return{...J,parentToolUseId:B}}if(A.role==="info"){let J={role:"info",content:A.content,messageId:Q,protocolMessageID:A.messageId};if(B===void 0)return J;return{...J,parentToolUseId:B}}let $={role:"user",content:A.content,meta:L30(A.meta),userState:A.userState,readAt:A.readAt,messageId:Q,protocolMessageID:A.messageId};if(B===void 0)return $;return{...$,parentToolUseId:B}}class OF0{accumulator;currentVersion=0;constructor(A){this.accumulator=new ls0(A)}get version(){return this.currentVersion}setThreadID(A){this.accumulator.setThreadID(A)}reset(A){let Q=this.accumulator.sortedMessages().length;return this.accumulator.reset(A),this.currentVersion+=1,{changed:Q>0,previousMessageCount:Q,nextMessageCount:0,changedIndices:sE5(Q,0),version:this.currentVersion}}apply(A){if(A.type==="message_added"&&tE5(A)===void 0||A.type==="message_updated")this.setThreadID(A.message.threadId);let Q=this.accumulator.sortedMessages();if(!this.accumulator.apply(A))return{changed:!1,previousMessageCount:Q.length,nextMessageCount:Q.length,changedIndices:[],version:this.currentVersion};let $=this.accumulator.sortedMessages();return this.currentVersion+=1,{changed:!0,previousMessageCount:Q.length,nextMessageCount:$.length,changedIndices:rE5(Q,$),version:this.currentVersion}}protocolMessages(){return this.accumulator.sortedMessages()}coreMessages(){return this.accumulator.sortedMessages().map((A,Q)=>hy4(A,Q))}buildTranscriptEntries(A={}){return cv4(this.protocolMessages(),{threadID:this.accumulator.getThreadID(),...A})}}function rE5(A,Q){let B=Math.max(A.length,Q.length),$=[];for(let J=0;J<B;J+=1)if(A[J]!==Q[J])$.push(J);return $}function sE5(A,Q){return Array.from({length:Math.max(A,Q)},(B,$)=>$)}function tE5(A){return A.parentToolUseId??A.message.parentToolUseId}d0();M1();var eE5=1000,Az5=30000,Qz5=124,Bz5=30000,$z5=15000,Jz5=1000,Yz5=200,gy4="Connection timed out. Retrying...",Zz5=30000,my4=["online","focus","pageshow","keydown","pointerdown"],py4=["visibilitychange"];function ns0(){return globalThis}function cy4(A){if(!A||typeof A!=="object")return null;let Q=A;if(typeof Q.addEventListener!=="function"||typeof Q.removeEventListener!=="function")return null;return Q}function dy4(){return cy4(ns0().window)}function is0(){let A=ns0().document;if(!cy4(A))return null;return A}function Fz5(){let A=ns0().navigator;if(!A||typeof A!=="object")return null;return A}function T9(A){if(A.state!=="connected")return!1;return A.requiredRole===null||A.role===A.requiredRole}function Xz5(A){if(!A)return"none";let Q=[A.type];if(A.code!==void 0)Q.push(`code=${A.code}`);if(A.reason!==void 0)Q.push(`reason=${A.reason}`);if(A.error!==void 0)Q.push(`error=${A.error}`);return Q.join(" ")}class as0{ws=null;connectionInfo={state:"disconnected",role:null,requiredRole:null,clientId:null};reconnectCause=null;reconnectAttempts=0;reconnectTimeoutID=null;reconnectResetTimeoutID=null;pingIntervalID=null;latencyTimeoutIDs=new Set;connectPromise=null;disposed=!1;lastServerFrameAt=Date.now();intentionallyClosedSockets=new WeakSet;reconnectActivityCleanup=null;lifecycleEventID=0;lifecycleEvents=[];connectionSubject=new A4({state:"disconnected",role:null,requiredRole:null,clientId:null});lifecycleEventSubject=new A4([]);config;threadIDSubject=new A4(null);_currentThreadID=null;log=j;get currentThreadID(){return this._currentThreadID}set currentThreadID(A){if(A!==null&&A!==this._currentThreadID)this._currentThreadID=A,this.log=j.with({threadId:A}),this.threadIDSubject.next(A);else this._currentThreadID=A}constructor(A){let Q=A.requiredRole??null;this.connectionInfo={...this.connectionInfo,requiredRole:Q},this.connectionSubject.next({...this.connectionInfo}),this.config={threadId:A.threadId,webSocketProvider:A.webSocketProvider,reconnectDelayMs:A.reconnectDelayMs??eE5,maxReconnectDelayMs:A.maxReconnectDelayMs??Az5,maxReconnectAttempts:A.maxReconnectAttempts??Qz5,pingIntervalMs:A.pingIntervalMs??Bz5,connectTimeoutMs:A.connectTimeoutMs??$z5,webSocketLatencyMs:A.webSocketLatencyMs??(()=>0)},this.currentThreadID=A.threadId??null,this.recordLifecycleEvent("transport_initialized",`threadId=${this.currentThreadID??"none"}`)}getThreadId(){return this.currentThreadID}connectionChanges(){return this.connectionSubject}getConnectionInfo(){return{...this.connectionInfo}}waitForConnected(A){if(this.connectionInfo.state==="connected")return Promise.resolve(!0);if(this.disposed||A<=0)return Promise.resolve(!1);return new Promise((Q)=>{let B=!1,$=null,J=null,Y=(Z)=>{if(B)return;if(B=!0,$)clearTimeout($),$=null;J?.unsubscribe(),J=null,Q(Z)};$=setTimeout(()=>{Y(!1)},A),J=this.connectionSubject.subscribe({next:(Z)=>{if(Z.state==="connected")Y(!0)},error:()=>{Y(!1)},complete:()=>{Y(!1)}})})}connectionLifecycleChanges(){return this.lifecycleEventSubject}getConnectionLifecycleEvents(){return[...this.lifecycleEvents]}async connect(){return this.connectInternal({fromReconnect:!1})}recordLifecycleEvent(A,Q){let B={id:++this.lifecycleEventID,at:Date.now(),type:A,...Q?{details:Q}:{}},$=Yz5,J=this.lifecycleEvents.slice(-($-1));this.lifecycleEvents=[...J,B],this.lifecycleEventSubject.next([...this.lifecycleEvents])}async connectInternal(A){if(this.connectPromise)return this.connectPromise;let Q=this.connectInternalOnce(A);this.connectPromise=Q;try{return await Q}finally{if(this.connectPromise===Q)this.connectPromise=null}}async connectInternalOnce(A){if(this.disposed)throw new c3("Transport is disposed");if(this.ws)return;this.recordLifecycleEvent("connect_requested",A.fromReconnect?`mode=reconnect attempt=${this.reconnectAttempts}`:"mode=initial"),this.updateConnectionState("connecting");try{let{webSocket:Q,threadId:B}=await this.openWebSocketProviderWithTimeout();try{Q.binaryType="arraybuffer"}catch{}await this.waitForOpen(Q),this.currentThreadID=B,this.ws=Q,this.lastServerFrameAt=Date.now(),this.setupWebSocketHandlers(Q),this.stopWaitingForReconnectActivity(),this.scheduleReconnectAttemptsReset(),this.reconnectCause=null,this.updateConnectionState("connected"),this.recordLifecycleEvent("connect_succeeded",`threadId=${this.currentThreadID??"none"} attempt=${this.reconnectAttempts}`)}catch(Q){let B=Q instanceof Error?Q.message:String(Q),$=Q instanceof c3&&Q.cause instanceof Error?Q.cause.message:null,J=`mode=${A.fromReconnect?"reconnect":"initial"} error=${B}`;if(this.recordLifecycleEvent("connect_failed",$?`${J} cause=${$}`:J),!A.fromReconnect&&!this.disposed)this.reconnectCause={type:"connect_failed",at:Date.now(),error:B},this.scheduleReconnect();throw Q}}disconnect(){this.recordLifecycleEvent("disconnect_requested"),this.clearWebSocketLatencyTimeouts(),this.stopPingInterval(),this.cancelReconnect(),this.reconnectCause=null;let A=this.ws;if(A){if(this.ws=null,this.intentionallyClosedSockets.add(A),A.readyState===WebSocket.OPEN)A.close(1000,"Client disconnect")}this.updateConnectionState("disconnected")}forceReconnect(A){if(this.disposed)return;let Q=this.ws;if(!Q&&this.connectionInfo.state!=="connected")return;if(this.recordLifecycleEvent("force_reconnect_requested",`reason=${A}`),this.clearWebSocketLatencyTimeouts(),this.reconnectCause={type:"error",at:Date.now(),error:A},this.ws=null,this.stopPingInterval(),this.cancelReconnectAttemptsReset(),Q&&(Q.readyState===WebSocket.OPEN||Q.readyState===WebSocket.CONNECTING))Q.close(4000,A);this.scheduleReconnect({immediate:!0,bypassActivityGate:!0})}retryConnect(A){if(this.disposed)return;if(this.recordLifecycleEvent("reconnect_attempts_reset",`reason=${A}`),this.reconnectAttempts=0,this.cancelReconnectAttemptsReset(),this.reconnectTimeoutID)return;this.scheduleReconnect({immediate:!0,bypassActivityGate:!0})}async disconnectAndWait(A){let Q=this.ws;if(!Q||Q.readyState!==WebSocket.OPEN)return this.disconnect(),{status:"not_connected"};let B=this.waitForSocketClose(Q,A?.waitForCloseTimeoutMs??Jz5);return this.disconnect(),B}dispose(){if(this.disposed)return;this.recordLifecycleEvent("disposed"),this.disposed=!0,this.disconnect(),this.connectionSubject.complete(),this.lifecycleEventSubject.complete()}sendRaw(A){if(!this.hasOpenSocket())throw new c3("WebSocket is not connected");let Q=this.ws;if(!Q)throw new c3("WebSocket is not connected");this.runAfterWebSocketLatency(()=>{if(Q!==this.ws||Q.readyState!==WebSocket.OPEN)return;Q.send(A)}),this.startPingIntervalOnce()}hasOpenSocket(){return!!this.ws&&this.ws.readyState===WebSocket.OPEN}runAfterWebSocketLatency(A){let Q=this.config.webSocketLatencyMs();if(!Number.isFinite(Q)||Q<=0){A();return}let B=setTimeout(()=>{this.latencyTimeoutIDs.delete(B),A()},Q);this.latencyTimeoutIDs.add(B)}clearWebSocketLatencyTimeouts(){for(let A of this.latencyTimeoutIDs)clearTimeout(A);this.latencyTimeoutIDs.clear()}waitForSocketClose(A,Q){return new Promise((B)=>{let $=!1,J=null,Y=(F)=>{if($)return;if($=!0,J)clearTimeout(J);A.removeEventListener("close",Z),B(F)},Z=(F)=>{let X=F;Y({status:X.code===1000?"server_acknowledged":"timeout",...typeof X.code==="number"?{closeCode:X.code}:{},...typeof X.reason==="string"?{closeReason:X.reason}:{}})};if(J=setTimeout(()=>{Y({status:"timeout"})},Q),A.addEventListener("close",Z),A.readyState===WebSocket.CLOSED)Y({status:"timeout"})})}async openWebSocketProviderWithTimeout(){let A=!1,Q=null,B=this.config.webSocketProvider();B.then((J)=>{if(A)this.closeSocketDuringConnect(J.webSocket,4000,"Connection attempt timed out")},()=>{return});let $=new Promise((J,Y)=>{Q=setTimeout(()=>{A=!0,Y(new c3(gy4,Error(`WebSocket provider timed out after ${this.config.connectTimeoutMs}ms`)))},this.config.connectTimeoutMs)});try{return await Promise.race([B,$])}finally{if(Q)clearTimeout(Q)}}closeSocketDuringConnect(A,Q,B){try{if(A.readyState===WebSocket.OPEN||A.readyState===WebSocket.CONNECTING)A.close(Q,B)}catch{}}updateConnectionState(A){let Q={...this.connectionInfo};if(A==="disconnected"||A==="reconnecting"){let $={state:A,role:null,requiredRole:this.connectionInfo.requiredRole,clientId:null};if(this.reconnectCause)$.reconnectCause=this.reconnectCause;this.connectionInfo=$}else if(this.connectionInfo.state=A,A==="connected")this.reconnectCause=null,delete this.connectionInfo.reconnectCause;else if(this.reconnectCause)this.connectionInfo.reconnectCause=this.reconnectCause;let B={...this.connectionInfo};this.connectionSubject.next(B),this.log.info("[thread-client] Transport connection state changed",{previousState:Q.state,nextState:B.state,previousRole:Q.role,nextRole:B.role,clientId:B.clientId,reconnectCauseType:this.reconnectCause?.type,reconnectCode:this.reconnectCause?.code,reconnectReason:this.reconnectCause?.reason}),this.recordLifecycleEvent("state_changed",`state=${A} cause=${Xz5(this.reconnectCause)}`)}onRawMessage(A){}onWebSocketTraffic(A){}onMaxReconnectExceeded(A){}async waitForOpen(A){if(A.readyState===WebSocket.OPEN)return;return new Promise((Q,B)=>{let $=setTimeout(()=>{J(),this.closeSocketDuringConnect(A,4000,"Connection attempt timed out"),B(new c3(gy4,Error(`WebSocket connection timed out after ${this.config.connectTimeoutMs}ms`)))},this.config.connectTimeoutMs),J=()=>{clearTimeout($),A.removeEventListener("open",Y),A.removeEventListener("error",Z),A.removeEventListener("close",F)},Y=()=>{J(),Q()},Z=(X)=>{J();let D="message"in X?X.message:("error"in X)&&X.error instanceof Error?X.error.message:X.type;B(new c3(`WebSocket connection failed: ${D}`))},F=(X)=>{J(),B(new c3(`WebSocket closed during connect: code=${X.code} reason=${X.reason||"none"}`))};if(A.addEventListener("open",Y),A.addEventListener("error",Z),A.addEventListener("close",F),A.readyState===WebSocket.OPEN)return Y();if(A.readyState===WebSocket.CLOSED||A.readyState===WebSocket.CLOSING)return F({code:1006,reason:"Socket already closed before connect"})})}setupWebSocketHandlers(A){A.addEventListener("message",(Q)=>{let B=Q.data;this.runAfterWebSocketLatency(()=>this.handleWebSocketMessage(A,B))}),A.addEventListener("close",(Q)=>{this.handleClose(A,Q.code,Q.reason)}),A.addEventListener("error",()=>{this.handleError(A)})}handleWebSocketMessage(A,Q){if(A!==this.ws)return;if(this.lastServerFrameAt=Date.now(),this.startPingIntervalOnce(),this.onWebSocketTraffic(Q),typeof Q==="string"){if(Q==="pong")return;this.onRawMessage(Q)}else if(Q instanceof ArrayBuffer)this.onRawMessage(new TextDecoder().decode(Q))}handleClose(A,Q,B){let $=this.intentionallyClosedSockets.has(A);if($)this.intentionallyClosedSockets.delete(A);if(this.log.info("[thread-client] Transport socket close observed",{code:Q,reason:B||void 0,intentional:$,isCurrentSocket:A===this.ws,stateBeforeClose:this.connectionInfo.state,roleBeforeClose:this.connectionInfo.role,clientIdBeforeClose:this.connectionInfo.clientId,reconnectCauseType:this.reconnectCause?.type,reconnectCode:this.reconnectCause?.code,reconnectReason:this.reconnectCause?.reason}),this.recordLifecycleEvent("socket_closed",`code=${Q} reason=${B||"none"} intentional=${$}`),A!==this.ws)return;if(this.ws=null,this.clearWebSocketLatencyTimeouts(),this.stopPingInterval(),this.cancelReconnectAttemptsReset(),!this.disposed&&!$){let J=this.reconnectCause,Y=J?.type==="ping_timeout"&&Q===4000&&!B?{...J,at:Date.now(),code:Q}:{type:"close",at:Date.now(),code:Q,...B?{reason:B}:{}};this.reconnectCause=Y,this.scheduleReconnect()}else this.reconnectCause=null,this.updateConnectionState("disconnected")}handleError(A){if(A!==this.ws)return;if(this.recordLifecycleEvent("socket_error","error=WebSocket error event"),this.reconnectCause={type:"error",at:Date.now(),error:"WebSocket error event"},this.ws)this.ws.close()}scheduleReconnect(A){if(this.disposed||this.reconnectTimeoutID)return;if(this.reconnectAttempts>=this.config.maxReconnectAttempts){this.stopWaitingForReconnectActivity(),this.recordLifecycleEvent("reconnect_exhausted",`attempts=${this.reconnectAttempts} max=${this.config.maxReconnectAttempts}`),this.updateConnectionState("disconnected"),this.onMaxReconnectExceeded(this.config.maxReconnectAttempts);return}if(!A?.bypassActivityGate&&this.shouldWaitForReconnectActivity()){this.recordLifecycleEvent("reconnect_waiting_for_activity",`offline=${this.isBrowserOffline()} hidden=${this.isDocumentHidden()}`),this.updateConnectionState("reconnecting"),this.waitForReconnectActivity();return}this.stopWaitingForReconnectActivity(),this.updateConnectionState("reconnecting"),this.reconnectAttempts++;let Q=A?.immediate?0:this.getReconnectDelayMs();this.log.info("[thread-client] Scheduling transport reconnect",{attempt:this.reconnectAttempts,delayMs:Math.round(Q),immediate:A?.immediate===!0,bypassActivityGate:A?.bypassActivityGate===!0,state:this.connectionInfo.state,role:this.connectionInfo.role,clientId:this.connectionInfo.clientId,reconnectCauseType:this.reconnectCause?.type,reconnectCode:this.reconnectCause?.code,reconnectReason:this.reconnectCause?.reason}),this.recordLifecycleEvent("reconnect_scheduled",`attempt=${this.reconnectAttempts} delayMs=${Math.round(Q)}`),this.reconnectTimeoutID=setTimeout(()=>{this.reconnectTimeoutID=null,this.connectInternal({fromReconnect:!0}).catch((B)=>{if(this.reconnectCause={type:"connect_failed",at:Date.now(),error:B instanceof Error?B.message:String(B)},!this.disposed)this.scheduleReconnect()})},Q)}cancelReconnect(){if(this.reconnectTimeoutID)clearTimeout(this.reconnectTimeoutID),this.reconnectTimeoutID=null;this.stopWaitingForReconnectActivity(),this.cancelReconnectAttemptsReset(),this.reconnectAttempts=0}getReconnectDelayMs(){let A=Math.min(this.config.reconnectDelayMs*2**(this.reconnectAttempts-1),this.config.maxReconnectDelayMs),Q=0.8+Math.random()*0.4;return A*Q}shouldWaitForReconnectActivity(){let A=dy4(),Q=is0();if(!A&&!Q)return!1;return this.isBrowserOffline()||this.isDocumentHidden()}isBrowserOffline(){let A=Fz5();if(typeof A?.onLine!=="boolean")return!1;return A.onLine===!1}isDocumentHidden(){let A=is0();if(!A)return!1;return A.visibilityState==="hidden"}waitForReconnectActivity(){if(this.reconnectActivityCleanup)return;let A=dy4(),Q=is0();if(!A&&!Q)return;let B=()=>{this.handleReconnectActivity()};for(let $ of my4)A?.addEventListener($,B);for(let $ of py4)Q?.addEventListener($,B);this.reconnectActivityCleanup=()=>{for(let $ of my4)A?.removeEventListener($,B);for(let $ of py4)Q?.removeEventListener($,B)}}stopWaitingForReconnectActivity(){this.reconnectActivityCleanup?.(),this.reconnectActivityCleanup=null}handleReconnectActivity(){if(this.disposed||this.ws){this.stopWaitingForReconnectActivity();return}if(this.shouldWaitForReconnectActivity())return;this.stopWaitingForReconnectActivity(),this.recordLifecycleEvent("reconnect_activity_detected"),this.scheduleReconnect({immediate:!0,bypassActivityGate:!0})}scheduleReconnectAttemptsReset(){this.cancelReconnectAttemptsReset(),this.reconnectResetTimeoutID=setTimeout(()=>{this.reconnectResetTimeoutID=null,this.reconnectAttempts=0},Zz5)}cancelReconnectAttemptsReset(){if(this.reconnectResetTimeoutID)clearTimeout(this.reconnectResetTimeoutID),this.reconnectResetTimeoutID=null}startPingIntervalOnce(){if(this.pingIntervalID)return;this.startPingInterval()}startPingInterval(){this.stopPingInterval();let A=Date.now();this.pingIntervalID=setInterval(()=>{let Q=Date.now(),B=Q-A;if(A=Q,B>this.config.pingIntervalMs*3){this.lastServerFrameAt=Q;return}if(this.hasOpenSocket()){let $=Q-this.lastServerFrameAt,J=this.config.pingIntervalMs*2;if($>J){this.recordLifecycleEvent("ping_timeout",`elapsedMs=${$} thresholdMs=${J}`);let Y=`No server frame received for ${$}ms (threshold ${J}ms)`;this.reconnectCause={type:"ping_timeout",at:Q,code:4000,reason:"Pong timeout",error:Y},this.ws?.close(4000,"Pong timeout");return}try{this.ws?.send("ping")}catch{}}},this.config.pingIntervalMs)}stopPingInterval(){if(this.pingIntervalID)clearInterval(this.pingIntervalID),this.pingIntervalID=null}}function jF0(A,Q={}){let B=!1,$=!1;return A.connectionChanges().subscribe({next:(J)=>{let Y=Q.requireRole??J.requiredRole,Z=T9({state:J.state,role:J.role,requiredRole:Y});if(Z&&!B){if($)try{A.resumeFromVersion(A.getResumeVersion())}catch(F){Q.onError?.({threadID:A.getThreadId(),error:F})}$=!0}B=Z}})}Wl();M1();var Dz5=J2(Ss0.options),Gz5=J2(Qo),Vz5=J2(gs0.options),Uz5=J2(ps0.options),Kz5=J2(vs0.options),Ez5=J2(ys0.options),zz5=J2(xs0.options),Wz5=J2(fs0.options),Hz5=J2(bs0.options),qz5=J2(us0.options),Nz5=J2(hs0.options),Iz5=J2(ms0.options),wz5=J2(Gs0.options),Cz5=J2(Vs0.options),Mz5=J2(Rs0.options),Lz5=J2(Ps0.options),Oz5=J2(Us0.options),jz5=J2(Ks0.options),Rz5=J2(Es0.options),ny4=J2(BI.options),Pz5=J2(zs0.options),_z5=J2(Ws0.options);function J2(A){return new Set(A)}function _z(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}function oB(A,Q){return typeof A==="string"&&Q.has(A)}function Tz5(A){return typeof A==="number"&&Number.isInteger(A)&&A>=0}function ly4(A){let Q;try{Q=JSON.stringify(A)}catch{return null}let B=Ty4.safeDecode(Q);return B.success?B.data:null}function ay4(A){let Q;try{Q=JSON.parse(A)}catch{return[]}let B=Array.isArray(Q)?Q:[Q],$=[];for(let J of B){let Y=kz5(J);if(Y)$.push(Y)}return $}function kz5(A){let Q=ly4(A);if(Q)return Q;if(!_z(A)||typeof A.type!=="string")return null;let B=Sz5(A);return B?ly4(B):null}function Sz5(A){switch(A.type){case"agent_state":return vz5(A);case"thread_settings":return yz5(A);case"error":return fz5(A);case"executor_tool_lease_revoked":return uz5(A);case"tool_approval_queue":return tz5(A);case"executor_error":return bz5(A);case"delta":return hz5(A);case"queued_messages":return gz5(A);case"queued_message_added":return mz5(A);case"message_added":case"message_updated":return pz5(A);case"executor_status":return oz5(A);case"thread_relationships":return AW5(A);default:return null}}function vz5(A){let Q={...A};if(!oB(Q.state,Gz5))Q.state="working";if(Q.agentMode!==void 0&&!Pz.safeParse(Q.agentMode).success)delete Q.agentMode;if(Q.reasoningEffort!==void 0&&!oB(Q.reasoningEffort,ny4))delete Q.reasoningEffort;return Q}function yz5(A){if(!_z(A.settings))return A;return{...A,settings:xz5(A.settings)}}function xz5(A){let Q={...A};if(zx(Q,"anthropic.provider",Oz5),zx(Q,"openai.speed",jz5),zx(Q,"painter.model",Rz5),zx(Q,"reasoning.effort",ny4),zx(Q,"internal.oracleReasoningEffort",Pz5),zx(Q,"gemini.thinkingLevel",_z5),Q["internal.compactionThresholdPercent"]!==void 0&&(typeof Q["internal.compactionThresholdPercent"]!=="number"||Q["internal.compactionThresholdPercent"]<0||Q["internal.compactionThresholdPercent"]>100))delete Q["internal.compactionThresholdPercent"];return Q}function zx(A,Q,B){if(A[Q]!==void 0&&!oB(A[Q],B))delete A[Q]}function fz5(A){let Q={...A};if(Q.code!==void 0&&!oB(Q.code,Vz5))delete Q.code;return Q}function bz5(A){let Q={...A};if(!oB(Q.code,Uz5))Q.code="INTERNAL_ERROR";return Q}function uz5(A){let Q={...A};if(!oB(Q.reason,Iz5))Q.reason="reassigned";return Q}function hz5(A){if(A.role!=="assistant"&&A.role!=="user")return null;let Q={...A};if(A.role==="assistant"){if(!oB(Q.state,Dz5))Q.state="generating";if(Array.isArray(Q.blocks)){if(Q.blocks=nz5(Q.blocks),!Tz5(Q.blockIndex))Q.blockIndex=0}else if(Q.blocks!==void 0)delete Q.blocks,delete Q.blockIndex;return Q}if(Q.state="complete",Array.isArray(Q.blocks))Q.blocks=rs0(Q.blocks,"user");else if(Q.blocks!==void 0)delete Q.blocks;return delete Q.blockIndex,Q}function gz5(A){if(!Array.isArray(A.messages))return A;return{...A,messages:A.messages.map(oy4).filter((Q)=>Q!==null)}}function mz5(A){let Q=oy4(A.message);return Q?{...A,message:Q}:null}function oy4(A){if(!_z(A)||!_z(A.queuedMessage))return null;let Q=ry4(A.queuedMessage);return Q?{...A,queuedMessage:Q}:null}function pz5(A){let Q=dz5(A.message);return Q?{...A,message:Q}:null}function dz5(A){if(!_z(A))return null;if(A.role==="user")return ry4(A);if(A.role==="assistant")return cz5(A);if(A.role==="info")return lz5(A);return null}function ry4(A){if(A.role!=="user"||!Array.isArray(A.content))return null;return{...A,content:rs0(A.content,"user")}}function cz5(A){if(A.role!=="assistant"||!Array.isArray(A.content))return null;let Q={...A,content:rs0(A.content,"assistant")};if(Q.state!==void 0&&!iz5(Q.state))delete Q.state;return Q}function lz5(A){if(A.role!=="info"||!Array.isArray(A.content))return null;return{...A,content:az5(A.content)}}function iz5(A){return Os0.safeParse(A).success}function rs0(A,Q){let B=[];for(let $ of A){let J=sy4($,Q);if(J)B.push(J)}return B}function nz5(A){return A.map((Q)=>sy4(Q,"assistant")??{type:"text",text:"",hidden:!0})}function sy4(A,Q){let $=(Q==="assistant"?ta:sa).safeParse([A]);return $.success?$.data[0]??null:null}function az5(A){let Q=[];for(let B of A){let $=Cs0.safeParse([B]);if($.success&&$.data[0])Q.push($.data[0])}return Q}function oz5(A){let Q={...A};if(!oB(Q.status,Kz5))Q.status="starting";if(Q.details!==void 0){let B=rz5(Q.details);if(B)Q.details=B;else delete Q.details}return Q}function rz5(A){if(!_z(A))return null;let Q={...A};if(Q.reasonCode!==void 0&&!oB(Q.reasonCode,Nz5))delete Q.reasonCode;if(Q.executionEnvironment!==void 0){let B=sz5(Q.executionEnvironment);if(B)Q.executionEnvironment=B;else delete Q.executionEnvironment}return Q}function sz5(A){if(!_z(A))return null;let Q={...A};return iy4(Q,"setupState",zz5),iy4(Q,"setupPhase",Wz5),os0(Q,"stage",Ez5),os0(Q,"operation",Hz5),os0(Q,"providerState",qz5),Q}function os0(A,Q,B){if(A[Q]!==void 0&&!oB(A[Q],B))delete A[Q]}function iy4(A,Q,B){if(A[Q]!==void 0&&A[Q]!==null&&!oB(A[Q],B))delete A[Q]}function tz5(A){if(!Array.isArray(A.approvals))return A;return{...A,approvals:A.approvals.map(ez5).filter((Q)=>Q!==null)}}function ez5(A){if(!_z(A))return null;let Q={...A};if(!oB(Q.context,Mz5))Q.context="thread";if(Q.ruleSource!==void 0&&!oB(Q.ruleSource,Lz5))delete Q.ruleSource;return Q}function AW5(A){if(!Array.isArray(A.relationships))return A;return{...A,relationships:A.relationships.filter(QW5)}}function QW5(A){return _z(A)&&oB(A.type,wz5)&&oB(A.role,Cz5)}var ss0=Number.MAX_SAFE_INTEGER;class ts0{callbacks;agentLoopState=null;pending=new Map;constructor(A){this.callbacks=A}setAgentLoopState(A){this.agentLoopState=A}emitOptimisticUserMessage(A){if(this.pending.has(A.messageId))return;let Q=this.nextEventType();this.pending.set(A.messageId,Q),this.dispatchOptimistic(Q,A)}emitOptimisticQueuedUserMessage(A){if(this.pending.has(A.messageId))return;this.pending.set(A.messageId,"queued_message_added"),this.dispatchOptimistic("queued_message_added",A)}reconcileMessageAdded(A){let Q=A.message.messageId;if(this.pending.get(Q)==="queued_message_added")this.emitQueuedMessages({type:"queued_message_dequeued",queuedMessageId:Q,seq:ss0});this.pending.delete(Q),this.emitMessageAdded(A)}reconcileQueuedMessageAdded(A){let Q=A.message.queuedMessage.messageId,B=this.pending.get(Q);if(B==="queued_message_added")return;if(B==="message_added")this.pending.set(Q,"queued_message_added");this.emitQueuedMessages(A)}reconcileQueuedMessagesSnapshot(A){let Q=new Set;for(let B of A.messages)Q.add(B.queuedMessage.messageId);for(let B of Q)if(this.pending.get(B)==="message_added")this.pending.set(B,"queued_message_added");for(let[B,$]of this.pending)if($==="queued_message_added"&&!Q.has(B))return;this.emitQueuedMessages(A)}reconcileQueuedMessageRemoved(A){this.pending.delete(A.queuedMessageId),this.emitQueuedMessages(A)}reset(){this.agentLoopState=null,this.pending.clear()}nextEventType(){if(this.pending.size>0)return"queued_message_added";if(this.agentLoopState===null||this.agentLoopState==="idle")return"message_added";return"queued_message_added"}dispatchOptimistic(A,Q){if(A==="message_added"){this.emitMessageAdded({type:"message_added",message:{role:"user",messageId:Q.messageId,content:Q.content,agentMode:Q.agentMode,threadId:this.callbacks.getThreadID()??"T-00000000-0000-0000-0000-000000000000"},seq:ss0});return}this.emitQueuedMessages({type:"queued_message_added",message:{steer:!1,queuedMessage:{role:"user",messageId:Q.messageId,content:Q.content,userState:Q.userState}},seq:ss0})}emitMessageAdded(A){this.callbacks.observerCallbacks((Q)=>{Q.onMessageAdded?.(A)})}emitQueuedMessages(A){this.callbacks.observerCallbacks((Q)=>{Q.onQueuedMessages?.(A)})}}class es0{options;queue=[];active=null;retryTimer=null;constructor(A){this.options=A}send(A){this.queue.push({message:A,sent:!1}),this.pump()}retry(){this.clearRetryTimer(),this.pump({forceActiveRetry:!0})}handleServerMessage(A){if(!this.active||!this.active.sent||this.active.message.type!=="client_append_user_msg")return;if(!$W5(this.active.message,A))return;let Q=this.active.message.messageId;this.clearRetryTimer(),this.active=null,this.options.onAckedUserMessage?.(Q),this.pump()}reset(){this.clearRetryTimer(),this.queue.length=0,this.active=null}pump(A){if(this.active){if(!this.active.sent||A?.forceActiveRetry)this.tryActive();return}let Q=this.queue.shift();if(!Q)return;this.active=Q,this.tryActive()}tryActive(){let A=this.active;if(!A||A.sent&&A.message.type!=="client_append_user_msg")return;if(!this.options.trySend(A.message)){this.scheduleRetry();return}if(A.sent=!0,A.message.type!=="client_append_user_msg"){this.clearRetryTimer(),this.active=null,this.pump();return}this.scheduleRetry()}scheduleRetry(){if(this.retryTimer!==null)return;this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.pump({forceActiveRetry:!0})},1000),BW5(this.retryTimer)}clearRetryTimer(){if(this.retryTimer===null)return;clearTimeout(this.retryTimer),this.retryTimer=null}}function BW5(A){if(typeof A!=="object"||A===null||!("unref"in A))return;let Q=A.unref;if(typeof Q==="function")Q.call(A)}function $W5(A,Q){switch(Q.type){case"message_added":return Q.message.messageId===A.messageId;case"queued_message_added":return Q.message.queuedMessage.messageId===A.messageId;case"queued_messages":return JW5(Q.messages,A.messageId);default:return!1}}function JW5(A,Q){return A.some((B)=>B.queuedMessage.messageId===Q)}function SD(A){return typeof A==="object"&&A!==null}function RF0(A,Q){return Object.hasOwn(A,Q)}function H5(A,Q){let B=A[Q];return typeof B==="string"?B:void 0}function PF0(A,Q){let B=A[Q];return typeof B==="number"&&Number.isFinite(B)?B:void 0}function Nj(A,Q){let B=A[Q];return typeof B==="boolean"?B:void 0}function $o(A,Q){let B=A[Q];return SD(B)?B:void 0}function iY(A,Q){let B=A[Q];return Array.isArray(B)?B:void 0}function t4(A,Q,B){if(B!==void 0)A[Q]=B}function At0(A){return A?.map((Q)=>Q.type)}function Qt0(A){let Q=A?.flatMap((B)=>B.blockState?[B.blockState]:[]);return Q&&Q.length>0?Q:void 0}function YW5(A){return A?.some((Q)=>ey4(Q.blockState))??!1}function ey4(A){return A==="start"||A==="complete"}function Ax4(A){return A.flatMap((Q)=>{if(!SD(Q))return[];let B=H5(Q,"type");return B?[B]:[]})}function Qx4(A){let Q=A.flatMap((B)=>{if(!SD(B))return[];let $=H5(B,"blockState");return $?[$]:[]});return Q.length>0?Q:void 0}function ZW5(A){return A?.some((Q)=>{if(!SD(Q))return!1;return ey4(H5(Q,"blockState"))})??!1}function FW5(A,Q){if(!Array.isArray(Q))return;A.blockCount=Q.length,A.blockTypes=Ax4(Q),t4(A,"blockStates",Qx4(Q))}function _F0(A,Q){let B={type:A};return t4(B,"direction",Q.direction),t4(B,"clientID",Q.clientID),t4(B,"frameMessageCount",Q.frameMessageCount),t4(B,"frameMessageIndex",Q.frameMessageIndex),t4(B,"frameLength",Q.frameLength),B}function Bx4(A,Q){t4(A,"seq",PF0(Q,"seq")),t4(A,"messageId",H5(Q,"messageId")),t4(A,"toolCallId",H5(Q,"toolCallId")),t4(A,"parentToolCallId",H5(Q,"parentToolCallId")),t4(A,"requestId",H5(Q,"requestId")),t4(A,"queuedMessageId",H5(Q,"queuedMessageId")),t4(A,"editId",H5(Q,"editId")),t4(A,"threadId",H5(Q,"threadId")),t4(A,"threadID",H5(Q,"threadID"))}function XW5(A,Q){Bx4(A,Q)}function DW5(A,Q){if(A.messageId=Q.messageId,A.role=Q.role,A.blockCount=Q.content.length,A.blockTypes=At0(Q.content),t4(A,"blockStates",Qt0(Q.content)),Q.role==="assistant")t4(A,"messageState",Q.state?.type),A.hasUsage=Q.usage!==void 0}function GW5(A,Q){if(A.subtype=`${Q.role}.${Q.state}`,A.role=Q.role,A.deltaState=Q.state,A.blockCount=Q.blocks?.length??0,t4(A,"blockTypes",At0(Q.blocks)),t4(A,"blockStates",Qt0(Q.blocks)),A.hasUsage=Q.role==="assistant"&&Q.usage!==void 0,Q.role==="assistant"&&Q.blockIndex!==void 0)A.blockIndex=Q.blockIndex}function $x4(A,Q){if(!SD(Q)){if(Q!==void 0)A.hasProgress=!0;return}let B=H5(Q,"type"),$=H5(Q,"state");if(t4(A,"progressType",B),t4(A,"progressState",$),B)A.subtype=$?`${B}.${$}`:B;let J=iY(Q,"blocks");if(J)A.progressBlockCount=J.length,A.progressBlockTypes=Ax4(J),t4(A,"progressBlockStates",Qx4(J));if(RF0(Q,"value"))A.hasProgressValue=!0}function Jx4(A,Q){if(!SD(Q))return;let B=H5(Q,"type");t4(A,"subtype",B),t4(A,"rpcType",B),t4(A,"rpcMethod",H5(Q,"method"))}function ty4(A,Q){if(!SD(Q))return;t4(A,"runStatus",H5(Q,"status")),A.hasRunProgress=RF0(Q,"progress"),A.hasRunResult=RF0(Q,"result"),A.hasRunError=RF0(Q,"error");let B=iY(Q,"trackFiles");if(B)A.trackFileCount=B.length}function VW5(A,Q){let B=iY(Q,"files");if(B)A.fileCount=B.length;t4(A,"fileCount",PF0(Q,"fileCount"));let $=iY(Q,"withContent");if($)A.withContentCount=$.length;let J=iY(Q,"contentOmitted");if(J)A.contentOmittedCount=J.length}function UW5(A,Q){t4(A,"ok",Nj(Q,"ok"));let B=iY(Q,"entries");if(B)A.entryCount=B.length;let $=H5(Q,"contentBase64");if($!==void 0)A.contentBase64Length=$.length;let J=$o(Q,"error");t4(A,"errorCode",J?H5(J,"code"):void 0)}function KW5(A,Q){switch(A.type){case"executor_connect":{t4(A,"clientId",H5(Q,"clientId")),t4(A,"executorType",H5(Q,"executorType"));let B=$o(Q,"capabilities");if(B)A.capabilityCount=Object.keys(B).length;return}case"client_update_thread_settings":A.settingsCount=Object.keys($o(Q,"settings")??{}).length;return;case"executor_tools_register":A.toolCount=iY(Q,"tools")?.length??0;return;case"executor_tools_unregister":A.toolCount=iY(Q,"toolNames")?.length??0;return;case"executor_tools_bootstrap_complete":t4(A,"ok",Nj(Q,"ok")),A.hasError=H5(Q,"error")!==void 0;return;case"tool_progress":$x4(A,Q.progress);return;case"executor_tool_result":ty4(A,Q.run);return;case"executor_guidance_snapshot":case"executor_guidance_discovery":VW5(A,Q),t4(A,"snapshotId",H5(Q,"snapshotId")),t4(A,"isLast",Nj(Q,"isLast"));return;case"executor_skill_snapshot":t4(A,"snapshotId",H5(Q,"snapshotId")),A.skillCount=iY(Q,"skills")?.length??0,A.errorCount=iY(Q,"errors")?.length??0,t4(A,"isLast",Nj(Q,"isLast"));return;case"executor_environment_snapshot":case"executor_environment_update":A.hasEnvironment=SD(Q.environment);return;case"executor_artifact_upsert":{let B=$o(Q,"artifact");t4(A,"artifactKey",B&&H5(B,"key")),t4(A,"artifactDataType",B&&H5(B,"dataType"));return}case"executor_artifact_delete":t4(A,"artifactKey",H5(Q,"key"));return;case"executor_plugin_message":Jx4(A,Q.message);return;case"client_append_user_msg":case"client_edit_message":FW5(A,Q.content),t4(A,"agentMode",H5(Q,"agentMode")),t4(A,"reasoningEffort",H5(Q,"reasoningEffort")),t4(A,"steer",Nj(Q,"steer"));return;case"client_set_thread_title":t4(A,"titleLength",H5(Q,"title")?.length);return;case"executor_filesystem_read_directory_result":case"executor_filesystem_read_file_result":UW5(A,Q);return;case"client_resume":t4(A,"version",PF0(Q,"version"));return;case"client_dismiss_active_error":t4(A,"seq",PF0(Q,"seq"));return;case"client_append_manual_bash_invocation":A.argCount=iY($o(Q,"args")??{},"args")?.length??0,t4(A,"hidden",Nj(Q,"hidden")),ty4(A,Q.run);return;case"client_tool_approval_response":t4(A,"accepted",Nj(Q,"accepted")),A.hasInput=SD(Q.input);return;case"client_spawn_executor":A.additionalRepositoryCount=iY(Q,"additionalRepositories")?.length??0,A.hasRepositoryURL=H5(Q,"repositoryURL")!==void 0,A.hasProjectID=H5(Q,"projectID")!==void 0;return;case"executor_tool_lease_ack":case"executor_tool_approval_request":case"client_remove_queued_msg":case"client_steer_queued_msg":case"client_mark_message_read":case"client_mark_message_unread":case"client_upsert_notification_subscription":case"client_filesystem_read_directory":case"client_filesystem_read_file":case"client_retry":case"client_cancel":return}}function EW5(A,Q){switch(Q.type){case"agent_state":A.subtype=Q.state,t4(A,"agentMode",Q.agentMode),t4(A,"reasoningEffort",Q.reasoningEffort);return;case"inference_tools":t4(A,"agentMode",Q.agentMode),A.toolCount=Q.tools.length;return;case"error":t4(A,"subtype",Q.code);return;case"error_set":t4(A,"subtype",Q.error.code),t4(A,"retryAt",Q.error.retryAt),t4(A,"attempt",Q.error.attempt);return;case"retry_scheduled":A.attempt=Q.attempt,A.maxAttempts=Q.maxAttempts,A.retryAt=Q.retryAt;return;case"executor_connected":A.executorId=Q.executorId,A.registeredToolCount=Q.registeredToolCount,A.guidanceInventoryCount=Q.guidanceInventory.length,A.rejectedToolCount=Q.rejectedTools?.length??0,A.resumeBootstrap=Q.resumeBootstrap===!0;return;case"tool_lease":A.subtype=Q.toolName,A.toolName=Q.toolName;return;case"client_filesystem_read_directory_result":case"client_filesystem_read_file_result":t4(A,"subtype",Q.ok?"ok":Q.error?.code),A.ok=Q.ok,t4(A,"errorCode",Q.error?.code);return;case"tool_approval_queue":A.approvalCount=Q.approvals.length;return;case"executor_tool_lease_revoked":A.subtype=Q.reason;return;case"plugin_message":Jx4(A,Q.message);return;case"executor_tool_approval_response":A.subtype=Q.accepted?"accepted":"rejected",A.accepted=Q.accepted;return;case"tool_progress":$x4(A,Q.progress);return;case"executor_error":A.subtype=Q.code;return;case"delta":GW5(A,Q);return;case"queued_messages":A.queuedMessageCount=Q.messages.length;return;case"queued_message_added":A.seq=Q.seq,A.messageId=Q.message.queuedMessage.messageId,A.blockCount=Q.message.queuedMessage.content.length,A.blockTypes=At0(Q.message.queuedMessage.content),t4(A,"blockStates",Qt0(Q.message.queuedMessage.content));return;case"queued_message_removed":case"queued_message_dequeued":A.messageId=Q.queuedMessageId;return;case"message_added":case"message_updated":DW5(A,Q.message);return;case"thread_truncated":A.truncateFromMessage=Q.truncateFromMessage;return;case"observers":A.observerCount=Q.count,A.hasExecutor=Q.hasExecutor===!0;return;case"executor_status":A.subtype=Q.status,t4(A,"executorId",Q.executorId),t4(A,"spawnId",Q.spawnId);return;case"artifacts_snapshot":A.artifactCount=Q.artifacts.length;return;case"artifact_upserted":A.subtype=Q.artifact.dataType,A.artifactDataType=Q.artifact.dataType,t4(A,"toolCallId",Q.artifact.toolCallId);return;case"thread_relationships":A.relationshipCount=Q.relationships.length;return;case"compaction_complete":A.cutMessageId=Q.cutMessageId;return;case"compaction_records":A.recordCount=Q.records.length;return;case"cancelled":case"thread_settings":case"error_cleared":case"retry_started":case"retry_cancelled":case"executor_filesystem_read_directory":case"executor_filesystem_read_file":case"executor_tool_result_ack":case"environment_update":case"artifact_deleted":case"thread_title":case"thread_status":case"compaction_started":case"edit_rejected":return}}function zW5(A){if(!SD(A))return!1;if(H5(A,"type")!=="delta")return!1;if(H5(A,"state")!=="generating")return!1;return!ZW5(iY(A,"blocks"))}function TF0(A,Q={}){let B=_F0(A.type,Q);return XW5(B,A),EW5(B,A),B}function Bt0(A,Q={}){if(!SD(A)){let $=_F0("unknown",Q);return $.messageKind=typeof A,$}let B=_F0(H5(A,"type")??"unknown",Q);return Bx4(B,A),KW5(B,A),B}function Yx4(A){return _F0("decode_failed",{direction:"receive",frameMessageCount:0,frameMessageIndex:0,frameLength:A})}function kF0(A){if(A.type==="delta")return A.state!=="generating"||YW5(A.blocks);if(A.type==="tool_progress")return!zW5(A.progress);return!0}function $t0(A,Q,B){if(!kF0(Q))return;A.info("[thread-client] Received server message",TF0(Q,{direction:"receive",...B}))}function Jt0(A,Q){A.info("[thread-client] Failed to decode received server message",Yx4(Q))}var WW5=3000,HW5=30000,qW5=5;function Zx4(A){if(A instanceof J9)return A;if(A instanceof Error){let Q=A.message||"Unknown thread-client connection error";return new J9(Q,A)}if(typeof A==="string"&&A.length>0)return new J9(A,A);return new J9("Unknown thread-client connection error",A)}function NW5(A){let Q=atob(A),B=new Uint8Array(Q.length);for(let $=0;$<Q.length;$++)B[$]=Q.charCodeAt($);return B}function IW5(A){return{type:"error",message:`Failed to send user message: ${A}`,code:"MESSAGE_ERROR"}}class PU extends as0{ensureConnectedPromise=null;pendingReadDirectoryRequests=new Map;pendingReadFileRequests=new Map;pendingThreadSettings=null;outbox;optimisticUserMessages;pendingCancelAgentLoop=!1;pendingDismissActiveError=null;fileSystemRequestCounter=0;wasConnectionReady=!1;observerCallbacks=null;executorCallbacks=null;pendingObserverDispatches=[];pendingExecutorDispatches=[];resumeCursor=ds0(0);threadHistoryLoader;executorConnectedListeners=new Set;executorErrorListeners=new Set;environmentSubject=new A4(null);threadIDSubscription;constructor(A){super(A.transport);if(this.threadHistoryLoader=A.threadHistoryLoader,this.outbox=new es0({trySend:(Q)=>this.trySendOutboxMessage(Q),onAckedUserMessage:(Q)=>{this.dispatchObserverCallbacks((B)=>{B.onUserMessageSendAck?.(Q)})}}),this.optimisticUserMessages=new ts0({getThreadID:()=>this.getThreadId(),observerCallbacks:(Q)=>this.dispatchObserverCallbacks(Q)}),this.threadIDSubscription=this.threadIDSubject.subscribe((Q)=>{if(Q!==null)this.dispatchObserverCallbacks((B)=>{B.onThreadId?.(Q)})}),A.observerCallbacks)this.setObserverCallbacks(A.observerCallbacks);if(A.executorCallbacks)this.setExecutorCallbacks(A.executorCallbacks)}setObserverCallbacks(A){if(this.observerCallbacks&&this.observerCallbacks!==A)throw Error("Observer callbacks are already set and cannot be replaced");if(this.observerCallbacks===A)return;if(this.observerCallbacks=A,this.pendingObserverDispatches.length===0)return;for(let Q of this.pendingObserverDispatches)Q(A);this.pendingObserverDispatches.length=0}setExecutorCallbacks(A){if(this.executorCallbacks&&this.executorCallbacks!==A)throw Error("Executor callbacks are already set and cannot be replaced");if(this.executorCallbacks===A)return;if(this.executorCallbacks=A,this.pendingExecutorDispatches.length===0)return;for(let Q of this.pendingExecutorDispatches)Q(A);this.pendingExecutorDispatches.length=0}async connect(){try{await super.connect()}catch(A){throw Zx4(A)}}async reconnect(){await this.disconnectAndWait(),await this.connect()}async ensureConnected(A){if(this.ensureConnectedPromise)return this.ensureConnectedPromise;this.ensureConnectedPromise=this.ensureConnectedInternal(A);try{return await this.ensureConnectedPromise}finally{this.ensureConnectedPromise=null}}async ensureConnectedInternal(A){let Q=A?.baseDelayMs??WW5,B=A?.maxDelayMs??HW5,$=A?.maxAttempts??qW5;if(A?.forceReconnectWhenReconnecting&&this.getConnectionInfo().state==="reconnecting")this.disconnect();for(let J=0;J<$;J++){try{await this.connect()}catch(X){let D=Zx4(X);if(this.getConnectionInfo().state!=="reconnecting")throw D;A?.onRetryableConnectError?.(D)}let Y=A?.waitForConnectedTimeoutMs??Math.min(Q*2**J,B);if(await this.waitForConnected(Y))return!0;let F=J+1<$?Math.min(Q*2**(J+1),B):null;A?.onAttemptTimeout?.({attempt:J+1,maxAttempts:$,nextDelayMs:F})}return!1}async loadThreadHistory(A){let Q=await this.threadHistoryLoader(A);if(!Q)return null;let B=Q.title;if(B!==void 0)this.dispatchObserverCallbacks(($)=>{$.onThreadTitle?.({type:"thread_title",title:B})});for(let[$,J]of Q.messages.entries())this.dispatchObserverCallbacks((Y)=>{let Z={type:"message_added",message:J,seq:$},F=l3.safeParse(J.parentToolUseId);if(F.success)Z.parentToolUseId=F.data;Y.onMessageAdded?.(Z)});return Q}getResumeVersion(){return this.resumeCursor.getVersion()}sendUserMessage(A,Q,B){let $=B?.messageId??qF0(),J={type:"client_append_user_msg",content:$J(A),agentMode:Q,reasoningEffort:B?.reasoningEffort,messageId:$,steer:B?.steer,userState:B?.userState};return this.dispatchObserverCallbacks((Y)=>{Y.onUserMessageSendPending?.($,Date.now())}),this.optimisticUserMessages.emitOptimisticUserMessage(J),this.outbox.send(J),this.retryConnectIfTerminallyDisconnected("user message sent"),$}retryConnectIfTerminallyDisconnected(A){if(this.getConnectionInfo().state!=="disconnected")return;this.retryConnect(A)}removeQueuedMessage(A){this.dispatchObserverCallbacks((Q)=>{Q.onUserActionMessageDeliveryStatusChanged?.(A,"buffered",Date.now())}),this.outbox.send({type:"client_remove_queued_msg",queuedMessageId:A}),this.retryConnectIfTerminallyDisconnected("queued message remove requested")}steerQueuedMessage(A){this.outbox.send({type:"client_steer_queued_msg",queuedMessageId:A}),this.retryConnectIfTerminallyDisconnected("queued message steer requested")}editUserMessage(A,Q,B,$,J){this.outbox.send({type:"client_edit_message",messageId:A,editId:B,content:$J(Q),agentMode:$,reasoningEffort:J?.reasoningEffort}),this.retryConnectIfTerminallyDisconnected("user message edit requested")}markMessageRead(A){this.send({type:"client_mark_message_read",messageId:A})}markMessageUnread(A){this.send({type:"client_mark_message_unread",messageId:A})}setThreadTitle(A){this.send({type:"client_set_thread_title",title:A})}upsertNotificationSubscription(A,Q){this.send({type:"client_upsert_notification_subscription",subscription:A,threadURL:Q})}readDirectory(A){return this.requestReadDirectory(A)}readFile(A){return this.requestReadFile(A)}resumeFromVersion(A){this.send({type:"client_resume",version:A}),this.resumeCursor.reset(A)}retryAgentLoop(){this.send({type:"client_retry"})}dismissActiveError(A){let Q=A===void 0?{}:{seq:A};if(!this.canSendClientMessage()){this.pendingDismissActiveError=Q;return}this.pendingDismissActiveError=null,this.send({type:"client_dismiss_active_error",...Q})}cancelAgentLoop(){if(!this.canSendClientMessage()){this.pendingCancelAgentLoop=!0,this.retryConnectIfTerminallyDisconnected("agent loop cancel requested");return}this.pendingCancelAgentLoop=!1,this.send({type:"client_cancel"})}appendManualBashInvocation(A){this.send({type:"client_append_manual_bash_invocation",args:$J(A.args),run:$J(A.run),hidden:A.hidden})}resolveToolApproval(A,Q,B){this.send({type:"client_tool_approval_response",toolCallId:A,accepted:Q,input:B})}requestExecutorSpawn(A,Q){this.send({type:"client_spawn_executor",requestId:A,repositoryURL:Q?.repositoryURL,projectID:Q?.projectID,additionalRepositories:Q?.additionalRepositories})}executePluginCommand(A,Q,B,$){this.sendPluginMessage({type:"request",id:A,method:"command.execute",params:{pluginName:Q,commandId:B,threadID:$}})}executorHandshake(A,Q,B){if(this.disposed)throw new c3("Transport is disposed");if(!this.hasOpenSocket()){if(this.getConnectionInfo().state==="connected")this.forceReconnect("executor handshake attempted without open socket");throw new c3("WebSocket is not connected. Call connect() first.")}let $=performance.now(),J=60000,Y={clientId:A,executorType:B?.executorType,timeoutMs:J};return this.log.info("[thread-client] Starting executor handshake",{...Y,connectionState:this.getConnectionInfo().state}),new Promise((Z,F)=>{let X=!1,D=null,G=null,V=()=>Math.round(performance.now()-$),U=(W,H,q)=>{let N=this.getConnectionInfo();this.log.error(W,{...Y,durationMs:V(),connectionState:N.state,role:N.role,reconnectCauseType:N.reconnectCause?.type,reconnectCode:N.reconnectCause?.code,reconnectReason:N.reconnectCause?.reason,error:H,...q})},K=(W)=>{this.log.info("[thread-client] Executor handshake completed",{...Y,durationMs:V(),executorId:W.executorId,registeredToolCount:W.registeredToolCount,resumeBootstrap:W.resumeBootstrap}),z(()=>Z(W))},E=(W)=>{let H=Error(W.message);U("[thread-client] Executor handshake rejected by server",H,{code:W.code}),z(()=>F(H))},z=(W)=>{if(X)return;if(X=!0,D)clearTimeout(D),D=null;this.executorConnectedListeners.delete(K),this.executorErrorListeners.delete(E),G?.unsubscribe(),W()};this.executorConnectedListeners.add(K),this.executorErrorListeners.add(E),G=this.connectionChanges().subscribe({next:(W)=>{if(W.state==="connected")return;let H=new c3(W.state==="reconnecting"?"Executor handshake interrupted by reconnect":"Executor handshake interrupted by disconnect");U("[thread-client] Executor handshake interrupted",H),z(()=>F(H))}}),this.send({type:"executor_connect",clientId:A,capabilities:Q,executorType:B?.executorType}),D=setTimeout(()=>{let W=Error("Executor connect timeout");U("[thread-client] Executor handshake timed out",W),z(()=>F(W))},J)})}ackToolLease(A){this.send({type:"executor_tool_lease_ack",toolCallId:A})}sendToolProgress(A,Q){let B=Ex(Q,"snapshot");this.send({type:"tool_progress",toolCallId:A,progress:B})}sendExecutorToolResult(A,Q){this.send({type:"executor_tool_result",toolCallId:A,run:Q})}sendExecutorFileSystemReadDirectoryResult(A,Q){this.send({type:"executor_filesystem_read_directory_result",requestId:A,...Q})}sendExecutorFileSystemReadFileResult(A,Q){this.send({type:"executor_filesystem_read_file_result",requestId:A,...Q})}sendExecutorToolApprovalRequest(A){this.send({type:"executor_tool_approval_request",approval:A})}sendPluginMessage(A){this.send({type:"executor_plugin_message",message:A})}sendExecutorGuidanceSnapshot(A){this.send({type:"executor_guidance_snapshot",...A})}sendExecutorGuidanceDiscovery(A){this.send({type:"executor_guidance_discovery",...A})}sendExecutorSkillSnapshot(A){this.send({type:"executor_skill_snapshot",...A})}sendClientUpdateThreadSettings(A){if(!this.canSendClientMessage()){this.pendingThreadSettings=A;return}try{this.pendingThreadSettings=null,this.send({type:"client_update_thread_settings",settings:A})}catch(Q){if(!this.canSendClientMessage()){this.pendingThreadSettings=A;return}throw Q}}registerTools(A){this.send({type:"executor_tools_register",tools:A})}sendExecutorToolsBootstrapComplete(A,Q){this.send({type:"executor_tools_bootstrap_complete",ok:A,error:Q})}sendEnvironmentSnapshot(A){this.send({type:"executor_environment_snapshot",environment:A}),this.environmentSubject.next(A)}sendEnvironmentUpdate(A){this.send({type:"executor_environment_update",environment:A}),this.environmentSubject.next(A)}environmentChanges(){return this.environmentSubject}getEnvironmentSnapshot(){return this.environmentSubject.getValue()}sendExecutorArtifactUpsert(A,Q){this.send({type:"executor_artifact_upsert",artifact:A,toolCallId:Q})}sendExecutorArtifactDelete(A){this.send({type:"executor_artifact_delete",key:A})}unregisterTools(A){this.send({type:"executor_tools_unregister",toolNames:A})}dispose(){if(this.disposed)return;super.dispose(),this.threadIDSubscription.unsubscribe(),this.pendingThreadSettings=null,this.outbox.reset(),this.optimisticUserMessages.reset(),this.pendingCancelAgentLoop=!1,this.pendingDismissActiveError=null,this.pendingObserverDispatches.length=0,this.pendingExecutorDispatches.length=0,this.resumeCursor=ds0(0),this.wasConnectionReady=!1,this.environmentSubject.complete(),this.rejectPendingFileSystemRequests("Transport disposed")}updateConnectionState(A){if(super.updateConnectionState(A),this.flushPendingReadyWork(),this.emitConnectionChanged(),A==="reconnecting"||A==="disconnected")this.rejectPendingFileSystemRequests("Connection closed before filesystem request completed")}onRawMessage(A){let Q=ay4(A);if(Q.length===0){Jt0(this.log,A.length);return}for(let[B,$]of Q.entries())$t0(this.log,$,{frameMessageCount:Q.length,frameMessageIndex:B,frameLength:A.length}),this.handleServerMessage($)}onWebSocketTraffic(A){if(this.connectionInfo.requiredRole!=="observer"||this.connectionInfo.role!==null)return;this.connectionInfo.role="observer",this.connectionSubject.next({...this.connectionInfo}),this.flushPendingReadyWork(),this.emitConnectionChanged()}onMaxReconnectExceeded(A){this.dispatchObserverCallbacks((Q)=>{Q.onErrorNotice?.({type:"error",message:`Failed to reconnect after ${A} attempts`,code:"MAX_RECONNECT_EXCEEDED"})})}handleServerMessage(A){switch(this.advanceResumeCursor(A),this.reconcileOptimisticUserMessage(A),this.outbox.handleServerMessage(A),A.type){case"agent_state":this.dispatchObserverCallbacks((Q)=>{Q.onAgentState?.(A)});break;case"inference_tools":this.dispatchObserverCallbacks((Q)=>{Q.onInferenceTools?.(A)});break;case"thread_settings":this.dispatchObserverCallbacks((Q)=>{Q.onThreadSettings?.(A)});break;case"error":this.dispatchObserverCallbacks((Q)=>{Q.onErrorNotice?.(A)});break;case"error_set":case"error_cleared":this.dispatchObserverCallbacks((Q)=>{Q.onActiveError?.(A)});break;case"cancelled":this.dispatchObserverCallbacks((Q)=>{Q.onCancelled?.(A)});break;case"retry_scheduled":case"retry_started":case"retry_cancelled":this.dispatchObserverCallbacks((Q)=>{Q.onRetryEvent?.(A)});break;case"delta":this.dispatchObserverCallbacks((Q)=>{Q.onDelta?.(A)});break;case"message_updated":this.dispatchObserverCallbacks((Q)=>{Q.onMessageUpdated?.(A)});break;case"edit_rejected":this.dispatchObserverCallbacks((Q)=>{Q.onEditRejected?.(A)});break;case"executor_connected":this.connectionInfo.role="executor",this.connectionInfo.clientId=A.executorId,this.connectionSubject.next({...this.connectionInfo}),this.flushPendingReadyWork(),this.emitConnectionChanged(),this.dispatchObserverCallbacks((Q)=>{Q.onExecutorConnected?.(A)});for(let Q of this.executorConnectedListeners)Q(A);break;case"tool_lease":this.dispatchExecutorCallbacks((Q)=>{Q.onToolLease?.(A)});break;case"executor_filesystem_read_directory":this.dispatchExecutorCallbacks((Q)=>{Q.onFileSystemReadDirectoryRequest?.(A)});break;case"executor_filesystem_read_file":this.dispatchExecutorCallbacks((Q)=>{Q.onFileSystemReadFileRequest?.(A)});break;case"executor_tool_lease_revoked":this.dispatchExecutorCallbacks((Q)=>{Q.onToolLeaseRevoked?.(A)});break;case"executor_tool_result_ack":this.dispatchExecutorCallbacks((Q)=>{Q.onExecutorToolResultAck?.(A)});break;case"tool_approval_queue":this.dispatchObserverCallbacks((Q)=>{Q.onToolApprovalQueue?.(A)});break;case"plugin_message":this.dispatchObserverCallbacks((Q)=>{Q.onPluginMessage?.(A)}),this.dispatchExecutorCallbacks((Q)=>{Q.onPluginMessage?.(A)});break;case"executor_tool_approval_response":this.dispatchObserverCallbacks((Q)=>{Q.onExecutorToolApprovalResponse?.(A)});break;case"tool_progress":this.dispatchObserverCallbacks((Q)=>{Q.onToolProgress?.(A)});break;case"executor_error":this.dispatchObserverCallbacks((Q)=>{Q.onExecutorError?.(A)}),this.dispatchExecutorCallbacks((Q)=>{Q.onExecutorError?.(A)});for(let Q of this.executorErrorListeners)Q(A);break;case"observers":this.dispatchObserverCallbacks((Q)=>{Q.onObservers?.(A)});break;case"executor_status":this.dispatchObserverCallbacks((Q)=>{Q.onExecutorStatus?.(A)});break;case"environment_update":this.environmentSubject.next(A.environment),this.dispatchObserverCallbacks((Q)=>{Q.onEnvironmentUpdate?.(A)});break;case"artifacts_snapshot":case"artifact_upserted":case"artifact_deleted":this.dispatchObserverCallbacks((Q)=>{Q.onArtifactEvent?.(A)});break;case"thread_title":this.dispatchObserverCallbacks((Q)=>{Q.onThreadTitle?.(A)});break;case"thread_relationships":this.dispatchObserverCallbacks((Q)=>{Q.onThreadRelationships?.(A)});break;case"thread_truncated":this.dispatchObserverCallbacks((Q)=>{Q.onTruncate?.(A)});break;case"client_filesystem_read_directory_result":this.handleReadDirectoryResult(A);break;case"client_filesystem_read_file_result":this.handleReadFileResult(A);break;case"compaction_started":case"compaction_complete":case"compaction_records":this.dispatchObserverCallbacks((Q)=>{Q.onCompactionEvent?.(A)});break;case"thread_status":break}}flushPendingReadyWork(){if(!T9(this.connectionInfo)){this.wasConnectionReady=!1;return}if(this.wasConnectionReady)return;this.wasConnectionReady=!0,this.flushPendingThreadSettings(),this.outbox.retry(),this.flushPendingCancelAgentLoop(),this.flushPendingDismissActiveError()}flushPendingThreadSettings(){if(!this.pendingThreadSettings||!this.canSendClientMessage())return;let A=this.pendingThreadSettings;try{this.pendingThreadSettings=null,this.send({type:"client_update_thread_settings",settings:A})}catch{if(!this.canSendClientMessage())this.pendingThreadSettings=A}}flushPendingCancelAgentLoop(){if(!this.pendingCancelAgentLoop||!this.canSendClientMessage())return;try{this.send({type:"client_cancel"}),this.pendingCancelAgentLoop=!1}catch{if(this.canSendClientMessage())this.pendingCancelAgentLoop=!1}}flushPendingDismissActiveError(){if(!this.pendingDismissActiveError||!this.canSendClientMessage())return;try{this.send({type:"client_dismiss_active_error",...this.pendingDismissActiveError}),this.pendingDismissActiveError=null}catch{if(this.canSendClientMessage())this.pendingDismissActiveError=null}}reconcileOptimisticUserMessage(A){switch(A.type){case"agent_state":this.optimisticUserMessages.setAgentLoopState(A.state);return;case"message_added":this.optimisticUserMessages.reconcileMessageAdded(A);return;case"queued_messages":this.optimisticUserMessages.reconcileQueuedMessagesSnapshot(A);return;case"queued_message_added":this.optimisticUserMessages.reconcileQueuedMessageAdded(A);return;case"queued_message_dequeued":this.optimisticUserMessages.reconcileQueuedMessageRemoved(A);return;case"queued_message_removed":this.optimisticUserMessages.reconcileQueuedMessageRemoved(A);return;default:return}}trySendOutboxMessage(A){if(!this.canSendClientMessage())return!1;try{return this.send(A),!0}catch(Q){let B=Q instanceof Error?Q.message:String(Q);return this.dispatchObserverCallbacks(($)=>{$.onErrorNotice?.(IW5(B))}),!1}}canSendClientMessage(){return this.hasOpenSocket()&&T9(this.connectionInfo)}emitConnectionChanged(){let A=this.getConnectionInfo();this.log.info("[thread-client] Emitting connection change callbacks",{state:A.state,role:A.role,clientId:A.clientId,reconnectCauseType:A.reconnectCause?.type,reconnectCode:A.reconnectCause?.code,reconnectReason:A.reconnectCause?.reason,hasExecutorCallbacks:this.executorCallbacks!==null,hasObserverCallbacks:this.observerCallbacks!==null,pendingExecutorDispatches:this.pendingExecutorDispatches.length,pendingObserverDispatches:this.pendingObserverDispatches.length}),this.dispatchExecutorCallbacks((Q)=>{Q.onConnectionChange?.(A)}),this.dispatchObserverCallbacks((Q)=>{Q.onConnectionChanged?.(A)})}dispatchObserverCallbacks(A){let Q=this.observerCallbacks;if(!Q){this.pendingObserverDispatches.push(A);return}A(Q)}dispatchExecutorCallbacks(A){let Q=this.executorCallbacks;if(!Q){this.pendingExecutorDispatches.push(A);return}A(Q)}requestReadDirectory(A){let Q=this.nextFileSystemRequestID("read-directory");return this.createPendingReadRequest(this.pendingReadDirectoryRequests,Q,()=>{this.send({type:"client_filesystem_read_directory",requestId:Q,uri:A})})}requestReadFile(A){let Q=this.nextFileSystemRequestID("read-file");return this.createPendingReadRequest(this.pendingReadFileRequests,Q,()=>{this.send({type:"client_filesystem_read_file",requestId:Q,uri:A})})}createPendingReadRequest(A,Q,B){if(!this.hasOpenSocket())return Promise.reject(new c3("WebSocket is not connected"));return new Promise(($,J)=>{let Y=setTimeout(()=>{A.delete(Q),J(new c3(`Filesystem request timed out: ${Q}`))},qy4);A.set(Q,{resolve:$,reject:J,timeoutID:Y});try{B()}catch(Z){clearTimeout(Y),A.delete(Q),J(Z instanceof Error?Z:Error(String(Z)))}})}nextFileSystemRequestID(A){let Q=this.fileSystemRequestCounter++;return`${A}-${Date.now()}-${Q}`}handleReadDirectoryResult(A){let Q=this.pendingReadDirectoryRequests.get(A.requestId);if(!Q)return;if(clearTimeout(Q.timeoutID),this.pendingReadDirectoryRequests.delete(A.requestId),A.ok&&A.entries){Q.resolve(A.entries);return}if(A.ok){Q.reject(Error("Invalid filesystem read_directory response: missing entries"));return}if(!A.error){Q.reject(Error("Invalid filesystem read_directory response: missing error"));return}Q.reject(this.createFileSystemError(A.error))}handleReadFileResult(A){let Q=this.pendingReadFileRequests.get(A.requestId);if(!Q)return;if(clearTimeout(Q.timeoutID),this.pendingReadFileRequests.delete(A.requestId),!A.ok&&A.error){Q.reject(this.createFileSystemError(A.error));return}if(!A.ok){Q.reject(Error("Invalid filesystem read_file response: missing error"));return}if(A.contentBase64===void 0){Q.reject(Error("Invalid filesystem read_file response: missing content"));return}try{Q.resolve(NW5(A.contentBase64))}catch{Q.reject(Error("Invalid base64 payload in filesystem read_file response"))}}createFileSystemError(A){return Error(`Filesystem error (${A.code}): ${A.message}`)}rejectPendingFileSystemRequests(A){for(let[Q,B]of this.pendingReadDirectoryRequests)clearTimeout(B.timeoutID),B.reject(new c3(A)),this.pendingReadDirectoryRequests.delete(Q);for(let[Q,B]of this.pendingReadFileRequests)clearTimeout(B.timeoutID),B.reject(new c3(A)),this.pendingReadFileRequests.delete(Q)}advanceResumeCursor(A){if(!("seq"in A)||!Number.isFinite(A.seq))return;this.resumeCursor.advanceFromSeq(A.seq)}send(A){try{this.sendRaw(_y4.encode(A))}catch(Q){let B=Q instanceof Error?Q.message:String(Q);throw new c3(`Failed to encode thread-protocol message "${A.type}": ${B}`,Q)}}}M1();function Yt0(A){return{...A,pendingRemoval:!0}}function Fx4(A,Q){if(Q.find(($)=>$.queuedMessage.messageId===A.queuedMessage.messageId)?.pendingRemoval!==!0)return A;return Yt0(A)}function Xx4(A,Q,B){if(Q.type==="queued_messages")return Q.messages.map(($)=>Fx4($,A));if(Q.type==="queued_message_added"){if(A.find((J)=>J.queuedMessage.messageId===Q.message.queuedMessage.messageId)&&B.dedupeAdded)return[...A];return[...A,Fx4(Q.message,A)]}if(!A.some(($)=>$.queuedMessage.messageId===Q.queuedMessageId))return[...A];return A.filter(($)=>$.queuedMessage.messageId!==Q.queuedMessageId)}function Dx4(A){if(A.connectionState==="disconnected")return"disconnected";if(A.compactionState==="compacting")return"compacting";if(A.connectionState!=="connected")return"connecting";if(!A.connectionReady)return"preparing_thread";switch(A.agentLoopState){case"awaiting_approval":return"awaiting_approval";case"tool_use":case"running_tools":return"running_tools";case"streaming":return A.streamingBlockKind==="text"||A.streamingBlockKind==="tool_use"?"streaming":"thinking";case"working":return"working";case"error":return"error";case"idle":if(A.pendingSend)return"sending";if(A.executorStatus?.status==="starting")return"waiting_for_executor";if(A.expectingAgentLoop)return"working";return"idle"}}function Jo(A){let Q=0;for(let B=0;B<A.length;B++){let $=A.codePointAt(B)??0;if($<128)Q+=1;else if($<2048)Q+=2;else if($<65536)Q+=3;else Q+=4,B++}return Q}function wW5(A){if(A.complete)return Jo(JSON.stringify(A.input));let Q=A.inputPartialJSON?.json;if(typeof Q==="string")return Jo(Q);return Jo(JSON.stringify(A.input))}var Gx4={state:"disconnected",role:null,requiredRole:null,clientId:null},CW5=750;function Vx4(A){return[...A].sort((Q,B)=>Q.key.localeCompare(B.key))}function MW5(A,Q){let B=A.findIndex((J)=>J.key===Q.key);if(B===-1)return Vx4([...A,Q]);let $=[...A];return $[B]=Q,$}function Ux4(A){switch(A.type){case"thinking":case"redacted_thinking":return"thinking";case"text":if(A.hidden===!0)return null;return"text";case"tool_use":case"server_tool_use":return"tool_use"}}function LW5(A,Q){let B=Q;for(let $ of A){let J=Ux4($);if(J===null)continue;if(J==="thinking"&&B!==null)continue;B=J}return B}class SF0{connectionInfo;agentLoopState;pendingSend=new A4(!1);streamingBlockKind=new A4(null);activeStreamingBlockKinds=new Map;expectingAgentLoop=!1;expectingAgentLoopTimer=null;status=new A4("idle");stageBytes=new A4(null);currentStage=null;currentStageBytes=0;toolBlockLatestBytes=new Map;queuedMessages=new A4([]);pendingApprovals=new A4([]);lastError=new A4(null);activeError=new A4(null);cancelledMessageId=new A4(null);retryState=new A4(null);executorError=new A4(null);observers=new A4(null);executorStatus=new A4(null);environment=new A4(null);compactionState=new A4("idle");compactionRecords=new A4([]);artifacts=new A4([]);threadSettings;threadTitle=new A4(void 0);threadId=new A4(null);messageAddedEvents=new m4;messageUpdatedEvents=new m4;deltaEvents=new m4;toolProgressEvents=new m4;truncateEvents=new m4;pluginMessages=new m4;now;dedupeQueuedMessageAdds;compactionRecordsState;constructor(A={}){this.connectionInfo=new A4(A.initialConnectionInfo??Gx4),this.agentLoopState=new A4(A.initialAgentLoopState??"idle"),this.threadSettings=new A4(A.initialThreadSettings??null),this.dedupeQueuedMessageAdds=A.dedupeQueuedMessageAdds??!0,this.compactionRecordsState=A.compactionRecordsState??null,this.now=A.now??(()=>new Date().toISOString()),this.recomputeStatus()}callbacks(){return this}recomputeStatus(){let A=this.connectionInfo.getValue(),Q=Dx4({connectionState:A.state,connectionReady:T9(A),compactionState:this.compactionState.getValue(),pendingSend:this.pendingSend.getValue(),executorStatus:this.executorStatus.getValue(),agentLoopState:this.agentLoopState.getValue(),streamingBlockKind:this.streamingBlockKind.getValue(),expectingAgentLoop:this.expectingAgentLoop});if(Q!==this.status.getValue())this.status.next(Q);this.syncStageBytes(Q)}syncStageBytes(A){let Q=A==="thinking"||A==="streaming"?A:null;if(Q===this.currentStage)return;this.currentStage=Q,this.currentStageBytes=0,this.toolBlockLatestBytes.clear(),this.stageBytes.next(Q===null?null:{stage:Q,bytes:0})}onConnectionChanged(A){if(!T9(A))this.clearExpectingAgentLoop();this.connectionInfo.next(A),this.recomputeStatus()}onAgentState(A){let Q=BQ(this.agentLoopState.getValue()),B=BQ(A.state);if(B)this.pendingSend.next(!1);if(A.state==="idle")this.clearStreamingBlockKind();if(B)this.clearExpectingAgentLoop();else if(A.state==="idle"&&Q)this.scheduleExpectingAgentLoop();else this.clearExpectingAgentLoop();this.agentLoopState.next(A.state),this.recomputeStatus()}onUserMessageSendPending(A,Q){this.pendingSend.next(!0),this.recomputeStatus()}onUserMessageSendAck(A){if(this.pendingSend.next(!1),!BQ(this.agentLoopState.getValue()))this.scheduleExpectingAgentLoop();this.recomputeStatus()}scheduleExpectingAgentLoop(){this.clearExpectingAgentLoopTimer(),this.expectingAgentLoop=!0,this.expectingAgentLoopTimer=setTimeout(()=>{this.expectingAgentLoopTimer=null,this.expectingAgentLoop=!1,this.recomputeStatus()},CW5)}clearExpectingAgentLoop(){this.clearExpectingAgentLoopTimer(),this.expectingAgentLoop=!1}clearExpectingAgentLoopTimer(){if(this.expectingAgentLoopTimer!==null)clearTimeout(this.expectingAgentLoopTimer),this.expectingAgentLoopTimer=null}onThreadSettings(A){this.threadSettings.next(A.settings)}onMessageAdded(A){this.messageAddedEvents.next(A)}onMessageUpdated(A){this.messageUpdatedEvents.next(A)}onDelta(A){this.updateStreamingBlockKinds(A),this.accumulateStageBytes(A),this.deltaEvents.next(A)}accumulateStageBytes(A){if(A.role!=="assistant")return;if(this.currentStage===null)return;let Q=A.blocks;if(!Q||Q.length===0)return;let B=A.blockIndex??0,$=0;for(let[J,Y]of Q.entries())if(this.currentStage==="streaming"){if(Y.type==="text"&&Y.hidden!==!0)$+=Jo(Y.text);else if(Y.type==="tool_use"){let Z=B+J,F=wW5(Y),X=this.toolBlockLatestBytes.get(Z)??0;if(F>X)$+=F-X,this.toolBlockLatestBytes.set(Z,F)}}else if(this.currentStage==="thinking"&&Y.type==="thinking")$+=Jo(Y.thinking);if($===0)return;this.currentStageBytes+=$,this.stageBytes.next({stage:this.currentStage,bytes:this.currentStageBytes})}updateStreamingBlockKinds(A){if(A.role!=="assistant")return;let Q=!1;if(A.state==="start")Q=this.clearStreamingBlockKind();let B=A.blocks;if(!B){if(Q)this.recomputeStatus();return}if(B.some(($)=>$.blockState!==void 0))Q=this.applyStreamingBlockLifecycle(B,A.blockIndex??0)||Q;else{let $=LW5(B,this.streamingBlockKind.getValue());if($!==this.streamingBlockKind.getValue())this.streamingBlockKind.next($),Q=!0}if(Q)this.recomputeStatus()}applyStreamingBlockLifecycle(A,Q){let B=!1;for(let[$,J]of A.entries()){let Y=Ux4(J);if(Y===null||J.blockState===void 0)continue;let Z=Q+$;if(J.blockState==="complete")B=this.activeStreamingBlockKinds.delete(Z)||B;else if(this.activeStreamingBlockKinds.get(Z)!==Y)this.activeStreamingBlockKinds.set(Z,Y),B=!0}return this.syncStreamingBlockKind()||B}clearStreamingBlockKind(){let A=this.activeStreamingBlockKinds.size>0;if(this.activeStreamingBlockKinds.clear(),this.streamingBlockKind.getValue()===null)return A;return this.streamingBlockKind.next(null),!0}syncStreamingBlockKind(){let A=this.deriveStreamingBlockKind();if(A===this.streamingBlockKind.getValue())return!1;return this.streamingBlockKind.next(A),!0}deriveStreamingBlockKind(){let A=-1,Q=null;for(let[B,$]of this.activeStreamingBlockKinds)if(B>A)A=B,Q=$;return Q}onToolProgress(A){this.toolProgressEvents.next(A)}onTruncate(A){this.truncateEvents.next(A)}onPluginMessage(A){this.pluginMessages.next(A)}onQueuedMessages(A){this.queuedMessages.next(Xx4(this.queuedMessages.getValue(),A,{dedupeAdded:this.dedupeQueuedMessageAdds}))}onUserActionMessageDeliveryStatusChanged(A,Q,B){if(Q!=="buffered")return;let $=this.queuedMessages.getValue(),J=$.findIndex((F)=>F.queuedMessage.messageId===A);if(J===-1)return;let Y=$[J];if(!Y)return;let Z=[...$];Z[J]=Yt0(Y),this.queuedMessages.next(Z)}onToolApprovalQueue(A){this.pendingApprovals.next(A.approvals)}onErrorNotice(A){this.clearPendingSendIfIdle(),this.lastError.next(A),this.recomputeStatus()}onActiveError(A){if(A.type==="error_set")this.clearPendingSendIfIdle(),this.compactionState.next("idle");this.cancelledMessageId.next(null),this.activeError.next(A.type==="error_set"?A.error:null),this.recomputeStatus()}onCancelled(A){this.cancelledMessageId.next(A.messageId??null),this.activeError.next(null)}onExecutorError(A){this.executorError.next(A)}onRetryEvent(A){this.retryState.next(A)}onObservers(A){this.observers.next({count:A.count,observers:A.observers,hasExecutor:A.hasExecutor??!1})}onExecutorStatus(A){if(this.executorStatus.next(A),A.status==="running")this.executorError.next(null);this.recomputeStatus()}onEnvironmentUpdate(A){this.environment.next(A.environment)}onArtifactEvent(A){let Q=this.artifacts.getValue();switch(A.type){case"artifacts_snapshot":this.artifacts.next(Vx4(A.artifacts));return;case"artifact_upserted":this.artifacts.next(MW5(Q,A.artifact));return;case"artifact_deleted":this.artifacts.next(Q.filter((B)=>B.key!==A.key));return}}onCompactionEvent(A){if(A.type==="compaction_started"){this.compactionState.next("compacting"),this.recomputeStatus();return}if(A.type==="compaction_complete"){this.compactionState.next("idle"),this.addCompactionRecord({cutMessageId:A.cutMessageId,createdAt:this.now()}),this.recomputeStatus();return}if(this.compactionRecords.next(A.records),this.compactionRecordsState!==null)this.compactionState.next(this.compactionRecordsState),this.recomputeStatus()}onThreadTitle(A){this.threadTitle.next(A.title||void 0)}onThreadId(A){this.threadId.next(A)}resetRuntimeState(){this.connectionInfo.next(Gx4),this.agentLoopState.next("idle"),this.pendingSend.next(!1),this.clearStreamingBlockKind(),this.clearExpectingAgentLoop(),this.queuedMessages.next([]),this.pendingApprovals.next([]),this.activeError.next(null),this.executorError.next(null),this.cancelledMessageId.next(null),this.retryState.next(null),this.observers.next(null),this.executorStatus.next(null),this.environment.next(null),this.compactionState.next("idle"),this.artifacts.next([]),this.recomputeStatus()}dispose(){this.clearExpectingAgentLoopTimer(),this.connectionInfo.complete(),this.agentLoopState.complete(),this.pendingSend.complete(),this.streamingBlockKind.complete(),this.status.complete(),this.stageBytes.complete(),this.queuedMessages.complete(),this.pendingApprovals.complete(),this.lastError.complete(),this.activeError.complete(),this.cancelledMessageId.complete(),this.retryState.complete(),this.executorError.complete(),this.observers.complete(),this.executorStatus.complete(),this.environment.complete(),this.compactionState.complete(),this.compactionRecords.complete(),this.artifacts.complete(),this.threadSettings.complete(),this.threadTitle.complete(),this.threadId.complete(),this.messageAddedEvents.complete(),this.messageUpdatedEvents.complete(),this.deltaEvents.complete(),this.toolProgressEvents.complete(),this.truncateEvents.complete(),this.pluginMessages.complete()}addCompactionRecord(A){let Q=this.compactionRecords.getValue();if(Q.some((B)=>B.cutMessageId===A.cutMessageId))return;this.compactionRecords.next([...Q,A])}clearPendingSendIfIdle(){if(this.pendingSend.getValue()&&!BQ(this.agentLoopState.getValue()))this.pendingSend.next(!1)}}d0();function vF0(A){let{client:Q,observer:B,toolService:$,callbacks:J}=A,Y=new Set,Z=[],F=!1,X=!1,D=null,G=!1,V=[],U=setInterval(()=>{},1000),E=Gx(()=>{if(G)return;j.debug("User cancelled (SIGINT/SIGTERM); cancelling remote agent loop");try{Q.cancelAgentLoop()}catch(W){j.warn("Failed to cancel remote agent loop on signal",{error:W})}J.onSignal()});return E.install(),V.push(B.activeError$.subscribe((W)=>{if(!W)return;J.onError(W.message)})),V.push(B.errorNotice$.subscribe((W)=>{J.onError(W)})),V.push($.pendingApprovals$.subscribe((W)=>{Z=W})),V.push(B.agentState$.subscribe((W)=>{D=W.state;let H=BQ(W.state);if(H&&W.messageId)Y.add(W.messageId);if(H){F=!0,X=!0;return}if(X=!1,!F)return;J.onTransitionToIdle(Z)})),V.push(B.messageAdded$.subscribe((W)=>{J.onMessageAdded(W)})),{currentTurnAssistantIds:Y,pendingApprovals:()=>Z,agentStarted:()=>F,agentActive:()=>X,agentIdle:()=>D==="idle",dispose:()=>{if(G)return;G=!0,E.remove(),clearInterval(U);for(let W of V)W.unsubscribe()}}}d0();import OW5 from"node:process";var yF0=j.getChild("thread-actors-transport"),Zt0=Number(OW5.env.SIMULATE_LATENCY??0),jW5=Number.isFinite(Zt0)&&Zt0>0?Zt0:0;function Wx(A,Q){let B=Q,$=0;return async()=>{let J=++$,Y=await A(B);if(J===$)B=Y.threadId;return Y}}function Hx(A){let Q=OU({endpoint:A.rivetEndpoint}),B={pingIntervalMs:A.pingIntervalMs??5000,webSocketLatencyMs:()=>jW5,webSocketProvider:async()=>{yF0.debug("Fetching connection credentials");let $=await A.credentialsProvider({forceRefresh:!0});yF0.debug("Fetched connection credentials",{threadId:$.threadId,threadVersion:$.threadVersion});let J=Q.threadActor.getOrCreate([$.threadId],{params:{wsToken:$.wsToken},createWithInput:{threadId:$.threadId,threadVersion:$.threadVersion,ownerUserId:$.ownerUserId,...$.agentMode?{agentMode:$.agentMode}:{}}});yF0.debug("Opening Rivet actor WebSocket",{threadId:$.threadId});let Y=await J.webSocket("/",void 0,{skipReadyWait:!0});return yF0.debug("Opened Rivet actor WebSocket",{threadId:$.threadId}),{webSocket:Y,threadId:$.threadId}}};if(A.initialThreadID)B.threadId=A.initialThreadID;if(A.maxReconnectAttempts!==void 0)B.maxReconnectAttempts=A.maxReconnectAttempts;if(A.requiredRole!==void 0)B.requiredRole=A.requiredRole;return B}i4();function xF0(A){let Q=A.agentMode||Gp(A);if(!Q)throw Error("agent mode could not be determined from thread");return{version:A.v,title:A.title??null,messages:A.messages.map((B)=>zx4(A,B)),agentMode:Q,needsImport:!PW5(A)}}function Ex4(A){let Q=A.agentMode||Gp(A);if(!Q)throw Error("agent mode could not be determined from thread");return{id:A.id,v:A.v,...A.title?{title:A.title}:{},messages:A.messages.map((B)=>RW5(A,B)),agentMode:Q,...A.meta?{meta:A.meta}:{}}}function RW5(A,Q){let{threadId:B,parentToolUseId:$,...J}=zx4(A,Q);if(Q.parentToolUseId!==void 0)return{...J,parentToolUseId:Q.parentToolUseId};return J}function PW5(A){if(!A.meta||typeof A.meta!=="object")return!1;return A.meta.usesThreadActors===!0}function zx4(A,Q){let B=_W5(Q);switch(Q.role){case"user":return Ft0(Q,{threadId:A.id,role:"user",content:[...Q.content],meta:L30(Q.meta),userState:TW5(Q.userState),readAt:Q.readAt,messageId:B});case"assistant":return Ft0(Q,{threadId:A.id,role:"assistant",content:[...Q.content],state:Q.state?.type==="cancelled"?{type:"cancelled"}:void 0,usage:Q.usage,readAt:Q.readAt,messageId:B});case"info":return Ft0(Q,{threadId:A.id,role:"info",content:Q.content.filter(kW5),messageId:B})}}function Ft0(A,Q){if(A.parentToolUseId!==void 0)Q.parentToolUseId=A.parentToolUseId;return Q}function _W5(A){let Q=Kx4(A.protocolMessageID);if(Q)return Q;let B=A.messageId;if(typeof B==="string"){let $=Kx4(B);if($)return $}return qF0()}function Kx4(A){if(!A)return null;let Q=f6.safeParse(A);return Q.success?Q.data:null}function TW5(A){if(!A)return;return{...A,currentlyVisibleFiles:[...A.currentlyVisibleFiles],runningTerminalCommands:A.runningTerminalCommands?[...A.runningTerminalCommands]:void 0,aggmanContext:A.aggmanContext?{...A.aggmanContext,availableProjects:A.aggmanContext.availableProjects?A.aggmanContext.availableProjects.map((Q)=>({...Q})):void 0,recentUnreadThreads:A.aggmanContext.recentUnreadThreads?A.aggmanContext.recentUnreadThreads.map((Q)=>({...Q})):void 0}:void 0}}function kW5(A){return A.type==="manual_bash_invocation"}_Q();r1();import Yo from"node:path";class Ij extends Error{code;constructor(A,Q){super(Q);this.code=A;this.name="ExecutorFileSystemPathError"}}function Hx4(A,Q){let B=o0.parse(A);if(B.scheme!=="file")throw new Ij("INVALID_URI","Only file:// URIs are supported");if(!B.path.startsWith("/"))throw new Ij("INVALID_URI","File URI path must be absolute");if(B.path.split("/").some((X)=>X===".."))throw new Ij("ACCESS_DENIED","File URI resolves outside workspace root");let J=Yo.posix.normalize(B.path).replace(/^\/+/u,"");if(J===".."||J.startsWith("../"))throw new Ij("ACCESS_DENIED","File URI resolves outside workspace root");let Y=Yo.resolve(Q),Z=J.length>0?Yo.resolve(Y,J):Y,F=Yo.relative(Y,Z);if(F.startsWith("..")||Yo.isAbsolute(F))throw new Ij("ACCESS_DENIED","File URI resolves outside workspace root");return Z}async function qx(A,Q){try{let B=Hx4(Q,A.workspaceRoot),$=await A.fileSystem.readdir(o0.file(B));return{ok:!0,entries:await Promise.all($.map(async(Y)=>{let Z=Y.isDirectory?"directory":"file",F=Z==="file"?await SW5(A.fileSystem,Y.uri):void 0;return[Y1.basename(Y.uri),Z,F]}))}}catch(B){return{ok:!1,error:Nx4(B,"read_directory")}}}async function SW5(A,Q){try{let B=await A.getMtime(Q);if(!Number.isFinite(B)||B<0)return;return{mtimeMs:B}}catch{return}}async function qx4(A,Q){try{let B=Hx4(Q,A.workspaceRoot),$=await A.fileSystem.readBinaryFile(o0.file(B));return{ok:!0,contentBase64:Buffer.from($).toString("base64")}}catch(B){return{ok:!1,error:Nx4(B,"read_file")}}}function Nx4(A,Q){if(A instanceof Ij)return{code:A.code,message:A.message};if(y8(A))return{code:"NOT_FOUND",message:"File or directory not found"};if(fF0(A,"EISDIR"))return{code:"IS_DIRECTORY",message:"Expected a file but found a directory"};if(fF0(A,"ENOTDIR"))return{code:Q==="read_directory"?"NOT_DIRECTORY":"INTERNAL_ERROR",message:Q==="read_directory"?"Expected a directory":Wx4(A)};if(fF0(A,"EACCES")||fF0(A,"EPERM"))return{code:"ACCESS_DENIED",message:"Permission denied"};return{code:"INTERNAL_ERROR",message:Wx4(A)}}function fF0(A,Q){if(!(A instanceof Error))return!1;return"code"in A&&A.code===Q}function Wx4(A){if(A instanceof Error)return A.message;return String(A)}d0();v5();Wl();i4();r1();M1();d0();function bF0(A){return(Q)=>{let B=Q.message;if(B.type!=="request")return;let $=Date.now();j.info("Plugin hook dispatcher request received",{method:B.method,id:B.id}),vW5(A.pluginService,B.method,B.params).then((J)=>{j.info("Plugin hook dispatcher request completed",{method:B.method,id:B.id,durationMs:Date.now()-$}),A.sendPluginMessage(Ix4(B.id,J))}).catch((J)=>{j.warn("Plugin hook dispatcher request failed",{method:B.method,id:B.id,durationMs:Date.now()-$,error:J}),A.sendPluginMessage(Ix4(B.id,void 0,J instanceof Error?J.message:String(J)))})}}function Ix4(A,Q,B){if(B!==void 0)return{type:"response",id:A,error:B};if(Q===void 0)return{type:"response",id:A};return{type:"response",id:A,result:Q}}async function vW5(A,Q,B){switch(Q){case"session.start":{let{event:$}=B;return await A.event.sessionStart($),{}}case"agent.start":{let{event:$}=B;return await A.event.agentStart($)}case"agent.end":{let{event:$}=B;return await A.event.agentEnd($)}case"command.execute":{let{pluginName:$,commandId:J,threadID:Y}=B;return await A.commands.execute($,J,Y?{threadID:Y}:void 0),{ok:!0}}default:throw Error(`Unknown plugin hook method: ${Q}`)}}import{exec as yW5}from"node:child_process";import{promisify as xW5}from"node:util";kV();i4();r1();var fW5=xW5(yW5);async function wx4(A){let Q=await Iz(),B=MQ(A)?A:c2(),$=await $D({filesystem:j3},Q,B),J=await bW5($.workingDirectory??$.workspaceRoot);return{...Q,...$,...J?{git:{branch:J}}:{},updatedAt:new Date().toISOString()}}async function bW5(A){if(!A)return;let Q;try{Q=o0.parse(A).fsPath}catch{return}try{let{stdout:B}=await fW5("git symbolic-ref --quiet --short HEAD",{cwd:Q});return B.trim()||void 0}catch{return}}function uW5(A){return new TextEncoder().encode(JSON.stringify(A)).length}function Nx(A,Q,B){if(A.length===0)return[];let $=[],J=[];for(let Y of A){let Z=[...J,Y],F=uW5(B(Z));if(J.length>0&&F>Q){$.push(J),J=[Y];continue}J=Z}if(J.length>0)$.push(J);return $}var Mx4=1048576;function Cx4(A){let Q=new Map;for(let B of A)Q.set(B.name,{schema:B,serializedSchema:JSON.stringify(B)});return Q}function hW5(A){let Q={...A.executionProfile?.serial!==void 0?{serial:A.executionProfile.serial}:{},...A.meta?.deferred!==void 0?{deferred:A.meta.deferred}:{},...A.meta?.skillNames!==void 0?{skillNames:[...A.meta.skillNames]}:{}};return Object.keys(Q).length>0?Q:void 0}function gW5(A){return{name:A.name,description:A.description??"",inputSchema:{type:"object",properties:A.inputSchema.properties??{},required:A.inputSchema.required,additionalProperties:A.inputSchema.additionalProperties},source:A.source,meta:hW5(A)}}function Xt0(A){return A.map((Q)=>gW5(Q.spec))}function Lx4(A,Q){let B=Cx4(A),$=Cx4(Q);return{toolsToRegister:Q.filter((J)=>{let Y=B.get(J.name),Z=$.get(J.name);return Y?.serializedSchema!==Z?.serializedSchema}),toolNamesToUnregister:[...B.keys()].filter((J)=>!$.has(J))}}function Ox4(A,Q=Mx4){return Nx(A,Q,(B)=>({type:"executor_tools_register",tools:B}))}function jx4(A,Q=Mx4){return Nx(A,Q,(B)=>({type:"executor_tools_unregister",toolNames:B}))}import{execFile as lW5}from"node:child_process";import{createHash as iW5}from"node:crypto";import{readFile as nW5,stat as aW5}from"node:fs/promises";import{basename as oW5,join as rW5}from"node:path";import yx4 from"node:process";import{promisify as sW5}from"node:util";async function Rx4(A,Q,B){let $=[];for(let J=0;J<A.length;J+=Q){let Y=A.slice(J,J+Q);$.push(...await Promise.all(Y.map(B)))}return $}var Px4=2097152,JI="(Content omitted — git status artifact exceeds size limit)";function mW5(A){return(A.fullFileDiff?.length??0)+(A.oldContent?.length??0)+(A.newContent?.length??0)}function pW5(A){let Q=!1;if(A.fullFileDiff!==void 0&&A.fullFileDiff!==A.diff)A.fullFileDiff=A.diff,Q=!0;if(A.oldContent!==void 0&&A.oldContent!==JI)A.oldContent=JI,Q=!0;if(A.newContent!==void 0&&A.newContent!==JI)A.newContent=JI,Q=!0;return Q}function dW5(A){let Q=!1;if(A.oldContent!==void 0)A.oldContent=void 0,Q=!0;if(A.newContent!==void 0)A.newContent=void 0,Q=!0;if(A.fullFileDiff!==void 0)A.fullFileDiff=void 0,Q=!0;return Q}function cW5(A){let Q=!1;if(A.diff!==JI)A.diff=JI,Q=!0;if(A.fullFileDiff!==void 0&&A.fullFileDiff!==JI)A.fullFileDiff=JI,Q=!0;return Q}function Ix(A){let Q=Buffer.from(JSON.stringify(A),"utf8").toString("base64"),B=new TextEncoder().encode(JSON.stringify({type:"executor_artifact_upsert",artifact:{key:cS,dataType:"application/json",contentBase64:Q}})).length;return{contentBase64:Q,messageSizeBytes:B}}function _x4(A,Q){let B={...A,aheadCommits:[...A.aheadCommits],files:A.files.map((Z)=>({...Z}))},$=Ix(B);if($.messageSizeBytes<=Q)return $.contentBase64;let J=B.files.map((Z,F)=>({index:F,weight:mW5(Z)})).filter((Z)=>Z.weight>0).sort((Z,F)=>F.weight-Z.weight);for(let{index:Z}of J){let F=B.files[Z];if(!F||!pW5(F))continue;if($=Ix(B),$.messageSizeBytes<=Q)return $.contentBase64}for(let{index:Z}of J){let F=B.files[Z];if(!F||!dW5(F))continue;if($=Ix(B),$.messageSizeBytes<=Q)return $.contentBase64}let Y=B.files.map((Z,F)=>({index:F,weight:Z.diff.length+(Z.fullFileDiff?.length??0)})).filter((Z)=>Z.weight>0).sort((Z,F)=>F.weight-Z.weight);for(let{index:Z}of Y){let F=B.files[Z];if(!F||!cW5(F))continue;if($=Ix(B),$.messageSizeBytes<=Q)return $.contentBase64}if(B.aheadCommits.length>0){if(B.aheadCommits=[],$=Ix(B),$.messageSizeBytes<=Q)return $.contentBase64}while(B.files.length>0)if(B.files.pop(),$=Ix(B),$.messageSizeBytes<=Q)return $.contentBase64;return $.contentBase64}var tW5=sW5(lW5),Cx=20971520,eW5=["GIT_CONFIG","GIT_CONFIG_COUNT","GIT_CONFIG_PARAMETERS"],uF0=["-c","core.quotepath=false","diff","--no-color","--no-ext-diff"],AH5=999999,Tx4="refs/remotes/origin/",QH5=20,BH5=10;function hF0(A){return A.replace(/\n+$/,"")}var Dt0=yx4.platform==="win32"?"NUL":"/dev/null";function $H5(A=yx4.env,Q={}){let{isolateGitConfig:B=!0}=Q,$={...A};if(B){for(let J of Object.keys($))if(eW5.includes(J)||J.startsWith("GIT_CONFIG_KEY_")||J.startsWith("GIT_CONFIG_VALUE_"))delete $[J];$.GIT_CONFIG_NOSYSTEM="1",$.GIT_CONFIG_SYSTEM=Dt0,$.GIT_CONFIG_GLOBAL=Dt0}return $}function kx4(A,Q){return{provider:"git",capturedAt:A,available:!1,repositoryRoot:null,repositoryName:null,branch:null,head:null,files:[],unavailableReason:Q}}function JH5(A){return A instanceof Error}async function wx(A,Q,B={}){try{let{stdout:$}=await tW5("git",Q,{cwd:A,env:$H5(),maxBuffer:B.maxBufferBytes??Cx});return $}catch($){if(B?.allowExitCodeOne&&JH5($)&&($.code===1||$.code==="1")&&typeof $.stdout==="string")return $.stdout;throw $}}async function Tz(A,Q){try{return await wx(A,Q)}catch{return null}}function YH5(A){if(A==="??")return"untracked";let Q=A[0]??" ",B=A[1]??" ";if(Q==="U"||B==="U"||A==="AA"||A==="DD")return"unmerged";if(Q==="R"||B==="R")return"renamed";if(Q==="C"||B==="C")return"copied";if(Q==="A"||B==="A")return"added";if(Q==="D"||B==="D")return"deleted";if(Q==="T"||B==="T")return"type_changed";return"modified"}function Gt0(A){let Q=[],B=A.split("\x00");for(let $=0;$<B.length;$++){let J=B[$];if(!J||J.length<4)continue;let Y=J.slice(0,2),Z=J.slice(3);if(!Z)continue;let F=YH5(Y);if(F==="renamed"||F==="copied"){let X=B[$+1];if(X){Q.push({path:Z,previousPath:X,changeType:F}),$+=1;continue}}Q.push({path:Z,changeType:F})}return Q.sort(($,J)=>$.path.localeCompare(J.path))}function ZH5(A){let Q=0,B=0,$=0,J=0,Y=0,Z=()=>{if(J===0&&Y===0)return;$+=Math.min(J,Y),J=0,Y=0};for(let F of A.split(`
4702
- `)){if(F.startsWith("+")&&!F.startsWith("+++")){Q+=1,J+=1;continue}if(F.startsWith("-")&&!F.startsWith("---")){B+=1,Y+=1;continue}Z()}return Z(),{added:Q,deleted:B,changed:$}}function FH5(A){let Q=iW5("sha256");for(let B of A)Q.update(B.path),Q.update("\x00"),Q.update(B.diff),Q.update("\x00");return Q.digest("hex")}async function Sx4(A,Q,B,$,J=Cx){let Y=$!==void 0?[`--unified=${$}`]:[];if(B)return wx(A,[...uF0,...Y,"HEAD","--",Q],{maxBufferBytes:J});let[Z,F]=await Promise.all([wx(A,[...uF0,...Y,"--cached","--",Q],{maxBufferBytes:J}).catch(()=>""),wx(A,[...uF0,...Y,"--",Q],{maxBufferBytes:J}).catch(()=>"")]);return[hF0(Z),hF0(F)].filter(Boolean).join(`
4703
- `)}async function XH5(A,Q,B=Cx){return wx(A,[...uF0,"--no-index","--",Dt0,Q],{allowExitCodeOne:!0,maxBufferBytes:B})}async function DH5(A,Q,B,$=Cx){let J=B??"HEAD";try{return await wx(A,["show",`${J}:${Q}`],{maxBufferBytes:$})}catch{return}}async function GH5(A,Q,B=Cx){try{let $=rW5(A,Q);if((await aW5($)).size>B)return;return await nW5($,"utf-8")}catch{return}}function vx4(A){let Q=Number.parseInt(A.trim(),10);if(!Number.isFinite(Q))return null;return Q}async function VH5(A){let Q=(await Tz(A,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]))?.trim();if(!Q?.startsWith(Tx4))return null;let B=Q.slice(Tx4.length);if(!B)return null;let $=`origin/${B}`,Y=(await Tz(A,["rev-parse","--verify","--quiet",`${$}^{commit}`]))?.trim();if(!Y)return null;return{baseRef:B,comparisonRef:$,baseRefHead:Y}}function UH5(A){let Q=A.split("\x00"),B=[];for(let $=0;$+1<Q.length;$+=2){let J=Q[$],Y=Q[$+1]??"";if(!J)continue;B.push({hash:J,shortHash:J.slice(0,12),subject:Y})}return B}async function KH5(A,Q){let B=await Tz(A,["log","-z",`--max-count=${QH5}`,"--format=%H%x00%s",`${Q}..HEAD`]);if(!B)return[];return UH5(B)}async function EH5(A,Q){if(!Q)return null;let B=await VH5(A);if(!B)return null;let $=await Tz(A,["rev-list","--count",`${B.comparisonRef}..HEAD`]);if(!$)return null;let J=await Tz(A,["rev-list","--count",`HEAD..${B.comparisonRef}`]);if(!J)return null;let Y=vx4($);if(Y===null)return null;let Z=vx4(J);if(Z===null)return null;return{baseRef:B.baseRef,comparisonRef:B.comparisonRef,baseRefHead:B.baseRefHead,aheadCount:Y,behindCount:Z}}async function gF0(A,Q={}){let{maxDiffBufferBytes:B=Cx}=Q,$=Date.now(),J=await Tz(A,["rev-parse","--show-toplevel"]);if(!J)return kx4($,"not a git repository");let Y=J.trim(),Z=oW5(Y),[F,X,D]=await Promise.all([Tz(Y,["rev-parse","--verify","HEAD"]),Tz(Y,["symbolic-ref","--short","HEAD"]),Tz(Y,["status","--porcelain=v1","--untracked-files=all","-z"])]);if(D===null)return kx4($,"failed to read git status");let G=F?.trim()||null,V=X?.trim()||null,U=Gt0(D),K=await EH5(Y,G),E=K?.aheadCount&&K.aheadCount>0?await KH5(Y,K.comparisonRef):[],z=await Rx4(U,BH5,async(W)=>{let H=hF0(W.changeType==="untracked"?await XH5(Y,W.path,B).catch(()=>""):await Sx4(Y,W.path,G,void 0,B).catch(()=>"")),q=hF0(W.changeType==="modified"?await Sx4(Y,W.path,G,AH5,B).catch(()=>""):H),N=W.changeType!=="added"&&W.changeType!=="untracked"?await DH5(Y,W.previousPath??W.path,G,B):void 0,I=W.changeType!=="deleted"?await GH5(Y,W.path,B):void 0;return{path:W.path,previousPath:W.previousPath,changeType:W.changeType,created:W.changeType==="added"||W.changeType==="untracked",diff:H,fullFileDiff:q,oldContent:N,newContent:I,diffStat:ZH5(H)}});return{provider:"git",capturedAt:$,available:!0,repositoryRoot:Y,repositoryName:Z,branch:V,head:G,diffHash:FH5(z),baseRef:K?.baseRef??null,baseRefHead:K?.baseRefHead??null,aheadCount:K?.aheadCount??0,behindCount:K?.behindCount,aheadCommits:E,files:z}}function zH5(A){return{provider:A.provider,capturedAt:A.capturedAt,available:A.available,repositoryRoot:A.repositoryRoot,repositoryName:A.repositoryName,branch:A.branch,head:A.head,diffHash:A.diffHash,baseRef:A.baseRef??null,baseRefHead:A.baseRefHead??null,aheadCount:A.aheadCount??0,behindCount:A.behindCount,...A.unavailableReason!==void 0?{unavailableReason:A.unavailableReason}:{},aheadCommits:A.aheadCommits??[],files:A.files.map((Q)=>({path:Q.path,previousPath:Q.previousPath,changeType:Q.changeType,created:Q.created,diff:Q.diff,fullFileDiff:Q.fullFileDiff,oldContent:Q.oldContent,newContent:Q.newContent,diffStat:Q.diffStat}))}}function Vt0(A){let Q=_x4(zH5(A),Px4);return{key:cS,dataType:"application/json",contentBase64:Q}}import{createHash as WH5}from"node:crypto";function Ut0(A){return WH5("sha256").update(A).digest("hex")}class Zo{entries=new Map;initialized=!1;static key(A,Q){return`${A}\x00${Q}`}replace(A){this.entries.clear();for(let Q of A)this.entries.set(Zo.key(Q.uri,Q.hash),Q);this.initialized=!0}clear(){this.entries.clear(),this.initialized=!1}has(A,Q){if(!this.initialized||typeof Q!=="string"||Q.length===0)return!1;return this.entries.has(Zo.key(A,Q))}isInitialized(){return this.initialized}}function Kt0(A,Q){return A.map((B)=>{if(typeof B.hash==="string"&&Q.has(B.uri,B.hash)){let $={uri:B.uri,hash:B.hash};if(typeof B.lineCount==="number")$.lineCount=B.lineCount;return $}return B})}var xx4=1048576;function fx4(A,Q,B,$=xx4){return Nx(A,$,(J)=>({type:"executor_guidance_snapshot",snapshotId:Q,files:J,isLast:!1,userConfigDir:B}))}function bx4(A,Q,B=xx4){return Nx(A,B,($)=>({type:"executor_guidance_discovery",toolCallId:Q,files:$,isLast:!1}))}var Mx={baseDelayMs:1000,maxDelayMs:30000,maxAttempts:5};function mF0(A,Q){if(A>=Q.maxAttempts)return null;let B=Math.max(1,A);return Math.min(Q.baseDelayMs*2**(B-1),Q.maxDelayMs)}var rB=j.getChild("executor");function HH5(A){return typeof A==="object"&&A!==null&&"output"in A&&A.output===""}function qH5(){let A=()=>{return},Q=()=>{return};return{promise:new Promise(($,J)=>{A=$,Q=J}),resolve:A,reject:Q}}function NH5(A){if(A==="darwin")return"darwin";if(A==="win32")return"windows";return"linux"}function ux4(A){let Q=A.previouslyAdvertisedTools??[],{toolsToRegister:B,toolNamesToUnregister:$}=Lx4(Q,A.nextTools),J=A.forceRegisterAll?[...A.nextTools]:B;for(let Y of Ox4(J))A.logMessage?.("SEND",{type:"executor_tools_register",tools:Y.map((Z)=>Z.name)}),A.transport.registerTools(Y);for(let Y of jx4($))A.logMessage?.("SEND",{type:"executor_tools_unregister",toolNames:Y}),A.transport.unregisterTools(Y);return[...A.nextTools]}async function IH5(A){let{transport:Q,threadId:B,configService:$,skillService:J,logMessage:Y}=A,Z=A.fileSystem??j3,F=performance.now(),X={clientID:A.executorClientID,threadID:B,executorType:A.executorType,allowResumeBootstrap:A.allowResumeBootstrap===!0},D={},G="executorHandshake",V=!1,U=performance.now(),K=(W)=>{D[`${W}Ms`]=Math.round(performance.now()-U)};rB.info("Starting executor bootstrap",X);let E={workspaceId:A.workspaceRoot,workingDirectory:A.workspaceRoot,environment:{os:NH5(process.platform)},tags:[]};Y?.("SEND",{type:"executor_connect",clientId:A.executorClientID,capabilities:E,executorType:A.executorType}),G="executorHandshake",U=performance.now();let z=await Q.executorHandshake(A.executorClientID,E,{executorType:A.executorType});K(G),Y?.("RECV",z),A.guidanceContentCache?.replace(z.guidanceInventory),V=A.allowResumeBootstrap===!0&&z.resumeBootstrap===!0;try{if(!V){A.onBootstrapProgress?.("environment"),G="buildEnvironmentSnapshot",U=performance.now();let N=await wx4(B);K(G),Y?.("SEND",{type:"executor_environment_snapshot",environment:N}),Q.sendEnvironmentSnapshot(N);let w={trees:N.workspaceRoot?[{uri:N.workspaceRoot}]:[],platform:N.platform,tags:N.tags};if(A.onBootstrapProgress?.("guidance"),G="sendGuidanceSnapshot",U=performance.now(),await wH5(Q,Z,$,w,Y,A.guidanceContentCache),K(G),A.onBootstrapProgress?.("skills"),G="sendSkillSnapshot",U=performance.now(),await CH5(Q,J,Y),K(G),A.sendGitSnapshot!==!1){A.onBootstrapProgress?.("git");try{G="sendGitSnapshot",U=performance.now();let O=await gF0(A.workspaceRoot);Y?.("SEND",{type:"executor_artifact_upsert",available:O.available,fileCount:O.files.length,branch:O.branch,head:O.head}),Q.sendExecutorArtifactUpsert(Vt0(O)),K(G)}catch{}}}A.onBootstrapProgress?.("tools"),G="initialToolDiscovery",U=performance.now(),await A.initialToolDiscovery,K(G),G="loadToolStatuses",U=performance.now();let W=await T1(A.toolService.tools);K(G);let H=Xt0(W);G="syncExecutorToolRegistrations",U=performance.now();let q=ux4({transport:Q,nextTools:H,previouslyAdvertisedTools:A.previouslyAdvertisedTools,forceRegisterAll:!V,logMessage:Y});return K(G),Y?.("SEND",{type:"executor_tools_bootstrap_complete",ok:!0}),Q.sendExecutorToolsBootstrapComplete(!0),rB.info("Executor bootstrap completed",{...X,resumeBootstrap:V,toolCount:H.length,advertisedToolCount:q.length,totalMs:Math.round(performance.now()-F),...D}),{advertisedTools:q}}catch(W){let H=W instanceof Error?W.message:String(W);throw Y?.("SEND",{type:"executor_tools_bootstrap_complete",ok:!1,error:H}),Q.sendExecutorToolsBootstrapComplete(!1,H),rB.error("Executor bootstrap failed",{...X,currentPhase:G,resumeBootstrap:V,totalMs:Math.round(performance.now()-F),...D,error:W}),W}}async function wH5(A,Q,B,$,J,Y){let F=(await _q({filesystem:Q,configService:B,threadService:{observe:()=>m0.of({id:c2(),created:Date.now(),v:0,messages:[],env:{initial:$}})}},{messages:[],env:{initial:$}})).map((U)=>({uri:U.uri,content:U.content,lineCount:U.content.split(`
4704
- `).length,hash:Ut0(U.content)})),X=Y?Kt0(F,Y):F,D=crypto.randomUUID(),G=B.userConfigDir?b1(B.userConfigDir):void 0;if(X.length===0){J?.("SEND",{type:"executor_guidance_snapshot",snapshotId:D,fileCount:0,withContent:[],contentOmitted:[],isLast:!0}),A.sendExecutorGuidanceSnapshot({snapshotId:D,files:[],isLast:!0,userConfigDir:G});return}let V=fx4(X,D,G);for(let U=0;U<V.length;U++){let K=V[U];if(!K)continue;let E=U===V.length-1,z=K.filter((H)=>H.content!==void 0).map((H)=>H.uri),W=K.filter((H)=>H.content===void 0).map((H)=>H.uri);J?.("SEND",{type:"executor_guidance_snapshot",snapshotId:D,fileCount:K.length,withContent:z,contentOmitted:W,isLast:E}),A.sendExecutorGuidanceSnapshot({snapshotId:D,files:K,isLast:E,userConfigDir:G})}}async function CH5(A,Q,B){let[$,J]=await Promise.all([Q.getSkills(),Q.getSkillErrors()]),Y=crypto.randomUUID(),Z=20,F=$.map((D)=>({name:D.name,description:D.description,baseDir:D.baseDir,frontmatter:D.frontmatter,files:D.files,source:D.source})),X=J.map((D)=>({path:D.path,error:D.error,...D.hint?{hint:D.hint}:{}}));if(F.length===0){B?.("SEND",{type:"executor_skill_snapshot",snapshotId:Y,skillCount:0,errorCount:X.length,isLast:!0}),A.sendExecutorSkillSnapshot({snapshotId:Y,skills:[],isLast:!0,errors:X});return}for(let D=0;D<F.length;D+=20){let G=F.slice(D,D+20),V=D+20>=F.length;B?.("SEND",{type:"executor_skill_snapshot",snapshotId:Y,skillCount:G.length,...V?{errorCount:X.length}:{},isLast:V}),A.sendExecutorSkillSnapshot({snapshotId:Y,skills:G,isLast:V,...V?{errors:X}:{}})}}class hx4{options;inFlight=null;readyWaiter=null;retryTimer=null;readyTimer=null;readyTimeoutConfig=null;attempt=0;generation=0;lastInfo=null;disposed=!1;baseDelayMs;maxDelayMs;maxAttempts;pollDelayMs;constructor(A){this.options=A;this.baseDelayMs=A.baseDelayMs??Mx.baseDelayMs,this.maxDelayMs=A.maxDelayMs??Mx.maxDelayMs,this.maxAttempts=A.maxAttempts??Mx.maxAttempts,this.pollDelayMs=A.pollDelayMs??30000}ensureHandshake(A){return this.tryHandshake(A)}ensureReady(A){if(this.disposed)return Promise.reject(Error("Executor handshake manager is disposed"));if(this.isReady())return Promise.resolve();if(!this.readyWaiter)this.readyWaiter=qH5();if(A?.timeoutMs)this.readyTimeoutConfig={timeoutMs:A.timeoutMs,timeoutMessage:A.timeoutMessage??`Timed out waiting for handshake after ${A.timeoutMs}ms`},this.armReadyTimeout();return this.tryHandshake("connect"),this.readyWaiter.promise}handleConnectionChange(A){let Q=this.lastInfo;this.lastInfo=A;let B=A.state!=="connected"?"reset_disconnected":A.role==="executor"?"mark_ready":"ensure_handshake";if(rB.info("Handshake manager handling connection change",{action:B,state:A.state,role:A.role,clientId:A.clientId,reconnectCauseType:A.reconnectCause?.type,reconnectCauseCode:A.reconnectCause?.code,reconnectCauseReason:A.reconnectCause?.reason,attempt:this.attempt,hasInFlightHandshake:this.inFlight!==null,hasRetryTimer:this.retryTimer!==null}),A.state!=="connected"){this.reset("disconnected");return}if(A.role==="executor"){this.reset("executor"),this.resolveReadyWaiter();return}if(!Q||Q.state!=="connected")this.armReadyTimeout();this.tryHandshake("connect")}dispose(){this.disposed=!0,this.generation++,this.clearRetryTimer(),this.clearReadyTimer(),this.readyTimeoutConfig=null,this.rejectReadyWaiter(Error("Executor handshake manager is disposed"))}isReady(){return this.lastInfo?.state==="connected"&&this.lastInfo.role==="executor"}resolveReadyWaiter(){this.clearReadyTimer(),this.readyTimeoutConfig=null;let A=this.readyWaiter;if(!A)return;this.readyWaiter=null,A.resolve()}rejectReadyWaiter(A){this.clearReadyTimer(),this.readyTimeoutConfig=null;let Q=this.readyWaiter;if(!Q)return;this.readyWaiter=null,Q.reject(A)}reset(A){this.generation++,this.attempt=0,this.clearRetryTimer(),this.clearReadyTimer()}clearRetryTimer(){if(!this.retryTimer)return;clearTimeout(this.retryTimer),this.retryTimer=null}armReadyTimeout(){if(!this.readyTimeoutConfig||!this.readyWaiter)return;this.clearReadyTimer();let{timeoutMs:A,timeoutMessage:Q}=this.readyTimeoutConfig;this.readyTimer=setTimeout(()=>{this.readyTimer=null,this.rejectReadyWaiter(Error(Q))},A)}clearReadyTimer(){if(!this.readyTimer)return;clearTimeout(this.readyTimer),this.readyTimer=null}tryHandshake(A){if(this.disposed)return rB.info("Handshake manager ignored trigger while disposed",{trigger:A}),this.inFlight;if(this.inFlight)return rB.info("Handshake manager reused in-flight handshake",{trigger:A,attempt:this.attempt,state:this.lastInfo?.state,role:this.lastInfo?.role}),this.inFlight;let Q=this.generation;rB.info("Handshake manager starting handshake",{trigger:A,generation:Q,attempt:this.attempt,state:this.lastInfo?.state,role:this.lastInfo?.role});let B=this.options.handshake(A);return this.inFlight=B,B.then(()=>{if(this.disposed||Q!==this.generation)return;rB.info("Handshake manager handshake succeeded",{trigger:A,generation:Q}),this.attempt=0,this.clearRetryTimer(),this.resolveReadyWaiter()}).catch(($)=>{if(this.disposed||Q!==this.generation)return;this.scheduleRetry(A,$)}).finally(()=>{if(this.inFlight===B)this.inFlight=null}),B}scheduleRetry(A,Q){if(this.disposed)return;if(!this.lastInfo||this.lastInfo.state!=="connected"||this.lastInfo.role==="executor")return;this.attempt+=1;let B=mF0(this.attempt,{baseDelayMs:this.baseDelayMs,maxDelayMs:this.maxDelayMs,maxAttempts:this.maxAttempts}),$=B===null;if($)rB.error("Handshake manager exhausted fast retries",{trigger:A,attempt:this.attempt,maxAttempts:this.maxAttempts,pollDelayMs:this.pollDelayMs,error:Q}),this.options.onExhausted?.({attempt:this.attempt,maxAttempts:this.maxAttempts,error:Q}),this.rejectReadyWaiter(Q instanceof Error?Q:Error("Executor handshake failed and exhausted retries")),this.options.forceReconnect?.("executor handshake exhausted");let J=B??this.pollDelayMs;this.clearRetryTimer(),rB.info("Handshake manager scheduled retry",{trigger:A,attempt:this.attempt,delayMs:J,state:this.lastInfo.state,role:this.lastInfo.role,mode:$?"poll":"fast",error:Q instanceof Error?Q.message:String(Q)}),this.options.onError?.({trigger:A,attempt:this.attempt,delayMs:J,error:Q}),this.retryTimer=setTimeout(()=>{if(this.retryTimer=null,!this.lastInfo||this.lastInfo.state!=="connected"||this.lastInfo.role==="executor")return;this.tryHandshake("retry")},J)}}class gx4{options;clientID;transport;sentApprovalRequests=new Set;discoveredGuidanceFileURIs=new Set;activeTools=new Map;pendingTerminalResults=new Map;gitStatusQueue={inFlight:!1,queued:!1,queuedToolCallId:void 0};disposing=!1;constructor(A){this.options=A;this.clientID=A.clientID,this.transport=A.transport}async handleToolLease(A){if(this.disposing)return;let{toolCallId:Q,toolName:B}=A;if(this.activeTools.has(Q)){this.options.log.info(`${this.clientID} ignoring duplicate active lease`,{toolCallId:Q,toolName:B});return}let $=this.pendingTerminalResults.get(Q);if($){this.options.log.info(`${this.clientID} replaying pending terminal result for duplicate lease`,{toolCallId:Q,toolName:B}),this.sendPendingTerminalResult(Q,$,"flush");return}let J=Date.now();this.options.log.info(`${this.clientID} executing tool: ${B}`,{toolCallId:Q}),this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_lease_ack",toolCallId:Q}),this.transport.ackToolLease(Q);let Y=new AbortController,Z={subscription:{unsubscribe:()=>{}},abortController:Y,needsProgressSnapshot:!1};this.activeTools.set(Q,Z);let F=()=>{this.activeTools.delete(Q)};try{let X=A;if(this.options.requestPluginToolCall&&this.options.threadId){let V=await this.requestPluginToolCall(A);if(Y.signal.aborted){F();return}if("shortCircuitRun"in V){this.prepareAndSendToolResult(A,V.shortCircuitRun,Z);return}X=V.lease}let D=await this.options.invokeTool(X);this.options.log.info(`${this.clientID} tool service returned observable`,{toolCallId:Q,toolName:B,elapsedMs:Date.now()-J});let G=D.subscribe({next:(V)=>{if(Y.signal.aborted)return;let U=V.status==="in-progress"?V.progress??V.result:void 0,K=U!==void 0?$J(U):void 0;if(K!==void 0&&!HH5(K)){let E=Ex(K,"snapshot"),z=MF0(Z.progress,E),W=Z.needsProgressSnapshot&&z.type==="snapshot"?z:Ry4(Z.sentProgress,z);if(Z.progress=z,this.options.log.wsMessage("SEND",this.clientID,{type:"tool_progress",toolCallId:Q,progress:W}),this.sendTransportMessage("tool_progress",()=>this.transport.sendToolProgress(Q,W),{toolCallId:Q}))Z.sentProgress=z,Z.needsProgressSnapshot=!1;else Z.needsProgressSnapshot=!0}if(S5(V.status))G.unsubscribe(),this.prepareAndSendToolResult(X,V,Z);if(V.status==="blocked-on-user")this.options.log.info(`${this.clientID} awaiting tool approval`,{toolCallId:Q,toolName:B})},error:(V)=>{if(Y.signal.aborted){F();return}this.options.log.error(`${this.clientID} tool execution failed: ${B}`,V);let U={status:"error",error:{message:V instanceof Error?V.message:"Unknown error"}};this.prepareAndSendToolResult(X,U,Z)}});Z.subscription=G}catch(X){this.options.log.error(`${this.clientID} tool execution setup failed: ${B}`,X);let D={status:"error",error:{message:X instanceof Error?X.message:String(X)}};this.prepareAndSendToolResult(A,D,Z)}}flushBufferedTerminalResults(){if(this.disposing||this.pendingTerminalResults.size===0)return;for(let[A,Q]of this.pendingTerminalResults)this.sendPendingTerminalResult(A,Q,"flush")}markActiveProgressSnapshotsRequired(){for(let A of this.activeTools.values())A.needsProgressSnapshot=!0}handleToolRevocation(A){if(this.disposing)return;let{toolCallId:Q,reason:B}=A;this.options.log.info(`${this.clientID} lease revoked: ${Q}`,{reason:B});let $=this.activeTools.get(Q);if($)$.abortController.abort(),$.subscription.unsubscribe(),this.activeTools.delete(Q);this.sentApprovalRequests.delete(Q)}triggerGitStatus(A){this.queueGitStatusSnapshot(A)}dispose(){this.disposing=!0;for(let[,A]of this.activeTools)A.abortController.abort(),A.subscription.unsubscribe();this.activeTools.clear(),this.pendingTerminalResults.clear()}async prepareAndSendToolResult(A,Q,B){try{let $=this.toToolRun(Q);if(this.options.requestPluginToolResult&&this.options.threadId)$=await this.requestPluginToolResult(A,$);if(this.disposing||B.abortController.signal.aborted||this.activeTools.get(A.toolCallId)!==B)return;this.sendToolResult(A.toolCallId,$)}catch($){this.options.log.error(`${this.clientID} failed to prepare tool result`,$)}finally{if(this.activeTools.get(A.toolCallId)===B)this.activeTools.delete(A.toolCallId)}}sendToolResult(A,Q){let B=Date.now(),$=$J(Q),{run:J,files:Y}=this.extractGuidanceFromRun($),Z=this.prepareGuidanceDiscoveryBatches(A,Y),F={run:J,guidanceBatches:Z};this.pendingTerminalResults.set(A,F),this.sendPendingTerminalResult(A,F,"live",{guidanceFileCount:Y.length,elapsedMs:Date.now()-B}),this.sentApprovalRequests.delete(A),this.queueGitStatusSnapshot(A)}sendPendingTerminalResult(A,Q,B,$){if(!this.sendGuidanceDiscoveryBatches(A,Q.guidanceBatches))return!1;return this.sendTerminalResult(A,Q.run,B,$)}async requestPluginToolCall(A){let Q=this.options.threadId,B=this.options.requestPluginToolCall;if(!Q||!B)return{lease:A};let $={thread:{id:Q},toolUseID:A.toolCallId,tool:A.toolName,input:this.getLeaseArgs(A)};try{let J=await B($);switch(J.action){case"allow":return{lease:A};case"modify":return{lease:{...A,args:J.input}};case"reject-and-continue":return{shortCircuitRun:{status:"done",result:`Tool rejected by plugin: ${J.message}`}};case"synthesize":return{shortCircuitRun:{status:"done",result:J.result.output}};case"error":return{shortCircuitRun:{status:"error",error:{message:`Plugin error: ${J.message}`,displayMessage:J.message}}}}}catch(J){return this.options.log.error(`${this.clientID} plugin tool.call failed`,J),{shortCircuitRun:{status:"error",error:{message:J instanceof Error?J.message:String(J)}}}}}async requestPluginToolResult(A,Q){let B=this.options.threadId,$=this.options.requestPluginToolResult;if(!B||!$||Q.status!=="done"&&Q.status!=="error"&&Q.status!=="cancelled")return Q;let J={thread:{id:B},toolUseID:A.toolCallId,tool:A.toolName,input:this.getLeaseArgs(A),status:Q.status,error:Q.status==="error"?Q.error?.message:void 0,output:Q.status==="done"?Q.result:void 0};try{let Y=await $(J);if(!Y)return Q;switch(Y.status){case"done":return{status:"done",result:Y.output??(Q.status==="done"?Q.result:""),progress:Q.progress,trackFiles:Q.status==="done"?Q.trackFiles:void 0};case"error":return{status:"error",progress:Q.progress,error:{message:Y.error??(Q.status==="error"?Q.error?.message??"Tool execution failed":"Tool execution failed")}};case"cancelled":return{status:"cancelled",progress:Q.progress,reason:Y.error??(Q.status==="cancelled"?Q.reason:void 0)}}}catch(Y){this.options.log.error(`${this.clientID} plugin tool.result failed`,Y)}return Q}getLeaseArgs(A){if(typeof A.args==="object"&&A.args!==null&&!Array.isArray(A.args))return A.args;return{}}sendTerminalResult(A,Q,B,$){this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_result",toolCallId:A,run:Q});let J=this.sendTransportMessage("executor_tool_result",()=>this.transport.sendExecutorToolResult(A,Q),{toolCallId:A,source:B});return this.options.log.info(`${this.clientID} executor_tool_result send attempted`,{toolCallId:A,status:Q.status,sent:J,source:B,...$}),J}ackTerminalResult(A){if(this.pendingTerminalResults.delete(A.toolCallId))this.options.log.info(`${this.clientID} executor_tool_result acknowledged`,{toolCallId:A.toolCallId})}handleExecutorError(A){if(A.code!=="LEASE_NOT_FOUND"||A.toolCallId===void 0)return;if(this.pendingTerminalResults.delete(A.toolCallId))this.options.log.info(`${this.clientID} executor_tool_result rejected`,{toolCallId:A.toolCallId,code:A.code})}prepareGuidanceDiscoveryBatches(A,Q){let B=Q.map((Y)=>{if(typeof Y.hash==="string"||typeof Y.content!=="string")return Y;return{...Y,hash:Ut0(Y.content)}}),$=this.options.guidanceContentCache,J=$?Kt0(B,$):B;return this.options.batchGuidanceFiles(J,A)}sendGuidanceDiscoveryBatches(A,Q){for(let B=0;B<Q.length;B++){let $=Q[B];if(!$)continue;let J=B===Q.length-1,Y=$.filter((F)=>F.content!==void 0).map((F)=>F.uri),Z=$.filter((F)=>F.content===void 0).map((F)=>F.uri);if(this.options.log.wsMessage("SEND",this.clientID,{type:"executor_guidance_discovery",toolCallId:A,fileCount:$.length,withContent:Y,contentOmitted:Z,isLast:J}),!this.sendTransportMessage("executor_guidance_discovery",()=>this.transport.sendExecutorGuidanceDiscovery({toolCallId:A,files:$,isLast:J}),{toolCallId:A,isLast:J,fileCount:$.length,withContent:Y,contentOmitted:Z}))return!1}return!0}queueGitStatusSnapshot(A){if(this.disposing||!this.options.captureGitStatus)return;if(this.gitStatusQueue.inFlight){if(this.gitStatusQueue.queued=!0,A)this.gitStatusQueue.queuedToolCallId=A;return}this.gitStatusQueue.inFlight=!0,this.sendGitStatusSnapshot(A).finally(()=>{if(this.gitStatusQueue.inFlight=!1,!this.gitStatusQueue.queued)return;let Q=this.gitStatusQueue.queuedToolCallId;this.gitStatusQueue.queued=!1,this.gitStatusQueue.queuedToolCallId=void 0,this.queueGitStatusSnapshot(Q)})}async sendGitStatusSnapshot(A){try{if(!this.options.captureGitStatus)return;let Q=await this.options.captureGitStatus();this.options.log.wsMessage("SEND",this.clientID,{type:"executor_artifact_upsert",available:Q.available,fileCount:Q.files.length,toolCallId:A,branch:Q.branch,head:Q.head}),this.transport.sendExecutorArtifactUpsert(Vt0(Q),A)}catch(Q){this.options.log.error("Failed to send git status snapshot",Q)}}toToolRun(A){switch(A.status){case"done":return{status:"done",result:A.result,progress:A.progress,trackFiles:A.trackFiles?[...A.trackFiles]:void 0};case"error":return{status:"error",error:{message:A.error?this.options.renderToolRunError(A.error):"Tool execution failed"}};case"rejected-by-user":return{status:"rejected-by-user",reason:A.reason};case"cancelled":return{status:"cancelled",reason:A.reason};default:return{status:"error",error:{message:`Unexpected status: ${A.status}`}}}}extractGuidanceFromRun(A){if(A.status!=="done")return{run:A,files:[]};if(!A.result||typeof A.result!=="object"||Array.isArray(A.result))return{run:A,files:[]};let Q=A.result;if(!("discoveredGuidanceFiles"in Q))return{run:A,files:[]};let B=ky4(Q.discoveredGuidanceFiles),{discoveredGuidanceFiles:$,...J}=Q;return{run:{...A,result:J},files:B}}sendTransportMessage(A,Q,B){try{return Q(),!0}catch($){if($ instanceof c3)return this.options.log.info(`${this.clientID} dropped ${A} while reconnecting`,{messageType:A,...B}),this.options.onTransportSendFailure?.(this.clientID,A,$,B),!1;return this.options.log.error(`${this.clientID} failed to send ${A}`,$),!1}}}class wj{options;toolRunner;sentApprovalRequests;handshakeManager;runtimeLog;guidanceContentCache=new Zo;toolSyncSubscription;advertisedExecutorTools=[];hasCompletedBootstrap=!1;executorCallbacksAttached=!1;constructor(A){this.options=A;this.runtimeLog=this.options.log??{info:(Q,B)=>rB.info(Q,{...B,threadId:this.options.threadId}),error:(Q,B)=>rB.error(Q,{error:B,threadId:this.options.threadId}),wsMessage:(Q,B,$)=>{rB.info("websocket message",{threadId:this.options.threadId,...Bt0($,{direction:Q,clientID:B})})}},this.toolSyncSubscription=this.options.toolService.tools.subscribe({next:(Q)=>{this.syncExecutorToolRegistrations(Xt0(Q))}}),this.handshakeManager=new hx4({handshake:(Q)=>this.bootstrapExecutor({executorType:this.options.executorType,trigger:Q,suppressConnectLog:!0}),forceReconnect:(Q)=>this.options.transport.forceReconnect(Q),...this.options.handshakeManagerOptions}),this.toolRunner=new gx4({clientID:this.options.clientID,transport:this.options.transport,log:this.runtimeLog,threadId:this.options.threadId,invokeTool:(Q)=>this.invokeTool(Q),requestPluginToolCall:this.options.requestPluginToolCall,requestPluginToolResult:this.options.requestPluginToolResult,captureGitStatus:this.options.captureGitStatus,batchGuidanceFiles:this.options.batchGuidanceFiles??((Q)=>[Q]),guidanceContentCache:this.guidanceContentCache,renderToolRunError:this.options.renderToolRunError??((Q)=>Q?.message??"Tool run failed"),onTransportSendFailure:this.options.onTransportSendFailure}),this.sentApprovalRequests=this.toolRunner.sentApprovalRequests}ensureHandshake(A){return this.handshakeManager.ensureHandshake(A)}ensureReady(A){return this.handshakeManager.ensureReady(A)}handleConnectionChange(A){if(this.runtimeLog.info(`${this.options.clientID} handling connection change`,{state:A.state,role:A.role,transportClientId:A.clientId,reconnectCauseType:A.reconnectCause?.type,reconnectCauseCode:A.reconnectCause?.code,reconnectCauseReason:A.reconnectCause?.reason,hasCompletedBootstrap:this.hasCompletedBootstrap,executorCallbacksAttached:this.executorCallbacksAttached}),A.state!=="connected"||A.role!=="executor")this.toolRunner.markActiveProgressSnapshotsRequired();if(A.state!=="connected"&&A.role==="executor")this.guidanceContentCache.clear();this.handshakeManager.handleConnectionChange(A)}onToolLeaseMessage(A){this.handleToolLease(A)}onToolLeaseRevokedMessage(A){this.handleToolLeaseRevoked(A)}onExecutorFileSystemReadDirectoryRequestMessage(A){this.handleExecutorFileSystemReadDirectoryRequest(A)}onExecutorFileSystemReadFileRequestMessage(A){this.handleExecutorFileSystemReadFileRequest(A)}attachTransportExecutorCallbacks(A){if(!this.options.transport.setExecutorCallbacks){this.executorCallbacksAttached=!0;return}let Q=A?.includeConnectionChanges??!1,B=this.getInboundExecutorHandlers(),$={onToolLease:(J)=>{this.runtimeLog.info("onToolLease",{data:J}),B.onToolLease(J)},onToolLeaseRevoked:(J)=>{this.runtimeLog.info("onToolLeaseRevoked",{data:J}),B.onToolLeaseRevoked(J)},onExecutorToolResultAck:(J)=>{this.runtimeLog.info("onExecutorToolResultAck",{data:J}),this.toolRunner.ackTerminalResult(J)},onExecutorError:(J)=>{this.runtimeLog.info("onExecutorError",{data:J}),this.toolRunner.handleExecutorError(J)},onFileSystemReadFileRequest:(J)=>{this.runtimeLog.info("onFileSystemReadFileRequest",{data:J}),B.onFileSystemReadFileRequest(J)}};if(Q)$.onConnectionChange=(J)=>{this.runtimeLog.info("onConnectionChange",{data:J}),this.handleConnectionChange(J)};if(B.onFileSystemReadDirectoryRequest){let J=B.onFileSystemReadDirectoryRequest;$.onFileSystemReadDirectoryRequest=(Y)=>{this.runtimeLog.info("onFileSystemReadDirectoryRequest",{data:Y}),J(Y)}}if(this.options.pluginService){let J=bF0({pluginService:this.options.pluginService,sendPluginMessage:(Y)=>this.options.transport.sendPluginMessage(Y)});$.onPluginMessage=(Y)=>{this.runtimeLog.info("onPluginMessage",{data:Y}),J(Y)}}this.options.transport.setExecutorCallbacks($),this.executorCallbacksAttached=!0}advertisePluginReadinessIfEnabled(){if(!this.options.pluginService)return;try{this.options.transport.sendPluginMessage({type:"event",event:"plugins.ready",data:{}})}catch(A){this.runtimeLog.error("failed to advertise plugin readiness",A)}}dispose(){this.toolSyncSubscription?.unsubscribe(),this.toolSyncSubscription=void 0,this.clearTransportExecutorCallbacks(),this.toolRunner.dispose(),this.handshakeManager.dispose()}syncExecutorToolRegistrations(A){let Q=this.options.transport.getConnectionInfo();if(Q.state!=="connected"||Q.role!=="executor")return;this.advertisedExecutorTools=ux4({transport:this.options.transport,nextTools:A,previouslyAdvertisedTools:this.advertisedExecutorTools,logMessage:(B,$)=>{this.runtimeLog.wsMessage(B,this.options.clientID,$)}})}clearTransportExecutorCallbacks(){if(!this.executorCallbacksAttached)return;this.executorCallbacksAttached=!1}async invokeTool(A){return this.options.invokeTool(A)}async bootstrapExecutor(A){await this.connectAsExecutor(A.executorType??this.options.executorType,A.workspaceRoot??this.options.workspaceRoot??"",A.threadId??this.options.threadId,A.trigger,A.suppressConnectLog)}async connectAsExecutor(A,Q,B,$,J=!1){if(!J)rB.info(`Connecting ${this.options.clientID} as executor...`);try{let{advertisedTools:Y}=await IH5({transport:this.options.transport,executorClientID:this.options.clientID,workspaceRoot:Q,threadId:B,configService:this.options.configService,toolService:this.options.toolService,skillService:this.options.skillService,fileSystem:this.options.fileSystem,logMessage:this.options.bootstrapLogMessage,executorType:A,initialToolDiscovery:this.options.initialToolDiscovery,sendGitSnapshot:this.options.sendGitSnapshot??!1,previouslyAdvertisedTools:this.advertisedExecutorTools,allowResumeBootstrap:this.hasCompletedBootstrap,onBootstrapProgress:this.options.onBootstrapProgress,guidanceContentCache:this.guidanceContentCache});if(this.advertisedExecutorTools=Y,this.hasCompletedBootstrap=!0,this.toolRunner.flushBufferedTerminalResults(),await this.options.pluginService?.event.sessionStart({thread:{id:B}}),this.advertisePluginReadinessIfEnabled(),this.options.onBootstrapSuccess)await this.options.onBootstrapSuccess($)}catch(Y){throw rB.error(`executor ${this.options.clientID} bootstrap failed`,Y),Y}}getInboundExecutorHandlers(){let A={onToolLease:(Q)=>{this.handleToolLease(Q)},onToolLeaseRevoked:(Q)=>{this.handleToolLeaseRevoked(Q)},onFileSystemReadFileRequest:(Q)=>{this.handleExecutorFileSystemReadFileRequest(Q)}};if(this.options.handleExecutorFileSystemReadDirectoryRequest||this.options.readFileSystemDirectory)A.onFileSystemReadDirectoryRequest=(Q)=>{this.handleExecutorFileSystemReadDirectoryRequest(Q)};return A}maybeLogInboundExecutorMessage(A){if(!this.options.logInboundExecutorMessages)return;this.runtimeLog.wsMessage("RECV",this.options.clientID,A)}handleToolLease(A){this.maybeLogInboundExecutorMessage(A),this.toolRunner.handleToolLease(A)}handleToolLeaseRevoked(A){this.maybeLogInboundExecutorMessage(A),this.toolRunner.handleToolRevocation(A)}async handleExecutorFileSystemReadDirectoryRequest(A){if(this.maybeLogInboundExecutorMessage(A),this.options.handleExecutorFileSystemReadDirectoryRequest){await this.options.handleExecutorFileSystemReadDirectoryRequest(A);return}if(!this.options.readFileSystemDirectory)throw Error("Method not implemented.");let Q=await this.options.readFileSystemDirectory(A);this.options.transport.sendExecutorFileSystemReadDirectoryResult(A.requestId,Q)}handleExecutorFileSystemReadFileRequest(A){if(this.maybeLogInboundExecutorMessage(A),this.options.handleExecutorFileSystemReadFileRequest){this.options.handleExecutorFileSystemReadFileRequest(A);return}throw Error("Method not implemented.")}}E9();async function nY(A,Q,B,$={}){let J={...A?{threadId:A}:{},...$.repositoryURL?{repositoryURL:$.repositoryURL}:{},...!A&&$.executorType?{executorType:$.executorType}:{},...$.agentMode?{agentMode:$.agentMode}:{},...$.relationship?{relationship:$.relationship}:{},...$.usesThreadActors?{usesThreadActors:!0}:{}};if(!A&&$.threadMeta)J.threadMeta=$.threadMeta;let Y=await M2("/api/thread-actors",mx4({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(J),signal:$.signal},B),Q);if(!Y.ok)throw Error(`Failed to create thread-actors thread: ${Y.status} ${await Y.text()}`);let Z=await Y.json();if(!Z.threadId||!Z.wsToken)throw Error("Thread actors thread creation response missing threadId or wsToken");if(!Z.ownerUserId||typeof Z.threadVersion!=="number")throw Error("Thread actors thread creation response missing ownerUserId or threadVersion");return{threadId:Z.threadId,wsToken:Z.wsToken,usesDtw:Z.usesDtw??!0,usesThreadActors:Z.usesThreadActors??!1,executorType:Z.executorType??null,ownerUserId:Z.ownerUserId,threadVersion:Z.threadVersion,...Z.agentMode?{agentMode:Z.agentMode}:{}}}function mx4(A,Q){if(!Q)return A;return{...A,headers:{...A?.headers,Authorization:`Bearer ${Q}`}}}async function px4(A,Q,B,$={}){let J={};if($.executorType)J.executorType=$.executorType;let Y=await M2(`/api/thread-actors/${A}`,mx4({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(J),...$.signal?{signal:$.signal}:{}},B),Q);if(!Y.ok)throw Error(`Failed to mark thread ${A} as imported: ${Y.status} ${await Y.text()}`)}d0();i4();M1();function dx4(A){let{message:Q,sessionId:B,streamJsonThinking:$,currentTurnAssistantIds:J,currentTurnToolUseIds:Y}=A;if(!J.has(Q.messageId))return null;if(!Q.state)return null;if(Q.content.length===0)return null;let Z=Wv4(Q,B,null,{includeThinking:$});for(let F of Q.content)if(F.type==="tool_use")Y.add(F.id);return Z}function cx4(A){let{message:Q,sessionId:B,currentTurnToolUseIds:$}=A,J=Q.content.some((Z)=>Z.type==="tool_result"),Y=Q.content.some((Z)=>Z.type==="tool_result"&&$.has(Z.toolUseID));if(J&&!Y)return null;return Hv4(Q,B,null)}function lx4(A){return A.inputDone&&A.assistantDone&&A.idleSinceLastSend&&A.agentIdle}var ix4=1048576;async function nx4(A){let{client:Q,observer:B,dependencies:$,threadID:J,userInput:Y,stdinInput:Z,agentMode:F,reasoningEffort:X,streamJsonThinking:D,streamJsonInput:G,stdin:V}=A;if(Z&&Z.length>ix4)throw Error(`Stdin input too large: ${Z.length} bytes (max ${ix4})`);let U=J,K=Date.now(),E=F??"smart",z=OH5($),W=null,H=()=>{return W??=LH5($,E),W},q=!1,N=!1,I=0,w="",O=!1,L=!0,P=new Set;return new Promise((T,k)=>{let x=[],h="pending",f=null,S=null,u=UF0(async(Z0)=>{try{await Z0()}catch(R0){j.error("stream-json-actors emit failed",{error:R0})}}),d=async(Z0)=>{if(h==="emitted")return;let R0=await z;await jH5({sessionId:U,tools:Z0,mcpServers:R0,agentMode:E,reasoningEffort:X}),h="emitted";let B0=x.splice(0);for(let N0 of B0)await hF(N0)},c=(Z0)=>{if(h!=="pending")return;h="queued",f=Z0,u(async()=>{await d(Z0)})},g=(Z0)=>{if(h!=="emitted"){x.push(Z0);return}u(async()=>{await hF(Z0)})},l=async()=>{if(h==="emitted")return;await d(f??await H())},s=MH5({onSuccess:async()=>{await u(async()=>{await l(),await RH5({sessionId:U,startTime:K,numTurns:I,result:w})}),T({threadID:J,outcome:"success"})},onError:async(Z0)=>{await u(async()=>{await l(),await PH5({sessionId:U,startTime:K,numTurns:I,error:Z0})}),T({threadID:J,outcome:"error"})},onFatal:(Z0)=>k(Z0),cleanup:()=>{if(N)return;N=!0,S?.unsubscribe(),A0.dispose()},isComplete:()=>N}),A0=vF0({client:Q,observer:B,toolService:$.toolService,callbacks:{onError:(Z0)=>{s.error(Z0)},onTransitionToIdle:(Z0)=>{if(Z0.length>0){_H5({client:Q,approvals:Z0,complete:s});return}if(A0.agentIdle())L=!0;H0()},onMessageAdded:(Z0)=>{if(Z0.parentToolUseId)return;let R0=Z0.message;if(R0.role==="assistant"){let B0=dx4({message:R0,sessionId:U,streamJsonThinking:D,currentTurnAssistantIds:A0.currentTurnAssistantIds,currentTurnToolUseIds:P});if(!B0)return;if(g(B0),I++,B0.message.stop_reason==="end_turn")w=E8(R0.content),O=!0,H0()}else if(R0.role==="user"){let B0=cx4({message:R0,sessionId:U,currentTurnToolUseIds:P});if(!B0)return;g(B0)}},onSignal:()=>{s.error("User cancelled (SIGINT/SIGTERM)")}}});S=B.inferenceTools$.subscribe((Z0)=>{if(Z0.parentToolCallId)return;c(Z0.tools)});let H0=()=>{if(N)return;if(lx4({inputDone:q,assistantDone:O,idleSinceLastSend:L,agentIdle:A0.agentIdle()}))s.success()},V0=(Z0,R0)=>{L=!1,Q.sendUserMessage(Z0,E,R0)};if(G){(async()=>{try{for await(let Z0 of KF0(V)){if(N)break;V0(Z0.contentBlocks,TH5(Z0))}q=!0,H0()}catch(Z0){s.error(jU(Z0))}})();return}let w0=[{type:"text",text:Y}];if(Z)w0.unshift({type:"text",text:`Input received on stdin:
4699
+ `)}`:void 0}}function gV5(A){let Q=[],B=new Set,$=A.split(`
4700
+ `);for(let J=0;J<$.length;J++){let Z=$[J].match(/^\*\*\* (?:Add|Delete|Update) File: (.+)$/);if(!Z)continue;let F=Z[1],X=$[J+1]?.match(/^\*\*\* Move to: (.+)$/);if(X)F=X[1];if(B.has(F))continue;B.add(F),Q.push(F)}return Q}function $8(A){if(A.status!=="error"||!A.error)return;if(typeof A.error==="object"&&"message"in A.error){let Q=A.error.message;if(typeof Q==="string"&&Q.trim())return Q}return String(A.error)}function mV5(A,Q){if(A==="find_thread"){let B=typeof Q.query==="string"?Q.query.trim():void 0;return{kind:"search",title:B?`Searched threads: ${B}`:"Searched threads",icon:"search"}}if(A==="read_thread"){let B=typeof Q.threadID==="string"?Q.threadID.trim():void 0,$=typeof Q.goal==="string"?Q.goal.trim():void 0;return{kind:"thread",title:$?`Read thread: ${$}`:B?`Read thread ${B}`:"Read thread",icon:"threads"}}if(A==="slack_read"){let B=typeof Q.type==="string"?Q.type:void 0,$=typeof Q.query==="string"?Q.query.trim():void 0,J=$?`: ${$}`:"";if(B==="users")return{kind:"search",title:`Slack searched users${J}`,icon:"slack"};if(B==="channels")return{kind:"search",title:`Slack searched channels${J}`,icon:"slack"};if(B==="messages")return{kind:"read",title:`Slack read messages${J}`,icon:"slack"};if(B==="thread")return{kind:"read",title:"Slack read thread",icon:"slack"};return{kind:"read",title:$?`Slack read: ${$}`:"Slack read",icon:"slack"}}if(A==="docs_list"){let B=gF(Q);return{kind:"list",title:B?`Listed docs: ${B}`:"Listed docs",icon:"docs"}}if(A==="docs_read"){let B=gF(Q);return{kind:"read",title:B?`Read docs: ${B}`:"Read docs",icon:"docs"}}if(A==="github_repo_ci_status"){let B=gF(Q);return{kind:"read",title:B?`Read CI status: ${B}`:"Read CI status",icon:"github"}}if(A==="web_search"){let B=gF(Q);return{kind:"search",title:B?`Searched web: ${B}`:"Searched web",icon:"web"}}if(A==="read_web_page"){let B=gF(Q);return{kind:"web-page",title:B?`Read web page: ${B}`:"Read web page",icon:"web"}}if(A==="search_github"||A==="commit_search"||A==="glob_github"){let B=gF(Q);return{kind:"search",title:B?`Searched GitHub: ${B}`:"Searched GitHub",icon:"github"}}if(A==="list_directory_github"||A==="list_repositories"){let B=gF(Q);return{kind:"list",title:B?`Listed GitHub content: ${B}`:"Listed GitHub content",icon:"github"}}if(A==="read_github"||A==="diff"){let B=gF(Q);return{kind:"read",title:B?`Read GitHub content: ${B}`:"Read GitHub content",icon:"github"}}return}function zF0(A,Q){if(A==="Read"){let J=pV5(Q);if(J)return J}if(A==="read_thread"){let J=typeof Q.goal==="string"?Q.goal.trim():void 0;if(J)return`Read thread: ${J}`;let Y=typeof Q.threadID==="string"?Q.threadID.trim():void 0;return Y?`Read thread ${Y}`:"Read thread"}if(A==="find_thread"){let J=typeof Q.query==="string"?Q.query.trim():void 0;return J?`Searched threads: ${J}`:"Searched threads"}if(A==="skill")return`Read skill ${Q.name}`;if(A==="file_tree")return dV5(Q);if(A==="web_search"){let J=Fy4(Q);return J?`Web Search ${J}`:"Web Search"}if(A==="read_web_page"){let J=Zy4(Q);return J?`Read ${J}`:"Read"}if(A.toLowerCase()==="Grep".toLowerCase())return lV5(Q);let B=gF(Q);if(!B)return A;let $=B.includes("/")?YY(B):B;return`${A} ${$}`}function pV5(A){let Q=typeof A.path==="string"?A.path.trim():void 0,B=cV5(A.read_range);if(!Q)return B?`Read ${B}`:void 0;let $=YY(Q);return B?`Read ${$} ${B}`:`Read ${$}`}function dV5(A){let Q=typeof A.path==="string"?A.path.trim():void 0;if(!Q)return"List";let B=Q==="/"?Q:Q.replace(/\/+$/,"");return`List ${B.includes("/")?YY(B)||B:B}`}function cV5(A){if(!Array.isArray(A)||A.length!==2)return;let[Q,B]=A;if(typeof Q!=="number"||typeof B!=="number"||!Number.isInteger(Q)||!Number.isInteger(B))return;if(Q<1||B===-1||B<Q)return;if(Q===B)return`L${Q}`;return`L${Q}-${B}`}function lV5(A){let Q=A.path?.trim(),B=A.pattern?.trim();if(Q&&B)return`Grep ${Q} "${B}"`;if(B)return`Grep "${B}"`;if(Q)return`Grep ${Q}`;return"Grep"}function gF(A){for(let Q of["path","filePattern","pattern","query","url","objective","description","prompt"])if(typeof A[Q]==="string"&&A[Q].trim())return A[Q].trim();return}function Zy4(A){if(typeof A.url!=="string")return;return A.url.trim()||void 0}function Fy4(A){let Q=typeof A.query==="string"?A.query:void 0,B=typeof A.objective==="string"?A.objective:void 0;return(Q??B)?.trim()||void 0}function iV5(A){let Q=A.replace(/\/+$/,""),B=Q.lastIndexOf("/");return(B===-1?Q:Q.slice(B+1)).replace(/\.md$/i,"")||A}function nV5(A,Q){let B=aB(Q.result)?Q.result:void 0,$=aB(B?.check)?B.check:void 0;return typeof $?.name==="string"?$.name:iV5(A)}function aV5(A){if(A.status!=="done")return;let Q=aB(A.result)?A.result:void 0;return Array.isArray(Q?.issues)?Q.issues.length:void 0}function oV5(A){let Q=Object.entries(A).filter(([,B])=>B!==void 0&&B!==null&&B!=="");if(Q.length===0)return;return Q.map(([B,$])=>{let J=typeof $==="string"?$:JSON.stringify($);return`${B}: ${J}`}).join(`
4701
+ `)}function Zs0(A,Q){let B=[...A],$=new Set(B.map((J)=>`${J.kind}:${J.title}`));for(let J of Gy4(Q)){let Y=`${J.kind}:${J.title}`;if($.has(Y))continue;$.add(Y),B.push(Xy4(J,Q.status))}return B}function Xy4(A,Q){return{...A,status:Q}}function rV5(A){let{status:Q,...B}=A;return B}function Dy4(A){return A.activityKind!=="subagent"||A.status===void 0||vM(A.status)}function Gy4(A){return sV5(A).map((Q)=>({kind:"read",title:`Read ${QJ(Q.uri)}`,...typeof Q.content==="string"?{detail:Q.content}:{},icon:"docs"}))}function sV5(A){if(A.status!=="done"||!aB(A.result))return[];let{discoveredGuidanceFiles:Q}=A.result;if(!Array.isArray(Q))return[];return Q.flatMap((B)=>{if(!aB(B)||typeof B.uri!=="string"||typeof B.lineCount!=="number"||!Number.isFinite(B.lineCount))return[];return[{uri:B.uri,lineCount:B.lineCount,...typeof B.content==="string"?{content:B.content}:{}}]})}function tV5(A,Q,B){if(A==="oracle"){let $=typeof Q.task==="string"?Q.task.trim():void 0;return tr0({label:{active:"Oracle exploring",complete:"Oracle has spoken"},detail:$,run:B})}if(A==="librarian"){let $=typeof Q.query==="string"?Q.query.trim():void 0;return tr0({label:{active:"Librarian researching",complete:"Librarian researched"},detail:$,run:B})}if(A==="Task"){let $=typeof Q.description==="string"?Q.description.trim():void 0,J=typeof Q.prompt==="string"?Q.prompt.trim():void 0;return tr0({label:{active:"Subagent working",complete:"Subagent finished"},detail:$??J,run:B})}if(A==="code_review"){let $=AU5(B,Q),J=Zs0($.actions,B),Y={label:{active:"Reviewing code",complete:"Reviewed code"},activityKind:"subagent",actions:J,summary:$.summary,hasInProgress:vM(B.status),status:B.status},Z=typeof Q.diff_description==="string"?Q.diff_description.trim():void 0;if(Z!==void 0)Y.detail=Z;let F=$8(B);if(F!==void 0)Y.error=F;return Y}return}function tr0(A){let Q=Zs0([],A.run),B={label:A.label,activityKind:"subagent",actions:Q,summary:Qs0(Q),hasInProgress:vM(A.run.status),status:A.run.status};if(A.detail!==void 0)B.detail=A.detail;let $=$8(A.run);if($!==void 0)B.error=$;return B}function eV5(A){let Q="result"in A&&aB(A.result)?A.result:void 0,B=Qy4("progress"in A?A.progress:void 0),$=aB(B)?B:void 0;return{main:(aB(Q?.main)?Q.main:void 0)??(aB($?.main)?$.main:void 0),checks:(aB(Q?.checks)?Q.checks:void 0)??(aB($?.checks)?$.checks:void 0)}}function AU5(A,Q){let B=[],$=new Set,J=(G)=>{let V=`${G.kind}:${G.title}`;if($.has(V))return;$.add(V),B.push(G)},{main:Y,checks:Z}=eV5(A);if(A.status==="queued")J({kind:"review",title:"Code review queued"});if(A.status==="error"){let G=$8(A)??"Unknown error";J({kind:"review",title:`Code review failed: ${G}`})}let F=0,X=0;for(let[G,V]of Object.entries(Z??{})){if(!aB(V))continue;X+=1;let U=nV5(G,V);if(V.status==="done"){F+=1;let K=aV5(V);if(K===void 0)J({kind:"review",title:`Check ${U}: complete`});else if(K===0)J({kind:"review",title:`Check ${U}: ok`});else J({kind:"review",title:`Check ${U}: ${K} ${V4(K,"issue")} found`});continue}if(V.status==="error"){F+=1;let K=typeof V.error==="string"&&V.error.trim()?V.error.trim():"Unknown error";J({kind:"review",title:`Check ${U}: error (${K})`});continue}if(V.status==="in-progress"){let K=typeof V.message==="string"&&V.message.trim()?V.message.trim():"Running check...";J({kind:"review",title:`Check ${U}: ${K}`})}}if(Y?.status==="done"&&X>0&&F<X)J({kind:"review",title:"Main review complete, running checks..."});if(A.status==="done")J({kind:"review",title:"Code review complete"});if(B.length===0)J({kind:"review",title:A.status==="queued"?"Code review queued":"Reviewing code changes..."});let D=Q.thinking==="low"?"quick code review":"code review";return{actions:B,summary:X>0?`${F}/${X} checks · ${D}`:D}}function Qs0(A,Q=""){let B=0,$=0,J=new Map;for(let Z of A){if(Z.icon==="docs"&&(Z.title.startsWith("Read ")||Z.title.startsWith("Load "))){B++;continue}if(Z.title.startsWith("Read skill ")){$++;continue}J.set(Z.kind,(J.get(Z.kind)??0)+1)}let Y=[];for(let[Z,F,X]of[["read","file",void 0],["web-page","web page","web pages"],["thread","thread",void 0],["skill","skill",void 0],["guidance","guidance file","guidance files"],["search","search","searches"],["web","web search","web searches"],["review","review","reviews"],["list","list",void 0]]){let D=Z==="guidance"?B:Z==="skill"?$:J.get(Z);if(!D)continue;Y.push(`${D} ${V4(D,F,X)}`)}if(Y.length>0)return Y.join(", ");return Q}function QU5(A){if(A.kind==="search"&&BU5(A.program)&&A.query){if(A.path)return`Grep ${A.path} "${A.query}"`;return`Grep "${A.query}"`}return kY0(A)}function BU5(A){if(!A)return!1;return new Set(["rg","ripgrep","grep","egrep","fgrep","ag","ack","pt","git grep"]).has(A)}function aB(A){return typeof A==="object"&&A!==null}CB();function Fs0(A){let Q=A.replace(/-/g,"");if(Q.length!==32)throw Error(`Invalid UUID hex length: ${Q.length}`);let B=BigInt("0x"+Q),$="";while(B>0n)$="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[Number(B%62n)]+$,B=B/62n;return $.padStart(22,"0")}A3();MS();r1();kk0();CB();var z3=b.string().min(1),QI=z3.brand(),Ds0=b.string().regex(/^[0-9A-Za-z]{22}$/),$U5=b.templateLiteral([b.string().regex(/^[0-9a-f]{8}$/),"-",b.string().regex(/^[0-9a-f]{4}$/),"-",b.string().regex(/^[0-9a-f]{4}$/),"-",b.string().regex(/^[0-9a-f]{4}$/),"-",b.string().regex(/^[0-9a-f]{12}$/)]),ia=b.templateLiteral(["T-",$U5]),Gs0=b.enum(["fork","handoff","mention"]),Vs0=b.enum(["parent","child"]),Vy4=b.object({threadID:ia,type:Gs0,role:Vs0,messageIndex:b.number().int().nonnegative().optional(),blockIndex:b.number().int().nonnegative().optional(),createdAt:b.number().int().nonnegative(),comment:b.string().optional()}),f6=b.templateLiteral(["M-",Ds0]);function qF0(){return`M-${Fs0(cT())}`}var l3=b.templateLiteral(["TU-",Ds0]);var Uy4=b.templateLiteral(["E-",Ds0]);function Ky4(){return`E-${Fs0(cT())}`}var JU5=b.looseObject({type:b.literal("object"),properties:b.record(b.string(),b.unknown()),required:b.array(b.string()).optional(),additionalProperties:b.boolean().optional()}),YU5=b.union([b.literal("builtin"),b.object({toolbox:z3}).strict(),b.object({mcp:z3,target:b.enum(["global","workspace","flag","default"]).optional()}).strict(),b.object({plugin:z3}).strict(),b.object({remote:z3}).strict()]),ZU5=b.object({serial:b.boolean().optional(),deferred:b.boolean().optional(),skillNames:b.array(z3).optional()}),Ey4=b.looseObject({name:z3,description:b.string(),inputSchema:JU5,source:YU5,meta:ZU5.optional()}),NE8=b.object({id:z3,category:z3,title:z3,description:b.string().optional(),pluginName:z3}),BI=b.enum(["none","minimal","low","medium","high","xhigh","max"]),Us0=b.enum(["anthropic","vertex"]),Ks0=b.enum(["standard","fast"]),Es0=b.enum(["gemini-3-pro-image","gpt-image-2"]),zs0=b.enum(["none","minimal","low","medium","high","xhigh"]),Ws0=b.enum(["minimal","low","medium","high"]),NF0=b.object({"agent.skipTitleGenerationIfMessageContains":b.array(b.string()).optional(),"anthropic.thinking.enabled":b.boolean().optional(),"anthropic.interleavedThinking.enabled":b.boolean().optional(),"anthropic.temperature":b.number().optional(),"anthropic.provider":Us0.optional(),"openai.speed":Ks0.optional(),"painter.model":Es0.optional(),"reasoning.effort":BI.optional(),"internal.compactionThresholdPercent":b.number().min(0).max(100).optional(),"internal.model":b.union([b.string(),b.record(b.string(),b.string())]).optional(),"internal.oracleReasoningEffort":zs0.optional(),"gemini.thinkingLevel":Ws0.optional(),"tools.disable":b.array(b.string()).optional(),"tools.enable":b.array(b.string()).optional()}),zy4=b.object({workspaceId:b.string(),workingDirectory:b.string(),environment:b.object({os:b.enum(["darwin","linux","windows"]),hasDocker:b.boolean().optional(),hasBrowser:b.boolean().optional()}).strict(),tags:b.array(b.string())}).strict(),Wy4=b.enum(["sandbox","local-client"]),na=b.any().and(b.object({status:b.string()})),Hy4=b.discriminatedUnion("type",[b.object({type:b.literal("delta"),blocks:b.array(b.unknown()).optional(),state:b.enum(["start","generating","tool_use","complete","error","aborted"])}),b.object({type:b.literal("snapshot"),value:b.unknown()})]),RU=z3,qy4=30000,Kx=JY,FU5=b.enum(["file","directory"]),XU5=b.object({mtimeMs:b.number().nonnegative().optional()}),aa=b.tuple([b.string(),FU5,XU5.nullish()]),DU5=b.enum(["INVALID_URI","EXECUTOR_NOT_CONNECTED","NOT_FOUND","NOT_DIRECTORY","IS_DIRECTORY","ACCESS_DENIED","INTERNAL_ERROR"]),$I=b.object({code:DU5,message:b.string()}),GU5=b.object({ok:b.literal(!0),entries:b.array(aa)}),VU5=b.object({ok:b.literal(!1),error:$I}),IE8=b.discriminatedUnion("ok",[GU5,VU5]),UU5=b.object({ok:b.literal(!0),contentBase64:b.string()}),KU5=b.object({ok:b.literal(!1),error:$I}),wE8=b.discriminatedUnion("ok",[UU5,KU5]),EU5=z3,Hs0=b.object({key:z3,dataType:EU5,contentBase64:b.string()}),qs0=Hs0.extend({toolCallId:l3.optional(),updatedAt:b.string()}),Ns0=b.looseObject({uri:JY,content:b.string().optional(),lineCount:b.int().optional(),hash:b.string().optional()}),zU5=b.enum(KJ4),Ny4=b.object({path:JY,error:b.string(),hint:b.string().optional()}),Iy4=b.object({uri:JY,hash:b.string(),lineCount:b.int().optional()}),wy4=b.object({name:z3,description:b.string(),baseDir:JY,frontmatter:b.object({name:z3,description:b.string()}).catchall(b.unknown()),files:b.array(b.string()).optional(),source:zU5.optional()}),WU5=b.enum(["start","streaming","complete"]),oa=b.object({blockState:WU5.optional()}),Is0=b.object({type:b.literal("text"),text:b.string(),hidden:b.boolean().optional()}).extend(oa.shape),Cy4=b.looseObject({type:b.literal("image"),source:b.discriminatedUnion("type",[b.object({type:b.literal("base64"),mediaType:b.literal(["image/jpeg","image/png","image/gif","image/webp"]),data:b.string()}),b.object({type:b.literal("url"),url:b.string()})]),sourcePath:b.string()}),ra=b.array(b.discriminatedUnion("type",[Is0,Cy4])),Ux=b.record(b.string(),b.unknown()),My4=b.object({type:b.literal("tool_use"),id:b.string().min(1),name:b.string().min(1),normalizedName:b.string().optional(),metadata:b.record(b.string(),b.unknown()).optional()}).extend(oa.shape),HU5=My4.extend({complete:b.literal(!0),input:Ux,normalizedInput:Ux.optional()}),qU5=My4.extend({complete:b.literal(!1),input:Ux,inputIncomplete:Ux,inputPartialJSON:b.object({json:b.string()}),normalizedInput:Ux.optional()}),NU5=b.object({accepted:b.boolean(),askAnswers:b.record(b.string(),b.string()).optional(),denyFeedback:b.string().optional()}),IU5=b.object({type:b.literal("tool_result"),toolUseID:b.string().min(1),run:na,userInput:NU5.optional()}),wU5=b.object({type:b.literal("thinking"),thinking:b.string(),signature:b.string()}).extend(oa.shape),CU5=b.object({type:b.literal("redacted_thinking"),data:b.string()}).extend(oa.shape),MU5=b.object({type:b.literal("server_tool_use"),id:b.string().min(1),name:b.string().min(1),input:Ux}).extend(oa.shape),LU5=b.object({type:b.literal("manual_bash_invocation"),args:b.object({cmd:b.string(),args:b.array(b.string()).readonly().optional(),cwd:b.string().optional()}),toolRun:na,hidden:b.boolean().optional()}),ws0=b.object({sentAt:b.number().int().nonnegative().optional(),fromAggman:b.boolean().optional(),fromExecutorThreadID:ia.optional()}),OU5=b.union([Is0,Cy4,IU5]),jU5=b.union([Is0,wU5,CU5,HU5,qU5,MU5]),sa=b.array(OU5),ta=b.array(jU5),Cs0=b.array(LU5),Xs0=b.looseObject({line:b.number().int(),column:b.number().int()}),RU5=b.looseObject({start:Xs0,end:Xs0}),PU5=b.looseObject({name:b.string(),repositoryURL:b.string()}),_U5=b.looseObject({currentURL:b.string(),availableProjects:b.array(PU5).optional()}),Ms0=b.looseObject({currentlyVisibleFiles:b.array(JY),runningTerminalCommands:b.array(b.string()).optional(),activeEditor:b.any().optional(),cursorLocation:Xs0.optional(),cursorLocationLine:b.string().optional(),selectionRange:RU5.optional(),aggmanContext:_U5.optional()}),Pz=b.custom((A)=>typeof A==="string"&&b3(A)!==void 0),TU5=b.object({threadId:ia,role:b.literal("user"),content:sa,agentMode:Pz.optional(),meta:ws0.optional(),userState:Ms0.optional(),readAt:b.string().nullable().optional(),messageId:f6,createdAt:b.string().optional()}),Ls0=b.object({model:b.string().optional(),maxInputTokens:b.number(),inputTokens:b.number(),outputTokens:b.number(),cacheCreationInputTokens:b.number().nullable(),cacheReadInputTokens:b.number().nullable(),totalInputTokens:b.number(),thinkingBudget:b.number().optional(),timestamp:b.string().optional()}),Os0=b.union([b.object({type:b.literal("complete")}),b.object({type:b.literal("cancelled")})]),kU5=b.object({threadId:ia,role:b.literal("assistant"),content:ta,state:Os0.optional(),usage:Ls0.optional(),readAt:b.string().nullable().optional(),messageId:f6,createdAt:b.string().optional()}),SU5=b.object({threadId:ia,role:b.literal("info"),content:Cs0,messageId:f6,createdAt:b.string().optional()}),js0=b.discriminatedUnion("role",[TU5,kU5,SU5]),ea=b.object({workspaceRoot:JY.optional(),workingDirectory:JY.optional(),rootDirectoryListing:b.string().nullable().optional(),trees:b.array(b.any()).optional(),platform:b.any().optional(),tags:b.array(b.string()).optional(),git:b.object({branch:b.string().optional()}).optional(),updatedAt:b.string().optional()}),vU5=b.object({added:b.number().int().nonnegative(),deleted:b.number().int().nonnegative(),changed:b.number().int().nonnegative()}),yU5=b.object({path:b.string(),previousPath:b.string().optional(),changeType:b.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","untracked"]),created:b.boolean(),diff:b.string(),fullFileDiff:b.string().optional(),oldContent:b.string().optional(),newContent:b.string().optional(),diffStat:vU5}),xU5=b.object({hash:b.string(),shortHash:b.string(),subject:b.string()}),Ly4=b.object({provider:b.literal("git"),capturedAt:b.number(),available:b.boolean(),repositoryRoot:b.string().nullable(),repositoryName:b.string().nullable(),branch:b.string().nullable(),head:b.string().nullable(),baseRef:b.string().nullable().optional(),baseRefHead:b.string().nullable().optional(),aheadCount:b.number().int().nonnegative().optional(),behindCount:b.number().int().nonnegative().optional(),aheadCommits:b.array(xU5).optional(),diffHash:b.string().optional(),files:b.array(yU5),unavailableReason:b.string().optional(),unchanged:b.boolean().optional()}),Rs0=b.enum(["thread","subagent"]),Ps0=b.enum(["user","built-in"]),IF0=b.object({id:b.string(),toolCallId:l3,toolName:b.string(),args:b.record(b.string(),b.unknown()),reason:b.string().optional(),toAllow:b.array(b.string()).optional(),context:Rs0,subagentToolName:b.string().optional(),parentToolCallId:l3.optional(),timestamp:b.number(),matchedRule:b.object({tool:b.string(),action:b.string(),matches:b.record(b.string(),b.unknown()).optional()}).optional(),ruleSource:Ps0.optional()}),fU5=b.object({type:b.literal("request"),id:z3,method:z3,params:b.unknown()}),bU5=b.object({type:b.literal("response"),id:z3,result:b.unknown().optional(),error:b.string().optional()}),uU5=b.object({type:b.literal("event"),event:z3,data:b.unknown(),span:b.string().optional()}),wF0=b.discriminatedUnion("type",[fU5,bU5,uU5]);var hU5=b.object({type:b.literal("executor_connect"),clientId:QI,capabilities:zy4,executorType:Wy4.optional()}),gU5=b.object({type:b.literal("client_update_thread_settings"),settings:NF0}),mU5=b.object({type:b.literal("executor_tools_register"),tools:b.array(Ey4)}),pU5=b.object({type:b.literal("executor_tools_unregister"),toolNames:b.array(z3)}),dU5=b.object({type:b.literal("executor_tools_bootstrap_complete"),ok:b.boolean(),error:b.string().optional()}),cU5=b.object({type:b.literal("executor_tool_lease_ack"),toolCallId:l3}),_s0=b.object({type:b.literal("tool_progress"),toolCallId:l3,progress:b.union([Hy4,b.unknown()]).optional(),parentToolCallId:l3.optional()}),lU5=b.object({type:b.literal("executor_tool_result"),toolCallId:l3,run:na}),iU5=b.object({type:b.literal("executor_guidance_snapshot"),snapshotId:z3,files:b.array(Ns0),isLast:b.boolean(),userConfigDir:b.any().optional()}),nU5=b.object({type:b.literal("executor_guidance_discovery"),toolCallId:l3,files:b.array(Ns0),isLast:b.boolean()}),aU5=b.object({type:b.literal("executor_skill_snapshot"),snapshotId:z3,skills:b.array(wy4),isLast:b.boolean(),errors:b.array(Ny4).optional()}),oU5=b.object({type:b.literal("executor_environment_snapshot"),environment:ea}),rU5=b.object({type:b.literal("executor_environment_update"),environment:ea}),sU5=b.object({type:b.literal("executor_artifact_upsert"),artifact:Hs0,toolCallId:l3.optional()}),tU5=b.object({type:b.literal("executor_artifact_delete"),key:z3}),eU5=b.object({type:b.literal("executor_tool_approval_request"),approval:IF0}),AK5=b.object({type:b.literal("executor_plugin_message"),message:wF0}),QK5=b.object({type:b.literal("client_append_user_msg"),content:ra,userState:Ms0.optional(),agentMode:Pz.optional(),reasoningEffort:BI.optional(),messageId:f6,steer:b.boolean().optional()}),BK5=b.object({type:b.literal("client_remove_queued_msg"),queuedMessageId:f6}),$K5=b.object({type:b.literal("client_steer_queued_msg"),queuedMessageId:f6}),JK5=b.object({type:b.literal("client_edit_message"),messageId:f6,editId:Uy4,content:ra,agentMode:Pz.optional(),reasoningEffort:BI.optional()}),YK5=b.object({type:b.literal("client_mark_message_read"),messageId:f6}),ZK5=b.object({type:b.literal("client_mark_message_unread"),messageId:f6}),FK5=b.object({type:b.literal("client_set_thread_title"),title:b.string().trim().min(1).max(256)}),XK5=b.object({auth:b.string().min(1),p256dh:b.string().min(1)}),DK5=b.object({endpoint:b.string().url(),keys:XK5}),GK5=b.object({type:b.literal("client_upsert_notification_subscription"),subscription:DK5,threadURL:b.string().min(1)}),VK5=b.object({type:b.literal("client_filesystem_read_directory"),requestId:RU,uri:Kx}),UK5=b.object({type:b.literal("client_filesystem_read_file"),requestId:RU,uri:Kx}),KK5=b.object({type:b.literal("executor_filesystem_read_directory_result"),requestId:RU,ok:b.boolean(),entries:b.array(aa).optional(),error:$I.optional()}).superRefine((A,Q)=>{if(A.ok){if(!A.entries)Q.addIssue({code:b.ZodIssueCode.custom,message:"entries is required when ok is true"});if(A.error)Q.addIssue({code:b.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!A.error)Q.addIssue({code:b.ZodIssueCode.custom,message:"error is required when ok is false"});if(A.entries)Q.addIssue({code:b.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),EK5=b.object({type:b.literal("executor_filesystem_read_file_result"),requestId:RU,ok:b.boolean(),contentBase64:b.string().optional(),error:$I.optional()}).superRefine((A,Q)=>{if(A.ok){if(A.contentBase64===void 0)Q.addIssue({code:b.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(A.error)Q.addIssue({code:b.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!A.error)Q.addIssue({code:b.ZodIssueCode.custom,message:"error is required when ok is false"});if(A.contentBase64!==void 0)Q.addIssue({code:b.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),zK5=b.object({type:b.literal("client_resume"),version:b.number()}),WK5=b.object({type:b.literal("client_retry")}),HK5=b.object({type:b.literal("client_dismiss_active_error"),seq:b.number().optional()}),qK5=b.object({type:b.literal("client_cancel")}),NK5=b.object({type:b.literal("client_append_manual_bash_invocation"),args:b.object({cmd:b.string().trim().min(1,"cmd must contain at least one non-whitespace character"),args:b.array(b.string()).optional(),cwd:b.string().optional()}),run:na,hidden:b.boolean().optional()}),IK5=b.object({type:b.literal("client_tool_approval_response"),toolCallId:l3,accepted:b.boolean(),input:b.object({askAnswers:b.record(b.string(),b.string()).optional(),denyFeedback:b.string().optional()}).optional()}),wK5=b.union([b.object({name:b.string(),type:b.literal("git").optional(),url:b.string()}),b.object({driveName:b.string().min(1).describe("Drive name. Must be a single path component."),name:b.string(),namespace:b.string(),type:b.literal("drive")})]),CK5=b.object({type:b.literal("client_spawn_executor"),requestId:b.string().optional(),repositoryURL:b.string().optional(),projectID:b.uuid().optional(),additionalRepositories:b.array(wK5).optional()}),Oy4=b.discriminatedUnion("type",[hU5,gU5,mU5,pU5,dU5,cU5,_s0,lU5,iU5,nU5,aU5,oU5,rU5,sU5,tU5,eU5,AK5,QK5,BK5,$K5,JK5,YK5,ZK5,FK5,GK5,VK5,UK5,KK5,EK5,zK5,WK5,HK5,qK5,NK5,IK5,CK5]);CB();var CF0=(A)=>b.codec(b.string(),A,{decode:(Q,B)=>{try{return JSON.parse(Q)}catch($){return B.issues.push({code:"invalid_format",format:"json",input:Q,message:$.message}),b.NEVER}},encode:(Q)=>JSON.stringify(Q)});CB();CB();var Qo=["idle","working","streaming","tool_use","running_tools","awaiting_approval","error"],PE8=new Set(Qo);var MK5=["working","streaming","tool_use","running_tools"],LK5=new Set(MK5);function BQ(A){if(typeof A!=="string")return!1;return LK5.has(A)}function Ao(A){return typeof A==="object"&&A!==null}function OK5(A){return Ao(A)&&A.type==="text"&&typeof A.text==="string"}function Ts0(A){if(!A)return;let Q=A.filter(OK5).map((B)=>B.text).join("");return Q.length>0?Q:void 0}function ks0(A){if(typeof A==="string")return A;if(Array.isArray(A))return Ts0(A);if(!Ao(A))return;for(let Q of["output","displayMessage","message","reason"]){let B=A[Q];if(typeof B==="string")return B}for(let Q of["result","error","value"])if(Q in A){let B=ks0(A[Q]);if(B!==void 0)return B}return}function jy4(A,Q){if(typeof A==="string")return A+Q;if(Array.isArray(A)){if(!A.every((B)=>Ao(B)&&typeof B.type==="string"))return;return[...A,{type:"text",text:Q}]}if(!Ao(A))return;for(let B of["output","displayMessage","message","reason"]){let $=A[B];if(typeof $==="string")return{...A,[B]:$+Q}}if("value"in A){let B=jy4(A.value,Q);if(B!==void 0)return{...A,value:B}}return}function jK5(A){return Ao(A)&&typeof A.status==="string"}function RK5(A,Q){return{type:"delta",...A?{blocks:[{type:"text",text:A}]}:{},state:Q}}function PK5(A){if(!A)return;if(A.type==="snapshot")return ks0(A.value);return Ts0(A.blocks)}function Ex(A,Q){if(A&&typeof A==="object"&&"type"in A){let $=A;if($.type==="delta"||$.type==="snapshot")return $}if(Q==="snapshot")return{type:"snapshot",value:A};let B=typeof A==="string"?A:A!==void 0?JSON.stringify(A):"";return{type:"delta",blocks:B?[{type:"text",text:B}]:void 0,state:"generating"}}function Ry4(A,Q){if(Q.type!=="snapshot"||jK5(Q.value))return Q;let B=PK5(A),$=ks0(Q.value);if(B===void 0||$===void 0)return Q;if(!$.startsWith(B))return Q;return RK5($.slice(B.length),"generating")}function MF0(A,Q){let B=A===void 0?void 0:Ex(A,"snapshot"),$=Ex(Q,"snapshot");if($.type==="snapshot")return $;if(!B)return $;let J=Ts0($.blocks);if(J===void 0)return B;if(B.type==="snapshot"){let Z=jy4(B.value,J);if(Z!==void 0)return{type:"snapshot",value:Z}}return{type:"delta",blocks:[...B.type==="delta"?B.blocks??[]:Array.isArray(B.value)?B.value:[],...$.blocks??[]],state:$.state}}var _K5=b.enum(Qo),Ss0=b.enum(["start","generating","tool_use","complete","error","aborted"]),TK5=b.object({message:b.string(),code:b.string().optional(),stack:b.string().optional(),retryAt:b.number().optional(),attempt:b.number().optional()}),kK5=b.object({userId:b.string(),name:b.string(),avatarURL:b.string().optional()}),vs0=b.enum(["starting","running","failed"]),ys0=b.enum(["missing","allocating_environment","configuring_workspace","starting_headless","headless_ready","paused","failed"]),xs0=b.enum(["pending","ready","failed"]),SK5=xs0.nullable(),fs0=b.enum(["allocating_environment","configuring_workspace","starting_headless"]),vK5=fs0.nullable(),bs0=b.enum(["idle","creating","recovering"]),us0=b.enum(["unknown","running","paused","missing"]),hs0=b.enum(["spawn_requested","spawn_rejected","environment_recovering","waiting_for_executor_connect","executor_connected","executor_disconnected","connect_timeout","executor_connect_rejected","spawn_failed","restart_failed","environment_missing"]),gs0=b.enum(["ACCESS_DENIED","ACTOR_STOPPING","CONNECTION_ERROR","MAX_RECONNECT_EXCEEDED","MESSAGE_ERROR","LOOP_RUNNING","NO_THREAD_ID","NO_ERROR","INVALID_MESSAGE","PARSE_ERROR","UNKNOWN_TYPE","INTERNAL_ERROR"]),ms0=b.enum(["executor_disconnected","reassigned","user_canceled"]),ps0=b.enum(["NOT_CONNECTED","ACCESS_DENIED","INVALID_MESSAGE","TOOL_NOT_FOUND","LEASE_NOT_FOUND","DUPLICATE_TOOL","INTERNAL_ERROR"]),yK5=b.object({environmentId:b.string().nullable().optional(),stage:ys0.optional(),setupState:SK5.optional(),setupPhase:vK5.optional(),operation:bs0.optional(),providerState:us0.optional(),restartAttempts:b.number().optional()}),xK5=b.object({reasonCode:hs0.optional(),executionEnvironment:yK5.optional()}),fK5=b.object({cutMessageId:f6,createdAt:b.string()}),Py4=b.object({steer:b.boolean(),queuedMessage:b.object({role:b.literal("user"),messageId:f6,content:ra,userState:b.any().optional(),meta:ws0.optional(),createdAt:b.string().optional()})}),bK5=b.object({type:b.literal("agent_state"),state:_K5,messageId:f6.optional(),agentMode:Pz.optional(),reasoningEffort:BI.optional()}),uK5=b.object({type:b.literal("inference_tools"),messageId:f6,agentMode:Pz,tools:b.array(z3),parentToolCallId:l3.optional()}),hK5=b.object({type:b.literal("thread_settings"),settings:NF0}),gK5=b.object({type:b.literal("error"),message:b.string(),code:gs0.optional()}),mK5=b.object({type:b.literal("error_set"),seq:b.number(),error:TK5}),pK5=b.object({type:b.literal("error_cleared"),seq:b.number()}),dK5=b.object({type:b.literal("cancelled"),seq:b.number(),messageId:f6.optional()}),cK5=b.object({type:b.literal("retry_scheduled"),retryAt:b.number(),attempt:b.number(),maxAttempts:b.number(),reason:b.string()}),lK5=b.object({type:b.literal("retry_started")}),iK5=b.object({type:b.literal("retry_cancelled")}),nK5=b.object({type:b.literal("executor_connected"),executorId:QI,registeredToolCount:b.number(),guidanceInventory:b.array(Iy4),resumeBootstrap:b.boolean().optional(),rejectedTools:b.array(b.object({name:b.string(),reason:b.string()})).optional()}),aK5=b.object({type:b.literal("tool_lease"),toolCallId:l3,toolName:b.string(),args:b.unknown(),messageId:f6,parentToolCallId:l3.optional()}),oK5=b.object({type:b.literal("executor_filesystem_read_directory"),requestId:RU,uri:Kx}),rK5=b.object({type:b.literal("executor_filesystem_read_file"),requestId:RU,uri:Kx}),sK5=b.object({type:b.literal("client_filesystem_read_directory_result"),requestId:RU,ok:b.boolean(),entries:b.array(aa).optional(),error:$I.optional()}).superRefine((A,Q)=>{if(A.ok){if(!A.entries)Q.addIssue({code:"custom",message:"entries is required when ok is true"});if(A.error)Q.addIssue({code:"custom",message:"error must not be present when ok is true"});return}if(!A.error)Q.addIssue({code:"custom",message:"error is required when ok is false"});if(A.entries)Q.addIssue({code:"custom",message:"entries must not be present when ok is false"})}),tK5=b.object({type:b.literal("client_filesystem_read_file_result"),requestId:RU,ok:b.boolean(),contentBase64:b.string().optional(),error:$I.optional()}).superRefine((A,Q)=>{if(A.ok){if(A.contentBase64===void 0)Q.addIssue({code:"custom",message:"contentBase64 is required when ok is true"});if(A.error)Q.addIssue({code:"custom",message:"error must not be present when ok is true"});return}if(!A.error)Q.addIssue({code:"custom",message:"error is required when ok is false"});if(A.contentBase64!==void 0)Q.addIssue({code:"custom",message:"contentBase64 must not be present when ok is false"})}),eK5=b.object({type:b.literal("tool_approval_queue"),approvals:b.array(IF0)}),AE5=b.object({type:b.literal("executor_tool_lease_revoked"),toolCallId:l3,reason:ms0}),QE5=b.object({type:b.literal("executor_tool_result_ack"),toolCallId:l3}),BE5=b.object({type:b.literal("plugin_message"),message:wF0}),$E5=b.object({type:b.literal("executor_tool_approval_response"),toolCallId:l3,accepted:b.boolean(),input:b.object({askAnswers:b.record(b.string(),b.string()).optional(),denyFeedback:b.string().optional()}).optional()}),JE5=b.object({type:b.literal("executor_error"),message:b.string(),toolCallId:l3.optional(),code:ps0}),YE5=b.object({type:b.literal("delta"),messageId:f6,role:b.literal("assistant"),blocks:ta.optional(),blockIndex:b.number().int().nonnegative().optional(),state:Ss0,usage:Ls0.optional(),parentToolCallId:l3.optional()}),ZE5=b.object({type:b.literal("delta"),messageId:f6,role:b.literal("user"),blocks:sa.optional(),state:b.literal("complete"),parentToolCallId:l3.optional()}),FE5=b.discriminatedUnion("role",[YE5,ZE5]),XE5=b.object({type:b.literal("queued_messages"),messages:b.array(Py4)}),DE5=b.object({type:b.literal("queued_message_added"),message:Py4,seq:b.number()}),GE5=b.object({type:b.literal("queued_message_removed"),queuedMessageId:f6,seq:b.number()}),VE5=b.object({type:b.literal("queued_message_dequeued"),queuedMessageId:f6,seq:b.number()}),UE5=b.object({type:b.literal("message_added"),message:js0,seq:b.number(),parentToolUseId:l3.optional()}),KE5=b.object({type:b.literal("message_updated"),message:js0,seq:b.number()}),EE5=b.object({type:b.literal("edit_rejected"),editId:b.string(),message:b.string()}),zE5=b.object({type:b.literal("thread_truncated"),seq:b.number(),truncateFromMessage:f6}),WE5=b.object({type:b.literal("observers"),count:b.number(),observers:b.array(kK5),hasExecutor:b.boolean().optional()}),HE5=b.object({type:b.literal("executor_status"),spawnId:b.string().optional(),status:vs0,message:b.string().optional(),executorId:b.string().optional(),details:xK5.optional()}),qE5=b.object({type:b.literal("environment_update"),environment:ea}),NE5=b.object({type:b.literal("artifacts_snapshot"),artifacts:b.array(qs0)}),IE5=b.object({type:b.literal("artifact_upserted"),artifact:qs0}),wE5=b.object({type:b.literal("artifact_deleted"),key:z3}),CE5=b.object({type:b.literal("thread_title"),title:b.string().nullable()}),ME5=b.object({type:b.literal("thread_status"),status:b.union([b.literal("merging"),b.literal("merged"),b.null()])}),LE5=b.object({type:b.literal("thread_relationships"),seq:b.number(),relationships:b.array(Vy4)}),OE5=b.object({type:b.literal("compaction_started")}),jE5=b.object({type:b.literal("compaction_complete"),cutMessageId:f6}),RE5=b.object({type:b.literal("compaction_records"),records:b.array(fK5)}),LF0=b.discriminatedUnion("type",[bK5,uK5,hK5,gK5,mK5,pK5,dK5,cK5,lK5,iK5,nK5,aK5,oK5,rK5,sK5,tK5,eK5,AE5,QE5,BE5,$E5,_s0,JE5,FE5,zE5,XE5,DE5,GE5,VE5,UE5,KE5,EE5,WE5,HE5,qE5,NE5,IE5,wE5,CE5,ME5,LE5,OE5,jE5,RE5]);var _y4=CF0(Oy4),PE5=b.union([LF0,b.array(LF0)]),Ty4=CF0(LF0),hE8=CF0(PE5);r1();function ky4(A,Q={}){let $=(Q.mode??"lenient")==="strict";if(!Array.isArray(A))return $?null:[];let J=[];for(let Y of A){if(typeof Y!=="object"||Y===null){if($)return null;continue}let Z=Y;if(typeof Z.uri!=="string"||Z.uri.length===0){if($)return null;continue}let F;try{F=b1(o0.parse(Z.uri))}catch{if($)return null;continue}let X={uri:F};if(typeof Z.content==="string")X.content=Z.content;if(typeof Z.lineCount==="number"&&Number.isFinite(Z.lineCount))X.lineCount=Z.lineCount;if(typeof Z.hash==="string")X.hash=Z.hash;J.push(X)}return J}function ds0(A){let Q=Number.isFinite(A)?A:0;function B(J=Q){if(Number.isFinite(J))Q=J;return Q}function $(J){if(!Number.isFinite(J)||J<1)return Q;return Q=Math.max(Q,J),Q}return{getVersion:()=>Q,reset:B,advanceFromSeq:$}}function fy4(A,Q,B){let $;switch(Q.type){case"message_added":$=_E5(A,Q);break;case"message_updated":$=TE5(A,Q);break;case"delta":$=SE5(A,Q,B);break;case"tool_progress":$=vE5(A,Q,B);break;case"thread_truncated":$=yE5(A,Q);break}return $}function _E5(A,Q){let B=qj(Q.message,Q.parentToolUseId??Q.message.parentToolUseId);return by4(A,B)}function TE5(A,Q){let B=kE5(A,Q.message);return by4(A,B)}function by4(A,Q){let B=lE5(A,nE5(Q)),$=Bo(B,Q.messageId),J=B.slice();if($>=0)return J[$]=Q,J;return J.push(Q),J}function kE5(A,Q){let B=Bo(A,Q.messageId),$=B>=0?A[B]:void 0;return qj(Q,$?.parentToolUseId)}function qj(A,Q){let B={...A};if(Q!==void 0)B.parentToolUseId=Q;return B}function SE5(A,Q,B){let $=Q.role==="assistant"&&Q.state==="aborted"?gE5(A,Q.messageId):A;if(!Q.blocks||Q.blocks.length===0){if(Q.role==="assistant"&&(Q.state==="complete"||Q.state==="tool_use"))return yy4($,{...Q,blocks:[],blockIndex:Q.blockIndex??0},B);return $.slice()}if(Q.role==="assistant")return yy4($,Q,B);return xE5($,{...Q,blocks:Q.blocks},B)}function vE5(A,Q,B){let $=cE5(Q.progress);if($!==void 0&&$.status!=="in-progress"&&!S5($.status))return A.slice();if(xy4(A,Q.toolCallId,(V)=>S5(V.run.status)))return A.slice();let Y=xy4(A,Q.toolCallId),Z=$!==void 0&&S5($.status)?$:void 0;if(Z!==void 0){let V=Sy4(Q.toolCallId,Z,Y?.block.userInput);return vy4(A,Q,B,Y,V)}let F=Y&&"progress"in Y.block.run?Y.block.run.progress:void 0,X=Q.progress===void 0?F:MF0(F,Q.progress),D=X===void 0?{status:"in-progress"}:{status:"in-progress",progress:X},G=Sy4(Q.toolCallId,D,Y?.block.userInput);return vy4(A,Q,B,Y,G)}function Sy4(A,Q,B){if(B!==void 0)return{type:"tool_result",toolUseID:A,run:Q,userInput:B};return{type:"tool_result",toolUseID:A,run:Q}}function vy4(A,Q,B,$,J){if($)return mE5(A,$,J);return[...A,qj({threadId:B.threadId,messageId:uy4(Q.toolCallId),role:"user",content:[J]},Q.parentToolCallId)]}function yE5(A,Q){let B=Bo(A,Q.truncateFromMessage);return B>=0?A.slice(0,B):A.slice()}function yy4(A,Q,B){let $=Bo(A,Q.messageId),J=$>=0?A[$]:void 0,Y=J?.role==="assistant"?J.content:[],Z=fE5(Y,Q.blocks,Q.blockIndex),F=Q.parentToolCallId??J?.parentToolUseId,X=J?.role==="assistant"?qj({...J,content:Z},F):qj({threadId:B.threadId,messageId:Q.messageId,role:"assistant",content:Z},F);if(Q.usage!==void 0)X.usage=Q.usage;if(Q.state==="aborted")X.state={type:"cancelled"},delete X.isStreaming;else if(Q.state==="complete"||Q.state==="tool_use")X.state={type:"complete"},delete X.isStreaming;else X.isStreaming=!0;return cs0(A,$,X)}function xE5(A,Q,B){let $=Bo(A,Q.messageId),J=$>=0?A[$]:void 0,Y=J?.role==="user"?J.content:[],Z=hE5(Y,Q.blocks),F=Q.parentToolCallId??J?.parentToolUseId,X=J?.role==="user"?qj({...J,content:Z},F):qj({threadId:B.threadId,messageId:Q.messageId,role:"user",content:Z},F);return cs0(A,$,X)}function fE5(A,Q,B){let $=[...A];for(let[J,Y]of Q.entries()){let Z=B+J;bE5($,Z);let F=$[Z];if(uE5(F))$[Z]=Y;else if(F?.type==="text"&&Y.type==="text")$[Z]={...F,...Y,text:F.text+Y.text};else if(F?.type==="thinking"&&Y.type==="thinking")$[Z]={...F,...Y,thinking:F.thinking+Y.thinking};else $[Z]=Y}return $}function bE5(A,Q){while(A.length<Q)A.push({type:"text",text:"",hidden:!0})}function uE5(A){return A?.type==="text"&&A.hidden===!0&&A.text===""}function hE5(A,Q){let B=[...A];for(let $ of Q){let J=B.length-1,Y=B[J];if(Y?.type==="text"&&$.type==="text")B[J]={...Y,text:Y.text+$.text};else B.push($)}return B}function cs0(A,Q,B){let $=A.slice();if(Q>=0)return $[Q]=B,$;return $.push(B),$}function gE5(A,Q){return A.filter((B)=>B.messageId!==Q)}function Bo(A,Q){return A.findIndex((B)=>B.messageId===Q)}function xy4(A,Q,B=()=>!0){for(let[$,J]of A.entries()){if(J.role!=="user")continue;for(let[Y,Z]of J.content.entries())if(Z.type==="tool_result"&&Z.toolUseID===Q&&B(Z))return{messageIndex:$,blockIndex:Y,message:J,block:Z}}return}function mE5(A,Q,B){let $=Q.message.content.slice();return $[Q.blockIndex]=B,cs0(A,Q.messageIndex,{...Q.message,content:$})}var pE5=["queued","blocked-on-user","in-progress","rejected-by-user","cancellation-requested","cancelled","done","error"];function dE5(A){return typeof A==="string"&&pE5.includes(A)}function cE5(A){if(A===void 0||typeof A!=="object"||A===null)return;let Q=A;if(Q.type!=="snapshot")return;let B=Q.value;if(typeof B!=="object"||B===null)return;let $=B;return dE5($.status)?$:void 0}function lE5(A,Q){if(Q.size===0)return A;return A.filter((B)=>!iE5(B,Q))}function iE5(A,Q){if(A.role!=="user"||A.content.length!==1)return!1;let B=A.content[0];return B?.type==="tool_result"&&Q.has(B.toolUseID)&&A.messageId===uy4(B.toolUseID)}function nE5(A){let Q=new Set;if(A.role!=="user")return Q;for(let B of A.content)if(B.type==="tool_result")Q.add(B.toolUseID);return Q}function uy4(A){return`M-${A.replace(/^TU-/,"")}`}class ls0{inProgressMessageID=null;threadMessages=[];messageSeq=new Map;messageOrder=new Map;nextMessageOrder=0;threadID;constructor(A){this.threadID=A}setThreadID(A){this.threadID=A}getThreadID(){return this.threadID}reset(A){if(A!==void 0)this.threadID=A;this.threadMessages=[],this.messageSeq.clear(),this.messageOrder.clear(),this.nextMessageOrder=0,this.inProgressMessageID=null}apply(A){let Q=this.threadMessages;if(A.type==="delta"&&A.parentToolCallId===void 0&&A.state==="aborted"){if(this.applyThreadMessageEvent(A),this.inProgressMessageID===A.messageId)this.inProgressMessageID=null;return this.threadMessages!==Q}let B=aE5(A);if(B!==void 0)this.updateInProgressMessage(B);if(this.applyThreadMessageEvent(A),A.type==="delta"&&(A.state==="complete"||A.state==="tool_use"))this.inProgressMessageID=null;return this.threadMessages!==Q}messages(){return this.threadMessages}sortedMessages(){return this.sortThreadMessages(this.threadMessages)}applyThreadMessageEvent(A){this.recordMessageOrder(A);let Q=A.type==="thread_truncated"?this.sortThreadMessages(this.threadMessages):this.threadMessages;this.threadMessages=fy4(Q,A,{threadId:this.threadID}),this.pruneMessageOrder()}recordMessageOrder(A){if(A.type==="message_added"){this.recordMessage(A.message.messageId,A.seq);return}if(A.type==="message_updated"){this.recordMessage(A.message.messageId,this.messageSeq.has(A.message.messageId)?void 0:A.seq);return}if(A.type==="delta"){this.recordMessage(A.messageId);return}if(A.type==="tool_progress")this.recordMessage(rE5(A.toolCallId))}recordMessage(A,Q){if(!this.messageOrder.has(A))this.messageOrder.set(A,this.nextMessageOrder),this.nextMessageOrder+=1;if(Q!==void 0)this.messageSeq.set(A,Q)}sortThreadMessages(A){return A.slice().sort((Q,B)=>{let $=this.messageSeq.get(Q.messageId),J=this.messageSeq.get(B.messageId),Y=$!==void 0&&J!==void 0?$-J:this.messageSortOrder(Q.messageId)-this.messageSortOrder(B.messageId);if(Y!==0)return Y;return this.messageSortOrder(Q.messageId)-this.messageSortOrder(B.messageId)})}messageSortOrder(A){return this.messageOrder.get(A)??Number.MAX_SAFE_INTEGER}pruneMessageOrder(){let A=new Set(this.threadMessages.map((Q)=>Q.messageId));for(let Q of this.messageSeq.keys())if(!A.has(Q))this.messageSeq.delete(Q);for(let Q of this.messageOrder.keys())if(!A.has(Q))this.messageOrder.delete(Q);if(this.inProgressMessageID!==null&&!A.has(this.inProgressMessageID))this.inProgressMessageID=null}updateInProgressMessage(A){if(this.inProgressMessageID===A)return;if(this.inProgressMessageID!==null)this.markMessageNotInProgress(this.inProgressMessageID);this.inProgressMessageID=A}markMessageNotInProgress(A){this.threadMessages=this.threadMessages.map((Q)=>{if(Q.messageId!==A||Q.role!=="assistant"||Q.state!==void 0)return Q;let B={...Q,state:{type:"complete"}};return delete B.isStreaming,B})}}function aE5(A){if(A.type==="message_added"&&oE5(A)===void 0)return A.message.messageId;if(A.type==="delta"&&A.parentToolCallId===void 0)return A.messageId;return}function oE5(A){return A.parentToolUseId??A.message.parentToolUseId}function rE5(A){return`M-${A.replace(/^TU-/,"")}`}i4();function hy4(A,Q){let B=A.parentToolUseId;if(A.role==="assistant"){let J={role:"assistant",content:A.content,state:A.state?.type==="cancelled"?{type:"cancelled"}:A.isStreaming===!0?{type:"streaming"}:{type:"complete",stopReason:null},usage:A.usage,messageId:Q,protocolMessageID:A.messageId,readAt:A.readAt};if(B===void 0)return J;return{...J,parentToolUseId:B}}if(A.role==="info"){let J={role:"info",content:A.content,messageId:Q,protocolMessageID:A.messageId};if(B===void 0)return J;return{...J,parentToolUseId:B}}let $={role:"user",content:A.content,meta:L30(A.meta),userState:A.userState,readAt:A.readAt,messageId:Q,protocolMessageID:A.messageId};if(B===void 0)return $;return{...$,parentToolUseId:B}}class OF0{accumulator;currentVersion=0;constructor(A){this.accumulator=new ls0(A)}get version(){return this.currentVersion}setThreadID(A){this.accumulator.setThreadID(A)}reset(A){let Q=this.accumulator.sortedMessages().length;return this.accumulator.reset(A),this.currentVersion+=1,{changed:Q>0,previousMessageCount:Q,nextMessageCount:0,changedIndices:tE5(Q,0),version:this.currentVersion}}apply(A){if(A.type==="message_added"&&eE5(A)===void 0||A.type==="message_updated")this.setThreadID(A.message.threadId);let Q=this.accumulator.sortedMessages();if(!this.accumulator.apply(A))return{changed:!1,previousMessageCount:Q.length,nextMessageCount:Q.length,changedIndices:[],version:this.currentVersion};let $=this.accumulator.sortedMessages();return this.currentVersion+=1,{changed:!0,previousMessageCount:Q.length,nextMessageCount:$.length,changedIndices:sE5(Q,$),version:this.currentVersion}}protocolMessages(){return this.accumulator.sortedMessages()}coreMessages(){return this.accumulator.sortedMessages().map((A,Q)=>hy4(A,Q))}buildTranscriptEntries(A={}){return cv4(this.protocolMessages(),{threadID:this.accumulator.getThreadID(),...A})}}function sE5(A,Q){let B=Math.max(A.length,Q.length),$=[];for(let J=0;J<B;J+=1)if(A[J]!==Q[J])$.push(J);return $}function tE5(A,Q){return Array.from({length:Math.max(A,Q)},(B,$)=>$)}function eE5(A){return A.parentToolUseId??A.message.parentToolUseId}d0();M1();var Az5=1000,Qz5=30000,Bz5=124,$z5=30000,Jz5=15000,Yz5=1000,Zz5=200,gy4="Connection timed out. Retrying...",Fz5=30000,my4=["online","focus","pageshow","keydown","pointerdown"],py4=["visibilitychange"];function ns0(){return globalThis}function cy4(A){if(!A||typeof A!=="object")return null;let Q=A;if(typeof Q.addEventListener!=="function"||typeof Q.removeEventListener!=="function")return null;return Q}function dy4(){return cy4(ns0().window)}function is0(){let A=ns0().document;if(!cy4(A))return null;return A}function Xz5(){let A=ns0().navigator;if(!A||typeof A!=="object")return null;return A}function T9(A){if(A.state!=="connected")return!1;return A.requiredRole===null||A.role===A.requiredRole}function Dz5(A){if(!A)return"none";let Q=[A.type];if(A.code!==void 0)Q.push(`code=${A.code}`);if(A.reason!==void 0)Q.push(`reason=${A.reason}`);if(A.error!==void 0)Q.push(`error=${A.error}`);return Q.join(" ")}class as0{ws=null;connectionInfo={state:"disconnected",role:null,requiredRole:null,clientId:null};reconnectCause=null;reconnectAttempts=0;reconnectTimeoutID=null;reconnectResetTimeoutID=null;pingIntervalID=null;latencyTimeoutIDs=new Set;connectPromise=null;disposed=!1;lastServerFrameAt=Date.now();intentionallyClosedSockets=new WeakSet;reconnectActivityCleanup=null;lifecycleEventID=0;lifecycleEvents=[];connectionSubject=new A4({state:"disconnected",role:null,requiredRole:null,clientId:null});lifecycleEventSubject=new A4([]);config;threadIDSubject=new A4(null);_currentThreadID=null;log=j;get currentThreadID(){return this._currentThreadID}set currentThreadID(A){if(A!==null&&A!==this._currentThreadID)this._currentThreadID=A,this.log=j.with({threadId:A}),this.threadIDSubject.next(A);else this._currentThreadID=A}constructor(A){let Q=A.requiredRole??null;this.connectionInfo={...this.connectionInfo,requiredRole:Q},this.connectionSubject.next({...this.connectionInfo}),this.config={threadId:A.threadId,webSocketProvider:A.webSocketProvider,reconnectDelayMs:A.reconnectDelayMs??Az5,maxReconnectDelayMs:A.maxReconnectDelayMs??Qz5,maxReconnectAttempts:A.maxReconnectAttempts??Bz5,pingIntervalMs:A.pingIntervalMs??$z5,connectTimeoutMs:A.connectTimeoutMs??Jz5,webSocketLatencyMs:A.webSocketLatencyMs??(()=>0)},this.currentThreadID=A.threadId??null,this.recordLifecycleEvent("transport_initialized",`threadId=${this.currentThreadID??"none"}`)}getThreadId(){return this.currentThreadID}connectionChanges(){return this.connectionSubject}getConnectionInfo(){return{...this.connectionInfo}}waitForConnected(A){if(this.connectionInfo.state==="connected")return Promise.resolve(!0);if(this.disposed||A<=0)return Promise.resolve(!1);return new Promise((Q)=>{let B=!1,$=null,J=null,Y=(Z)=>{if(B)return;if(B=!0,$)clearTimeout($),$=null;J?.unsubscribe(),J=null,Q(Z)};$=setTimeout(()=>{Y(!1)},A),J=this.connectionSubject.subscribe({next:(Z)=>{if(Z.state==="connected")Y(!0)},error:()=>{Y(!1)},complete:()=>{Y(!1)}})})}connectionLifecycleChanges(){return this.lifecycleEventSubject}getConnectionLifecycleEvents(){return[...this.lifecycleEvents]}async connect(){return this.connectInternal({fromReconnect:!1})}recordLifecycleEvent(A,Q){let B={id:++this.lifecycleEventID,at:Date.now(),type:A,...Q?{details:Q}:{}},$=Zz5,J=this.lifecycleEvents.slice(-($-1));this.lifecycleEvents=[...J,B],this.lifecycleEventSubject.next([...this.lifecycleEvents])}async connectInternal(A){if(this.connectPromise)return this.connectPromise;let Q=this.connectInternalOnce(A);this.connectPromise=Q;try{return await Q}finally{if(this.connectPromise===Q)this.connectPromise=null}}async connectInternalOnce(A){if(this.disposed)throw new c3("Transport is disposed");if(this.ws)return;this.recordLifecycleEvent("connect_requested",A.fromReconnect?`mode=reconnect attempt=${this.reconnectAttempts}`:"mode=initial"),this.updateConnectionState("connecting");try{let{webSocket:Q,threadId:B}=await this.openWebSocketProviderWithTimeout();try{Q.binaryType="arraybuffer"}catch{}await this.waitForOpen(Q),this.currentThreadID=B,this.ws=Q,this.lastServerFrameAt=Date.now(),this.setupWebSocketHandlers(Q),this.stopWaitingForReconnectActivity(),this.scheduleReconnectAttemptsReset(),this.reconnectCause=null,this.updateConnectionState("connected"),this.recordLifecycleEvent("connect_succeeded",`threadId=${this.currentThreadID??"none"} attempt=${this.reconnectAttempts}`)}catch(Q){let B=Q instanceof Error?Q.message:String(Q),$=Q instanceof c3&&Q.cause instanceof Error?Q.cause.message:null,J=`mode=${A.fromReconnect?"reconnect":"initial"} error=${B}`;if(this.recordLifecycleEvent("connect_failed",$?`${J} cause=${$}`:J),!A.fromReconnect&&!this.disposed)this.reconnectCause={type:"connect_failed",at:Date.now(),error:B},this.scheduleReconnect();throw Q}}disconnect(){this.recordLifecycleEvent("disconnect_requested"),this.clearWebSocketLatencyTimeouts(),this.stopPingInterval(),this.cancelReconnect(),this.reconnectCause=null;let A=this.ws;if(A){if(this.ws=null,this.intentionallyClosedSockets.add(A),A.readyState===WebSocket.OPEN)A.close(1000,"Client disconnect")}this.updateConnectionState("disconnected")}forceReconnect(A){if(this.disposed)return;let Q=this.ws;if(!Q&&this.connectionInfo.state!=="connected")return;if(this.recordLifecycleEvent("force_reconnect_requested",`reason=${A}`),this.clearWebSocketLatencyTimeouts(),this.reconnectCause={type:"error",at:Date.now(),error:A},this.ws=null,this.stopPingInterval(),this.cancelReconnectAttemptsReset(),Q&&(Q.readyState===WebSocket.OPEN||Q.readyState===WebSocket.CONNECTING))Q.close(4000,A);this.scheduleReconnect({immediate:!0,bypassActivityGate:!0})}retryConnect(A){if(this.disposed)return;if(this.recordLifecycleEvent("reconnect_attempts_reset",`reason=${A}`),this.reconnectAttempts=0,this.cancelReconnectAttemptsReset(),this.reconnectTimeoutID)return;this.scheduleReconnect({immediate:!0,bypassActivityGate:!0})}async disconnectAndWait(A){let Q=this.ws;if(!Q||Q.readyState!==WebSocket.OPEN)return this.disconnect(),{status:"not_connected"};let B=this.waitForSocketClose(Q,A?.waitForCloseTimeoutMs??Yz5);return this.disconnect(),B}dispose(){if(this.disposed)return;this.recordLifecycleEvent("disposed"),this.disposed=!0,this.disconnect(),this.connectionSubject.complete(),this.lifecycleEventSubject.complete()}sendRaw(A){if(!this.hasOpenSocket())throw new c3("WebSocket is not connected");let Q=this.ws;if(!Q)throw new c3("WebSocket is not connected");this.runAfterWebSocketLatency(()=>{if(Q!==this.ws||Q.readyState!==WebSocket.OPEN)return;Q.send(A)}),this.startPingIntervalOnce()}hasOpenSocket(){return!!this.ws&&this.ws.readyState===WebSocket.OPEN}runAfterWebSocketLatency(A){let Q=this.config.webSocketLatencyMs();if(!Number.isFinite(Q)||Q<=0){A();return}let B=setTimeout(()=>{this.latencyTimeoutIDs.delete(B),A()},Q);this.latencyTimeoutIDs.add(B)}clearWebSocketLatencyTimeouts(){for(let A of this.latencyTimeoutIDs)clearTimeout(A);this.latencyTimeoutIDs.clear()}waitForSocketClose(A,Q){return new Promise((B)=>{let $=!1,J=null,Y=(F)=>{if($)return;if($=!0,J)clearTimeout(J);A.removeEventListener("close",Z),B(F)},Z=(F)=>{let X=F;Y({status:X.code===1000?"server_acknowledged":"timeout",...typeof X.code==="number"?{closeCode:X.code}:{},...typeof X.reason==="string"?{closeReason:X.reason}:{}})};if(J=setTimeout(()=>{Y({status:"timeout"})},Q),A.addEventListener("close",Z),A.readyState===WebSocket.CLOSED)Y({status:"timeout"})})}async openWebSocketProviderWithTimeout(){let A=!1,Q=null,B=this.config.webSocketProvider();B.then((J)=>{if(A)this.closeSocketDuringConnect(J.webSocket,4000,"Connection attempt timed out")},()=>{return});let $=new Promise((J,Y)=>{Q=setTimeout(()=>{A=!0,Y(new c3(gy4,Error(`WebSocket provider timed out after ${this.config.connectTimeoutMs}ms`)))},this.config.connectTimeoutMs)});try{return await Promise.race([B,$])}finally{if(Q)clearTimeout(Q)}}closeSocketDuringConnect(A,Q,B){try{if(A.readyState===WebSocket.OPEN||A.readyState===WebSocket.CONNECTING)A.close(Q,B)}catch{}}updateConnectionState(A){let Q={...this.connectionInfo};if(A==="disconnected"||A==="reconnecting"){let $={state:A,role:null,requiredRole:this.connectionInfo.requiredRole,clientId:null};if(this.reconnectCause)$.reconnectCause=this.reconnectCause;this.connectionInfo=$}else if(this.connectionInfo.state=A,A==="connected")this.reconnectCause=null,delete this.connectionInfo.reconnectCause;else if(this.reconnectCause)this.connectionInfo.reconnectCause=this.reconnectCause;let B={...this.connectionInfo};this.connectionSubject.next(B),this.log.info("[thread-client] Transport connection state changed",{previousState:Q.state,nextState:B.state,previousRole:Q.role,nextRole:B.role,clientId:B.clientId,reconnectCauseType:this.reconnectCause?.type,reconnectCode:this.reconnectCause?.code,reconnectReason:this.reconnectCause?.reason}),this.recordLifecycleEvent("state_changed",`state=${A} cause=${Dz5(this.reconnectCause)}`)}onRawMessage(A){}onWebSocketTraffic(A){}onMaxReconnectExceeded(A){}async waitForOpen(A){if(A.readyState===WebSocket.OPEN)return;return new Promise((Q,B)=>{let $=setTimeout(()=>{J(),this.closeSocketDuringConnect(A,4000,"Connection attempt timed out"),B(new c3(gy4,Error(`WebSocket connection timed out after ${this.config.connectTimeoutMs}ms`)))},this.config.connectTimeoutMs),J=()=>{clearTimeout($),A.removeEventListener("open",Y),A.removeEventListener("error",Z),A.removeEventListener("close",F)},Y=()=>{J(),Q()},Z=(X)=>{J();let D="message"in X?X.message:("error"in X)&&X.error instanceof Error?X.error.message:X.type;B(new c3(`WebSocket connection failed: ${D}`))},F=(X)=>{J(),B(new c3(`WebSocket closed during connect: code=${X.code} reason=${X.reason||"none"}`))};if(A.addEventListener("open",Y),A.addEventListener("error",Z),A.addEventListener("close",F),A.readyState===WebSocket.OPEN)return Y();if(A.readyState===WebSocket.CLOSED||A.readyState===WebSocket.CLOSING)return F({code:1006,reason:"Socket already closed before connect"})})}setupWebSocketHandlers(A){A.addEventListener("message",(Q)=>{let B=Q.data;this.runAfterWebSocketLatency(()=>this.handleWebSocketMessage(A,B))}),A.addEventListener("close",(Q)=>{this.handleClose(A,Q.code,Q.reason)}),A.addEventListener("error",()=>{this.handleError(A)})}handleWebSocketMessage(A,Q){if(A!==this.ws)return;if(this.lastServerFrameAt=Date.now(),this.startPingIntervalOnce(),this.onWebSocketTraffic(Q),typeof Q==="string"){if(Q==="pong")return;this.onRawMessage(Q)}else if(Q instanceof ArrayBuffer)this.onRawMessage(new TextDecoder().decode(Q))}handleClose(A,Q,B){let $=this.intentionallyClosedSockets.has(A);if($)this.intentionallyClosedSockets.delete(A);if(this.log.info("[thread-client] Transport socket close observed",{code:Q,reason:B||void 0,intentional:$,isCurrentSocket:A===this.ws,stateBeforeClose:this.connectionInfo.state,roleBeforeClose:this.connectionInfo.role,clientIdBeforeClose:this.connectionInfo.clientId,reconnectCauseType:this.reconnectCause?.type,reconnectCode:this.reconnectCause?.code,reconnectReason:this.reconnectCause?.reason}),this.recordLifecycleEvent("socket_closed",`code=${Q} reason=${B||"none"} intentional=${$}`),A!==this.ws)return;if(this.ws=null,this.clearWebSocketLatencyTimeouts(),this.stopPingInterval(),this.cancelReconnectAttemptsReset(),!this.disposed&&!$){let J=this.reconnectCause,Y=J?.type==="ping_timeout"&&Q===4000&&!B?{...J,at:Date.now(),code:Q}:{type:"close",at:Date.now(),code:Q,...B?{reason:B}:{}};this.reconnectCause=Y,this.scheduleReconnect()}else this.reconnectCause=null,this.updateConnectionState("disconnected")}handleError(A){if(A!==this.ws)return;if(this.recordLifecycleEvent("socket_error","error=WebSocket error event"),this.reconnectCause={type:"error",at:Date.now(),error:"WebSocket error event"},this.ws)this.ws.close()}scheduleReconnect(A){if(this.disposed||this.reconnectTimeoutID)return;if(this.reconnectAttempts>=this.config.maxReconnectAttempts){this.stopWaitingForReconnectActivity(),this.recordLifecycleEvent("reconnect_exhausted",`attempts=${this.reconnectAttempts} max=${this.config.maxReconnectAttempts}`),this.updateConnectionState("disconnected"),this.onMaxReconnectExceeded(this.config.maxReconnectAttempts);return}if(!A?.bypassActivityGate&&this.shouldWaitForReconnectActivity()){this.recordLifecycleEvent("reconnect_waiting_for_activity",`offline=${this.isBrowserOffline()} hidden=${this.isDocumentHidden()}`),this.updateConnectionState("reconnecting"),this.waitForReconnectActivity();return}this.stopWaitingForReconnectActivity(),this.updateConnectionState("reconnecting"),this.reconnectAttempts++;let Q=A?.immediate?0:this.getReconnectDelayMs();this.log.info("[thread-client] Scheduling transport reconnect",{attempt:this.reconnectAttempts,delayMs:Math.round(Q),immediate:A?.immediate===!0,bypassActivityGate:A?.bypassActivityGate===!0,state:this.connectionInfo.state,role:this.connectionInfo.role,clientId:this.connectionInfo.clientId,reconnectCauseType:this.reconnectCause?.type,reconnectCode:this.reconnectCause?.code,reconnectReason:this.reconnectCause?.reason}),this.recordLifecycleEvent("reconnect_scheduled",`attempt=${this.reconnectAttempts} delayMs=${Math.round(Q)}`),this.reconnectTimeoutID=setTimeout(()=>{this.reconnectTimeoutID=null,this.connectInternal({fromReconnect:!0}).catch((B)=>{if(this.reconnectCause={type:"connect_failed",at:Date.now(),error:B instanceof Error?B.message:String(B)},!this.disposed)this.scheduleReconnect()})},Q)}cancelReconnect(){if(this.reconnectTimeoutID)clearTimeout(this.reconnectTimeoutID),this.reconnectTimeoutID=null;this.stopWaitingForReconnectActivity(),this.cancelReconnectAttemptsReset(),this.reconnectAttempts=0}getReconnectDelayMs(){let A=Math.min(this.config.reconnectDelayMs*2**(this.reconnectAttempts-1),this.config.maxReconnectDelayMs),Q=0.8+Math.random()*0.4;return A*Q}shouldWaitForReconnectActivity(){let A=dy4(),Q=is0();if(!A&&!Q)return!1;return this.isBrowserOffline()||this.isDocumentHidden()}isBrowserOffline(){let A=Xz5();if(typeof A?.onLine!=="boolean")return!1;return A.onLine===!1}isDocumentHidden(){let A=is0();if(!A)return!1;return A.visibilityState==="hidden"}waitForReconnectActivity(){if(this.reconnectActivityCleanup)return;let A=dy4(),Q=is0();if(!A&&!Q)return;let B=()=>{this.handleReconnectActivity()};for(let $ of my4)A?.addEventListener($,B);for(let $ of py4)Q?.addEventListener($,B);this.reconnectActivityCleanup=()=>{for(let $ of my4)A?.removeEventListener($,B);for(let $ of py4)Q?.removeEventListener($,B)}}stopWaitingForReconnectActivity(){this.reconnectActivityCleanup?.(),this.reconnectActivityCleanup=null}handleReconnectActivity(){if(this.disposed||this.ws){this.stopWaitingForReconnectActivity();return}if(this.shouldWaitForReconnectActivity())return;this.stopWaitingForReconnectActivity(),this.recordLifecycleEvent("reconnect_activity_detected"),this.scheduleReconnect({immediate:!0,bypassActivityGate:!0})}scheduleReconnectAttemptsReset(){this.cancelReconnectAttemptsReset(),this.reconnectResetTimeoutID=setTimeout(()=>{this.reconnectResetTimeoutID=null,this.reconnectAttempts=0},Fz5)}cancelReconnectAttemptsReset(){if(this.reconnectResetTimeoutID)clearTimeout(this.reconnectResetTimeoutID),this.reconnectResetTimeoutID=null}startPingIntervalOnce(){if(this.pingIntervalID)return;this.startPingInterval()}startPingInterval(){this.stopPingInterval();let A=Date.now();this.pingIntervalID=setInterval(()=>{let Q=Date.now(),B=Q-A;if(A=Q,B>this.config.pingIntervalMs*3){this.lastServerFrameAt=Q;return}if(this.hasOpenSocket()){let $=Q-this.lastServerFrameAt,J=this.config.pingIntervalMs*2;if($>J){this.recordLifecycleEvent("ping_timeout",`elapsedMs=${$} thresholdMs=${J}`);let Y=`No server frame received for ${$}ms (threshold ${J}ms)`;this.reconnectCause={type:"ping_timeout",at:Q,code:4000,reason:"Pong timeout",error:Y},this.ws?.close(4000,"Pong timeout");return}try{this.ws?.send("ping")}catch{}}},this.config.pingIntervalMs)}stopPingInterval(){if(this.pingIntervalID)clearInterval(this.pingIntervalID),this.pingIntervalID=null}}function jF0(A,Q={}){let B=!1,$=!1;return A.connectionChanges().subscribe({next:(J)=>{let Y=Q.requireRole??J.requiredRole,Z=T9({state:J.state,role:J.role,requiredRole:Y});if(Z&&!B){if($)try{A.resumeFromVersion(A.getResumeVersion())}catch(F){Q.onError?.({threadID:A.getThreadId(),error:F})}$=!0}B=Z}})}Wl();M1();var Gz5=J2(Ss0.options),Vz5=J2(Qo),Uz5=J2(gs0.options),Kz5=J2(ps0.options),Ez5=J2(vs0.options),zz5=J2(ys0.options),Wz5=J2(xs0.options),Hz5=J2(fs0.options),qz5=J2(bs0.options),Nz5=J2(us0.options),Iz5=J2(hs0.options),wz5=J2(ms0.options),Cz5=J2(Gs0.options),Mz5=J2(Vs0.options),Lz5=J2(Rs0.options),Oz5=J2(Ps0.options),jz5=J2(Us0.options),Rz5=J2(Ks0.options),Pz5=J2(Es0.options),ny4=J2(BI.options),_z5=J2(zs0.options),Tz5=J2(Ws0.options);function J2(A){return new Set(A)}function _z(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}function oB(A,Q){return typeof A==="string"&&Q.has(A)}function kz5(A){return typeof A==="number"&&Number.isInteger(A)&&A>=0}function ly4(A){let Q;try{Q=JSON.stringify(A)}catch{return null}let B=Ty4.safeDecode(Q);return B.success?B.data:null}function ay4(A){let Q;try{Q=JSON.parse(A)}catch{return[]}let B=Array.isArray(Q)?Q:[Q],$=[];for(let J of B){let Y=Sz5(J);if(Y)$.push(Y)}return $}function Sz5(A){let Q=ly4(A);if(Q)return Q;if(!_z(A)||typeof A.type!=="string")return null;let B=vz5(A);return B?ly4(B):null}function vz5(A){switch(A.type){case"agent_state":return yz5(A);case"thread_settings":return xz5(A);case"error":return bz5(A);case"executor_tool_lease_revoked":return hz5(A);case"tool_approval_queue":return ez5(A);case"executor_error":return uz5(A);case"delta":return gz5(A);case"queued_messages":return mz5(A);case"queued_message_added":return pz5(A);case"message_added":case"message_updated":return dz5(A);case"executor_status":return rz5(A);case"thread_relationships":return QW5(A);default:return null}}function yz5(A){let Q={...A};if(!oB(Q.state,Vz5))Q.state="working";if(Q.agentMode!==void 0&&!Pz.safeParse(Q.agentMode).success)delete Q.agentMode;if(Q.reasoningEffort!==void 0&&!oB(Q.reasoningEffort,ny4))delete Q.reasoningEffort;return Q}function xz5(A){if(!_z(A.settings))return A;return{...A,settings:fz5(A.settings)}}function fz5(A){let Q={...A};if(zx(Q,"anthropic.provider",jz5),zx(Q,"openai.speed",Rz5),zx(Q,"painter.model",Pz5),zx(Q,"reasoning.effort",ny4),zx(Q,"internal.oracleReasoningEffort",_z5),zx(Q,"gemini.thinkingLevel",Tz5),Q["internal.compactionThresholdPercent"]!==void 0&&(typeof Q["internal.compactionThresholdPercent"]!=="number"||Q["internal.compactionThresholdPercent"]<0||Q["internal.compactionThresholdPercent"]>100))delete Q["internal.compactionThresholdPercent"];return Q}function zx(A,Q,B){if(A[Q]!==void 0&&!oB(A[Q],B))delete A[Q]}function bz5(A){let Q={...A};if(Q.code!==void 0&&!oB(Q.code,Uz5))delete Q.code;return Q}function uz5(A){let Q={...A};if(!oB(Q.code,Kz5))Q.code="INTERNAL_ERROR";return Q}function hz5(A){let Q={...A};if(!oB(Q.reason,wz5))Q.reason="reassigned";return Q}function gz5(A){if(A.role!=="assistant"&&A.role!=="user")return null;let Q={...A};if(A.role==="assistant"){if(!oB(Q.state,Gz5))Q.state="generating";if(Array.isArray(Q.blocks)){if(Q.blocks=az5(Q.blocks),!kz5(Q.blockIndex))Q.blockIndex=0}else if(Q.blocks!==void 0)delete Q.blocks,delete Q.blockIndex;return Q}if(Q.state="complete",Array.isArray(Q.blocks))Q.blocks=rs0(Q.blocks,"user");else if(Q.blocks!==void 0)delete Q.blocks;return delete Q.blockIndex,Q}function mz5(A){if(!Array.isArray(A.messages))return A;return{...A,messages:A.messages.map(oy4).filter((Q)=>Q!==null)}}function pz5(A){let Q=oy4(A.message);return Q?{...A,message:Q}:null}function oy4(A){if(!_z(A)||!_z(A.queuedMessage))return null;let Q=ry4(A.queuedMessage);return Q?{...A,queuedMessage:Q}:null}function dz5(A){let Q=cz5(A.message);return Q?{...A,message:Q}:null}function cz5(A){if(!_z(A))return null;if(A.role==="user")return ry4(A);if(A.role==="assistant")return lz5(A);if(A.role==="info")return iz5(A);return null}function ry4(A){if(A.role!=="user"||!Array.isArray(A.content))return null;return{...A,content:rs0(A.content,"user")}}function lz5(A){if(A.role!=="assistant"||!Array.isArray(A.content))return null;let Q={...A,content:rs0(A.content,"assistant")};if(Q.state!==void 0&&!nz5(Q.state))delete Q.state;return Q}function iz5(A){if(A.role!=="info"||!Array.isArray(A.content))return null;return{...A,content:oz5(A.content)}}function nz5(A){return Os0.safeParse(A).success}function rs0(A,Q){let B=[];for(let $ of A){let J=sy4($,Q);if(J)B.push(J)}return B}function az5(A){return A.map((Q)=>sy4(Q,"assistant")??{type:"text",text:"",hidden:!0})}function sy4(A,Q){let $=(Q==="assistant"?ta:sa).safeParse([A]);return $.success?$.data[0]??null:null}function oz5(A){let Q=[];for(let B of A){let $=Cs0.safeParse([B]);if($.success&&$.data[0])Q.push($.data[0])}return Q}function rz5(A){let Q={...A};if(!oB(Q.status,Ez5))Q.status="starting";if(Q.details!==void 0){let B=sz5(Q.details);if(B)Q.details=B;else delete Q.details}return Q}function sz5(A){if(!_z(A))return null;let Q={...A};if(Q.reasonCode!==void 0&&!oB(Q.reasonCode,Iz5))delete Q.reasonCode;if(Q.executionEnvironment!==void 0){let B=tz5(Q.executionEnvironment);if(B)Q.executionEnvironment=B;else delete Q.executionEnvironment}return Q}function tz5(A){if(!_z(A))return null;let Q={...A};return iy4(Q,"setupState",Wz5),iy4(Q,"setupPhase",Hz5),os0(Q,"stage",zz5),os0(Q,"operation",qz5),os0(Q,"providerState",Nz5),Q}function os0(A,Q,B){if(A[Q]!==void 0&&!oB(A[Q],B))delete A[Q]}function iy4(A,Q,B){if(A[Q]!==void 0&&A[Q]!==null&&!oB(A[Q],B))delete A[Q]}function ez5(A){if(!Array.isArray(A.approvals))return A;return{...A,approvals:A.approvals.map(AW5).filter((Q)=>Q!==null)}}function AW5(A){if(!_z(A))return null;let Q={...A};if(!oB(Q.context,Lz5))Q.context="thread";if(Q.ruleSource!==void 0&&!oB(Q.ruleSource,Oz5))delete Q.ruleSource;return Q}function QW5(A){if(!Array.isArray(A.relationships))return A;return{...A,relationships:A.relationships.filter(BW5)}}function BW5(A){return _z(A)&&oB(A.type,Cz5)&&oB(A.role,Mz5)}var ss0=Number.MAX_SAFE_INTEGER;class ts0{callbacks;agentLoopState=null;pending=new Map;constructor(A){this.callbacks=A}setAgentLoopState(A){this.agentLoopState=A}emitOptimisticUserMessage(A){if(this.pending.has(A.messageId))return;let Q=this.nextEventType();this.pending.set(A.messageId,Q),this.dispatchOptimistic(Q,A)}emitOptimisticQueuedUserMessage(A){if(this.pending.has(A.messageId))return;this.pending.set(A.messageId,"queued_message_added"),this.dispatchOptimistic("queued_message_added",A)}reconcileMessageAdded(A){let Q=A.message.messageId;if(this.pending.get(Q)==="queued_message_added")this.emitQueuedMessages({type:"queued_message_dequeued",queuedMessageId:Q,seq:ss0});this.pending.delete(Q),this.emitMessageAdded(A)}reconcileQueuedMessageAdded(A){let Q=A.message.queuedMessage.messageId,B=this.pending.get(Q);if(B==="queued_message_added")return;if(B==="message_added")this.pending.set(Q,"queued_message_added");this.emitQueuedMessages(A)}reconcileQueuedMessagesSnapshot(A){let Q=new Set;for(let B of A.messages)Q.add(B.queuedMessage.messageId);for(let B of Q)if(this.pending.get(B)==="message_added")this.pending.set(B,"queued_message_added");for(let[B,$]of this.pending)if($==="queued_message_added"&&!Q.has(B))return;this.emitQueuedMessages(A)}reconcileQueuedMessageRemoved(A){this.pending.delete(A.queuedMessageId),this.emitQueuedMessages(A)}reset(){this.agentLoopState=null,this.pending.clear()}nextEventType(){if(this.pending.size>0)return"queued_message_added";if(this.agentLoopState===null||this.agentLoopState==="idle")return"message_added";return"queued_message_added"}dispatchOptimistic(A,Q){if(A==="message_added"){this.emitMessageAdded({type:"message_added",message:{role:"user",messageId:Q.messageId,content:Q.content,agentMode:Q.agentMode,threadId:this.callbacks.getThreadID()??"T-00000000-0000-0000-0000-000000000000"},seq:ss0});return}this.emitQueuedMessages({type:"queued_message_added",message:{steer:!1,queuedMessage:{role:"user",messageId:Q.messageId,content:Q.content,userState:Q.userState}},seq:ss0})}emitMessageAdded(A){this.callbacks.observerCallbacks((Q)=>{Q.onMessageAdded?.(A)})}emitQueuedMessages(A){this.callbacks.observerCallbacks((Q)=>{Q.onQueuedMessages?.(A)})}}class es0{options;queue=[];active=null;retryTimer=null;constructor(A){this.options=A}send(A){this.queue.push({message:A,sent:!1}),this.pump()}retry(){this.clearRetryTimer(),this.pump({forceActiveRetry:!0})}handleServerMessage(A){if(!this.active||!this.active.sent||this.active.message.type!=="client_append_user_msg")return;if(!JW5(this.active.message,A))return;let Q=this.active.message.messageId;this.clearRetryTimer(),this.active=null,this.options.onAckedUserMessage?.(Q),this.pump()}reset(){this.clearRetryTimer(),this.queue.length=0,this.active=null}pump(A){if(this.active){if(!this.active.sent||A?.forceActiveRetry)this.tryActive();return}let Q=this.queue.shift();if(!Q)return;this.active=Q,this.tryActive()}tryActive(){let A=this.active;if(!A||A.sent&&A.message.type!=="client_append_user_msg")return;if(!this.options.trySend(A.message)){this.scheduleRetry();return}if(A.sent=!0,A.message.type!=="client_append_user_msg"){this.clearRetryTimer(),this.active=null,this.pump();return}this.scheduleRetry()}scheduleRetry(){if(this.retryTimer!==null)return;this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.pump({forceActiveRetry:!0})},1000),$W5(this.retryTimer)}clearRetryTimer(){if(this.retryTimer===null)return;clearTimeout(this.retryTimer),this.retryTimer=null}}function $W5(A){if(typeof A!=="object"||A===null||!("unref"in A))return;let Q=A.unref;if(typeof Q==="function")Q.call(A)}function JW5(A,Q){switch(Q.type){case"message_added":return Q.message.messageId===A.messageId;case"queued_message_added":return Q.message.queuedMessage.messageId===A.messageId;case"queued_messages":return YW5(Q.messages,A.messageId);default:return!1}}function YW5(A,Q){return A.some((B)=>B.queuedMessage.messageId===Q)}function SD(A){return typeof A==="object"&&A!==null}function RF0(A,Q){return Object.hasOwn(A,Q)}function H5(A,Q){let B=A[Q];return typeof B==="string"?B:void 0}function PF0(A,Q){let B=A[Q];return typeof B==="number"&&Number.isFinite(B)?B:void 0}function Nj(A,Q){let B=A[Q];return typeof B==="boolean"?B:void 0}function $o(A,Q){let B=A[Q];return SD(B)?B:void 0}function iY(A,Q){let B=A[Q];return Array.isArray(B)?B:void 0}function t4(A,Q,B){if(B!==void 0)A[Q]=B}function At0(A){return A?.map((Q)=>Q.type)}function Qt0(A){let Q=A?.flatMap((B)=>B.blockState?[B.blockState]:[]);return Q&&Q.length>0?Q:void 0}function ZW5(A){return A?.some((Q)=>ey4(Q.blockState))??!1}function ey4(A){return A==="start"||A==="complete"}function Ax4(A){return A.flatMap((Q)=>{if(!SD(Q))return[];let B=H5(Q,"type");return B?[B]:[]})}function Qx4(A){let Q=A.flatMap((B)=>{if(!SD(B))return[];let $=H5(B,"blockState");return $?[$]:[]});return Q.length>0?Q:void 0}function FW5(A){return A?.some((Q)=>{if(!SD(Q))return!1;return ey4(H5(Q,"blockState"))})??!1}function XW5(A,Q){if(!Array.isArray(Q))return;A.blockCount=Q.length,A.blockTypes=Ax4(Q),t4(A,"blockStates",Qx4(Q))}function _F0(A,Q){let B={type:A};return t4(B,"direction",Q.direction),t4(B,"clientID",Q.clientID),t4(B,"frameMessageCount",Q.frameMessageCount),t4(B,"frameMessageIndex",Q.frameMessageIndex),t4(B,"frameLength",Q.frameLength),B}function Bx4(A,Q){t4(A,"seq",PF0(Q,"seq")),t4(A,"messageId",H5(Q,"messageId")),t4(A,"toolCallId",H5(Q,"toolCallId")),t4(A,"parentToolCallId",H5(Q,"parentToolCallId")),t4(A,"requestId",H5(Q,"requestId")),t4(A,"queuedMessageId",H5(Q,"queuedMessageId")),t4(A,"editId",H5(Q,"editId")),t4(A,"threadId",H5(Q,"threadId")),t4(A,"threadID",H5(Q,"threadID"))}function DW5(A,Q){Bx4(A,Q)}function GW5(A,Q){if(A.messageId=Q.messageId,A.role=Q.role,A.blockCount=Q.content.length,A.blockTypes=At0(Q.content),t4(A,"blockStates",Qt0(Q.content)),Q.role==="assistant")t4(A,"messageState",Q.state?.type),A.hasUsage=Q.usage!==void 0}function VW5(A,Q){if(A.subtype=`${Q.role}.${Q.state}`,A.role=Q.role,A.deltaState=Q.state,A.blockCount=Q.blocks?.length??0,t4(A,"blockTypes",At0(Q.blocks)),t4(A,"blockStates",Qt0(Q.blocks)),A.hasUsage=Q.role==="assistant"&&Q.usage!==void 0,Q.role==="assistant"&&Q.blockIndex!==void 0)A.blockIndex=Q.blockIndex}function $x4(A,Q){if(!SD(Q)){if(Q!==void 0)A.hasProgress=!0;return}let B=H5(Q,"type"),$=H5(Q,"state");if(t4(A,"progressType",B),t4(A,"progressState",$),B)A.subtype=$?`${B}.${$}`:B;let J=iY(Q,"blocks");if(J)A.progressBlockCount=J.length,A.progressBlockTypes=Ax4(J),t4(A,"progressBlockStates",Qx4(J));if(RF0(Q,"value"))A.hasProgressValue=!0}function Jx4(A,Q){if(!SD(Q))return;let B=H5(Q,"type");t4(A,"subtype",B),t4(A,"rpcType",B),t4(A,"rpcMethod",H5(Q,"method"))}function ty4(A,Q){if(!SD(Q))return;t4(A,"runStatus",H5(Q,"status")),A.hasRunProgress=RF0(Q,"progress"),A.hasRunResult=RF0(Q,"result"),A.hasRunError=RF0(Q,"error");let B=iY(Q,"trackFiles");if(B)A.trackFileCount=B.length}function UW5(A,Q){let B=iY(Q,"files");if(B)A.fileCount=B.length;t4(A,"fileCount",PF0(Q,"fileCount"));let $=iY(Q,"withContent");if($)A.withContentCount=$.length;let J=iY(Q,"contentOmitted");if(J)A.contentOmittedCount=J.length}function KW5(A,Q){t4(A,"ok",Nj(Q,"ok"));let B=iY(Q,"entries");if(B)A.entryCount=B.length;let $=H5(Q,"contentBase64");if($!==void 0)A.contentBase64Length=$.length;let J=$o(Q,"error");t4(A,"errorCode",J?H5(J,"code"):void 0)}function EW5(A,Q){switch(A.type){case"executor_connect":{t4(A,"clientId",H5(Q,"clientId")),t4(A,"executorType",H5(Q,"executorType"));let B=$o(Q,"capabilities");if(B)A.capabilityCount=Object.keys(B).length;return}case"client_update_thread_settings":A.settingsCount=Object.keys($o(Q,"settings")??{}).length;return;case"executor_tools_register":A.toolCount=iY(Q,"tools")?.length??0;return;case"executor_tools_unregister":A.toolCount=iY(Q,"toolNames")?.length??0;return;case"executor_tools_bootstrap_complete":t4(A,"ok",Nj(Q,"ok")),A.hasError=H5(Q,"error")!==void 0;return;case"tool_progress":$x4(A,Q.progress);return;case"executor_tool_result":ty4(A,Q.run);return;case"executor_guidance_snapshot":case"executor_guidance_discovery":UW5(A,Q),t4(A,"snapshotId",H5(Q,"snapshotId")),t4(A,"isLast",Nj(Q,"isLast"));return;case"executor_skill_snapshot":t4(A,"snapshotId",H5(Q,"snapshotId")),A.skillCount=iY(Q,"skills")?.length??0,A.errorCount=iY(Q,"errors")?.length??0,t4(A,"isLast",Nj(Q,"isLast"));return;case"executor_environment_snapshot":case"executor_environment_update":A.hasEnvironment=SD(Q.environment);return;case"executor_artifact_upsert":{let B=$o(Q,"artifact");t4(A,"artifactKey",B&&H5(B,"key")),t4(A,"artifactDataType",B&&H5(B,"dataType"));return}case"executor_artifact_delete":t4(A,"artifactKey",H5(Q,"key"));return;case"executor_plugin_message":Jx4(A,Q.message);return;case"client_append_user_msg":case"client_edit_message":XW5(A,Q.content),t4(A,"agentMode",H5(Q,"agentMode")),t4(A,"reasoningEffort",H5(Q,"reasoningEffort")),t4(A,"steer",Nj(Q,"steer"));return;case"client_set_thread_title":t4(A,"titleLength",H5(Q,"title")?.length);return;case"executor_filesystem_read_directory_result":case"executor_filesystem_read_file_result":KW5(A,Q);return;case"client_resume":t4(A,"version",PF0(Q,"version"));return;case"client_dismiss_active_error":t4(A,"seq",PF0(Q,"seq"));return;case"client_append_manual_bash_invocation":A.argCount=iY($o(Q,"args")??{},"args")?.length??0,t4(A,"hidden",Nj(Q,"hidden")),ty4(A,Q.run);return;case"client_tool_approval_response":t4(A,"accepted",Nj(Q,"accepted")),A.hasInput=SD(Q.input);return;case"client_spawn_executor":A.additionalRepositoryCount=iY(Q,"additionalRepositories")?.length??0,A.hasRepositoryURL=H5(Q,"repositoryURL")!==void 0,A.hasProjectID=H5(Q,"projectID")!==void 0;return;case"executor_tool_lease_ack":case"executor_tool_approval_request":case"client_remove_queued_msg":case"client_steer_queued_msg":case"client_mark_message_read":case"client_mark_message_unread":case"client_upsert_notification_subscription":case"client_filesystem_read_directory":case"client_filesystem_read_file":case"client_retry":case"client_cancel":return}}function zW5(A,Q){switch(Q.type){case"agent_state":A.subtype=Q.state,t4(A,"agentMode",Q.agentMode),t4(A,"reasoningEffort",Q.reasoningEffort);return;case"inference_tools":t4(A,"agentMode",Q.agentMode),A.toolCount=Q.tools.length;return;case"error":t4(A,"subtype",Q.code);return;case"error_set":t4(A,"subtype",Q.error.code),t4(A,"retryAt",Q.error.retryAt),t4(A,"attempt",Q.error.attempt);return;case"retry_scheduled":A.attempt=Q.attempt,A.maxAttempts=Q.maxAttempts,A.retryAt=Q.retryAt;return;case"executor_connected":A.executorId=Q.executorId,A.registeredToolCount=Q.registeredToolCount,A.guidanceInventoryCount=Q.guidanceInventory.length,A.rejectedToolCount=Q.rejectedTools?.length??0,A.resumeBootstrap=Q.resumeBootstrap===!0;return;case"tool_lease":A.subtype=Q.toolName,A.toolName=Q.toolName;return;case"client_filesystem_read_directory_result":case"client_filesystem_read_file_result":t4(A,"subtype",Q.ok?"ok":Q.error?.code),A.ok=Q.ok,t4(A,"errorCode",Q.error?.code);return;case"tool_approval_queue":A.approvalCount=Q.approvals.length;return;case"executor_tool_lease_revoked":A.subtype=Q.reason;return;case"plugin_message":Jx4(A,Q.message);return;case"executor_tool_approval_response":A.subtype=Q.accepted?"accepted":"rejected",A.accepted=Q.accepted;return;case"tool_progress":$x4(A,Q.progress);return;case"executor_error":A.subtype=Q.code;return;case"delta":VW5(A,Q);return;case"queued_messages":A.queuedMessageCount=Q.messages.length;return;case"queued_message_added":A.seq=Q.seq,A.messageId=Q.message.queuedMessage.messageId,A.blockCount=Q.message.queuedMessage.content.length,A.blockTypes=At0(Q.message.queuedMessage.content),t4(A,"blockStates",Qt0(Q.message.queuedMessage.content));return;case"queued_message_removed":case"queued_message_dequeued":A.messageId=Q.queuedMessageId;return;case"message_added":case"message_updated":GW5(A,Q.message);return;case"thread_truncated":A.truncateFromMessage=Q.truncateFromMessage;return;case"observers":A.observerCount=Q.count,A.hasExecutor=Q.hasExecutor===!0;return;case"executor_status":A.subtype=Q.status,t4(A,"executorId",Q.executorId),t4(A,"spawnId",Q.spawnId);return;case"artifacts_snapshot":A.artifactCount=Q.artifacts.length;return;case"artifact_upserted":A.subtype=Q.artifact.dataType,A.artifactDataType=Q.artifact.dataType,t4(A,"toolCallId",Q.artifact.toolCallId);return;case"thread_relationships":A.relationshipCount=Q.relationships.length;return;case"compaction_complete":A.cutMessageId=Q.cutMessageId;return;case"compaction_records":A.recordCount=Q.records.length;return;case"cancelled":case"thread_settings":case"error_cleared":case"retry_started":case"retry_cancelled":case"executor_filesystem_read_directory":case"executor_filesystem_read_file":case"executor_tool_result_ack":case"environment_update":case"artifact_deleted":case"thread_title":case"thread_status":case"compaction_started":case"edit_rejected":return}}function WW5(A){if(!SD(A))return!1;if(H5(A,"type")!=="delta")return!1;if(H5(A,"state")!=="generating")return!1;return!FW5(iY(A,"blocks"))}function TF0(A,Q={}){let B=_F0(A.type,Q);return DW5(B,A),zW5(B,A),B}function Bt0(A,Q={}){if(!SD(A)){let $=_F0("unknown",Q);return $.messageKind=typeof A,$}let B=_F0(H5(A,"type")??"unknown",Q);return Bx4(B,A),EW5(B,A),B}function Yx4(A){return _F0("decode_failed",{direction:"receive",frameMessageCount:0,frameMessageIndex:0,frameLength:A})}function kF0(A){if(A.type==="delta")return A.state!=="generating"||ZW5(A.blocks);if(A.type==="tool_progress")return!WW5(A.progress);return!0}function $t0(A,Q,B){if(!kF0(Q))return;A.info("[thread-client] Received server message",TF0(Q,{direction:"receive",...B}))}function Jt0(A,Q){A.info("[thread-client] Failed to decode received server message",Yx4(Q))}var HW5=3000,qW5=30000,NW5=5;function Zx4(A){if(A instanceof J9)return A;if(A instanceof Error){let Q=A.message||"Unknown thread-client connection error";return new J9(Q,A)}if(typeof A==="string"&&A.length>0)return new J9(A,A);return new J9("Unknown thread-client connection error",A)}function IW5(A){let Q=atob(A),B=new Uint8Array(Q.length);for(let $=0;$<Q.length;$++)B[$]=Q.charCodeAt($);return B}function wW5(A){return{type:"error",message:`Failed to send user message: ${A}`,code:"MESSAGE_ERROR"}}class PU extends as0{ensureConnectedPromise=null;pendingReadDirectoryRequests=new Map;pendingReadFileRequests=new Map;pendingThreadSettings=null;outbox;optimisticUserMessages;pendingCancelAgentLoop=!1;pendingDismissActiveError=null;fileSystemRequestCounter=0;wasConnectionReady=!1;observerCallbacks=null;executorCallbacks=null;pendingObserverDispatches=[];pendingExecutorDispatches=[];resumeCursor=ds0(0);threadHistoryLoader;executorConnectedListeners=new Set;executorErrorListeners=new Set;environmentSubject=new A4(null);threadIDSubscription;constructor(A){super(A.transport);if(this.threadHistoryLoader=A.threadHistoryLoader,this.outbox=new es0({trySend:(Q)=>this.trySendOutboxMessage(Q),onAckedUserMessage:(Q)=>{this.dispatchObserverCallbacks((B)=>{B.onUserMessageSendAck?.(Q)})}}),this.optimisticUserMessages=new ts0({getThreadID:()=>this.getThreadId(),observerCallbacks:(Q)=>this.dispatchObserverCallbacks(Q)}),this.threadIDSubscription=this.threadIDSubject.subscribe((Q)=>{if(Q!==null)this.dispatchObserverCallbacks((B)=>{B.onThreadId?.(Q)})}),A.observerCallbacks)this.setObserverCallbacks(A.observerCallbacks);if(A.executorCallbacks)this.setExecutorCallbacks(A.executorCallbacks)}setObserverCallbacks(A){if(this.observerCallbacks&&this.observerCallbacks!==A)throw Error("Observer callbacks are already set and cannot be replaced");if(this.observerCallbacks===A)return;if(this.observerCallbacks=A,this.pendingObserverDispatches.length===0)return;for(let Q of this.pendingObserverDispatches)Q(A);this.pendingObserverDispatches.length=0}setExecutorCallbacks(A){if(this.executorCallbacks&&this.executorCallbacks!==A)throw Error("Executor callbacks are already set and cannot be replaced");if(this.executorCallbacks===A)return;if(this.executorCallbacks=A,this.pendingExecutorDispatches.length===0)return;for(let Q of this.pendingExecutorDispatches)Q(A);this.pendingExecutorDispatches.length=0}async connect(){try{await super.connect()}catch(A){throw Zx4(A)}}async reconnect(){await this.disconnectAndWait(),await this.connect()}async ensureConnected(A){if(this.ensureConnectedPromise)return this.ensureConnectedPromise;this.ensureConnectedPromise=this.ensureConnectedInternal(A);try{return await this.ensureConnectedPromise}finally{this.ensureConnectedPromise=null}}async ensureConnectedInternal(A){let Q=A?.baseDelayMs??HW5,B=A?.maxDelayMs??qW5,$=A?.maxAttempts??NW5;if(A?.forceReconnectWhenReconnecting&&this.getConnectionInfo().state==="reconnecting")this.disconnect();for(let J=0;J<$;J++){try{await this.connect()}catch(X){let D=Zx4(X);if(this.getConnectionInfo().state!=="reconnecting")throw D;A?.onRetryableConnectError?.(D)}let Y=A?.waitForConnectedTimeoutMs??Math.min(Q*2**J,B);if(await this.waitForConnected(Y))return!0;let F=J+1<$?Math.min(Q*2**(J+1),B):null;A?.onAttemptTimeout?.({attempt:J+1,maxAttempts:$,nextDelayMs:F})}return!1}async loadThreadHistory(A){let Q=await this.threadHistoryLoader(A);if(!Q)return null;let B=Q.title;if(B!==void 0)this.dispatchObserverCallbacks(($)=>{$.onThreadTitle?.({type:"thread_title",title:B})});for(let[$,J]of Q.messages.entries())this.dispatchObserverCallbacks((Y)=>{let Z={type:"message_added",message:J,seq:$},F=l3.safeParse(J.parentToolUseId);if(F.success)Z.parentToolUseId=F.data;Y.onMessageAdded?.(Z)});return Q}getResumeVersion(){return this.resumeCursor.getVersion()}sendUserMessage(A,Q,B){let $=B?.messageId??qF0(),J={type:"client_append_user_msg",content:$J(A),agentMode:Q,reasoningEffort:B?.reasoningEffort,messageId:$,steer:B?.steer,userState:B?.userState};return this.dispatchObserverCallbacks((Y)=>{Y.onUserMessageSendPending?.($,Date.now())}),this.optimisticUserMessages.emitOptimisticUserMessage(J),this.outbox.send(J),this.retryConnectIfTerminallyDisconnected("user message sent"),$}retryConnectIfTerminallyDisconnected(A){if(this.getConnectionInfo().state!=="disconnected")return;this.retryConnect(A)}removeQueuedMessage(A){this.dispatchObserverCallbacks((Q)=>{Q.onUserActionMessageDeliveryStatusChanged?.(A,"buffered",Date.now())}),this.outbox.send({type:"client_remove_queued_msg",queuedMessageId:A}),this.retryConnectIfTerminallyDisconnected("queued message remove requested")}steerQueuedMessage(A){this.outbox.send({type:"client_steer_queued_msg",queuedMessageId:A}),this.retryConnectIfTerminallyDisconnected("queued message steer requested")}editUserMessage(A,Q,B,$,J){this.outbox.send({type:"client_edit_message",messageId:A,editId:B,content:$J(Q),agentMode:$,reasoningEffort:J?.reasoningEffort}),this.retryConnectIfTerminallyDisconnected("user message edit requested")}markMessageRead(A){this.send({type:"client_mark_message_read",messageId:A})}markMessageUnread(A){this.send({type:"client_mark_message_unread",messageId:A})}setThreadTitle(A){this.send({type:"client_set_thread_title",title:A})}upsertNotificationSubscription(A,Q){this.send({type:"client_upsert_notification_subscription",subscription:A,threadURL:Q})}readDirectory(A){return this.requestReadDirectory(A)}readFile(A){return this.requestReadFile(A)}resumeFromVersion(A){this.send({type:"client_resume",version:A}),this.resumeCursor.reset(A)}retryAgentLoop(){this.send({type:"client_retry"})}dismissActiveError(A){let Q=A===void 0?{}:{seq:A};if(!this.canSendClientMessage()){this.pendingDismissActiveError=Q;return}this.pendingDismissActiveError=null,this.send({type:"client_dismiss_active_error",...Q})}cancelAgentLoop(){if(!this.canSendClientMessage()){this.pendingCancelAgentLoop=!0,this.retryConnectIfTerminallyDisconnected("agent loop cancel requested");return}this.pendingCancelAgentLoop=!1,this.send({type:"client_cancel"})}appendManualBashInvocation(A){this.send({type:"client_append_manual_bash_invocation",args:$J(A.args),run:$J(A.run),hidden:A.hidden})}resolveToolApproval(A,Q,B){this.send({type:"client_tool_approval_response",toolCallId:A,accepted:Q,input:B})}requestExecutorSpawn(A,Q){this.send({type:"client_spawn_executor",requestId:A,repositoryURL:Q?.repositoryURL,projectID:Q?.projectID,additionalRepositories:Q?.additionalRepositories})}executePluginCommand(A,Q,B,$){this.sendPluginMessage({type:"request",id:A,method:"command.execute",params:{pluginName:Q,commandId:B,threadID:$}})}executorHandshake(A,Q,B){if(this.disposed)throw new c3("Transport is disposed");if(!this.hasOpenSocket()){if(this.getConnectionInfo().state==="connected")this.forceReconnect("executor handshake attempted without open socket");throw new c3("WebSocket is not connected. Call connect() first.")}let $=performance.now(),J=60000,Y={clientId:A,executorType:B?.executorType,timeoutMs:J};return this.log.info("[thread-client] Starting executor handshake",{...Y,connectionState:this.getConnectionInfo().state}),new Promise((Z,F)=>{let X=!1,D=null,G=null,V=()=>Math.round(performance.now()-$),U=(W,H,q)=>{let N=this.getConnectionInfo();this.log.error(W,{...Y,durationMs:V(),connectionState:N.state,role:N.role,reconnectCauseType:N.reconnectCause?.type,reconnectCode:N.reconnectCause?.code,reconnectReason:N.reconnectCause?.reason,error:H,...q})},K=(W)=>{this.log.info("[thread-client] Executor handshake completed",{...Y,durationMs:V(),executorId:W.executorId,registeredToolCount:W.registeredToolCount,resumeBootstrap:W.resumeBootstrap}),z(()=>Z(W))},E=(W)=>{let H=Error(W.message);U("[thread-client] Executor handshake rejected by server",H,{code:W.code}),z(()=>F(H))},z=(W)=>{if(X)return;if(X=!0,D)clearTimeout(D),D=null;this.executorConnectedListeners.delete(K),this.executorErrorListeners.delete(E),G?.unsubscribe(),W()};this.executorConnectedListeners.add(K),this.executorErrorListeners.add(E),G=this.connectionChanges().subscribe({next:(W)=>{if(W.state==="connected")return;let H=new c3(W.state==="reconnecting"?"Executor handshake interrupted by reconnect":"Executor handshake interrupted by disconnect");U("[thread-client] Executor handshake interrupted",H),z(()=>F(H))}}),this.send({type:"executor_connect",clientId:A,capabilities:Q,executorType:B?.executorType}),D=setTimeout(()=>{let W=Error("Executor connect timeout");U("[thread-client] Executor handshake timed out",W),z(()=>F(W))},J)})}ackToolLease(A){this.send({type:"executor_tool_lease_ack",toolCallId:A})}sendToolProgress(A,Q){let B=Ex(Q,"snapshot");this.send({type:"tool_progress",toolCallId:A,progress:B})}sendExecutorToolResult(A,Q){this.send({type:"executor_tool_result",toolCallId:A,run:Q})}sendExecutorFileSystemReadDirectoryResult(A,Q){this.send({type:"executor_filesystem_read_directory_result",requestId:A,...Q})}sendExecutorFileSystemReadFileResult(A,Q){this.send({type:"executor_filesystem_read_file_result",requestId:A,...Q})}sendExecutorToolApprovalRequest(A){this.send({type:"executor_tool_approval_request",approval:A})}sendPluginMessage(A){this.send({type:"executor_plugin_message",message:A})}sendExecutorGuidanceSnapshot(A){this.send({type:"executor_guidance_snapshot",...A})}sendExecutorGuidanceDiscovery(A){this.send({type:"executor_guidance_discovery",...A})}sendExecutorSkillSnapshot(A){this.send({type:"executor_skill_snapshot",...A})}sendClientUpdateThreadSettings(A){if(!this.canSendClientMessage()){this.pendingThreadSettings=A;return}try{this.pendingThreadSettings=null,this.send({type:"client_update_thread_settings",settings:A})}catch(Q){if(!this.canSendClientMessage()){this.pendingThreadSettings=A;return}throw Q}}registerTools(A){this.send({type:"executor_tools_register",tools:A})}sendExecutorToolsBootstrapComplete(A,Q){this.send({type:"executor_tools_bootstrap_complete",ok:A,error:Q})}sendEnvironmentSnapshot(A){this.send({type:"executor_environment_snapshot",environment:A}),this.environmentSubject.next(A)}sendEnvironmentUpdate(A){this.send({type:"executor_environment_update",environment:A}),this.environmentSubject.next(A)}environmentChanges(){return this.environmentSubject}getEnvironmentSnapshot(){return this.environmentSubject.getValue()}sendExecutorArtifactUpsert(A,Q){this.send({type:"executor_artifact_upsert",artifact:A,toolCallId:Q})}sendExecutorArtifactDelete(A){this.send({type:"executor_artifact_delete",key:A})}unregisterTools(A){this.send({type:"executor_tools_unregister",toolNames:A})}dispose(){if(this.disposed)return;super.dispose(),this.threadIDSubscription.unsubscribe(),this.pendingThreadSettings=null,this.outbox.reset(),this.optimisticUserMessages.reset(),this.pendingCancelAgentLoop=!1,this.pendingDismissActiveError=null,this.pendingObserverDispatches.length=0,this.pendingExecutorDispatches.length=0,this.resumeCursor=ds0(0),this.wasConnectionReady=!1,this.environmentSubject.complete(),this.rejectPendingFileSystemRequests("Transport disposed")}updateConnectionState(A){if(super.updateConnectionState(A),this.flushPendingReadyWork(),this.emitConnectionChanged(),A==="reconnecting"||A==="disconnected")this.rejectPendingFileSystemRequests("Connection closed before filesystem request completed")}onRawMessage(A){let Q=ay4(A);if(Q.length===0){Jt0(this.log,A.length);return}for(let[B,$]of Q.entries())$t0(this.log,$,{frameMessageCount:Q.length,frameMessageIndex:B,frameLength:A.length}),this.handleServerMessage($)}onWebSocketTraffic(A){if(this.connectionInfo.requiredRole!=="observer"||this.connectionInfo.role!==null)return;this.connectionInfo.role="observer",this.connectionSubject.next({...this.connectionInfo}),this.flushPendingReadyWork(),this.emitConnectionChanged()}onMaxReconnectExceeded(A){this.dispatchObserverCallbacks((Q)=>{Q.onErrorNotice?.({type:"error",message:`Failed to reconnect after ${A} attempts`,code:"MAX_RECONNECT_EXCEEDED"})})}handleServerMessage(A){switch(this.advanceResumeCursor(A),this.reconcileOptimisticUserMessage(A),this.outbox.handleServerMessage(A),A.type){case"agent_state":this.dispatchObserverCallbacks((Q)=>{Q.onAgentState?.(A)});break;case"inference_tools":this.dispatchObserverCallbacks((Q)=>{Q.onInferenceTools?.(A)});break;case"thread_settings":this.dispatchObserverCallbacks((Q)=>{Q.onThreadSettings?.(A)});break;case"error":this.dispatchObserverCallbacks((Q)=>{Q.onErrorNotice?.(A)});break;case"error_set":case"error_cleared":this.dispatchObserverCallbacks((Q)=>{Q.onActiveError?.(A)});break;case"cancelled":this.dispatchObserverCallbacks((Q)=>{Q.onCancelled?.(A)});break;case"retry_scheduled":case"retry_started":case"retry_cancelled":this.dispatchObserverCallbacks((Q)=>{Q.onRetryEvent?.(A)});break;case"delta":this.dispatchObserverCallbacks((Q)=>{Q.onDelta?.(A)});break;case"message_updated":this.dispatchObserverCallbacks((Q)=>{Q.onMessageUpdated?.(A)});break;case"edit_rejected":this.dispatchObserverCallbacks((Q)=>{Q.onEditRejected?.(A)});break;case"executor_connected":this.connectionInfo.role="executor",this.connectionInfo.clientId=A.executorId,this.connectionSubject.next({...this.connectionInfo}),this.flushPendingReadyWork(),this.emitConnectionChanged(),this.dispatchObserverCallbacks((Q)=>{Q.onExecutorConnected?.(A)});for(let Q of this.executorConnectedListeners)Q(A);break;case"tool_lease":this.dispatchExecutorCallbacks((Q)=>{Q.onToolLease?.(A)});break;case"executor_filesystem_read_directory":this.dispatchExecutorCallbacks((Q)=>{Q.onFileSystemReadDirectoryRequest?.(A)});break;case"executor_filesystem_read_file":this.dispatchExecutorCallbacks((Q)=>{Q.onFileSystemReadFileRequest?.(A)});break;case"executor_tool_lease_revoked":this.dispatchExecutorCallbacks((Q)=>{Q.onToolLeaseRevoked?.(A)});break;case"executor_tool_result_ack":this.dispatchExecutorCallbacks((Q)=>{Q.onExecutorToolResultAck?.(A)});break;case"tool_approval_queue":this.dispatchObserverCallbacks((Q)=>{Q.onToolApprovalQueue?.(A)});break;case"plugin_message":this.dispatchObserverCallbacks((Q)=>{Q.onPluginMessage?.(A)}),this.dispatchExecutorCallbacks((Q)=>{Q.onPluginMessage?.(A)});break;case"executor_tool_approval_response":this.dispatchObserverCallbacks((Q)=>{Q.onExecutorToolApprovalResponse?.(A)});break;case"tool_progress":this.dispatchObserverCallbacks((Q)=>{Q.onToolProgress?.(A)});break;case"executor_error":this.dispatchObserverCallbacks((Q)=>{Q.onExecutorError?.(A)}),this.dispatchExecutorCallbacks((Q)=>{Q.onExecutorError?.(A)});for(let Q of this.executorErrorListeners)Q(A);break;case"observers":this.dispatchObserverCallbacks((Q)=>{Q.onObservers?.(A)});break;case"executor_status":this.dispatchObserverCallbacks((Q)=>{Q.onExecutorStatus?.(A)});break;case"environment_update":this.environmentSubject.next(A.environment),this.dispatchObserverCallbacks((Q)=>{Q.onEnvironmentUpdate?.(A)});break;case"artifacts_snapshot":case"artifact_upserted":case"artifact_deleted":this.dispatchObserverCallbacks((Q)=>{Q.onArtifactEvent?.(A)});break;case"thread_title":this.dispatchObserverCallbacks((Q)=>{Q.onThreadTitle?.(A)});break;case"thread_relationships":this.dispatchObserverCallbacks((Q)=>{Q.onThreadRelationships?.(A)});break;case"thread_truncated":this.dispatchObserverCallbacks((Q)=>{Q.onTruncate?.(A)});break;case"client_filesystem_read_directory_result":this.handleReadDirectoryResult(A);break;case"client_filesystem_read_file_result":this.handleReadFileResult(A);break;case"compaction_started":case"compaction_complete":case"compaction_records":this.dispatchObserverCallbacks((Q)=>{Q.onCompactionEvent?.(A)});break;case"thread_status":break}}flushPendingReadyWork(){if(!T9(this.connectionInfo)){this.wasConnectionReady=!1;return}if(this.wasConnectionReady)return;this.wasConnectionReady=!0,this.flushPendingThreadSettings(),this.outbox.retry(),this.flushPendingCancelAgentLoop(),this.flushPendingDismissActiveError()}flushPendingThreadSettings(){if(!this.pendingThreadSettings||!this.canSendClientMessage())return;let A=this.pendingThreadSettings;try{this.pendingThreadSettings=null,this.send({type:"client_update_thread_settings",settings:A})}catch{if(!this.canSendClientMessage())this.pendingThreadSettings=A}}flushPendingCancelAgentLoop(){if(!this.pendingCancelAgentLoop||!this.canSendClientMessage())return;try{this.send({type:"client_cancel"}),this.pendingCancelAgentLoop=!1}catch{if(this.canSendClientMessage())this.pendingCancelAgentLoop=!1}}flushPendingDismissActiveError(){if(!this.pendingDismissActiveError||!this.canSendClientMessage())return;try{this.send({type:"client_dismiss_active_error",...this.pendingDismissActiveError}),this.pendingDismissActiveError=null}catch{if(this.canSendClientMessage())this.pendingDismissActiveError=null}}reconcileOptimisticUserMessage(A){switch(A.type){case"agent_state":this.optimisticUserMessages.setAgentLoopState(A.state);return;case"message_added":this.optimisticUserMessages.reconcileMessageAdded(A);return;case"queued_messages":this.optimisticUserMessages.reconcileQueuedMessagesSnapshot(A);return;case"queued_message_added":this.optimisticUserMessages.reconcileQueuedMessageAdded(A);return;case"queued_message_dequeued":this.optimisticUserMessages.reconcileQueuedMessageRemoved(A);return;case"queued_message_removed":this.optimisticUserMessages.reconcileQueuedMessageRemoved(A);return;default:return}}trySendOutboxMessage(A){if(!this.canSendClientMessage())return!1;try{return this.send(A),!0}catch(Q){let B=Q instanceof Error?Q.message:String(Q);return this.dispatchObserverCallbacks(($)=>{$.onErrorNotice?.(wW5(B))}),!1}}canSendClientMessage(){return this.hasOpenSocket()&&T9(this.connectionInfo)}emitConnectionChanged(){let A=this.getConnectionInfo();this.log.info("[thread-client] Emitting connection change callbacks",{state:A.state,role:A.role,clientId:A.clientId,reconnectCauseType:A.reconnectCause?.type,reconnectCode:A.reconnectCause?.code,reconnectReason:A.reconnectCause?.reason,hasExecutorCallbacks:this.executorCallbacks!==null,hasObserverCallbacks:this.observerCallbacks!==null,pendingExecutorDispatches:this.pendingExecutorDispatches.length,pendingObserverDispatches:this.pendingObserverDispatches.length}),this.dispatchExecutorCallbacks((Q)=>{Q.onConnectionChange?.(A)}),this.dispatchObserverCallbacks((Q)=>{Q.onConnectionChanged?.(A)})}dispatchObserverCallbacks(A){let Q=this.observerCallbacks;if(!Q){this.pendingObserverDispatches.push(A);return}A(Q)}dispatchExecutorCallbacks(A){let Q=this.executorCallbacks;if(!Q){this.pendingExecutorDispatches.push(A);return}A(Q)}requestReadDirectory(A){let Q=this.nextFileSystemRequestID("read-directory");return this.createPendingReadRequest(this.pendingReadDirectoryRequests,Q,()=>{this.send({type:"client_filesystem_read_directory",requestId:Q,uri:A})})}requestReadFile(A){let Q=this.nextFileSystemRequestID("read-file");return this.createPendingReadRequest(this.pendingReadFileRequests,Q,()=>{this.send({type:"client_filesystem_read_file",requestId:Q,uri:A})})}createPendingReadRequest(A,Q,B){if(!this.hasOpenSocket())return Promise.reject(new c3("WebSocket is not connected"));return new Promise(($,J)=>{let Y=setTimeout(()=>{A.delete(Q),J(new c3(`Filesystem request timed out: ${Q}`))},qy4);A.set(Q,{resolve:$,reject:J,timeoutID:Y});try{B()}catch(Z){clearTimeout(Y),A.delete(Q),J(Z instanceof Error?Z:Error(String(Z)))}})}nextFileSystemRequestID(A){let Q=this.fileSystemRequestCounter++;return`${A}-${Date.now()}-${Q}`}handleReadDirectoryResult(A){let Q=this.pendingReadDirectoryRequests.get(A.requestId);if(!Q)return;if(clearTimeout(Q.timeoutID),this.pendingReadDirectoryRequests.delete(A.requestId),A.ok&&A.entries){Q.resolve(A.entries);return}if(A.ok){Q.reject(Error("Invalid filesystem read_directory response: missing entries"));return}if(!A.error){Q.reject(Error("Invalid filesystem read_directory response: missing error"));return}Q.reject(this.createFileSystemError(A.error))}handleReadFileResult(A){let Q=this.pendingReadFileRequests.get(A.requestId);if(!Q)return;if(clearTimeout(Q.timeoutID),this.pendingReadFileRequests.delete(A.requestId),!A.ok&&A.error){Q.reject(this.createFileSystemError(A.error));return}if(!A.ok){Q.reject(Error("Invalid filesystem read_file response: missing error"));return}if(A.contentBase64===void 0){Q.reject(Error("Invalid filesystem read_file response: missing content"));return}try{Q.resolve(IW5(A.contentBase64))}catch{Q.reject(Error("Invalid base64 payload in filesystem read_file response"))}}createFileSystemError(A){return Error(`Filesystem error (${A.code}): ${A.message}`)}rejectPendingFileSystemRequests(A){for(let[Q,B]of this.pendingReadDirectoryRequests)clearTimeout(B.timeoutID),B.reject(new c3(A)),this.pendingReadDirectoryRequests.delete(Q);for(let[Q,B]of this.pendingReadFileRequests)clearTimeout(B.timeoutID),B.reject(new c3(A)),this.pendingReadFileRequests.delete(Q)}advanceResumeCursor(A){if(!("seq"in A)||!Number.isFinite(A.seq))return;this.resumeCursor.advanceFromSeq(A.seq)}send(A){try{this.sendRaw(_y4.encode(A))}catch(Q){let B=Q instanceof Error?Q.message:String(Q);throw new c3(`Failed to encode thread-protocol message "${A.type}": ${B}`,Q)}}}M1();function Yt0(A){return{...A,pendingRemoval:!0}}function Fx4(A,Q){if(Q.find(($)=>$.queuedMessage.messageId===A.queuedMessage.messageId)?.pendingRemoval!==!0)return A;return Yt0(A)}function Xx4(A,Q,B){if(Q.type==="queued_messages")return Q.messages.map(($)=>Fx4($,A));if(Q.type==="queued_message_added"){if(A.find((J)=>J.queuedMessage.messageId===Q.message.queuedMessage.messageId)&&B.dedupeAdded)return[...A];return[...A,Fx4(Q.message,A)]}if(!A.some(($)=>$.queuedMessage.messageId===Q.queuedMessageId))return[...A];return A.filter(($)=>$.queuedMessage.messageId!==Q.queuedMessageId)}function Dx4(A){if(A.connectionState==="disconnected")return"disconnected";if(A.compactionState==="compacting")return"compacting";if(A.connectionState!=="connected")return"connecting";if(!A.connectionReady)return"preparing_thread";switch(A.agentLoopState){case"awaiting_approval":return"awaiting_approval";case"tool_use":case"running_tools":return"running_tools";case"streaming":return A.streamingBlockKind==="text"||A.streamingBlockKind==="tool_use"?"streaming":"thinking";case"working":return"working";case"error":return"error";case"idle":if(A.pendingSend)return"sending";if(A.executorStatus?.status==="starting")return"waiting_for_executor";if(A.expectingAgentLoop)return"working";return"idle"}}function Jo(A){let Q=0;for(let B=0;B<A.length;B++){let $=A.codePointAt(B)??0;if($<128)Q+=1;else if($<2048)Q+=2;else if($<65536)Q+=3;else Q+=4,B++}return Q}function CW5(A){if(A.complete)return Jo(JSON.stringify(A.input));let Q=A.inputPartialJSON?.json;if(typeof Q==="string")return Jo(Q);return Jo(JSON.stringify(A.input))}var Gx4={state:"disconnected",role:null,requiredRole:null,clientId:null},MW5=750;function Vx4(A){return[...A].sort((Q,B)=>Q.key.localeCompare(B.key))}function LW5(A,Q){let B=A.findIndex((J)=>J.key===Q.key);if(B===-1)return Vx4([...A,Q]);let $=[...A];return $[B]=Q,$}function Ux4(A){switch(A.type){case"thinking":case"redacted_thinking":return"thinking";case"text":if(A.hidden===!0)return null;return"text";case"tool_use":case"server_tool_use":return"tool_use"}}function OW5(A,Q){let B=Q;for(let $ of A){let J=Ux4($);if(J===null)continue;if(J==="thinking"&&B!==null)continue;B=J}return B}class SF0{connectionInfo;agentLoopState;pendingSend=new A4(!1);streamingBlockKind=new A4(null);activeStreamingBlockKinds=new Map;expectingAgentLoop=!1;expectingAgentLoopTimer=null;status=new A4("idle");stageBytes=new A4(null);currentStage=null;currentStageBytes=0;toolBlockLatestBytes=new Map;queuedMessages=new A4([]);pendingApprovals=new A4([]);lastError=new A4(null);activeError=new A4(null);cancelledMessageId=new A4(null);retryState=new A4(null);executorError=new A4(null);observers=new A4(null);executorStatus=new A4(null);environment=new A4(null);compactionState=new A4("idle");compactionRecords=new A4([]);artifacts=new A4([]);threadSettings;threadTitle=new A4(void 0);threadId=new A4(null);messageAddedEvents=new m4;messageUpdatedEvents=new m4;deltaEvents=new m4;toolProgressEvents=new m4;truncateEvents=new m4;pluginMessages=new m4;now;dedupeQueuedMessageAdds;compactionRecordsState;constructor(A={}){this.connectionInfo=new A4(A.initialConnectionInfo??Gx4),this.agentLoopState=new A4(A.initialAgentLoopState??"idle"),this.threadSettings=new A4(A.initialThreadSettings??null),this.dedupeQueuedMessageAdds=A.dedupeQueuedMessageAdds??!0,this.compactionRecordsState=A.compactionRecordsState??null,this.now=A.now??(()=>new Date().toISOString()),this.recomputeStatus()}callbacks(){return this}recomputeStatus(){let A=this.connectionInfo.getValue(),Q=Dx4({connectionState:A.state,connectionReady:T9(A),compactionState:this.compactionState.getValue(),pendingSend:this.pendingSend.getValue(),executorStatus:this.executorStatus.getValue(),agentLoopState:this.agentLoopState.getValue(),streamingBlockKind:this.streamingBlockKind.getValue(),expectingAgentLoop:this.expectingAgentLoop});if(Q!==this.status.getValue())this.status.next(Q);this.syncStageBytes(Q)}syncStageBytes(A){let Q=A==="thinking"||A==="streaming"?A:null;if(Q===this.currentStage)return;this.currentStage=Q,this.currentStageBytes=0,this.toolBlockLatestBytes.clear(),this.stageBytes.next(Q===null?null:{stage:Q,bytes:0})}onConnectionChanged(A){if(!T9(A))this.clearExpectingAgentLoop();this.connectionInfo.next(A),this.recomputeStatus()}onAgentState(A){let Q=BQ(this.agentLoopState.getValue()),B=BQ(A.state);if(B)this.pendingSend.next(!1);if(A.state==="idle")this.clearStreamingBlockKind();if(B)this.clearExpectingAgentLoop();else if(A.state==="idle"&&Q)this.scheduleExpectingAgentLoop();else this.clearExpectingAgentLoop();this.agentLoopState.next(A.state),this.recomputeStatus()}onUserMessageSendPending(A,Q){this.pendingSend.next(!0),this.recomputeStatus()}onUserMessageSendAck(A){if(this.pendingSend.next(!1),!BQ(this.agentLoopState.getValue()))this.scheduleExpectingAgentLoop();this.recomputeStatus()}scheduleExpectingAgentLoop(){this.clearExpectingAgentLoopTimer(),this.expectingAgentLoop=!0,this.expectingAgentLoopTimer=setTimeout(()=>{this.expectingAgentLoopTimer=null,this.expectingAgentLoop=!1,this.recomputeStatus()},MW5)}clearExpectingAgentLoop(){this.clearExpectingAgentLoopTimer(),this.expectingAgentLoop=!1}clearExpectingAgentLoopTimer(){if(this.expectingAgentLoopTimer!==null)clearTimeout(this.expectingAgentLoopTimer),this.expectingAgentLoopTimer=null}onThreadSettings(A){this.threadSettings.next(A.settings)}onMessageAdded(A){this.messageAddedEvents.next(A)}onMessageUpdated(A){this.messageUpdatedEvents.next(A)}onDelta(A){this.updateStreamingBlockKinds(A),this.accumulateStageBytes(A),this.deltaEvents.next(A)}accumulateStageBytes(A){if(A.role!=="assistant")return;if(this.currentStage===null)return;let Q=A.blocks;if(!Q||Q.length===0)return;let B=A.blockIndex??0,$=0;for(let[J,Y]of Q.entries())if(this.currentStage==="streaming"){if(Y.type==="text"&&Y.hidden!==!0)$+=Jo(Y.text);else if(Y.type==="tool_use"){let Z=B+J,F=CW5(Y),X=this.toolBlockLatestBytes.get(Z)??0;if(F>X)$+=F-X,this.toolBlockLatestBytes.set(Z,F)}}else if(this.currentStage==="thinking"&&Y.type==="thinking")$+=Jo(Y.thinking);if($===0)return;this.currentStageBytes+=$,this.stageBytes.next({stage:this.currentStage,bytes:this.currentStageBytes})}updateStreamingBlockKinds(A){if(A.role!=="assistant")return;let Q=!1;if(A.state==="start")Q=this.clearStreamingBlockKind();let B=A.blocks;if(!B){if(Q)this.recomputeStatus();return}if(B.some(($)=>$.blockState!==void 0))Q=this.applyStreamingBlockLifecycle(B,A.blockIndex??0)||Q;else{let $=OW5(B,this.streamingBlockKind.getValue());if($!==this.streamingBlockKind.getValue())this.streamingBlockKind.next($),Q=!0}if(Q)this.recomputeStatus()}applyStreamingBlockLifecycle(A,Q){let B=!1;for(let[$,J]of A.entries()){let Y=Ux4(J);if(Y===null||J.blockState===void 0)continue;let Z=Q+$;if(J.blockState==="complete")B=this.activeStreamingBlockKinds.delete(Z)||B;else if(this.activeStreamingBlockKinds.get(Z)!==Y)this.activeStreamingBlockKinds.set(Z,Y),B=!0}return this.syncStreamingBlockKind()||B}clearStreamingBlockKind(){let A=this.activeStreamingBlockKinds.size>0;if(this.activeStreamingBlockKinds.clear(),this.streamingBlockKind.getValue()===null)return A;return this.streamingBlockKind.next(null),!0}syncStreamingBlockKind(){let A=this.deriveStreamingBlockKind();if(A===this.streamingBlockKind.getValue())return!1;return this.streamingBlockKind.next(A),!0}deriveStreamingBlockKind(){let A=-1,Q=null;for(let[B,$]of this.activeStreamingBlockKinds)if(B>A)A=B,Q=$;return Q}onToolProgress(A){this.toolProgressEvents.next(A)}onTruncate(A){this.truncateEvents.next(A)}onPluginMessage(A){this.pluginMessages.next(A)}onQueuedMessages(A){this.queuedMessages.next(Xx4(this.queuedMessages.getValue(),A,{dedupeAdded:this.dedupeQueuedMessageAdds}))}onUserActionMessageDeliveryStatusChanged(A,Q,B){if(Q!=="buffered")return;let $=this.queuedMessages.getValue(),J=$.findIndex((F)=>F.queuedMessage.messageId===A);if(J===-1)return;let Y=$[J];if(!Y)return;let Z=[...$];Z[J]=Yt0(Y),this.queuedMessages.next(Z)}onToolApprovalQueue(A){this.pendingApprovals.next(A.approvals)}onErrorNotice(A){this.clearPendingSendIfIdle(),this.lastError.next(A),this.recomputeStatus()}onActiveError(A){if(A.type==="error_set")this.clearPendingSendIfIdle(),this.compactionState.next("idle");this.cancelledMessageId.next(null),this.activeError.next(A.type==="error_set"?A.error:null),this.recomputeStatus()}onCancelled(A){this.cancelledMessageId.next(A.messageId??null),this.activeError.next(null)}onExecutorError(A){this.executorError.next(A)}onRetryEvent(A){this.retryState.next(A)}onObservers(A){this.observers.next({count:A.count,observers:A.observers,hasExecutor:A.hasExecutor??!1})}onExecutorStatus(A){if(this.executorStatus.next(A),A.status==="running")this.executorError.next(null);this.recomputeStatus()}onEnvironmentUpdate(A){this.environment.next(A.environment)}onArtifactEvent(A){let Q=this.artifacts.getValue();switch(A.type){case"artifacts_snapshot":this.artifacts.next(Vx4(A.artifacts));return;case"artifact_upserted":this.artifacts.next(LW5(Q,A.artifact));return;case"artifact_deleted":this.artifacts.next(Q.filter((B)=>B.key!==A.key));return}}onCompactionEvent(A){if(A.type==="compaction_started"){this.compactionState.next("compacting"),this.recomputeStatus();return}if(A.type==="compaction_complete"){this.compactionState.next("idle"),this.addCompactionRecord({cutMessageId:A.cutMessageId,createdAt:this.now()}),this.recomputeStatus();return}if(this.compactionRecords.next(A.records),this.compactionRecordsState!==null)this.compactionState.next(this.compactionRecordsState),this.recomputeStatus()}onThreadTitle(A){this.threadTitle.next(A.title||void 0)}onThreadId(A){this.threadId.next(A)}resetRuntimeState(){this.connectionInfo.next(Gx4),this.agentLoopState.next("idle"),this.pendingSend.next(!1),this.clearStreamingBlockKind(),this.clearExpectingAgentLoop(),this.queuedMessages.next([]),this.pendingApprovals.next([]),this.activeError.next(null),this.executorError.next(null),this.cancelledMessageId.next(null),this.retryState.next(null),this.observers.next(null),this.executorStatus.next(null),this.environment.next(null),this.compactionState.next("idle"),this.artifacts.next([]),this.recomputeStatus()}dispose(){this.clearExpectingAgentLoopTimer(),this.connectionInfo.complete(),this.agentLoopState.complete(),this.pendingSend.complete(),this.streamingBlockKind.complete(),this.status.complete(),this.stageBytes.complete(),this.queuedMessages.complete(),this.pendingApprovals.complete(),this.lastError.complete(),this.activeError.complete(),this.cancelledMessageId.complete(),this.retryState.complete(),this.executorError.complete(),this.observers.complete(),this.executorStatus.complete(),this.environment.complete(),this.compactionState.complete(),this.compactionRecords.complete(),this.artifacts.complete(),this.threadSettings.complete(),this.threadTitle.complete(),this.threadId.complete(),this.messageAddedEvents.complete(),this.messageUpdatedEvents.complete(),this.deltaEvents.complete(),this.toolProgressEvents.complete(),this.truncateEvents.complete(),this.pluginMessages.complete()}addCompactionRecord(A){let Q=this.compactionRecords.getValue();if(Q.some((B)=>B.cutMessageId===A.cutMessageId))return;this.compactionRecords.next([...Q,A])}clearPendingSendIfIdle(){if(this.pendingSend.getValue()&&!BQ(this.agentLoopState.getValue()))this.pendingSend.next(!1)}}d0();function vF0(A){let{client:Q,observer:B,toolService:$,callbacks:J}=A,Y=new Set,Z=[],F=!1,X=!1,D=null,G=!1,V=[],U=setInterval(()=>{},1000),E=Gx(()=>{if(G)return;j.debug("User cancelled (SIGINT/SIGTERM); cancelling remote agent loop");try{Q.cancelAgentLoop()}catch(W){j.warn("Failed to cancel remote agent loop on signal",{error:W})}J.onSignal()});return E.install(),V.push(B.activeError$.subscribe((W)=>{if(!W)return;J.onError(W.message)})),V.push(B.errorNotice$.subscribe((W)=>{J.onError(W)})),V.push($.pendingApprovals$.subscribe((W)=>{Z=W})),V.push(B.agentState$.subscribe((W)=>{D=W.state;let H=BQ(W.state);if(H&&W.messageId)Y.add(W.messageId);if(H){F=!0,X=!0;return}if(X=!1,!F)return;J.onTransitionToIdle(Z)})),V.push(B.messageAdded$.subscribe((W)=>{J.onMessageAdded(W)})),{currentTurnAssistantIds:Y,pendingApprovals:()=>Z,agentStarted:()=>F,agentActive:()=>X,agentIdle:()=>D==="idle",dispose:()=>{if(G)return;G=!0,E.remove(),clearInterval(U);for(let W of V)W.unsubscribe()}}}d0();import jW5 from"node:process";var yF0=j.getChild("thread-actors-transport"),Zt0=Number(jW5.env.SIMULATE_LATENCY??0),RW5=Number.isFinite(Zt0)&&Zt0>0?Zt0:0;function Wx(A,Q){let B=Q,$=0;return async()=>{let J=++$,Y=await A(B);if(J===$)B=Y.threadId;return Y}}function Hx(A){let Q=OU({endpoint:A.rivetEndpoint}),B={pingIntervalMs:A.pingIntervalMs??5000,webSocketLatencyMs:()=>RW5,webSocketProvider:async()=>{yF0.debug("Fetching connection credentials");let $=await A.credentialsProvider({forceRefresh:!0});yF0.debug("Fetched connection credentials",{threadId:$.threadId,threadVersion:$.threadVersion});let J=Q.threadActor.getOrCreate([$.threadId],{params:{wsToken:$.wsToken},createWithInput:{threadId:$.threadId,threadVersion:$.threadVersion,ownerUserId:$.ownerUserId,...$.agentMode?{agentMode:$.agentMode}:{}}});yF0.debug("Opening Rivet actor WebSocket",{threadId:$.threadId});let Y=await J.webSocket("/",void 0,{skipReadyWait:!0});return yF0.debug("Opened Rivet actor WebSocket",{threadId:$.threadId}),{webSocket:Y,threadId:$.threadId}}};if(A.initialThreadID)B.threadId=A.initialThreadID;if(A.maxReconnectAttempts!==void 0)B.maxReconnectAttempts=A.maxReconnectAttempts;if(A.requiredRole!==void 0)B.requiredRole=A.requiredRole;return B}i4();function xF0(A){let Q=A.agentMode||Gp(A);if(!Q)throw Error("agent mode could not be determined from thread");return{version:A.v,title:A.title??null,messages:A.messages.map((B)=>zx4(A,B)),agentMode:Q,needsImport:!_W5(A)}}function Ex4(A){let Q=A.agentMode||Gp(A);if(!Q)throw Error("agent mode could not be determined from thread");return{id:A.id,v:A.v,...A.title?{title:A.title}:{},messages:A.messages.map((B)=>PW5(A,B)),agentMode:Q,...A.meta?{meta:A.meta}:{}}}function PW5(A,Q){let{threadId:B,parentToolUseId:$,...J}=zx4(A,Q);if(Q.parentToolUseId!==void 0)return{...J,parentToolUseId:Q.parentToolUseId};return J}function _W5(A){if(!A.meta||typeof A.meta!=="object")return!1;return A.meta.usesThreadActors===!0}function zx4(A,Q){let B=TW5(Q);switch(Q.role){case"user":return Ft0(Q,{threadId:A.id,role:"user",content:[...Q.content],meta:L30(Q.meta),userState:kW5(Q.userState),readAt:Q.readAt,messageId:B});case"assistant":return Ft0(Q,{threadId:A.id,role:"assistant",content:[...Q.content],state:Q.state?.type==="cancelled"?{type:"cancelled"}:void 0,usage:Q.usage,readAt:Q.readAt,messageId:B});case"info":return Ft0(Q,{threadId:A.id,role:"info",content:Q.content.filter(SW5),messageId:B})}}function Ft0(A,Q){if(A.parentToolUseId!==void 0)Q.parentToolUseId=A.parentToolUseId;return Q}function TW5(A){let Q=Kx4(A.protocolMessageID);if(Q)return Q;let B=A.messageId;if(typeof B==="string"){let $=Kx4(B);if($)return $}return qF0()}function Kx4(A){if(!A)return null;let Q=f6.safeParse(A);return Q.success?Q.data:null}function kW5(A){if(!A)return;return{...A,currentlyVisibleFiles:[...A.currentlyVisibleFiles],runningTerminalCommands:A.runningTerminalCommands?[...A.runningTerminalCommands]:void 0,aggmanContext:A.aggmanContext?{...A.aggmanContext,availableProjects:A.aggmanContext.availableProjects?A.aggmanContext.availableProjects.map((Q)=>({...Q})):void 0,recentUnreadThreads:A.aggmanContext.recentUnreadThreads?A.aggmanContext.recentUnreadThreads.map((Q)=>({...Q})):void 0}:void 0}}function SW5(A){return A.type==="manual_bash_invocation"}_Q();r1();import Yo from"node:path";class Ij extends Error{code;constructor(A,Q){super(Q);this.code=A;this.name="ExecutorFileSystemPathError"}}function Hx4(A,Q){let B=o0.parse(A);if(B.scheme!=="file")throw new Ij("INVALID_URI","Only file:// URIs are supported");if(!B.path.startsWith("/"))throw new Ij("INVALID_URI","File URI path must be absolute");if(B.path.split("/").some((X)=>X===".."))throw new Ij("ACCESS_DENIED","File URI resolves outside workspace root");let J=Yo.posix.normalize(B.path).replace(/^\/+/u,"");if(J===".."||J.startsWith("../"))throw new Ij("ACCESS_DENIED","File URI resolves outside workspace root");let Y=Yo.resolve(Q),Z=J.length>0?Yo.resolve(Y,J):Y,F=Yo.relative(Y,Z);if(F.startsWith("..")||Yo.isAbsolute(F))throw new Ij("ACCESS_DENIED","File URI resolves outside workspace root");return Z}async function qx(A,Q){try{let B=Hx4(Q,A.workspaceRoot),$=await A.fileSystem.readdir(o0.file(B));return{ok:!0,entries:await Promise.all($.map(async(Y)=>{let Z=Y.isDirectory?"directory":"file",F=Z==="file"?await vW5(A.fileSystem,Y.uri):void 0;return[Y1.basename(Y.uri),Z,F]}))}}catch(B){return{ok:!1,error:Nx4(B,"read_directory")}}}async function vW5(A,Q){try{let B=await A.getMtime(Q);if(!Number.isFinite(B)||B<0)return;return{mtimeMs:B}}catch{return}}async function qx4(A,Q){try{let B=Hx4(Q,A.workspaceRoot),$=await A.fileSystem.readBinaryFile(o0.file(B));return{ok:!0,contentBase64:Buffer.from($).toString("base64")}}catch(B){return{ok:!1,error:Nx4(B,"read_file")}}}function Nx4(A,Q){if(A instanceof Ij)return{code:A.code,message:A.message};if(y8(A))return{code:"NOT_FOUND",message:"File or directory not found"};if(fF0(A,"EISDIR"))return{code:"IS_DIRECTORY",message:"Expected a file but found a directory"};if(fF0(A,"ENOTDIR"))return{code:Q==="read_directory"?"NOT_DIRECTORY":"INTERNAL_ERROR",message:Q==="read_directory"?"Expected a directory":Wx4(A)};if(fF0(A,"EACCES")||fF0(A,"EPERM"))return{code:"ACCESS_DENIED",message:"Permission denied"};return{code:"INTERNAL_ERROR",message:Wx4(A)}}function fF0(A,Q){if(!(A instanceof Error))return!1;return"code"in A&&A.code===Q}function Wx4(A){if(A instanceof Error)return A.message;return String(A)}d0();v5();Wl();i4();r1();M1();d0();function bF0(A){return(Q)=>{let B=Q.message;if(B.type!=="request")return;let $=Date.now();j.info("Plugin hook dispatcher request received",{method:B.method,id:B.id}),yW5(A.pluginService,B.method,B.params).then((J)=>{j.info("Plugin hook dispatcher request completed",{method:B.method,id:B.id,durationMs:Date.now()-$}),A.sendPluginMessage(Ix4(B.id,J))}).catch((J)=>{j.warn("Plugin hook dispatcher request failed",{method:B.method,id:B.id,durationMs:Date.now()-$,error:J}),A.sendPluginMessage(Ix4(B.id,void 0,J instanceof Error?J.message:String(J)))})}}function Ix4(A,Q,B){if(B!==void 0)return{type:"response",id:A,error:B};if(Q===void 0)return{type:"response",id:A};return{type:"response",id:A,result:Q}}async function yW5(A,Q,B){switch(Q){case"session.start":{let{event:$}=B;return await A.event.sessionStart($),{}}case"agent.start":{let{event:$}=B;return await A.event.agentStart($)}case"agent.end":{let{event:$}=B;return await A.event.agentEnd($)}case"command.execute":{let{pluginName:$,commandId:J,threadID:Y}=B;return await A.commands.execute($,J,Y?{threadID:Y}:void 0),{ok:!0}}default:throw Error(`Unknown plugin hook method: ${Q}`)}}import{exec as xW5}from"node:child_process";import{promisify as fW5}from"node:util";kV();i4();r1();var bW5=fW5(xW5);async function wx4(A){let Q=await Iz(),B=MQ(A)?A:c2(),$=await $D({filesystem:j3},Q,B),J=await uW5($.workingDirectory??$.workspaceRoot);return{...Q,...$,...J?{git:{branch:J}}:{},updatedAt:new Date().toISOString()}}async function uW5(A){if(!A)return;let Q;try{Q=o0.parse(A).fsPath}catch{return}try{let{stdout:B}=await bW5("git symbolic-ref --quiet --short HEAD",{cwd:Q});return B.trim()||void 0}catch{return}}function hW5(A){return new TextEncoder().encode(JSON.stringify(A)).length}function Nx(A,Q,B){if(A.length===0)return[];let $=[],J=[];for(let Y of A){let Z=[...J,Y],F=hW5(B(Z));if(J.length>0&&F>Q){$.push(J),J=[Y];continue}J=Z}if(J.length>0)$.push(J);return $}var Mx4=1048576;function Cx4(A){let Q=new Map;for(let B of A)Q.set(B.name,{schema:B,serializedSchema:JSON.stringify(B)});return Q}function gW5(A){let Q={...A.executionProfile?.serial!==void 0?{serial:A.executionProfile.serial}:{},...A.meta?.deferred!==void 0?{deferred:A.meta.deferred}:{},...A.meta?.skillNames!==void 0?{skillNames:[...A.meta.skillNames]}:{}};return Object.keys(Q).length>0?Q:void 0}function mW5(A){return{name:A.name,description:A.description??"",inputSchema:{type:"object",properties:A.inputSchema.properties??{},required:A.inputSchema.required,additionalProperties:A.inputSchema.additionalProperties},source:A.source,meta:gW5(A)}}function Xt0(A){return A.map((Q)=>mW5(Q.spec))}function Lx4(A,Q){let B=Cx4(A),$=Cx4(Q);return{toolsToRegister:Q.filter((J)=>{let Y=B.get(J.name),Z=$.get(J.name);return Y?.serializedSchema!==Z?.serializedSchema}),toolNamesToUnregister:[...B.keys()].filter((J)=>!$.has(J))}}function Ox4(A,Q=Mx4){return Nx(A,Q,(B)=>({type:"executor_tools_register",tools:B}))}function jx4(A,Q=Mx4){return Nx(A,Q,(B)=>({type:"executor_tools_unregister",toolNames:B}))}import{execFile as iW5}from"node:child_process";import{createHash as nW5}from"node:crypto";import{readFile as aW5,stat as oW5}from"node:fs/promises";import{basename as rW5,join as sW5}from"node:path";import yx4 from"node:process";import{promisify as tW5}from"node:util";async function Rx4(A,Q,B){let $=[];for(let J=0;J<A.length;J+=Q){let Y=A.slice(J,J+Q);$.push(...await Promise.all(Y.map(B)))}return $}var Px4=2097152,JI="(Content omitted — git status artifact exceeds size limit)";function pW5(A){return(A.fullFileDiff?.length??0)+(A.oldContent?.length??0)+(A.newContent?.length??0)}function dW5(A){let Q=!1;if(A.fullFileDiff!==void 0&&A.fullFileDiff!==A.diff)A.fullFileDiff=A.diff,Q=!0;if(A.oldContent!==void 0&&A.oldContent!==JI)A.oldContent=JI,Q=!0;if(A.newContent!==void 0&&A.newContent!==JI)A.newContent=JI,Q=!0;return Q}function cW5(A){let Q=!1;if(A.oldContent!==void 0)A.oldContent=void 0,Q=!0;if(A.newContent!==void 0)A.newContent=void 0,Q=!0;if(A.fullFileDiff!==void 0)A.fullFileDiff=void 0,Q=!0;return Q}function lW5(A){let Q=!1;if(A.diff!==JI)A.diff=JI,Q=!0;if(A.fullFileDiff!==void 0&&A.fullFileDiff!==JI)A.fullFileDiff=JI,Q=!0;return Q}function Ix(A){let Q=Buffer.from(JSON.stringify(A),"utf8").toString("base64"),B=new TextEncoder().encode(JSON.stringify({type:"executor_artifact_upsert",artifact:{key:cS,dataType:"application/json",contentBase64:Q}})).length;return{contentBase64:Q,messageSizeBytes:B}}function _x4(A,Q){let B={...A,aheadCommits:[...A.aheadCommits],files:A.files.map((Z)=>({...Z}))},$=Ix(B);if($.messageSizeBytes<=Q)return $.contentBase64;let J=B.files.map((Z,F)=>({index:F,weight:pW5(Z)})).filter((Z)=>Z.weight>0).sort((Z,F)=>F.weight-Z.weight);for(let{index:Z}of J){let F=B.files[Z];if(!F||!dW5(F))continue;if($=Ix(B),$.messageSizeBytes<=Q)return $.contentBase64}for(let{index:Z}of J){let F=B.files[Z];if(!F||!cW5(F))continue;if($=Ix(B),$.messageSizeBytes<=Q)return $.contentBase64}let Y=B.files.map((Z,F)=>({index:F,weight:Z.diff.length+(Z.fullFileDiff?.length??0)})).filter((Z)=>Z.weight>0).sort((Z,F)=>F.weight-Z.weight);for(let{index:Z}of Y){let F=B.files[Z];if(!F||!lW5(F))continue;if($=Ix(B),$.messageSizeBytes<=Q)return $.contentBase64}if(B.aheadCommits.length>0){if(B.aheadCommits=[],$=Ix(B),$.messageSizeBytes<=Q)return $.contentBase64}while(B.files.length>0)if(B.files.pop(),$=Ix(B),$.messageSizeBytes<=Q)return $.contentBase64;return $.contentBase64}var eW5=tW5(iW5),Cx=20971520,AH5=["GIT_CONFIG","GIT_CONFIG_COUNT","GIT_CONFIG_PARAMETERS"],uF0=["-c","core.quotepath=false","diff","--no-color","--no-ext-diff"],QH5=999999,Tx4="refs/remotes/origin/",BH5=20,$H5=10;function hF0(A){return A.replace(/\n+$/,"")}var Dt0=yx4.platform==="win32"?"NUL":"/dev/null";function JH5(A=yx4.env,Q={}){let{isolateGitConfig:B=!0}=Q,$={...A};if(B){for(let J of Object.keys($))if(AH5.includes(J)||J.startsWith("GIT_CONFIG_KEY_")||J.startsWith("GIT_CONFIG_VALUE_"))delete $[J];$.GIT_CONFIG_NOSYSTEM="1",$.GIT_CONFIG_SYSTEM=Dt0,$.GIT_CONFIG_GLOBAL=Dt0}return $}function kx4(A,Q){return{provider:"git",capturedAt:A,available:!1,repositoryRoot:null,repositoryName:null,branch:null,head:null,files:[],unavailableReason:Q}}function YH5(A){return A instanceof Error}async function wx(A,Q,B={}){try{let{stdout:$}=await eW5("git",Q,{cwd:A,env:JH5(),maxBuffer:B.maxBufferBytes??Cx});return $}catch($){if(B?.allowExitCodeOne&&YH5($)&&($.code===1||$.code==="1")&&typeof $.stdout==="string")return $.stdout;throw $}}async function Tz(A,Q){try{return await wx(A,Q)}catch{return null}}function ZH5(A){if(A==="??")return"untracked";let Q=A[0]??" ",B=A[1]??" ";if(Q==="U"||B==="U"||A==="AA"||A==="DD")return"unmerged";if(Q==="R"||B==="R")return"renamed";if(Q==="C"||B==="C")return"copied";if(Q==="A"||B==="A")return"added";if(Q==="D"||B==="D")return"deleted";if(Q==="T"||B==="T")return"type_changed";return"modified"}function Gt0(A){let Q=[],B=A.split("\x00");for(let $=0;$<B.length;$++){let J=B[$];if(!J||J.length<4)continue;let Y=J.slice(0,2),Z=J.slice(3);if(!Z)continue;let F=ZH5(Y);if(F==="renamed"||F==="copied"){let X=B[$+1];if(X){Q.push({path:Z,previousPath:X,changeType:F}),$+=1;continue}}Q.push({path:Z,changeType:F})}return Q.sort(($,J)=>$.path.localeCompare(J.path))}function FH5(A){let Q=0,B=0,$=0,J=0,Y=0,Z=()=>{if(J===0&&Y===0)return;$+=Math.min(J,Y),J=0,Y=0};for(let F of A.split(`
4702
+ `)){if(F.startsWith("+")&&!F.startsWith("+++")){Q+=1,J+=1;continue}if(F.startsWith("-")&&!F.startsWith("---")){B+=1,Y+=1;continue}Z()}return Z(),{added:Q,deleted:B,changed:$}}function XH5(A){let Q=nW5("sha256");for(let B of A)Q.update(B.path),Q.update("\x00"),Q.update(B.diff),Q.update("\x00");return Q.digest("hex")}async function Sx4(A,Q,B,$,J=Cx){let Y=$!==void 0?[`--unified=${$}`]:[];if(B)return wx(A,[...uF0,...Y,"HEAD","--",Q],{maxBufferBytes:J});let[Z,F]=await Promise.all([wx(A,[...uF0,...Y,"--cached","--",Q],{maxBufferBytes:J}).catch(()=>""),wx(A,[...uF0,...Y,"--",Q],{maxBufferBytes:J}).catch(()=>"")]);return[hF0(Z),hF0(F)].filter(Boolean).join(`
4703
+ `)}async function DH5(A,Q,B=Cx){return wx(A,[...uF0,"--no-index","--",Dt0,Q],{allowExitCodeOne:!0,maxBufferBytes:B})}async function GH5(A,Q,B,$=Cx){let J=B??"HEAD";try{return await wx(A,["show",`${J}:${Q}`],{maxBufferBytes:$})}catch{return}}async function VH5(A,Q,B=Cx){try{let $=sW5(A,Q);if((await oW5($)).size>B)return;return await aW5($,"utf-8")}catch{return}}function vx4(A){let Q=Number.parseInt(A.trim(),10);if(!Number.isFinite(Q))return null;return Q}async function UH5(A){let Q=(await Tz(A,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]))?.trim();if(!Q?.startsWith(Tx4))return null;let B=Q.slice(Tx4.length);if(!B)return null;let $=`origin/${B}`,Y=(await Tz(A,["rev-parse","--verify","--quiet",`${$}^{commit}`]))?.trim();if(!Y)return null;return{baseRef:B,comparisonRef:$,baseRefHead:Y}}function KH5(A){let Q=A.split("\x00"),B=[];for(let $=0;$+1<Q.length;$+=2){let J=Q[$],Y=Q[$+1]??"";if(!J)continue;B.push({hash:J,shortHash:J.slice(0,12),subject:Y})}return B}async function EH5(A,Q){let B=await Tz(A,["log","-z",`--max-count=${BH5}`,"--format=%H%x00%s",`${Q}..HEAD`]);if(!B)return[];return KH5(B)}async function zH5(A,Q){if(!Q)return null;let B=await UH5(A);if(!B)return null;let $=await Tz(A,["rev-list","--count",`${B.comparisonRef}..HEAD`]);if(!$)return null;let J=await Tz(A,["rev-list","--count",`HEAD..${B.comparisonRef}`]);if(!J)return null;let Y=vx4($);if(Y===null)return null;let Z=vx4(J);if(Z===null)return null;return{baseRef:B.baseRef,comparisonRef:B.comparisonRef,baseRefHead:B.baseRefHead,aheadCount:Y,behindCount:Z}}async function gF0(A,Q={}){let{maxDiffBufferBytes:B=Cx}=Q,$=Date.now(),J=await Tz(A,["rev-parse","--show-toplevel"]);if(!J)return kx4($,"not a git repository");let Y=J.trim(),Z=rW5(Y),[F,X,D]=await Promise.all([Tz(Y,["rev-parse","--verify","HEAD"]),Tz(Y,["symbolic-ref","--short","HEAD"]),Tz(Y,["status","--porcelain=v1","--untracked-files=all","-z"])]);if(D===null)return kx4($,"failed to read git status");let G=F?.trim()||null,V=X?.trim()||null,U=Gt0(D),K=await zH5(Y,G),E=K?.aheadCount&&K.aheadCount>0?await EH5(Y,K.comparisonRef):[],z=await Rx4(U,$H5,async(W)=>{let H=hF0(W.changeType==="untracked"?await DH5(Y,W.path,B).catch(()=>""):await Sx4(Y,W.path,G,void 0,B).catch(()=>"")),q=hF0(W.changeType==="modified"?await Sx4(Y,W.path,G,QH5,B).catch(()=>""):H),N=W.changeType!=="added"&&W.changeType!=="untracked"?await GH5(Y,W.previousPath??W.path,G,B):void 0,I=W.changeType!=="deleted"?await VH5(Y,W.path,B):void 0;return{path:W.path,previousPath:W.previousPath,changeType:W.changeType,created:W.changeType==="added"||W.changeType==="untracked",diff:H,fullFileDiff:q,oldContent:N,newContent:I,diffStat:FH5(H)}});return{provider:"git",capturedAt:$,available:!0,repositoryRoot:Y,repositoryName:Z,branch:V,head:G,diffHash:XH5(z),baseRef:K?.baseRef??null,baseRefHead:K?.baseRefHead??null,aheadCount:K?.aheadCount??0,behindCount:K?.behindCount,aheadCommits:E,files:z}}function WH5(A){return{provider:A.provider,capturedAt:A.capturedAt,available:A.available,repositoryRoot:A.repositoryRoot,repositoryName:A.repositoryName,branch:A.branch,head:A.head,diffHash:A.diffHash,baseRef:A.baseRef??null,baseRefHead:A.baseRefHead??null,aheadCount:A.aheadCount??0,behindCount:A.behindCount,...A.unavailableReason!==void 0?{unavailableReason:A.unavailableReason}:{},aheadCommits:A.aheadCommits??[],files:A.files.map((Q)=>({path:Q.path,previousPath:Q.previousPath,changeType:Q.changeType,created:Q.created,diff:Q.diff,fullFileDiff:Q.fullFileDiff,oldContent:Q.oldContent,newContent:Q.newContent,diffStat:Q.diffStat}))}}function Vt0(A){let Q=_x4(WH5(A),Px4);return{key:cS,dataType:"application/json",contentBase64:Q}}import{createHash as HH5}from"node:crypto";function Ut0(A){return HH5("sha256").update(A).digest("hex")}class Zo{entries=new Map;initialized=!1;static key(A,Q){return`${A}\x00${Q}`}replace(A){this.entries.clear();for(let Q of A)this.entries.set(Zo.key(Q.uri,Q.hash),Q);this.initialized=!0}clear(){this.entries.clear(),this.initialized=!1}has(A,Q){if(!this.initialized||typeof Q!=="string"||Q.length===0)return!1;return this.entries.has(Zo.key(A,Q))}isInitialized(){return this.initialized}}function Kt0(A,Q){return A.map((B)=>{if(typeof B.hash==="string"&&Q.has(B.uri,B.hash)){let $={uri:B.uri,hash:B.hash};if(typeof B.lineCount==="number")$.lineCount=B.lineCount;return $}return B})}var xx4=1048576;function fx4(A,Q,B,$=xx4){return Nx(A,$,(J)=>({type:"executor_guidance_snapshot",snapshotId:Q,files:J,isLast:!1,userConfigDir:B}))}function bx4(A,Q,B=xx4){return Nx(A,B,($)=>({type:"executor_guidance_discovery",toolCallId:Q,files:$,isLast:!1}))}var Mx={baseDelayMs:1000,maxDelayMs:30000,maxAttempts:5};function mF0(A,Q){if(A>=Q.maxAttempts)return null;let B=Math.max(1,A);return Math.min(Q.baseDelayMs*2**(B-1),Q.maxDelayMs)}var rB=j.getChild("executor");function qH5(A){return typeof A==="object"&&A!==null&&"output"in A&&A.output===""}function NH5(){let A=()=>{return},Q=()=>{return};return{promise:new Promise(($,J)=>{A=$,Q=J}),resolve:A,reject:Q}}function IH5(A){if(A==="darwin")return"darwin";if(A==="win32")return"windows";return"linux"}function ux4(A){let Q=A.previouslyAdvertisedTools??[],{toolsToRegister:B,toolNamesToUnregister:$}=Lx4(Q,A.nextTools),J=A.forceRegisterAll?[...A.nextTools]:B;for(let Y of Ox4(J))A.logMessage?.("SEND",{type:"executor_tools_register",tools:Y.map((Z)=>Z.name)}),A.transport.registerTools(Y);for(let Y of jx4($))A.logMessage?.("SEND",{type:"executor_tools_unregister",toolNames:Y}),A.transport.unregisterTools(Y);return[...A.nextTools]}async function wH5(A){let{transport:Q,threadId:B,configService:$,skillService:J,logMessage:Y}=A,Z=A.fileSystem??j3,F=performance.now(),X={clientID:A.executorClientID,threadID:B,executorType:A.executorType,allowResumeBootstrap:A.allowResumeBootstrap===!0},D={},G="executorHandshake",V=!1,U=performance.now(),K=(W)=>{D[`${W}Ms`]=Math.round(performance.now()-U)};rB.info("Starting executor bootstrap",X);let E={workspaceId:A.workspaceRoot,workingDirectory:A.workspaceRoot,environment:{os:IH5(process.platform)},tags:[]};Y?.("SEND",{type:"executor_connect",clientId:A.executorClientID,capabilities:E,executorType:A.executorType}),G="executorHandshake",U=performance.now();let z=await Q.executorHandshake(A.executorClientID,E,{executorType:A.executorType});K(G),Y?.("RECV",z),A.guidanceContentCache?.replace(z.guidanceInventory),V=A.allowResumeBootstrap===!0&&z.resumeBootstrap===!0;try{if(!V){A.onBootstrapProgress?.("environment"),G="buildEnvironmentSnapshot",U=performance.now();let N=await wx4(B);K(G),Y?.("SEND",{type:"executor_environment_snapshot",environment:N}),Q.sendEnvironmentSnapshot(N);let w={trees:N.workspaceRoot?[{uri:N.workspaceRoot}]:[],platform:N.platform,tags:N.tags};if(A.onBootstrapProgress?.("guidance"),G="sendGuidanceSnapshot",U=performance.now(),await CH5(Q,Z,$,w,Y,A.guidanceContentCache),K(G),A.onBootstrapProgress?.("skills"),G="sendSkillSnapshot",U=performance.now(),await MH5(Q,J,Y),K(G),A.sendGitSnapshot!==!1){A.onBootstrapProgress?.("git");try{G="sendGitSnapshot",U=performance.now();let O=await gF0(A.workspaceRoot);Y?.("SEND",{type:"executor_artifact_upsert",available:O.available,fileCount:O.files.length,branch:O.branch,head:O.head}),Q.sendExecutorArtifactUpsert(Vt0(O)),K(G)}catch{}}}A.onBootstrapProgress?.("tools"),G="initialToolDiscovery",U=performance.now(),await A.initialToolDiscovery,K(G),G="loadToolStatuses",U=performance.now();let W=await T1(A.toolService.tools);K(G);let H=Xt0(W);G="syncExecutorToolRegistrations",U=performance.now();let q=ux4({transport:Q,nextTools:H,previouslyAdvertisedTools:A.previouslyAdvertisedTools,forceRegisterAll:!V,logMessage:Y});return K(G),Y?.("SEND",{type:"executor_tools_bootstrap_complete",ok:!0}),Q.sendExecutorToolsBootstrapComplete(!0),rB.info("Executor bootstrap completed",{...X,resumeBootstrap:V,toolCount:H.length,advertisedToolCount:q.length,totalMs:Math.round(performance.now()-F),...D}),{advertisedTools:q}}catch(W){let H=W instanceof Error?W.message:String(W);throw Y?.("SEND",{type:"executor_tools_bootstrap_complete",ok:!1,error:H}),Q.sendExecutorToolsBootstrapComplete(!1,H),rB.error("Executor bootstrap failed",{...X,currentPhase:G,resumeBootstrap:V,totalMs:Math.round(performance.now()-F),...D,error:W}),W}}async function CH5(A,Q,B,$,J,Y){let F=(await _q({filesystem:Q,configService:B,threadService:{observe:()=>m0.of({id:c2(),created:Date.now(),v:0,messages:[],env:{initial:$}})}},{messages:[],env:{initial:$}})).map((U)=>({uri:U.uri,content:U.content,lineCount:U.content.split(`
4704
+ `).length,hash:Ut0(U.content)})),X=Y?Kt0(F,Y):F,D=crypto.randomUUID(),G=B.userConfigDir?b1(B.userConfigDir):void 0;if(X.length===0){J?.("SEND",{type:"executor_guidance_snapshot",snapshotId:D,fileCount:0,withContent:[],contentOmitted:[],isLast:!0}),A.sendExecutorGuidanceSnapshot({snapshotId:D,files:[],isLast:!0,userConfigDir:G});return}let V=fx4(X,D,G);for(let U=0;U<V.length;U++){let K=V[U];if(!K)continue;let E=U===V.length-1,z=K.filter((H)=>H.content!==void 0).map((H)=>H.uri),W=K.filter((H)=>H.content===void 0).map((H)=>H.uri);J?.("SEND",{type:"executor_guidance_snapshot",snapshotId:D,fileCount:K.length,withContent:z,contentOmitted:W,isLast:E}),A.sendExecutorGuidanceSnapshot({snapshotId:D,files:K,isLast:E,userConfigDir:G})}}async function MH5(A,Q,B){let[$,J]=await Promise.all([Q.getSkills(),Q.getSkillErrors()]),Y=crypto.randomUUID(),Z=20,F=$.map((D)=>({name:D.name,description:D.description,baseDir:D.baseDir,frontmatter:D.frontmatter,files:D.files,source:D.source})),X=J.map((D)=>({path:D.path,error:D.error,...D.hint?{hint:D.hint}:{}}));if(F.length===0){B?.("SEND",{type:"executor_skill_snapshot",snapshotId:Y,skillCount:0,errorCount:X.length,isLast:!0}),A.sendExecutorSkillSnapshot({snapshotId:Y,skills:[],isLast:!0,errors:X});return}for(let D=0;D<F.length;D+=20){let G=F.slice(D,D+20),V=D+20>=F.length;B?.("SEND",{type:"executor_skill_snapshot",snapshotId:Y,skillCount:G.length,...V?{errorCount:X.length}:{},isLast:V}),A.sendExecutorSkillSnapshot({snapshotId:Y,skills:G,isLast:V,...V?{errors:X}:{}})}}class hx4{options;inFlight=null;readyWaiter=null;retryTimer=null;readyTimer=null;readyTimeoutConfig=null;attempt=0;generation=0;lastInfo=null;disposed=!1;baseDelayMs;maxDelayMs;maxAttempts;pollDelayMs;constructor(A){this.options=A;this.baseDelayMs=A.baseDelayMs??Mx.baseDelayMs,this.maxDelayMs=A.maxDelayMs??Mx.maxDelayMs,this.maxAttempts=A.maxAttempts??Mx.maxAttempts,this.pollDelayMs=A.pollDelayMs??30000}ensureHandshake(A){return this.tryHandshake(A)}ensureReady(A){if(this.disposed)return Promise.reject(Error("Executor handshake manager is disposed"));if(this.isReady())return Promise.resolve();if(!this.readyWaiter)this.readyWaiter=NH5();if(A?.timeoutMs)this.readyTimeoutConfig={timeoutMs:A.timeoutMs,timeoutMessage:A.timeoutMessage??`Timed out waiting for handshake after ${A.timeoutMs}ms`},this.armReadyTimeout();return this.tryHandshake("connect"),this.readyWaiter.promise}handleConnectionChange(A){let Q=this.lastInfo;this.lastInfo=A;let B=A.state!=="connected"?"reset_disconnected":A.role==="executor"?"mark_ready":"ensure_handshake";if(rB.info("Handshake manager handling connection change",{action:B,state:A.state,role:A.role,clientId:A.clientId,reconnectCauseType:A.reconnectCause?.type,reconnectCauseCode:A.reconnectCause?.code,reconnectCauseReason:A.reconnectCause?.reason,attempt:this.attempt,hasInFlightHandshake:this.inFlight!==null,hasRetryTimer:this.retryTimer!==null}),A.state!=="connected"){this.reset("disconnected");return}if(A.role==="executor"){this.reset("executor"),this.resolveReadyWaiter();return}if(!Q||Q.state!=="connected")this.armReadyTimeout();this.tryHandshake("connect")}dispose(){this.disposed=!0,this.generation++,this.clearRetryTimer(),this.clearReadyTimer(),this.readyTimeoutConfig=null,this.rejectReadyWaiter(Error("Executor handshake manager is disposed"))}isReady(){return this.lastInfo?.state==="connected"&&this.lastInfo.role==="executor"}resolveReadyWaiter(){this.clearReadyTimer(),this.readyTimeoutConfig=null;let A=this.readyWaiter;if(!A)return;this.readyWaiter=null,A.resolve()}rejectReadyWaiter(A){this.clearReadyTimer(),this.readyTimeoutConfig=null;let Q=this.readyWaiter;if(!Q)return;this.readyWaiter=null,Q.reject(A)}reset(A){this.generation++,this.attempt=0,this.clearRetryTimer(),this.clearReadyTimer()}clearRetryTimer(){if(!this.retryTimer)return;clearTimeout(this.retryTimer),this.retryTimer=null}armReadyTimeout(){if(!this.readyTimeoutConfig||!this.readyWaiter)return;this.clearReadyTimer();let{timeoutMs:A,timeoutMessage:Q}=this.readyTimeoutConfig;this.readyTimer=setTimeout(()=>{this.readyTimer=null,this.rejectReadyWaiter(Error(Q))},A)}clearReadyTimer(){if(!this.readyTimer)return;clearTimeout(this.readyTimer),this.readyTimer=null}tryHandshake(A){if(this.disposed)return rB.info("Handshake manager ignored trigger while disposed",{trigger:A}),this.inFlight;if(this.inFlight)return rB.info("Handshake manager reused in-flight handshake",{trigger:A,attempt:this.attempt,state:this.lastInfo?.state,role:this.lastInfo?.role}),this.inFlight;let Q=this.generation;rB.info("Handshake manager starting handshake",{trigger:A,generation:Q,attempt:this.attempt,state:this.lastInfo?.state,role:this.lastInfo?.role});let B=this.options.handshake(A);return this.inFlight=B,B.then(()=>{if(this.disposed||Q!==this.generation)return;rB.info("Handshake manager handshake succeeded",{trigger:A,generation:Q}),this.attempt=0,this.clearRetryTimer(),this.resolveReadyWaiter()}).catch(($)=>{if(this.disposed||Q!==this.generation)return;this.scheduleRetry(A,$)}).finally(()=>{if(this.inFlight===B)this.inFlight=null}),B}scheduleRetry(A,Q){if(this.disposed)return;if(!this.lastInfo||this.lastInfo.state!=="connected"||this.lastInfo.role==="executor")return;this.attempt+=1;let B=mF0(this.attempt,{baseDelayMs:this.baseDelayMs,maxDelayMs:this.maxDelayMs,maxAttempts:this.maxAttempts}),$=B===null;if($)rB.error("Handshake manager exhausted fast retries",{trigger:A,attempt:this.attempt,maxAttempts:this.maxAttempts,pollDelayMs:this.pollDelayMs,error:Q}),this.options.onExhausted?.({attempt:this.attempt,maxAttempts:this.maxAttempts,error:Q}),this.rejectReadyWaiter(Q instanceof Error?Q:Error("Executor handshake failed and exhausted retries")),this.options.forceReconnect?.("executor handshake exhausted");let J=B??this.pollDelayMs;this.clearRetryTimer(),rB.info("Handshake manager scheduled retry",{trigger:A,attempt:this.attempt,delayMs:J,state:this.lastInfo.state,role:this.lastInfo.role,mode:$?"poll":"fast",error:Q instanceof Error?Q.message:String(Q)}),this.options.onError?.({trigger:A,attempt:this.attempt,delayMs:J,error:Q}),this.retryTimer=setTimeout(()=>{if(this.retryTimer=null,!this.lastInfo||this.lastInfo.state!=="connected"||this.lastInfo.role==="executor")return;this.tryHandshake("retry")},J)}}class gx4{options;clientID;transport;sentApprovalRequests=new Set;discoveredGuidanceFileURIs=new Set;activeTools=new Map;pendingTerminalResults=new Map;gitStatusQueue={inFlight:!1,queued:!1,queuedToolCallId:void 0};disposing=!1;constructor(A){this.options=A;this.clientID=A.clientID,this.transport=A.transport}async handleToolLease(A){if(this.disposing)return;let{toolCallId:Q,toolName:B}=A;if(this.activeTools.has(Q)){this.options.log.info(`${this.clientID} ignoring duplicate active lease`,{toolCallId:Q,toolName:B});return}let $=this.pendingTerminalResults.get(Q);if($){this.options.log.info(`${this.clientID} replaying pending terminal result for duplicate lease`,{toolCallId:Q,toolName:B}),this.sendPendingTerminalResult(Q,$,"flush");return}let J=Date.now();this.options.log.info(`${this.clientID} executing tool: ${B}`,{toolCallId:Q}),this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_lease_ack",toolCallId:Q}),this.transport.ackToolLease(Q);let Y=new AbortController,Z={subscription:{unsubscribe:()=>{}},abortController:Y,needsProgressSnapshot:!1};this.activeTools.set(Q,Z);let F=()=>{this.activeTools.delete(Q)};try{let X=A;if(this.options.requestPluginToolCall&&this.options.threadId){let V=await this.requestPluginToolCall(A);if(Y.signal.aborted){F();return}if("shortCircuitRun"in V){this.prepareAndSendToolResult(A,V.shortCircuitRun,Z);return}X=V.lease}let D=await this.options.invokeTool(X);this.options.log.info(`${this.clientID} tool service returned observable`,{toolCallId:Q,toolName:B,elapsedMs:Date.now()-J});let G=D.subscribe({next:(V)=>{if(Y.signal.aborted)return;let U=V.status==="in-progress"?V.progress??V.result:void 0,K=U!==void 0?$J(U):void 0;if(K!==void 0&&!qH5(K)){let E=Ex(K,"snapshot"),z=MF0(Z.progress,E),W=Z.needsProgressSnapshot&&z.type==="snapshot"?z:Ry4(Z.sentProgress,z);if(Z.progress=z,this.options.log.wsMessage("SEND",this.clientID,{type:"tool_progress",toolCallId:Q,progress:W}),this.sendTransportMessage("tool_progress",()=>this.transport.sendToolProgress(Q,W),{toolCallId:Q}))Z.sentProgress=z,Z.needsProgressSnapshot=!1;else Z.needsProgressSnapshot=!0}if(S5(V.status))G.unsubscribe(),this.prepareAndSendToolResult(X,V,Z);if(V.status==="blocked-on-user")this.options.log.info(`${this.clientID} awaiting tool approval`,{toolCallId:Q,toolName:B})},error:(V)=>{if(Y.signal.aborted){F();return}this.options.log.error(`${this.clientID} tool execution failed: ${B}`,V);let U={status:"error",error:{message:V instanceof Error?V.message:"Unknown error"}};this.prepareAndSendToolResult(X,U,Z)}});Z.subscription=G}catch(X){this.options.log.error(`${this.clientID} tool execution setup failed: ${B}`,X);let D={status:"error",error:{message:X instanceof Error?X.message:String(X)}};this.prepareAndSendToolResult(A,D,Z)}}flushBufferedTerminalResults(){if(this.disposing||this.pendingTerminalResults.size===0)return;for(let[A,Q]of this.pendingTerminalResults)this.sendPendingTerminalResult(A,Q,"flush")}markActiveProgressSnapshotsRequired(){for(let A of this.activeTools.values())A.needsProgressSnapshot=!0}handleToolRevocation(A){if(this.disposing)return;let{toolCallId:Q,reason:B}=A;this.options.log.info(`${this.clientID} lease revoked: ${Q}`,{reason:B});let $=this.activeTools.get(Q);if($)$.abortController.abort(),$.subscription.unsubscribe(),this.activeTools.delete(Q);this.sentApprovalRequests.delete(Q)}triggerGitStatus(A){this.queueGitStatusSnapshot(A)}dispose(){this.disposing=!0;for(let[,A]of this.activeTools)A.abortController.abort(),A.subscription.unsubscribe();this.activeTools.clear(),this.pendingTerminalResults.clear()}async prepareAndSendToolResult(A,Q,B){try{let $=this.toToolRun(Q);if(this.options.requestPluginToolResult&&this.options.threadId)$=await this.requestPluginToolResult(A,$);if(this.disposing||B.abortController.signal.aborted||this.activeTools.get(A.toolCallId)!==B)return;this.sendToolResult(A.toolCallId,$)}catch($){this.options.log.error(`${this.clientID} failed to prepare tool result`,$)}finally{if(this.activeTools.get(A.toolCallId)===B)this.activeTools.delete(A.toolCallId)}}sendToolResult(A,Q){let B=Date.now(),$=$J(Q),{run:J,files:Y}=this.extractGuidanceFromRun($),Z=this.prepareGuidanceDiscoveryBatches(A,Y),F={run:J,guidanceBatches:Z};this.pendingTerminalResults.set(A,F),this.sendPendingTerminalResult(A,F,"live",{guidanceFileCount:Y.length,elapsedMs:Date.now()-B}),this.sentApprovalRequests.delete(A),this.queueGitStatusSnapshot(A)}sendPendingTerminalResult(A,Q,B,$){if(!this.sendGuidanceDiscoveryBatches(A,Q.guidanceBatches))return!1;return this.sendTerminalResult(A,Q.run,B,$)}async requestPluginToolCall(A){let Q=this.options.threadId,B=this.options.requestPluginToolCall;if(!Q||!B)return{lease:A};let $={thread:{id:Q},toolUseID:A.toolCallId,tool:A.toolName,input:this.getLeaseArgs(A)};try{let J=await B($);switch(J.action){case"allow":return{lease:A};case"modify":return{lease:{...A,args:J.input}};case"reject-and-continue":return{shortCircuitRun:{status:"done",result:`Tool rejected by plugin: ${J.message}`}};case"synthesize":return{shortCircuitRun:{status:"done",result:J.result.output}};case"error":return{shortCircuitRun:{status:"error",error:{message:`Plugin error: ${J.message}`,displayMessage:J.message}}}}}catch(J){return this.options.log.error(`${this.clientID} plugin tool.call failed`,J),{shortCircuitRun:{status:"error",error:{message:J instanceof Error?J.message:String(J)}}}}}async requestPluginToolResult(A,Q){let B=this.options.threadId,$=this.options.requestPluginToolResult;if(!B||!$||Q.status!=="done"&&Q.status!=="error"&&Q.status!=="cancelled")return Q;let J={thread:{id:B},toolUseID:A.toolCallId,tool:A.toolName,input:this.getLeaseArgs(A),status:Q.status,error:Q.status==="error"?Q.error?.message:void 0,output:Q.status==="done"?Q.result:void 0};try{let Y=await $(J);if(!Y)return Q;switch(Y.status){case"done":return{status:"done",result:Y.output??(Q.status==="done"?Q.result:""),progress:Q.progress,trackFiles:Q.status==="done"?Q.trackFiles:void 0};case"error":return{status:"error",progress:Q.progress,error:{message:Y.error??(Q.status==="error"?Q.error?.message??"Tool execution failed":"Tool execution failed")}};case"cancelled":return{status:"cancelled",progress:Q.progress,reason:Y.error??(Q.status==="cancelled"?Q.reason:void 0)}}}catch(Y){this.options.log.error(`${this.clientID} plugin tool.result failed`,Y)}return Q}getLeaseArgs(A){if(typeof A.args==="object"&&A.args!==null&&!Array.isArray(A.args))return A.args;return{}}sendTerminalResult(A,Q,B,$){this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_result",toolCallId:A,run:Q});let J=this.sendTransportMessage("executor_tool_result",()=>this.transport.sendExecutorToolResult(A,Q),{toolCallId:A,source:B});return this.options.log.info(`${this.clientID} executor_tool_result send attempted`,{toolCallId:A,status:Q.status,sent:J,source:B,...$}),J}ackTerminalResult(A){if(this.pendingTerminalResults.delete(A.toolCallId))this.options.log.info(`${this.clientID} executor_tool_result acknowledged`,{toolCallId:A.toolCallId})}handleExecutorError(A){if(A.code!=="LEASE_NOT_FOUND"||A.toolCallId===void 0)return;if(this.pendingTerminalResults.delete(A.toolCallId))this.options.log.info(`${this.clientID} executor_tool_result rejected`,{toolCallId:A.toolCallId,code:A.code})}prepareGuidanceDiscoveryBatches(A,Q){let B=Q.map((Y)=>{if(typeof Y.hash==="string"||typeof Y.content!=="string")return Y;return{...Y,hash:Ut0(Y.content)}}),$=this.options.guidanceContentCache,J=$?Kt0(B,$):B;return this.options.batchGuidanceFiles(J,A)}sendGuidanceDiscoveryBatches(A,Q){for(let B=0;B<Q.length;B++){let $=Q[B];if(!$)continue;let J=B===Q.length-1,Y=$.filter((F)=>F.content!==void 0).map((F)=>F.uri),Z=$.filter((F)=>F.content===void 0).map((F)=>F.uri);if(this.options.log.wsMessage("SEND",this.clientID,{type:"executor_guidance_discovery",toolCallId:A,fileCount:$.length,withContent:Y,contentOmitted:Z,isLast:J}),!this.sendTransportMessage("executor_guidance_discovery",()=>this.transport.sendExecutorGuidanceDiscovery({toolCallId:A,files:$,isLast:J}),{toolCallId:A,isLast:J,fileCount:$.length,withContent:Y,contentOmitted:Z}))return!1}return!0}queueGitStatusSnapshot(A){if(this.disposing||!this.options.captureGitStatus)return;if(this.gitStatusQueue.inFlight){if(this.gitStatusQueue.queued=!0,A)this.gitStatusQueue.queuedToolCallId=A;return}this.gitStatusQueue.inFlight=!0,this.sendGitStatusSnapshot(A).finally(()=>{if(this.gitStatusQueue.inFlight=!1,!this.gitStatusQueue.queued)return;let Q=this.gitStatusQueue.queuedToolCallId;this.gitStatusQueue.queued=!1,this.gitStatusQueue.queuedToolCallId=void 0,this.queueGitStatusSnapshot(Q)})}async sendGitStatusSnapshot(A){try{if(!this.options.captureGitStatus)return;let Q=await this.options.captureGitStatus();this.options.log.wsMessage("SEND",this.clientID,{type:"executor_artifact_upsert",available:Q.available,fileCount:Q.files.length,toolCallId:A,branch:Q.branch,head:Q.head}),this.transport.sendExecutorArtifactUpsert(Vt0(Q),A)}catch(Q){this.options.log.error("Failed to send git status snapshot",Q)}}toToolRun(A){switch(A.status){case"done":return{status:"done",result:A.result,progress:A.progress,trackFiles:A.trackFiles?[...A.trackFiles]:void 0};case"error":return{status:"error",error:{message:A.error?this.options.renderToolRunError(A.error):"Tool execution failed"}};case"rejected-by-user":return{status:"rejected-by-user",reason:A.reason};case"cancelled":return{status:"cancelled",reason:A.reason};default:return{status:"error",error:{message:`Unexpected status: ${A.status}`}}}}extractGuidanceFromRun(A){if(A.status!=="done")return{run:A,files:[]};if(!A.result||typeof A.result!=="object"||Array.isArray(A.result))return{run:A,files:[]};let Q=A.result;if(!("discoveredGuidanceFiles"in Q))return{run:A,files:[]};let B=ky4(Q.discoveredGuidanceFiles),{discoveredGuidanceFiles:$,...J}=Q;return{run:{...A,result:J},files:B}}sendTransportMessage(A,Q,B){try{return Q(),!0}catch($){if($ instanceof c3)return this.options.log.info(`${this.clientID} dropped ${A} while reconnecting`,{messageType:A,...B}),this.options.onTransportSendFailure?.(this.clientID,A,$,B),!1;return this.options.log.error(`${this.clientID} failed to send ${A}`,$),!1}}}class wj{options;toolRunner;sentApprovalRequests;handshakeManager;runtimeLog;guidanceContentCache=new Zo;toolSyncSubscription;advertisedExecutorTools=[];hasCompletedBootstrap=!1;executorCallbacksAttached=!1;constructor(A){this.options=A;this.runtimeLog=this.options.log??{info:(Q,B)=>rB.info(Q,{...B,threadId:this.options.threadId}),error:(Q,B)=>rB.error(Q,{error:B,threadId:this.options.threadId}),wsMessage:(Q,B,$)=>{rB.info("websocket message",{threadId:this.options.threadId,...Bt0($,{direction:Q,clientID:B})})}},this.toolSyncSubscription=this.options.toolService.tools.subscribe({next:(Q)=>{this.syncExecutorToolRegistrations(Xt0(Q))}}),this.handshakeManager=new hx4({handshake:(Q)=>this.bootstrapExecutor({executorType:this.options.executorType,trigger:Q,suppressConnectLog:!0}),forceReconnect:(Q)=>this.options.transport.forceReconnect(Q),...this.options.handshakeManagerOptions}),this.toolRunner=new gx4({clientID:this.options.clientID,transport:this.options.transport,log:this.runtimeLog,threadId:this.options.threadId,invokeTool:(Q)=>this.invokeTool(Q),requestPluginToolCall:this.options.requestPluginToolCall,requestPluginToolResult:this.options.requestPluginToolResult,captureGitStatus:this.options.captureGitStatus,batchGuidanceFiles:this.options.batchGuidanceFiles??((Q)=>[Q]),guidanceContentCache:this.guidanceContentCache,renderToolRunError:this.options.renderToolRunError??((Q)=>Q?.message??"Tool run failed"),onTransportSendFailure:this.options.onTransportSendFailure}),this.sentApprovalRequests=this.toolRunner.sentApprovalRequests}ensureHandshake(A){return this.handshakeManager.ensureHandshake(A)}ensureReady(A){return this.handshakeManager.ensureReady(A)}handleConnectionChange(A){if(this.runtimeLog.info(`${this.options.clientID} handling connection change`,{state:A.state,role:A.role,transportClientId:A.clientId,reconnectCauseType:A.reconnectCause?.type,reconnectCauseCode:A.reconnectCause?.code,reconnectCauseReason:A.reconnectCause?.reason,hasCompletedBootstrap:this.hasCompletedBootstrap,executorCallbacksAttached:this.executorCallbacksAttached}),A.state!=="connected"||A.role!=="executor")this.toolRunner.markActiveProgressSnapshotsRequired();if(A.state!=="connected"&&A.role==="executor")this.guidanceContentCache.clear();this.handshakeManager.handleConnectionChange(A)}onToolLeaseMessage(A){this.handleToolLease(A)}onToolLeaseRevokedMessage(A){this.handleToolLeaseRevoked(A)}onExecutorFileSystemReadDirectoryRequestMessage(A){this.handleExecutorFileSystemReadDirectoryRequest(A)}onExecutorFileSystemReadFileRequestMessage(A){this.handleExecutorFileSystemReadFileRequest(A)}attachTransportExecutorCallbacks(A){if(!this.options.transport.setExecutorCallbacks){this.executorCallbacksAttached=!0;return}let Q=A?.includeConnectionChanges??!1,B=this.getInboundExecutorHandlers(),$={onToolLease:(J)=>{this.runtimeLog.info("onToolLease",{data:J}),B.onToolLease(J)},onToolLeaseRevoked:(J)=>{this.runtimeLog.info("onToolLeaseRevoked",{data:J}),B.onToolLeaseRevoked(J)},onExecutorToolResultAck:(J)=>{this.runtimeLog.info("onExecutorToolResultAck",{data:J}),this.toolRunner.ackTerminalResult(J)},onExecutorError:(J)=>{this.runtimeLog.info("onExecutorError",{data:J}),this.toolRunner.handleExecutorError(J)},onFileSystemReadFileRequest:(J)=>{this.runtimeLog.info("onFileSystemReadFileRequest",{data:J}),B.onFileSystemReadFileRequest(J)}};if(Q)$.onConnectionChange=(J)=>{this.runtimeLog.info("onConnectionChange",{data:J}),this.handleConnectionChange(J)};if(B.onFileSystemReadDirectoryRequest){let J=B.onFileSystemReadDirectoryRequest;$.onFileSystemReadDirectoryRequest=(Y)=>{this.runtimeLog.info("onFileSystemReadDirectoryRequest",{data:Y}),J(Y)}}if(this.options.pluginService){let J=bF0({pluginService:this.options.pluginService,sendPluginMessage:(Y)=>this.options.transport.sendPluginMessage(Y)});$.onPluginMessage=(Y)=>{this.runtimeLog.info("onPluginMessage",{data:Y}),J(Y)}}this.options.transport.setExecutorCallbacks($),this.executorCallbacksAttached=!0}advertisePluginReadinessIfEnabled(){if(!this.options.pluginService)return;try{this.options.transport.sendPluginMessage({type:"event",event:"plugins.ready",data:{}})}catch(A){this.runtimeLog.error("failed to advertise plugin readiness",A)}}dispose(){this.toolSyncSubscription?.unsubscribe(),this.toolSyncSubscription=void 0,this.clearTransportExecutorCallbacks(),this.toolRunner.dispose(),this.handshakeManager.dispose()}syncExecutorToolRegistrations(A){let Q=this.options.transport.getConnectionInfo();if(Q.state!=="connected"||Q.role!=="executor")return;this.advertisedExecutorTools=ux4({transport:this.options.transport,nextTools:A,previouslyAdvertisedTools:this.advertisedExecutorTools,logMessage:(B,$)=>{this.runtimeLog.wsMessage(B,this.options.clientID,$)}})}clearTransportExecutorCallbacks(){if(!this.executorCallbacksAttached)return;this.executorCallbacksAttached=!1}async invokeTool(A){return this.options.invokeTool(A)}async bootstrapExecutor(A){await this.connectAsExecutor(A.executorType??this.options.executorType,A.workspaceRoot??this.options.workspaceRoot??"",A.threadId??this.options.threadId,A.trigger,A.suppressConnectLog)}async connectAsExecutor(A,Q,B,$,J=!1){if(!J)rB.info(`Connecting ${this.options.clientID} as executor...`);try{let{advertisedTools:Y}=await wH5({transport:this.options.transport,executorClientID:this.options.clientID,workspaceRoot:Q,threadId:B,configService:this.options.configService,toolService:this.options.toolService,skillService:this.options.skillService,fileSystem:this.options.fileSystem,logMessage:this.options.bootstrapLogMessage,executorType:A,initialToolDiscovery:this.options.initialToolDiscovery,sendGitSnapshot:this.options.sendGitSnapshot??!1,previouslyAdvertisedTools:this.advertisedExecutorTools,allowResumeBootstrap:this.hasCompletedBootstrap,onBootstrapProgress:this.options.onBootstrapProgress,guidanceContentCache:this.guidanceContentCache});if(this.advertisedExecutorTools=Y,this.hasCompletedBootstrap=!0,this.toolRunner.flushBufferedTerminalResults(),await this.options.pluginService?.event.sessionStart({thread:{id:B}}),this.advertisePluginReadinessIfEnabled(),this.options.onBootstrapSuccess)await this.options.onBootstrapSuccess($)}catch(Y){throw rB.error(`executor ${this.options.clientID} bootstrap failed`,Y),Y}}getInboundExecutorHandlers(){let A={onToolLease:(Q)=>{this.handleToolLease(Q)},onToolLeaseRevoked:(Q)=>{this.handleToolLeaseRevoked(Q)},onFileSystemReadFileRequest:(Q)=>{this.handleExecutorFileSystemReadFileRequest(Q)}};if(this.options.handleExecutorFileSystemReadDirectoryRequest||this.options.readFileSystemDirectory)A.onFileSystemReadDirectoryRequest=(Q)=>{this.handleExecutorFileSystemReadDirectoryRequest(Q)};return A}maybeLogInboundExecutorMessage(A){if(!this.options.logInboundExecutorMessages)return;this.runtimeLog.wsMessage("RECV",this.options.clientID,A)}handleToolLease(A){this.maybeLogInboundExecutorMessage(A),this.toolRunner.handleToolLease(A)}handleToolLeaseRevoked(A){this.maybeLogInboundExecutorMessage(A),this.toolRunner.handleToolRevocation(A)}async handleExecutorFileSystemReadDirectoryRequest(A){if(this.maybeLogInboundExecutorMessage(A),this.options.handleExecutorFileSystemReadDirectoryRequest){await this.options.handleExecutorFileSystemReadDirectoryRequest(A);return}if(!this.options.readFileSystemDirectory)throw Error("Method not implemented.");let Q=await this.options.readFileSystemDirectory(A);this.options.transport.sendExecutorFileSystemReadDirectoryResult(A.requestId,Q)}handleExecutorFileSystemReadFileRequest(A){if(this.maybeLogInboundExecutorMessage(A),this.options.handleExecutorFileSystemReadFileRequest){this.options.handleExecutorFileSystemReadFileRequest(A);return}throw Error("Method not implemented.")}}E9();async function nY(A,Q,B,$={}){let J={...A?{threadId:A}:{},...$.repositoryURL?{repositoryURL:$.repositoryURL}:{},...!A&&$.executorType?{executorType:$.executorType}:{},...$.agentMode?{agentMode:$.agentMode}:{},...$.relationship?{relationship:$.relationship}:{},...$.usesThreadActors?{usesThreadActors:!0}:{}};if(!A&&$.threadMeta)J.threadMeta=$.threadMeta;let Y=await M2("/api/thread-actors",mx4({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(J),signal:$.signal},B),Q);if(!Y.ok)throw Error(`Failed to create thread-actors thread: ${Y.status} ${await Y.text()}`);let Z=await Y.json();if(!Z.threadId||!Z.wsToken)throw Error("Thread actors thread creation response missing threadId or wsToken");if(!Z.ownerUserId||typeof Z.threadVersion!=="number")throw Error("Thread actors thread creation response missing ownerUserId or threadVersion");return{threadId:Z.threadId,wsToken:Z.wsToken,usesDtw:Z.usesDtw??!0,usesThreadActors:Z.usesThreadActors??!1,executorType:Z.executorType??null,ownerUserId:Z.ownerUserId,threadVersion:Z.threadVersion,...Z.agentMode?{agentMode:Z.agentMode}:{}}}function mx4(A,Q){if(!Q)return A;return{...A,headers:{...A?.headers,Authorization:`Bearer ${Q}`}}}async function px4(A,Q,B,$={}){let J={};if($.executorType)J.executorType=$.executorType;let Y=await M2(`/api/thread-actors/${A}`,mx4({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(J),...$.signal?{signal:$.signal}:{}},B),Q);if(!Y.ok)throw Error(`Failed to mark thread ${A} as imported: ${Y.status} ${await Y.text()}`)}d0();i4();M1();function dx4(A){let{message:Q,sessionId:B,streamJsonThinking:$,currentTurnAssistantIds:J,currentTurnToolUseIds:Y}=A;if(!J.has(Q.messageId))return null;if(!Q.state)return null;if(Q.content.length===0)return null;let Z=Wv4(Q,B,null,{includeThinking:$});for(let F of Q.content)if(F.type==="tool_use")Y.add(F.id);return Z}function cx4(A){let{message:Q,sessionId:B,currentTurnToolUseIds:$}=A,J=Q.content.some((Z)=>Z.type==="tool_result"),Y=Q.content.some((Z)=>Z.type==="tool_result"&&$.has(Z.toolUseID));if(J&&!Y)return null;return Hv4(Q,B,null)}function lx4(A){return A.inputDone&&A.assistantDone&&A.idleSinceLastSend&&A.agentIdle}var ix4=1048576;async function nx4(A){let{client:Q,observer:B,dependencies:$,threadID:J,userInput:Y,stdinInput:Z,agentMode:F,reasoningEffort:X,streamJsonThinking:D,streamJsonInput:G,stdin:V}=A;if(Z&&Z.length>ix4)throw Error(`Stdin input too large: ${Z.length} bytes (max ${ix4})`);let U=J,K=Date.now(),E=F??"smart",z=jH5($),W=null,H=()=>{return W??=OH5($,E),W},q=!1,N=!1,I=0,w="",O=!1,L=!0,P=new Set;return new Promise((T,k)=>{let x=[],h="pending",f=null,S=null,u=UF0(async(Z0)=>{try{await Z0()}catch(R0){j.error("stream-json-actors emit failed",{error:R0})}}),d=async(Z0)=>{if(h==="emitted")return;let R0=await z;await RH5({sessionId:U,tools:Z0,mcpServers:R0,agentMode:E,reasoningEffort:X}),h="emitted";let B0=x.splice(0);for(let N0 of B0)await hF(N0)},c=(Z0)=>{if(h!=="pending")return;h="queued",f=Z0,u(async()=>{await d(Z0)})},g=(Z0)=>{if(h!=="emitted"){x.push(Z0);return}u(async()=>{await hF(Z0)})},l=async()=>{if(h==="emitted")return;await d(f??await H())},s=LH5({onSuccess:async()=>{await u(async()=>{await l(),await PH5({sessionId:U,startTime:K,numTurns:I,result:w})}),T({threadID:J,outcome:"success"})},onError:async(Z0)=>{await u(async()=>{await l(),await _H5({sessionId:U,startTime:K,numTurns:I,error:Z0})}),T({threadID:J,outcome:"error"})},onFatal:(Z0)=>k(Z0),cleanup:()=>{if(N)return;N=!0,S?.unsubscribe(),A0.dispose()},isComplete:()=>N}),A0=vF0({client:Q,observer:B,toolService:$.toolService,callbacks:{onError:(Z0)=>{s.error(Z0)},onTransitionToIdle:(Z0)=>{if(Z0.length>0){TH5({client:Q,approvals:Z0,complete:s});return}if(A0.agentIdle())L=!0;H0()},onMessageAdded:(Z0)=>{if(Z0.parentToolUseId)return;let R0=Z0.message;if(R0.role==="assistant"){let B0=dx4({message:R0,sessionId:U,streamJsonThinking:D,currentTurnAssistantIds:A0.currentTurnAssistantIds,currentTurnToolUseIds:P});if(!B0)return;if(g(B0),I++,B0.message.stop_reason==="end_turn")w=E8(R0.content),O=!0,H0()}else if(R0.role==="user"){let B0=cx4({message:R0,sessionId:U,currentTurnToolUseIds:P});if(!B0)return;g(B0)}},onSignal:()=>{s.error("User cancelled (SIGINT/SIGTERM)")}}});S=B.inferenceTools$.subscribe((Z0)=>{if(Z0.parentToolCallId)return;c(Z0.tools)});let H0=()=>{if(N)return;if(lx4({inputDone:q,assistantDone:O,idleSinceLastSend:L,agentIdle:A0.agentIdle()}))s.success()},V0=(Z0,R0)=>{L=!1,Q.sendUserMessage(Z0,E,R0)};if(G){(async()=>{try{for await(let Z0 of KF0(V)){if(N)break;V0(Z0.contentBlocks,kH5(Z0))}q=!0,H0()}catch(Z0){s.error(jU(Z0))}})();return}let w0=[{type:"text",text:Y}];if(Z)w0.unshift({type:"text",text:`Input received on stdin:
4705
4705
  \`\`\`
4706
4706
  ${Z}
4707
- \`\`\``});try{V0(w0),q=!0}catch(Z0){s.error(jU(Z0))}})}function MH5(A){let{onSuccess:Q,onError:B,onFatal:$,cleanup:J,isComplete:Y}=A;return{success:async()=>{if(Y())return;J();try{await Q()}catch(Z){$(Z)}},error:async(Z)=>{if(Y())return;J();try{await B(Z)}catch(F){$(F)}}}}async function LH5(A,Q){try{return(await T1(A.toolService.getTools(Q).pipe(w2(1),MB(5000)))).map(($)=>$.spec.name)}catch(B){return j.warn("Unable to obtain fallback tool list for system init message",{err:B}),[]}}async function OH5(A){try{return(await T1(A.mcpService.servers.pipe(w2(1),MB(5000)))).map((B)=>({name:B.name,status:B.status.type}))}catch(Q){return j.warn("Unable to obtain MCP server list for system init message",{err:Q}),[]}}async function jH5(A){let Q={type:"system",subtype:"init",cwd:process.cwd(),session_id:A.sessionId,tools:A.tools,mcp_servers:A.mcpServers,agent_mode:A.agentMode};if(A.reasoningEffort!==void 0)Q.reasoning_effort=A.reasoningEffort;await hF(Q)}async function RH5(A){let Q={type:"result",subtype:"success",duration_ms:Date.now()-A.startTime,is_error:!1,num_turns:A.numTurns,result:A.result,session_id:A.sessionId};await hF(Q)}async function PH5(A){let Q={type:"result",subtype:"error_during_execution",duration_ms:Date.now()-A.startTime,is_error:!0,num_turns:A.numTurns,error:A.error,session_id:A.sessionId};await hF(Q)}function _H5(A){let{client:Q,approvals:B,complete:$}=A;for(let Z of B)try{Q.resolveToolApproval(Z.toolUseId,!1,{denyFeedback:"stream-json execute-mode rejected blocked approval"})}catch(F){j.warn("Failed to resolve blocked approval",{error:F})}let J=[...new Set(B.map((Z)=>Z.toolName))],Y=J.length>0?`The following tools require user approval, which is not supported in stream JSON mode: ${J.join(", ")}`:"A tool requires user approval, which is not supported in stream JSON mode";$.error(Y)}function TH5(A){return A.steer!==void 0?{steer:A.steer}:void 0}eX();wY0();Cc();wn0();kV();i4();r1();M1();async function YI(A){let{toolName:Q,dtwArtifactSyncService:B,configService:$,toolService:J,mcpService:Y,skillService:Z,fsTracker:F,toolUseID:X,discoveredGuidanceFileURIs:D,threadId:G}=A,V={id:G??c2(),created:Date.now(),v:0,messages:[]},U=o0.file(process.cwd()),K=X??iZ(),E=await $.getLatest(),z,W;if(F)z=F.trackedFileSystem(K),W=F.tracker;else W=NY0(Mu0,V.id,async()=>{}),z=Cn0(j3,W,K);let H=(q,N)=>$D({filesystem:z},q,N);return{dir:U,tool:Q,thread:V,dtwArtifactSyncService:B,trackedFiles:new vQ,toolUseID:K,todos:void 0,configService:$,toolService:J,mcpService:Y,config:E,filesystem:z,fileChangeTracker:W,getAllTrackedChanges:async()=>W.getAllRecords(),threadEnvironment:{trees:[],platform:"cli"},handleThreadDelta:()=>Promise.resolve(),threadService:{observe:()=>m0.of(V),get:()=>Promise.resolve(V),getPrimitiveProperty:(q,N)=>Promise.resolve(V[N]),flushVersion:()=>Promise.resolve(),updateThreadMeta:()=>Promise.resolve()},getThreadEnvironment:()=>Promise.resolve({trees:[],platform:"cli"}),getEnvironmentData:H,threadSummaryService:{summarizeThread:()=>Promise.resolve({summary:"CLI execution",prompt:"CLI execution",title:"CLI Tool"})},osFileSystem:j3,deleteThread:()=>Promise.resolve(),generateThreadTitle:()=>Promise.resolve({title:"CLI Tool Execution"}),fileChangeTrackerStorage:Mu0,discoveredGuidanceFileURIs:D??new Set,skillService:Z??{getSkills:()=>Promise.resolve([]),getTargetDir:()=>Promise.resolve("/tmp/skills"),listInstalled:()=>[],reload:()=>{}}}}var ax4=45000;async function ox4(A){let{apiKey:Q,ampURL:B,workspaceRoot:$,dependencies:J,userInput:Y,stdinInput:Z,stats:F,streamJson:X,streamJsonThinking:D,streamJsonInput:G,stdin:V,agentMode:U,reasoningEffort:K,labels:E,initialThreadID:z,initialThreadMeta:W,initialSettings:H}=A,q=process.env.RIVET_PUBLIC_ENDPOINT??uF(B),N=Ll(J.configService),I=async(k)=>{let x=await N.getThread(k);return x?xF0(x):null},w=new rx4,O=Wx((k)=>{let x={executorType:"local-client"};if(U)x.agentMode=U;if(W&&!k)x.threadMeta=W;return nY(k,J.configService,Q,x)},z),L=new PU({transport:Hx({rivetEndpoint:q,credentialsProvider:O,initialThreadID:z,pingIntervalMs:5000}),threadHistoryLoader:I,observerCallbacks:w}),P=QI.parse(`amp-x-${kH5()}`),T=null;try{let k=z?(await L.loadThreadHistory(z))?.version??0:0;await L.connect();let x=L.getThreadId();if(!x)throw new J9("Thread client connected without a thread ID");if(!z&&H)L.sendClientUpdateThreadSettings(H);if(T=new wj({transport:L,toolService:J.toolService,configService:J.configService,clientID:P,threadId:x,pluginService:J.pluginService,requestPluginToolCall:(f)=>J.pluginService.event.toolCall(f),requestPluginToolResult:(f)=>J.pluginService.event.toolResult(f),invokeTool:async(f)=>{let S=typeof f.args==="object"&&f.args!==null?f.args:{},u=await YI({toolName:f.toolName,configService:J.configService,toolService:J.toolService,mcpService:J.mcpService,skillService:J.skillService,toolUseID:f.toolCallId,threadId:x});return J.toolService.invokeTool(f.toolName,{args:S},u)},readFileSystemDirectory:({uri:f})=>qx({fileSystem:J.fileSystem,workspaceRoot:$},f),skillService:J.skillService,sendGitSnapshot:!1,executorType:"local-client",workspaceRoot:$}),T.attachTransportExecutorCallbacks({includeConnectionChanges:!0}),T.handleConnectionChange(L.getConnectionInfo()),await T.ensureReady({timeoutMs:ax4,timeoutMessage:`Timed out waiting for executor handshake after ${ax4}ms`}),L.resumeFromVersion(k),X){let f=await nx4({client:L,observer:w,dependencies:J,threadID:x,userInput:Y,stdinInput:Z,agentMode:U,reasoningEffort:K,streamJsonThinking:!!D,streamJsonInput:!!G,stdin:V??process.stdin});if(f.outcome==="success"&&E&&E.length>0)await Hj(f.threadID,E,J.configService);return f.threadID}let h=await SH5(L,w,J,Y,Z,U,F,x);if(E&&E.length>0)await Hj(h,E,J.configService);return h}finally{if(T)T.dispose();L.dispose()}}function SH5(A,Q,B,$,J,Y,Z,F){return new Promise((X,D)=>{let G=!1,V=()=>{if(G)return;G=!0,K.dispose(),X(F)},U=(z)=>{j.error("error",{error:z}),process.stderr.write(`Error: ${z}
4708
- `),V()},K=vF0({client:A,observer:Q,toolService:B.toolService,callbacks:{onError:U,onTransitionToIdle:(z)=>{if(z.length===0)return;vH5(A,z[0]),V()},onMessageAdded:(z)=>{if(z.parentToolUseId)return;let W=z.message;if(!K.agentStarted())return;if(W.role!=="assistant")return;if(!K.currentTurnAssistantIds.has(W.messageId))return;if(!W.state)return;if(W.content.some((q)=>q.type==="tool_use"))return;let H=W.content.filter((q)=>q.type==="text").map((q)=>q.text).join("").trim();if(Z){let q=W.usage,N={result:H,usage:{input_tokens:q?.inputTokens||0,output_tokens:q?.outputTokens||0,cache_creation_input_tokens:q?.cacheCreationInputTokens||0,cache_read_input_tokens:q?.cacheReadInputTokens||0}};process.stdout.write(`${JSON.stringify(N)}
4707
+ \`\`\``});try{V0(w0),q=!0}catch(Z0){s.error(jU(Z0))}})}function LH5(A){let{onSuccess:Q,onError:B,onFatal:$,cleanup:J,isComplete:Y}=A;return{success:async()=>{if(Y())return;J();try{await Q()}catch(Z){$(Z)}},error:async(Z)=>{if(Y())return;J();try{await B(Z)}catch(F){$(F)}}}}async function OH5(A,Q){try{return(await T1(A.toolService.getTools(Q).pipe(w2(1),MB(5000)))).map(($)=>$.spec.name)}catch(B){return j.warn("Unable to obtain fallback tool list for system init message",{err:B}),[]}}async function jH5(A){try{return(await T1(A.mcpService.servers.pipe(w2(1),MB(5000)))).map((B)=>({name:B.name,status:B.status.type}))}catch(Q){return j.warn("Unable to obtain MCP server list for system init message",{err:Q}),[]}}async function RH5(A){let Q={type:"system",subtype:"init",cwd:process.cwd(),session_id:A.sessionId,tools:A.tools,mcp_servers:A.mcpServers,agent_mode:A.agentMode};if(A.reasoningEffort!==void 0)Q.reasoning_effort=A.reasoningEffort;await hF(Q)}async function PH5(A){let Q={type:"result",subtype:"success",duration_ms:Date.now()-A.startTime,is_error:!1,num_turns:A.numTurns,result:A.result,session_id:A.sessionId};await hF(Q)}async function _H5(A){let Q={type:"result",subtype:"error_during_execution",duration_ms:Date.now()-A.startTime,is_error:!0,num_turns:A.numTurns,error:A.error,session_id:A.sessionId};await hF(Q)}function TH5(A){let{client:Q,approvals:B,complete:$}=A;for(let Z of B)try{Q.resolveToolApproval(Z.toolUseId,!1,{denyFeedback:"stream-json execute-mode rejected blocked approval"})}catch(F){j.warn("Failed to resolve blocked approval",{error:F})}let J=[...new Set(B.map((Z)=>Z.toolName))],Y=J.length>0?`The following tools require user approval, which is not supported in stream JSON mode: ${J.join(", ")}`:"A tool requires user approval, which is not supported in stream JSON mode";$.error(Y)}function kH5(A){return A.steer!==void 0?{steer:A.steer}:void 0}eX();wY0();Cc();wn0();kV();i4();r1();M1();async function YI(A){let{toolName:Q,dtwArtifactSyncService:B,configService:$,toolService:J,mcpService:Y,skillService:Z,fsTracker:F,toolUseID:X,discoveredGuidanceFileURIs:D,threadId:G}=A,V={id:G??c2(),created:Date.now(),v:0,messages:[]},U=o0.file(process.cwd()),K=X??iZ(),E=await $.getLatest(),z,W;if(F)z=F.trackedFileSystem(K),W=F.tracker;else W=NY0(Mu0,V.id,async()=>{}),z=Cn0(j3,W,K);let H=(q,N)=>$D({filesystem:z},q,N);return{dir:U,tool:Q,thread:V,dtwArtifactSyncService:B,trackedFiles:new vQ,toolUseID:K,todos:void 0,configService:$,toolService:J,mcpService:Y,config:E,filesystem:z,fileChangeTracker:W,getAllTrackedChanges:async()=>W.getAllRecords(),threadEnvironment:{trees:[],platform:"cli"},handleThreadDelta:()=>Promise.resolve(),threadService:{observe:()=>m0.of(V),get:()=>Promise.resolve(V),getPrimitiveProperty:(q,N)=>Promise.resolve(V[N]),flushVersion:()=>Promise.resolve(),updateThreadMeta:()=>Promise.resolve()},getThreadEnvironment:()=>Promise.resolve({trees:[],platform:"cli"}),getEnvironmentData:H,threadSummaryService:{summarizeThread:()=>Promise.resolve({summary:"CLI execution",prompt:"CLI execution",title:"CLI Tool"})},osFileSystem:j3,deleteThread:()=>Promise.resolve(),generateThreadTitle:()=>Promise.resolve({title:"CLI Tool Execution"}),fileChangeTrackerStorage:Mu0,discoveredGuidanceFileURIs:D??new Set,skillService:Z??{getSkills:()=>Promise.resolve([]),getTargetDir:()=>Promise.resolve("/tmp/skills"),listInstalled:()=>[],reload:()=>{}}}}var ax4=45000;async function ox4(A){let{apiKey:Q,ampURL:B,workspaceRoot:$,dependencies:J,userInput:Y,stdinInput:Z,stats:F,streamJson:X,streamJsonThinking:D,streamJsonInput:G,stdin:V,agentMode:U,reasoningEffort:K,labels:E,initialThreadID:z,initialThreadMeta:W,initialSettings:H}=A,q=process.env.RIVET_PUBLIC_ENDPOINT??uF(B),N=Ll(J.configService),I=async(k)=>{let x=await N.getThread(k);return x?xF0(x):null},w=new rx4,O=Wx((k)=>{let x={executorType:"local-client"};if(U)x.agentMode=U;if(W&&!k)x.threadMeta=W;return nY(k,J.configService,Q,x)},z),L=new PU({transport:Hx({rivetEndpoint:q,credentialsProvider:O,initialThreadID:z,pingIntervalMs:5000}),threadHistoryLoader:I,observerCallbacks:w}),P=QI.parse(`amp-x-${SH5()}`),T=null;try{let k=z?(await L.loadThreadHistory(z))?.version??0:0;await L.connect();let x=L.getThreadId();if(!x)throw new J9("Thread client connected without a thread ID");if(!z&&H)L.sendClientUpdateThreadSettings(H);if(T=new wj({transport:L,toolService:J.toolService,configService:J.configService,clientID:P,threadId:x,pluginService:J.pluginService,requestPluginToolCall:(f)=>J.pluginService.event.toolCall(f),requestPluginToolResult:(f)=>J.pluginService.event.toolResult(f),invokeTool:async(f)=>{let S=typeof f.args==="object"&&f.args!==null?f.args:{},u=await YI({toolName:f.toolName,configService:J.configService,toolService:J.toolService,mcpService:J.mcpService,skillService:J.skillService,toolUseID:f.toolCallId,threadId:x});return J.toolService.invokeTool(f.toolName,{args:S},u)},readFileSystemDirectory:({uri:f})=>qx({fileSystem:J.fileSystem,workspaceRoot:$},f),skillService:J.skillService,sendGitSnapshot:!1,executorType:"local-client",workspaceRoot:$}),T.attachTransportExecutorCallbacks({includeConnectionChanges:!0}),T.handleConnectionChange(L.getConnectionInfo()),await T.ensureReady({timeoutMs:ax4,timeoutMessage:`Timed out waiting for executor handshake after ${ax4}ms`}),L.resumeFromVersion(k),X){let f=await nx4({client:L,observer:w,dependencies:J,threadID:x,userInput:Y,stdinInput:Z,agentMode:U,reasoningEffort:K,streamJsonThinking:!!D,streamJsonInput:!!G,stdin:V??process.stdin});if(f.outcome==="success"&&E&&E.length>0)await Hj(f.threadID,E,J.configService);return f.threadID}let h=await vH5(L,w,J,Y,Z,U,F,x);if(E&&E.length>0)await Hj(h,E,J.configService);return h}finally{if(T)T.dispose();L.dispose()}}function vH5(A,Q,B,$,J,Y,Z,F){return new Promise((X,D)=>{let G=!1,V=()=>{if(G)return;G=!0,K.dispose(),X(F)},U=(z)=>{j.error("error",{error:z}),process.stderr.write(`Error: ${z}
4708
+ `),V()},K=vF0({client:A,observer:Q,toolService:B.toolService,callbacks:{onError:U,onTransitionToIdle:(z)=>{if(z.length===0)return;yH5(A,z[0]),V()},onMessageAdded:(z)=>{if(z.parentToolUseId)return;let W=z.message;if(!K.agentStarted())return;if(W.role!=="assistant")return;if(!K.currentTurnAssistantIds.has(W.messageId))return;if(!W.state)return;if(W.content.some((q)=>q.type==="tool_use"))return;let H=W.content.filter((q)=>q.type==="text").map((q)=>q.text).join("").trim();if(Z){let q=W.usage,N={result:H,usage:{input_tokens:q?.inputTokens||0,output_tokens:q?.outputTokens||0,cache_creation_input_tokens:q?.cacheCreationInputTokens||0,cache_read_input_tokens:q?.cacheReadInputTokens||0}};process.stdout.write(`${JSON.stringify(N)}
4709
4709
  `)}else if(H)process.stdout.write(`${H}
4710
4710
  `);V()},onSignal:V}}),E=[{type:"text",text:$}];if(J)E.unshift({type:"text",text:`Input received on stdin:
4711
4711
  \`\`\`
4712
4712
  ${J}
4713
- \`\`\``});try{A.sendUserMessage(E,Y??"smart")}catch(z){if(G)return;G=!0,K.dispose(),D(z)}})}function vH5(A,Q){if(!Q)return;try{A.resolveToolApproval(Q.toolUseId,!1,{denyFeedback:"execute-mode rejected blocked approval"})}catch(B){j.warn("Failed to resolve blocked approval",{error:B})}if(Q.toolName===tA){let B=bN(Q.args);process.stderr.write(`Error: The ${tA} tool tried to run a command that isn't allowlisted. Rerun with --dangerously-allow-all to bypass, or add to the command allowlist in permissions (https://ampcode.com/manual#permissions).
4713
+ \`\`\``});try{A.sendUserMessage(E,Y??"smart")}catch(z){if(G)return;G=!0,K.dispose(),D(z)}})}function yH5(A,Q){if(!Q)return;try{A.resolveToolApproval(Q.toolUseId,!1,{denyFeedback:"execute-mode rejected blocked approval"})}catch(B){j.warn("Failed to resolve blocked approval",{error:B})}if(Q.toolName===tA){let B=bN(Q.args);process.stderr.write(`Error: The ${tA} tool tried to run a command that isn't allowlisted. Rerun with --dangerously-allow-all to bypass, or add to the command allowlist in permissions (https://ampcode.com/manual#permissions).
4714
4714
 
4715
4715
  Command:
4716
4716
 
4717
- ${xH5("\t",B??"(unknown)")}
4717
+ ${fH5("\t",B??"(unknown)")}
4718
4718
 
4719
4719
  `)}else process.stderr.write(`Error: The ${Q.toolName} tool is not allowed to run in execute mode. Rerun with --dangerously-allow-all to bypass.
4720
- `)}class rx4{messageAdded$=new m4;agentState$=new m4;inferenceTools$=new m4;activeError$=new A4(null);errorNotice$=new m4;seenMessageIds=new Set;onMessageAdded(A){if(this.seenMessageIds.has(A.message.messageId))return;this.seenMessageIds.add(A.message.messageId),this.messageAdded$.next({message:A.message,parentToolUseId:A.parentToolUseId??yH5(A.message)})}onAgentState(A){this.agentState$.next(A)}onInferenceTools(A){this.inferenceTools$.next(A)}onActiveError(A){this.activeError$.next(A.type==="error_set"?A.error:null)}onErrorNotice(A){this.errorNotice$.next(A.message)}}function yH5(A){let Q=A.parentToolUseId;return typeof Q==="string"&&Q.length>0?Q:null}function xH5(A,Q){if(!Q)return Q;return A+Q.split(`
4720
+ `)}class rx4{messageAdded$=new m4;agentState$=new m4;inferenceTools$=new m4;activeError$=new A4(null);errorNotice$=new m4;seenMessageIds=new Set;onMessageAdded(A){if(this.seenMessageIds.has(A.message.messageId))return;this.seenMessageIds.add(A.message.messageId),this.messageAdded$.next({message:A.message,parentToolUseId:A.parentToolUseId??xH5(A.message)})}onAgentState(A){this.agentState$.next(A)}onInferenceTools(A){this.inferenceTools$.next(A)}onActiveError(A){this.activeError$.next(A.type==="error_set"?A.error:null)}onErrorNotice(A){this.errorNotice$.next(A.message)}}function xH5(A){let Q=A.parentToolUseId;return typeof Q==="string"&&Q.length>0?Q:null}function fH5(A,Q){if(!Q)return Q;return A+Q.split(`
4721
4721
  `).join(`
4722
- ${A}`)}d0();k50();import{mkdir as sx4,open as fH5,readFile as tx4,unlink as ex4,writeFile as Et0}from"node:fs/promises";import{homedir as bH5}from"node:os";import Fo from"node:path";var uH5=Fo.join(TH||Fo.join(bH5(),".local/share"),"amp"),hH5=Fo.join(uH5,"history.jsonl"),gH5=2097152;function zt0(A){return A.text.length+(A.cwd?.length??0)}class Xo{history=[];historyBytes=0;index=-1;loaded=!1;historyFile;maxBytes;constructor(A){this.historyFile=A?.historyFile||hH5,this.maxBytes=A?.maxBytes??gH5,this.ensureLoaded()}async ensureLoaded(){if(!this.loaded)await this.cleanupStaleLockFile(),this.history=await this.readHistoryFromDisk(),this.historyBytes=this.history.reduce((A,Q)=>A+zt0(Q),0),this.loaded=!0}async cleanupStaleLockFile(){let A=this.historyFile+".lock";try{await ex4(A),j.info("Cleaned up stale lock file",{lockFile:A})}catch(Q){if(Q.code!=="ENOENT")j.warn("Failed to clean up stale lock file",{lockFile:A,error:Q instanceof Error?Q.message:String(Q)})}}async readHistoryFromDisk(){try{let A=await tx4(this.historyFile,"utf-8");if(!A.trim())return[];return this.parseJsonlContent(A)}catch(A){if(A.code!=="ENOENT")return j.warn("Failed to read history file",{error:A instanceof Error?A.message:String(A)}),[];if(this.historyFile.endsWith(".jsonl")){let Q=this.historyFile.replace(".jsonl",".json");try{let B=await tx4(Q,"utf-8");if(B.trim()){let $=JSON.parse(B);j.info("Migrating from old history.json to history.jsonl",{oldFile:Q,newFile:this.historyFile,size:$.length});let J=$.map((Y)=>({text:Y}));await this.writeHistoryToDisk(J);try{await import("node:fs/promises").then((Y)=>Y.unlink(Q))}catch{}return J}}catch{}}return[]}}parseJsonlContent(A){let Q=A.trim().split(`
4722
+ ${A}`)}d0();k50();import{mkdir as sx4,open as bH5,readFile as tx4,unlink as ex4,writeFile as Et0}from"node:fs/promises";import{homedir as uH5}from"node:os";import Fo from"node:path";var hH5=Fo.join(TH||Fo.join(uH5(),".local/share"),"amp"),gH5=Fo.join(hH5,"history.jsonl"),mH5=2097152;function zt0(A){return A.text.length+(A.cwd?.length??0)}class Xo{history=[];historyBytes=0;index=-1;loaded=!1;historyFile;maxBytes;constructor(A){this.historyFile=A?.historyFile||gH5,this.maxBytes=A?.maxBytes??mH5,this.ensureLoaded()}async ensureLoaded(){if(!this.loaded)await this.cleanupStaleLockFile(),this.history=await this.readHistoryFromDisk(),this.historyBytes=this.history.reduce((A,Q)=>A+zt0(Q),0),this.loaded=!0}async cleanupStaleLockFile(){let A=this.historyFile+".lock";try{await ex4(A),j.info("Cleaned up stale lock file",{lockFile:A})}catch(Q){if(Q.code!=="ENOENT")j.warn("Failed to clean up stale lock file",{lockFile:A,error:Q instanceof Error?Q.message:String(Q)})}}async readHistoryFromDisk(){try{let A=await tx4(this.historyFile,"utf-8");if(!A.trim())return[];return this.parseJsonlContent(A)}catch(A){if(A.code!=="ENOENT")return j.warn("Failed to read history file",{error:A instanceof Error?A.message:String(A)}),[];if(this.historyFile.endsWith(".jsonl")){let Q=this.historyFile.replace(".jsonl",".json");try{let B=await tx4(Q,"utf-8");if(B.trim()){let $=JSON.parse(B);j.info("Migrating from old history.json to history.jsonl",{oldFile:Q,newFile:this.historyFile,size:$.length});let J=$.map((Y)=>({text:Y}));await this.writeHistoryToDisk(J);try{await import("node:fs/promises").then((Y)=>Y.unlink(Q))}catch{}return J}}catch{}}return[]}}parseJsonlContent(A){let Q=A.trim().split(`
4723
4723
  `),B=[];for(let $ of Q)if($.trim())try{let J=JSON.parse($);if(typeof J==="string")B.push({text:J});else if(typeof J==="object"&&J!==null&&typeof J.text==="string")B.push({text:J.text,cwd:typeof J.cwd==="string"?J.cwd:void 0});else j.warn("Skipping invalid entry in history",{line:$,type:typeof J})}catch(J){j.warn("Skipping invalid JSONL line in history",{line:$})}return B}async writeHistoryToDisk(A){await sx4(Fo.dirname(this.historyFile),{recursive:!0});let Q=A.map((B)=>JSON.stringify(B)).join(`
4724
4724
  `)+`
4725
4725
  `;await Et0(this.historyFile,Q,{encoding:"utf-8",mode:384})}async add(A,Q){if(!A.trim())return;if(await this.ensureLoaded(),this.history.length>0&&this.history[this.history.length-1]?.text===A)return;let B={text:A,cwd:Q};try{if(await sx4(Fo.dirname(this.historyFile),{recursive:!0}),await this.atomicAppend(B),this.history.push(B),this.historyBytes+=zt0(B),this.historyBytes>this.maxBytes){let $=0;while($<this.history.length&&this.historyBytes>this.maxBytes){let J=this.history[$];if(J)this.historyBytes-=zt0(J);$++}this.history=this.history.slice($),await this.writeHistoryToDisk(this.history)}}catch($){j.error(`Failed to save history: ${$ instanceof Error?$.message:String($)}`)}this.reset()}async atomicAppend(A){let Q=JSON.stringify(A)+`
4726
- `,B=this.historyFile+".lock",$=10,J=50;for(let Y=0;Y<10;Y++)try{let Z=await fH5(B,"wx");try{await Et0(this.historyFile,Q,{flag:"a",encoding:"utf-8",mode:384})}finally{await Z.close(),await Et0(B,"",{flag:"w"});try{await ex4(B)}catch{}}return}catch(Z){if(Z.code==="EEXIST"&&Y<9){await new Promise((F)=>setTimeout(F,50));continue}throw Z}throw Error("Failed to acquire lock for history file after multiple attempts")}getAll(){return[...this.history]}previous(){if(this.history.length===0)return null;if(this.index===0)return this.history[0]?.text??null;if(this.index===-1)this.index=this.history.length-1;else this.index--;return this.history[this.index]?.text??null}next(){if(this.history.length===0||this.index===-1)return null;if(this.index++,this.index>=this.history.length)return this.index=-1,null;return this.history[this.index]?.text??null}reset(){this.index=-1}}d0();import Kf4 from"node:os";import FI from"node:path";import{Worker as Zq5}from"node:worker_threads";d0();d0();import{exec as mH5,execFile as pH5,execSync as Af4}from"node:child_process";import{promises as pF0}from"node:fs";import{join as Do}from"node:path";import{promisify as Qf4}from"node:util";var dH5=Qf4(mH5),dF0=Qf4(pH5),cH5="git --no-optional-locks status --porcelain=v2 --untracked-files=normal --no-renames -z";class Bf4{async watch(A){}unwatch(A){}dispose(){}onFileSystemEvent(A){}offFileSystemEvent(A){}getWatchedPaths(){return[]}isSupported(){return!1}}class $f4{watchedPaths=new Map;callbacks=[];pollInterval;constructor(A=1000){this.pollInterval=A}async watch(A){if(this.watchedPaths.has(A))return;let{promises:Q}=await import("node:fs"),B=new Map;try{await this.scanPath(Q,A,B)}catch(J){throw Error(`Failed to watch path ${A}: ${J}`)}let $=setInterval(async()=>{try{await this.checkForChanges(Q,A,B)}catch(J){j.warn("Error polling path",{path:A,error:J})}},this.pollInterval);this.watchedPaths.set(A,{interval:$,lastModified:B})}unwatch(A){let Q=this.watchedPaths.get(A);if(Q)clearInterval(Q.interval),this.watchedPaths.delete(A)}dispose(){for(let A of Array.from(this.watchedPaths.keys()))this.unwatch(A);this.callbacks.length=0}onFileSystemEvent(A){this.callbacks.push(A)}offFileSystemEvent(A){let Q=this.callbacks.indexOf(A);if(Q>=0)this.callbacks.splice(Q,1)}getWatchedPaths(){return Array.from(this.watchedPaths.keys())}isSupported(){return!0}async scanPath(A,Q,B){try{let $=await A.stat(Q);if(B.set(Q,$.mtime.getTime()),$.isDirectory()){let J=await A.readdir(Q);for(let Y of J){let Z=Do(Q,Y);await this.scanPath(A,Z,B)}}}catch($){}}async checkForChanges(A,Q,B){let $=[],J=new Map;await this.scanPath(A,Q,J);for(let[Y,Z]of Array.from(J.entries())){let F=B.get(Y);if(F===void 0)$.push({type:"created",path:Y,timestamp:Date.now(),isDirectory:await this.isDirectory(A,Y)});else if(Z>F)$.push({type:"modified",path:Y,timestamp:Date.now(),isDirectory:await this.isDirectory(A,Y)})}for(let Y of Array.from(B.keys()))if(!J.has(Y))$.push({type:"deleted",path:Y,timestamp:Date.now(),isDirectory:!1});B.clear();for(let[Y,Z]of Array.from(J.entries()))B.set(Y,Z);if($.length>0)for(let Y of this.callbacks)try{Y($)}catch(Z){j.error("Error in file watcher callback",{error:Z})}}async isDirectory(A,Q){try{return(await A.stat(Q)).isDirectory()}catch{return!1}}}class Lx{static isRepo(A){try{return Af4("git rev-parse --is-inside-work-tree",{cwd:A,stdio:"ignore"}),!0}catch{return!1}}repos=new Map;callbacks=[];ongoingScans=new Map;scanCooldownMs;constructor(A=5000){this.scanCooldownMs=A}async resolveRepoRoot(A){let{stdout:Q}=await dF0("git",["rev-parse","--show-toplevel"],{cwd:A});return Q.trim()}async watch(A){let Q=await this.resolveRepoRoot(A);if(this.repos.has(Q))return;await this.initialise(Q)}unwatch(A){if(!this.repos.get(A))return;this.repos.delete(A),this.ongoingScans.delete(A)}dispose(){for(let A of Array.from(this.repos.keys()))this.unwatch(A);this.callbacks.length=0}onFileSystemEvent(A){this.callbacks.push(A)}offFileSystemEvent(A){let Q=this.callbacks.indexOf(A);if(Q!==-1)this.callbacks.splice(Q,1)}getWatchedPaths(){return Array.from(this.repos.keys())}isSupported(){try{return Af4("git --version",{stdio:"ignore"}),!0}catch{return!1}}async triggerScan(A,Q=!1){let B=await this.resolveRepoRoot(A),$=this.repos.get(B);if(!$){if(j.debug("First time watching repo",{repoRoot:B}),await this.watch(A),$=this.repos.get(B),!$)return;return}let J=Date.now(),Y=J-$.lastScanTime;if(!Q&&Y<this.scanCooldownMs)return;j.debug("Starting scan",{repoRoot:B,force:Q,timeSinceLastScan:Y}),$.lastScanTime=J,await this.scan(B)}async reset(A){let Q=await this.resolveRepoRoot(A),B=this.repos.get(Q);if(!B)return;B.cancelled=!0;let $=this.ongoingScans.get(Q);if($)await $.catch(()=>{});this.repos.delete(Q),this.ongoingScans.delete(Q),await this.watch(A)}async initialise(A){let Q=Date.now(),B=await dF0("git",["ls-files","--others","--exclude-standard","-z"],{cwd:A,maxBuffer:67108864}),$=new Set,J=B.stdout.split("\x00").filter(Boolean);for(let Y of J){let Z=Do(A,Y);$.add(Z)}this.repos.set(A,{lastScanTime:Q,seenUntracked:$})}async scan(A){let Q=this.repos.get(A);if(!Q||Q.cancelled)return;let B=this.performScan(A);this.ongoingScans.set(A,B);try{await B}finally{if(this.ongoingScans.get(A)===B)this.ongoingScans.delete(A)}}async performScan(A){let Q=this.repos.get(A);if(!Q||Q.cancelled)return;let B=Date.now();try{let[$,J]=await Promise.all([dF0("git",["ls-files","--others","--exclude-standard","-z"],{cwd:A,maxBuffer:1/0,timeout:60000}),dF0("git",["ls-files","--deleted","-z"],{cwd:A,maxBuffer:1/0,timeout:60000})]),Y=$.stdout.split("\x00").filter(Boolean),Z=J.stdout.split("\x00").filter(Boolean),F=[],X=[],D=this.repos.get(A);if(!D||D.cancelled)return;let G=[],V=new Set;for(let U of Y){let K=Do(A,U);V.add(K);try{let E=await pF0.stat(K);if(!E.isFile())continue;if(!D.seenUntracked.has(K))F.push(K),G.push({type:"created",path:K,timestamp:E.mtimeMs,isDirectory:!1});else X.push(K)}catch{}}for(let U of Array.from(D.seenUntracked))if(!V.has(U)){if(!await pF0.access(U).then(()=>!0).catch(()=>!1))G.push({type:"deleted",path:U,timestamp:B,isDirectory:!1})}for(let U of Z){let K=Do(A,U);G.push({type:"deleted",path:K,timestamp:B,isDirectory:!1})}if(D.seenUntracked=V,D.lastScanTime=B,G.length)for(let U of this.callbacks)U(G)}catch($){j.warn("Fast ls-files scan failed, falling back to full status",{repoRoot:A,error:$ instanceof Error?$.message:String($),duration:Date.now()-B}),await this.performFullStatusScan(A)}}async performFullStatusScan(A){let Q=this.repos.get(A);if(!Q||Q.cancelled)return;let B=Date.now(),{stdout:$}=await dH5(cH5,{cwd:A,maxBuffer:16777216}),J=this.repos.get(A);if(!J||J.cancelled)return;let Y=[],Z=[],F=[],X=[],D=[];for(let G of this.parseStatus($)){let V=Do(A,G.path);if(G.type==="created"){Z.push(V);let U=await pF0.stat(V).catch(()=>null);if(!U){D.push(V);continue}if(U.isFile()&&U.mtimeMs>J.lastScanTime)X.push(V),Y.push({type:"created",path:V,timestamp:U.mtimeMs,isDirectory:!1});else D.push(V)}if(G.type==="deleted")F.push(V),Y.push({type:"deleted",path:V,timestamp:B,isDirectory:!1})}if(j.debug("Git status discovery (status)",{repoRoot:A,createdDiscovered:Z,deletedDiscovered:F,createdNew:X,createdNotNew:D,counts:{createdDiscovered:Z.length,deletedDiscovered:F.length,createdNew:X.length,createdNotNew:D.length}}),Y.length)for(let G of this.callbacks)G(Y)}parseStatus(A){let Q=[],B=A.split("\x00");for(let $ of B){if(!$)continue;let J=$[0];if(J==="?"){let Y=$.slice(2);Q.push({type:"created",path:Y});continue}if(J==="1"){let Y=$[2],Z=$.substring($.indexOf("\t")+1);if(Y==="D")Q.push({type:"deleted",path:Z});else if(Y==="A")Q.push({type:"created",path:Z})}}return Q}}function cF0(A){if(A?.useGit)return new Lx(A.pollInterval);if(A?.usePolling)return new $f4(A.pollInterval);let Q=A?.rootPath||process.cwd();if(Lx.isRepo(Q)){let B=new Lx(A?.pollInterval);if(B.isSupported())return j.info("Git repository detected, using GitFileWatcher",{rootPath:Q}),B}return j.info("Not a git repository, using NoOpFileWatcher",{rootPath:Q}),new Bf4}r1();d0();var Df4=v4(KE(),1);import{EventEmitter as tH5}from"node:events";import{promises as eH5}from"node:fs";import{relative as Aq5}from"node:path";r1();d0();var Zf4=v4(KE(),1);import{spawn as iH5}from"node:child_process";import{promises as Cj}from"node:fs";import{realpath as Jf4}from"node:fs/promises";import{dirname as nH5,join as Go,relative as Vo,resolve as aH5}from"node:path";class sB{bits;constructor(A){this.bits=A}static empty(){return new sB(0n)}static fromString(A){let Q=0n;for(let B=0;B<A.length;B++){let $=A.charCodeAt(B),J=sB.charToBitIndex($);if(J>=0)Q|=1n<<BigInt(J)}return new sB(Q)}static fromPath(A){let Q=0n,B=A.split(/[/\\]/);for(let $ of B){if($===""||$==="."||$==="..")continue;for(let J=0;J<$.length;J++){let Y=$.charCodeAt(J),Z=sB.charToBitIndex(Y);if(Z>=0)Q|=1n<<BigInt(Z)}}return new sB(Q)}hasChars(A){return(this.bits&A.bits)===A.bits}union(A){return new sB(this.bits|A.bits)}intersection(A){return new sB(this.bits&A.bits)}isEmpty(){return this.bits===0n}getCharCount(){return this.bits.toString(2).split("").filter((A)=>A==="1").length}toString(){let A=[];for(let Q=0;Q<64;Q++)if((this.bits&1n<<BigInt(Q))!==0n){let B=sB.bitIndexToChar(Q);if(B)A.push(B)}return`CharBag{${A.join("")}}`}toJSON(){return{bits:this.bits.toString()}}static fromJSON(A){return new sB(BigInt(A.bits))}equals(A){return this.bits===A.bits}static charToBitIndex(A){if(A>=65&&A<=90)A+=32;if(A>=48&&A<=57)return A-48;if(A>=97&&A<=122)return A-97+10;return-1}static bitIndexToChar(A){if(A>=0&&A<=9)return String.fromCharCode(48+A);if(A>=10&&A<=35)return String.fromCharCode(97+A-10);return null}}class ZI{id;kind;path;uri;charBag;metadata;isIgnored;isExternal;isPrivate;isAlwaysIncluded;constructor(A){this.id=A.id,this.kind=A.kind,this.path=A.path,this.uri=A.uri,this.metadata=A.metadata,this.isIgnored=A.isIgnored??!1,this.isExternal=A.isExternal??!1,this.isPrivate=A.isPrivate??!1,this.isAlwaysIncluded=A.isAlwaysIncluded??!1,this.charBag=sB.fromPath(this.path)}withUpdates(A){return new ZI({id:this.id,kind:A.kind??this.kind,path:this.path,uri:this.uri,metadata:A.metadata??this.metadata,isIgnored:A.isIgnored??this.isIgnored,isExternal:A.isExternal??this.isExternal,isPrivate:A.isPrivate??this.isPrivate,isAlwaysIncluded:A.isAlwaysIncluded??this.isAlwaysIncluded})}isFile(){return this.kind==="file"}isDirectory(){return this.kind==="directory"||this.kind==="unloaded-directory"||this.kind==="pending-directory"}isLoadedDirectory(){return this.kind==="directory"}getFilename(){return this.path.split(/[/\\]/).pop()||this.path}getExtension(){let A=this.getFilename(),Q=A.lastIndexOf(".");return Q>0?A.slice(Q+1):""}getDirectory(){let A=this.path.split(/[/\\]/);return A.length>1?A.slice(0,-1).join("/"):""}shouldIncludeInResults(){if(this.isAlwaysIncluded)return!0;if(this.isIgnored||this.isPrivate)return!1;return!0}shouldIncludeInMentions(){if(this.isAlwaysIncluded)return!0;if(this.isIgnored||this.isPrivate)return!1;if(this.isFile())return!0;return this.isLoadedDirectory()}getImportanceBoost(){return this.isAlwaysIncluded?0.1:0}toJSON(){return{id:this.id,kind:this.kind,path:this.path,uri:this.uri.toString(),metadata:this.metadata,isIgnored:this.isIgnored,isExternal:this.isExternal,isPrivate:this.isPrivate,isAlwaysIncluded:this.isAlwaysIncluded,charBag:this.charBag.toJSON()}}static fromJSON(A,Q){return new ZI({id:A.id,kind:A.kind,path:A.path,uri:Q(A.uri),metadata:A.metadata,isIgnored:A.isIgnored,isExternal:A.isExternal,isPrivate:A.isPrivate,isAlwaysIncluded:A.isAlwaysIncluded})}equals(A){return this.id===A.id&&this.kind===A.kind&&this.path===A.path&&this.metadata.mtime===A.metadata.mtime&&this.metadata.size===A.metadata.size}hashCode(){return`${this.path}:${this.metadata.mtime}:${this.metadata.size}`}toString(){return`Entry{${this.kind}:${this.path}}`}}class iQ{static DEFAULT_PATTERNS=[{pattern:"node_modules",type:"directory",description:"Node.js dependencies"},{pattern:"vendor",type:"directory",description:"PHP/Go/Ruby dependencies"},{pattern:"deps",type:"directory",description:"Elixir dependencies"},{pattern:"packages",type:"directory",description:".NET/NuGet packages"},{pattern:".gradle",type:"directory",description:"Gradle cache"},{pattern:".m2",type:"directory",description:"Maven repository"},{pattern:".dart_tool",type:"directory",description:"Dart/Flutter tools"},{pattern:".stack-work",type:"directory",description:"Haskell Stack build"},{pattern:".bundle",type:"directory",description:"Ruby Bundler cache"},{pattern:"__pycache__",type:"directory",description:"Python bytecode cache"},{pattern:".venv",type:"directory",description:"Python virtual environment"},{pattern:"venv",type:"directory",description:"Python virtual environment"},{pattern:".git",type:"directory",description:"Git repository"},{pattern:".svn",type:"directory",description:"Subversion repository"},{pattern:".hg",type:"directory",description:"Mercurial repository"},{pattern:"dist",type:"directory",description:"Distribution files"},{pattern:"build",type:"directory",description:"Build output"},{pattern:"out",type:"directory",description:"Output directory"},{pattern:"target",type:"directory",description:"Rust/Java build target"},{pattern:"_build",type:"directory",description:"Elixir build output"},{pattern:"dist-newstyle",type:"directory",description:"Haskell Cabal build"},{pattern:"zig-cache",type:"directory",description:"Zig build cache"},{pattern:"zig-out",type:"directory",description:"Zig build output"},{pattern:"nimcache",type:"directory",description:"Nim build cache"},{pattern:".dub",type:"directory",description:"D package manager cache"},{pattern:"bin",type:"directory",description:"Binary output"},{pattern:"obj",type:"directory",description:"Object files"},{pattern:"coverage",type:"directory",description:"Test coverage reports"},{pattern:".nyc_output",type:"directory",description:"NYC coverage output"},{pattern:"reports",type:"directory",description:"Test/build reports"},{pattern:".next",type:"directory",description:"Next.js build output"},{pattern:".nuxt",type:"directory",description:"Nuxt.js build output"},{pattern:".cache",type:"directory",description:"Cache directory"},{pattern:".parcel-cache",type:"directory",description:"Parcel cache"},{pattern:".webpack",type:"directory",description:"Webpack cache"},{pattern:".vscode",type:"directory",description:"VS Code settings"},{pattern:".idea",type:"directory",description:"IntelliJ IDEA settings"},{pattern:".elixir_ls",type:"directory",description:"Elixir Language Server cache"},{pattern:".sublime-project",type:"file",description:"Sublime Text project"},{pattern:".sublime-workspace",type:"file",description:"Sublime Text workspace"},{pattern:".DS_Store",type:"file",description:"macOS metadata"},{pattern:"Thumbs.db",type:"file",description:"Windows thumbnails"},{pattern:"desktop.ini",type:"file",description:"Windows folder settings"},{pattern:"*.log",type:"file",description:"Log files"},{pattern:"*.tmp",type:"file",description:"Temporary files"},{pattern:"*.temp",type:"file",description:"Temporary files"},{pattern:"*.swp",type:"file",description:"Vim swap files"},{pattern:"*.swo",type:"file",description:"Vim swap files"},{pattern:"*~",type:"file",description:"Backup files"},{pattern:"*.zip",type:"file",description:"ZIP archives"},{pattern:"*.tar.gz",type:"file",description:"Tar archives"},{pattern:"*.exe",type:"file",description:"Windows executables"},{pattern:"*.dll",type:"file",description:"Windows libraries"},{pattern:"*.so",type:"file",description:"Shared libraries"},{pattern:"*.dylib",type:"file",description:"macOS dynamic libraries"},{pattern:"*.class",type:"file",description:"Java bytecode"},{pattern:"*.pyc",type:"file",description:"Python bytecode"},{pattern:"*.pyo",type:"file",description:"Python optimized bytecode"}];static customPatterns=[];static shouldIgnore(A,Q){let B=[...iQ.DEFAULT_PATTERNS,...iQ.customPatterns];for(let $ of B){if($.type==="directory"&&!Q)continue;if($.type==="file"&&Q)continue;if(iQ.matchesPattern(A,$.pattern))return!0}return!1}static addCustomPattern(A){iQ.customPatterns.push(A)}static clearCustomPatterns(){iQ.customPatterns=[]}static getAllPatterns(){return[...iQ.DEFAULT_PATTERNS,...iQ.customPatterns]}static matchesPattern(A,Q){let $=A.replace(/\\/g,"/").split("/"),J=$[$.length-1];if(Q.includes("*"))return iQ.matchesGlob(J??"",Q);return $.some((Y)=>Y===Q)}static matchesGlob(A,Q){let B=Q.replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${B}$`).test(A)}}var Yf4=500000,Wt0=1e4;class Ht0{async scanDirectory(A,Q={respectIgnorePatterns:!0}){let B=Date.now(),$=aH5(A),{respectIgnorePatterns:J=!0,maxDepth:Y=20,maxFiles:Z=1e5,onProgress:F,signal:X,forceNodeJS:D=!1,strategy:G="auto",followSymlinks:V=!1,alwaysIncludePaths:U=[]}=Q,K=U.length>0?Zf4.default(U,{dot:!0}):void 0,E="nodejs",z=[],W=!1,H=0,q=await Jf4($).catch(()=>$),N=new Set;try{if(D||G==="nodejs")E="nodejs";else{let L=await this.tryExternalTools($,G,X,{followSymlinks:V,alwaysIncludeMatcher:K});if(L)z=L.entries,E=L.strategy,W=!0;else E="nodejs"}if(E==="nodejs"){let L=await this.scanWithNodeJS($,{respectIgnorePatterns:J,maxDepth:Y,maxFiles:Z,onProgress:F||(()=>{}),signal:X||new AbortController().signal,alwaysIncludeMatcher:K},{followSymlinks:V,rootRealPath:q,visitedRealDirs:N});z=L.entries,H=L.skippedPaths}if(E!=="nodejs"){if(isFinite(Z))z=z.slice(0,Z);if(F){let L=z.filter((T)=>T.kind==="file").length,P=z.filter((T)=>T.kind==="directory").length;F({scannedFiles:L,scannedDirectories:P,currentPath:$})}if(U.length>0){let L=await this.scanAlwaysIncludePaths($,U,K,z,{followSymlinks:V,rootRealPath:q,visitedRealDirs:N});z=[...z,...L]}}}catch(L){if(L instanceof Error&&(L.name==="AbortError"||L.message==="Scan aborted"))throw L;j.warn("Directory scan completed with errors",{error:L})}let I=Date.now()-B,w=z.filter((L)=>L.kind==="file").length,O=z.filter((L)=>L.kind==="directory").length;return{entries:z,stats:{totalFiles:w,totalDirectories:O,scanDuration:I,skippedPaths:H,strategy:E,externalToolsAvailable:W}}}async tryExternalTools(A,Q,B,$){let J=[];if(Q==="auto")if($.followSymlinks)J.push("ripgrep");else J.push("git","ripgrep");else if(Q==="git"){if(!$.followSymlinks)J.push("git")}else if(Q==="ripgrep")J.push("ripgrep");for(let Y of J)try{let Z=await this.runExternalTool(Y,A,B,{followSymlinks:$.followSymlinks,alwaysIncludeMatcher:$.alwaysIncludeMatcher});if(Z.length>0)return{entries:Z,strategy:Y};else j.debug("External tool returned no entries, trying next",{tool:Y})}catch(Z){j.debug("External tool failed, trying next",{tool:Y,error:Z})}return j.debug("All external tools failed, falling back to Node.js scanning"),null}async runExternalTool(A,Q,B,$){let J=A==="git"?"git":await Eq(),Y=A==="git"?["ls-files","--exclude-standard","--cached","--others"]:$.followSymlinks?["--files","--follow","--hidden","--glob","!.git/","--glob","!.jj/"]:["--files","--hidden","--glob","!.git/","--glob","!.jj/"];return new Promise((Z,F)=>{let X=iH5(J,Y,{cwd:Q,stdio:["ignore","pipe","pipe"]}),D=[],G="",V="",U=!1,K=(E)=>{if(!E||U)return;if(D.push(E),D.length>=Yf4){if(!U)j.warn("External directory scan limit reached. Returning partial results.",{tool:A,rootPath:Q,limit:Yf4}),U=!0,X.kill()}};if(X.stdout?.on("data",(E)=>{if(U)return;G+=E.toString("utf8");let z;while((z=G.indexOf(`
4726
+ `,B=this.historyFile+".lock",$=10,J=50;for(let Y=0;Y<10;Y++)try{let Z=await bH5(B,"wx");try{await Et0(this.historyFile,Q,{flag:"a",encoding:"utf-8",mode:384})}finally{await Z.close(),await Et0(B,"",{flag:"w"});try{await ex4(B)}catch{}}return}catch(Z){if(Z.code==="EEXIST"&&Y<9){await new Promise((F)=>setTimeout(F,50));continue}throw Z}throw Error("Failed to acquire lock for history file after multiple attempts")}getAll(){return[...this.history]}previous(){if(this.history.length===0)return null;if(this.index===0)return this.history[0]?.text??null;if(this.index===-1)this.index=this.history.length-1;else this.index--;return this.history[this.index]?.text??null}next(){if(this.history.length===0||this.index===-1)return null;if(this.index++,this.index>=this.history.length)return this.index=-1,null;return this.history[this.index]?.text??null}reset(){this.index=-1}}d0();import Kf4 from"node:os";import FI from"node:path";import{Worker as Fq5}from"node:worker_threads";d0();d0();import{exec as pH5,execFile as dH5,execSync as Af4}from"node:child_process";import{promises as pF0}from"node:fs";import{join as Do}from"node:path";import{promisify as Qf4}from"node:util";var cH5=Qf4(pH5),dF0=Qf4(dH5),lH5="git --no-optional-locks status --porcelain=v2 --untracked-files=normal --no-renames -z";class Bf4{async watch(A){}unwatch(A){}dispose(){}onFileSystemEvent(A){}offFileSystemEvent(A){}getWatchedPaths(){return[]}isSupported(){return!1}}class $f4{watchedPaths=new Map;callbacks=[];pollInterval;constructor(A=1000){this.pollInterval=A}async watch(A){if(this.watchedPaths.has(A))return;let{promises:Q}=await import("node:fs"),B=new Map;try{await this.scanPath(Q,A,B)}catch(J){throw Error(`Failed to watch path ${A}: ${J}`)}let $=setInterval(async()=>{try{await this.checkForChanges(Q,A,B)}catch(J){j.warn("Error polling path",{path:A,error:J})}},this.pollInterval);this.watchedPaths.set(A,{interval:$,lastModified:B})}unwatch(A){let Q=this.watchedPaths.get(A);if(Q)clearInterval(Q.interval),this.watchedPaths.delete(A)}dispose(){for(let A of Array.from(this.watchedPaths.keys()))this.unwatch(A);this.callbacks.length=0}onFileSystemEvent(A){this.callbacks.push(A)}offFileSystemEvent(A){let Q=this.callbacks.indexOf(A);if(Q>=0)this.callbacks.splice(Q,1)}getWatchedPaths(){return Array.from(this.watchedPaths.keys())}isSupported(){return!0}async scanPath(A,Q,B){try{let $=await A.stat(Q);if(B.set(Q,$.mtime.getTime()),$.isDirectory()){let J=await A.readdir(Q);for(let Y of J){let Z=Do(Q,Y);await this.scanPath(A,Z,B)}}}catch($){}}async checkForChanges(A,Q,B){let $=[],J=new Map;await this.scanPath(A,Q,J);for(let[Y,Z]of Array.from(J.entries())){let F=B.get(Y);if(F===void 0)$.push({type:"created",path:Y,timestamp:Date.now(),isDirectory:await this.isDirectory(A,Y)});else if(Z>F)$.push({type:"modified",path:Y,timestamp:Date.now(),isDirectory:await this.isDirectory(A,Y)})}for(let Y of Array.from(B.keys()))if(!J.has(Y))$.push({type:"deleted",path:Y,timestamp:Date.now(),isDirectory:!1});B.clear();for(let[Y,Z]of Array.from(J.entries()))B.set(Y,Z);if($.length>0)for(let Y of this.callbacks)try{Y($)}catch(Z){j.error("Error in file watcher callback",{error:Z})}}async isDirectory(A,Q){try{return(await A.stat(Q)).isDirectory()}catch{return!1}}}class Lx{static isRepo(A){try{return Af4("git rev-parse --is-inside-work-tree",{cwd:A,stdio:"ignore"}),!0}catch{return!1}}repos=new Map;callbacks=[];ongoingScans=new Map;scanCooldownMs;constructor(A=5000){this.scanCooldownMs=A}async resolveRepoRoot(A){let{stdout:Q}=await dF0("git",["rev-parse","--show-toplevel"],{cwd:A});return Q.trim()}async watch(A){let Q=await this.resolveRepoRoot(A);if(this.repos.has(Q))return;await this.initialise(Q)}unwatch(A){if(!this.repos.get(A))return;this.repos.delete(A),this.ongoingScans.delete(A)}dispose(){for(let A of Array.from(this.repos.keys()))this.unwatch(A);this.callbacks.length=0}onFileSystemEvent(A){this.callbacks.push(A)}offFileSystemEvent(A){let Q=this.callbacks.indexOf(A);if(Q!==-1)this.callbacks.splice(Q,1)}getWatchedPaths(){return Array.from(this.repos.keys())}isSupported(){try{return Af4("git --version",{stdio:"ignore"}),!0}catch{return!1}}async triggerScan(A,Q=!1){let B=await this.resolveRepoRoot(A),$=this.repos.get(B);if(!$){if(j.debug("First time watching repo",{repoRoot:B}),await this.watch(A),$=this.repos.get(B),!$)return;return}let J=Date.now(),Y=J-$.lastScanTime;if(!Q&&Y<this.scanCooldownMs)return;j.debug("Starting scan",{repoRoot:B,force:Q,timeSinceLastScan:Y}),$.lastScanTime=J,await this.scan(B)}async reset(A){let Q=await this.resolveRepoRoot(A),B=this.repos.get(Q);if(!B)return;B.cancelled=!0;let $=this.ongoingScans.get(Q);if($)await $.catch(()=>{});this.repos.delete(Q),this.ongoingScans.delete(Q),await this.watch(A)}async initialise(A){let Q=Date.now(),B=await dF0("git",["ls-files","--others","--exclude-standard","-z"],{cwd:A,maxBuffer:67108864}),$=new Set,J=B.stdout.split("\x00").filter(Boolean);for(let Y of J){let Z=Do(A,Y);$.add(Z)}this.repos.set(A,{lastScanTime:Q,seenUntracked:$})}async scan(A){let Q=this.repos.get(A);if(!Q||Q.cancelled)return;let B=this.performScan(A);this.ongoingScans.set(A,B);try{await B}finally{if(this.ongoingScans.get(A)===B)this.ongoingScans.delete(A)}}async performScan(A){let Q=this.repos.get(A);if(!Q||Q.cancelled)return;let B=Date.now();try{let[$,J]=await Promise.all([dF0("git",["ls-files","--others","--exclude-standard","-z"],{cwd:A,maxBuffer:1/0,timeout:60000}),dF0("git",["ls-files","--deleted","-z"],{cwd:A,maxBuffer:1/0,timeout:60000})]),Y=$.stdout.split("\x00").filter(Boolean),Z=J.stdout.split("\x00").filter(Boolean),F=[],X=[],D=this.repos.get(A);if(!D||D.cancelled)return;let G=[],V=new Set;for(let U of Y){let K=Do(A,U);V.add(K);try{let E=await pF0.stat(K);if(!E.isFile())continue;if(!D.seenUntracked.has(K))F.push(K),G.push({type:"created",path:K,timestamp:E.mtimeMs,isDirectory:!1});else X.push(K)}catch{}}for(let U of Array.from(D.seenUntracked))if(!V.has(U)){if(!await pF0.access(U).then(()=>!0).catch(()=>!1))G.push({type:"deleted",path:U,timestamp:B,isDirectory:!1})}for(let U of Z){let K=Do(A,U);G.push({type:"deleted",path:K,timestamp:B,isDirectory:!1})}if(D.seenUntracked=V,D.lastScanTime=B,G.length)for(let U of this.callbacks)U(G)}catch($){j.warn("Fast ls-files scan failed, falling back to full status",{repoRoot:A,error:$ instanceof Error?$.message:String($),duration:Date.now()-B}),await this.performFullStatusScan(A)}}async performFullStatusScan(A){let Q=this.repos.get(A);if(!Q||Q.cancelled)return;let B=Date.now(),{stdout:$}=await cH5(lH5,{cwd:A,maxBuffer:16777216}),J=this.repos.get(A);if(!J||J.cancelled)return;let Y=[],Z=[],F=[],X=[],D=[];for(let G of this.parseStatus($)){let V=Do(A,G.path);if(G.type==="created"){Z.push(V);let U=await pF0.stat(V).catch(()=>null);if(!U){D.push(V);continue}if(U.isFile()&&U.mtimeMs>J.lastScanTime)X.push(V),Y.push({type:"created",path:V,timestamp:U.mtimeMs,isDirectory:!1});else D.push(V)}if(G.type==="deleted")F.push(V),Y.push({type:"deleted",path:V,timestamp:B,isDirectory:!1})}if(j.debug("Git status discovery (status)",{repoRoot:A,createdDiscovered:Z,deletedDiscovered:F,createdNew:X,createdNotNew:D,counts:{createdDiscovered:Z.length,deletedDiscovered:F.length,createdNew:X.length,createdNotNew:D.length}}),Y.length)for(let G of this.callbacks)G(Y)}parseStatus(A){let Q=[],B=A.split("\x00");for(let $ of B){if(!$)continue;let J=$[0];if(J==="?"){let Y=$.slice(2);Q.push({type:"created",path:Y});continue}if(J==="1"){let Y=$[2],Z=$.substring($.indexOf("\t")+1);if(Y==="D")Q.push({type:"deleted",path:Z});else if(Y==="A")Q.push({type:"created",path:Z})}}return Q}}function cF0(A){if(A?.useGit)return new Lx(A.pollInterval);if(A?.usePolling)return new $f4(A.pollInterval);let Q=A?.rootPath||process.cwd();if(Lx.isRepo(Q)){let B=new Lx(A?.pollInterval);if(B.isSupported())return j.info("Git repository detected, using GitFileWatcher",{rootPath:Q}),B}return j.info("Not a git repository, using NoOpFileWatcher",{rootPath:Q}),new Bf4}r1();d0();var Df4=v4(KE(),1);import{EventEmitter as eH5}from"node:events";import{promises as Aq5}from"node:fs";import{relative as Qq5}from"node:path";r1();d0();var Zf4=v4(KE(),1);import{spawn as nH5}from"node:child_process";import{promises as Cj}from"node:fs";import{realpath as Jf4}from"node:fs/promises";import{dirname as aH5,join as Go,relative as Vo,resolve as oH5}from"node:path";class sB{bits;constructor(A){this.bits=A}static empty(){return new sB(0n)}static fromString(A){let Q=0n;for(let B=0;B<A.length;B++){let $=A.charCodeAt(B),J=sB.charToBitIndex($);if(J>=0)Q|=1n<<BigInt(J)}return new sB(Q)}static fromPath(A){let Q=0n,B=A.split(/[/\\]/);for(let $ of B){if($===""||$==="."||$==="..")continue;for(let J=0;J<$.length;J++){let Y=$.charCodeAt(J),Z=sB.charToBitIndex(Y);if(Z>=0)Q|=1n<<BigInt(Z)}}return new sB(Q)}hasChars(A){return(this.bits&A.bits)===A.bits}union(A){return new sB(this.bits|A.bits)}intersection(A){return new sB(this.bits&A.bits)}isEmpty(){return this.bits===0n}getCharCount(){return this.bits.toString(2).split("").filter((A)=>A==="1").length}toString(){let A=[];for(let Q=0;Q<64;Q++)if((this.bits&1n<<BigInt(Q))!==0n){let B=sB.bitIndexToChar(Q);if(B)A.push(B)}return`CharBag{${A.join("")}}`}toJSON(){return{bits:this.bits.toString()}}static fromJSON(A){return new sB(BigInt(A.bits))}equals(A){return this.bits===A.bits}static charToBitIndex(A){if(A>=65&&A<=90)A+=32;if(A>=48&&A<=57)return A-48;if(A>=97&&A<=122)return A-97+10;return-1}static bitIndexToChar(A){if(A>=0&&A<=9)return String.fromCharCode(48+A);if(A>=10&&A<=35)return String.fromCharCode(97+A-10);return null}}class ZI{id;kind;path;uri;charBag;metadata;isIgnored;isExternal;isPrivate;isAlwaysIncluded;constructor(A){this.id=A.id,this.kind=A.kind,this.path=A.path,this.uri=A.uri,this.metadata=A.metadata,this.isIgnored=A.isIgnored??!1,this.isExternal=A.isExternal??!1,this.isPrivate=A.isPrivate??!1,this.isAlwaysIncluded=A.isAlwaysIncluded??!1,this.charBag=sB.fromPath(this.path)}withUpdates(A){return new ZI({id:this.id,kind:A.kind??this.kind,path:this.path,uri:this.uri,metadata:A.metadata??this.metadata,isIgnored:A.isIgnored??this.isIgnored,isExternal:A.isExternal??this.isExternal,isPrivate:A.isPrivate??this.isPrivate,isAlwaysIncluded:A.isAlwaysIncluded??this.isAlwaysIncluded})}isFile(){return this.kind==="file"}isDirectory(){return this.kind==="directory"||this.kind==="unloaded-directory"||this.kind==="pending-directory"}isLoadedDirectory(){return this.kind==="directory"}getFilename(){return this.path.split(/[/\\]/).pop()||this.path}getExtension(){let A=this.getFilename(),Q=A.lastIndexOf(".");return Q>0?A.slice(Q+1):""}getDirectory(){let A=this.path.split(/[/\\]/);return A.length>1?A.slice(0,-1).join("/"):""}shouldIncludeInResults(){if(this.isAlwaysIncluded)return!0;if(this.isIgnored||this.isPrivate)return!1;return!0}shouldIncludeInMentions(){if(this.isAlwaysIncluded)return!0;if(this.isIgnored||this.isPrivate)return!1;if(this.isFile())return!0;return this.isLoadedDirectory()}getImportanceBoost(){return this.isAlwaysIncluded?0.1:0}toJSON(){return{id:this.id,kind:this.kind,path:this.path,uri:this.uri.toString(),metadata:this.metadata,isIgnored:this.isIgnored,isExternal:this.isExternal,isPrivate:this.isPrivate,isAlwaysIncluded:this.isAlwaysIncluded,charBag:this.charBag.toJSON()}}static fromJSON(A,Q){return new ZI({id:A.id,kind:A.kind,path:A.path,uri:Q(A.uri),metadata:A.metadata,isIgnored:A.isIgnored,isExternal:A.isExternal,isPrivate:A.isPrivate,isAlwaysIncluded:A.isAlwaysIncluded})}equals(A){return this.id===A.id&&this.kind===A.kind&&this.path===A.path&&this.metadata.mtime===A.metadata.mtime&&this.metadata.size===A.metadata.size}hashCode(){return`${this.path}:${this.metadata.mtime}:${this.metadata.size}`}toString(){return`Entry{${this.kind}:${this.path}}`}}class iQ{static DEFAULT_PATTERNS=[{pattern:"node_modules",type:"directory",description:"Node.js dependencies"},{pattern:"vendor",type:"directory",description:"PHP/Go/Ruby dependencies"},{pattern:"deps",type:"directory",description:"Elixir dependencies"},{pattern:"packages",type:"directory",description:".NET/NuGet packages"},{pattern:".gradle",type:"directory",description:"Gradle cache"},{pattern:".m2",type:"directory",description:"Maven repository"},{pattern:".dart_tool",type:"directory",description:"Dart/Flutter tools"},{pattern:".stack-work",type:"directory",description:"Haskell Stack build"},{pattern:".bundle",type:"directory",description:"Ruby Bundler cache"},{pattern:"__pycache__",type:"directory",description:"Python bytecode cache"},{pattern:".venv",type:"directory",description:"Python virtual environment"},{pattern:"venv",type:"directory",description:"Python virtual environment"},{pattern:".git",type:"directory",description:"Git repository"},{pattern:".svn",type:"directory",description:"Subversion repository"},{pattern:".hg",type:"directory",description:"Mercurial repository"},{pattern:"dist",type:"directory",description:"Distribution files"},{pattern:"build",type:"directory",description:"Build output"},{pattern:"out",type:"directory",description:"Output directory"},{pattern:"target",type:"directory",description:"Rust/Java build target"},{pattern:"_build",type:"directory",description:"Elixir build output"},{pattern:"dist-newstyle",type:"directory",description:"Haskell Cabal build"},{pattern:"zig-cache",type:"directory",description:"Zig build cache"},{pattern:"zig-out",type:"directory",description:"Zig build output"},{pattern:"nimcache",type:"directory",description:"Nim build cache"},{pattern:".dub",type:"directory",description:"D package manager cache"},{pattern:"bin",type:"directory",description:"Binary output"},{pattern:"obj",type:"directory",description:"Object files"},{pattern:"coverage",type:"directory",description:"Test coverage reports"},{pattern:".nyc_output",type:"directory",description:"NYC coverage output"},{pattern:"reports",type:"directory",description:"Test/build reports"},{pattern:".next",type:"directory",description:"Next.js build output"},{pattern:".nuxt",type:"directory",description:"Nuxt.js build output"},{pattern:".cache",type:"directory",description:"Cache directory"},{pattern:".parcel-cache",type:"directory",description:"Parcel cache"},{pattern:".webpack",type:"directory",description:"Webpack cache"},{pattern:".vscode",type:"directory",description:"VS Code settings"},{pattern:".idea",type:"directory",description:"IntelliJ IDEA settings"},{pattern:".elixir_ls",type:"directory",description:"Elixir Language Server cache"},{pattern:".sublime-project",type:"file",description:"Sublime Text project"},{pattern:".sublime-workspace",type:"file",description:"Sublime Text workspace"},{pattern:".DS_Store",type:"file",description:"macOS metadata"},{pattern:"Thumbs.db",type:"file",description:"Windows thumbnails"},{pattern:"desktop.ini",type:"file",description:"Windows folder settings"},{pattern:"*.log",type:"file",description:"Log files"},{pattern:"*.tmp",type:"file",description:"Temporary files"},{pattern:"*.temp",type:"file",description:"Temporary files"},{pattern:"*.swp",type:"file",description:"Vim swap files"},{pattern:"*.swo",type:"file",description:"Vim swap files"},{pattern:"*~",type:"file",description:"Backup files"},{pattern:"*.zip",type:"file",description:"ZIP archives"},{pattern:"*.tar.gz",type:"file",description:"Tar archives"},{pattern:"*.exe",type:"file",description:"Windows executables"},{pattern:"*.dll",type:"file",description:"Windows libraries"},{pattern:"*.so",type:"file",description:"Shared libraries"},{pattern:"*.dylib",type:"file",description:"macOS dynamic libraries"},{pattern:"*.class",type:"file",description:"Java bytecode"},{pattern:"*.pyc",type:"file",description:"Python bytecode"},{pattern:"*.pyo",type:"file",description:"Python optimized bytecode"}];static customPatterns=[];static shouldIgnore(A,Q){let B=[...iQ.DEFAULT_PATTERNS,...iQ.customPatterns];for(let $ of B){if($.type==="directory"&&!Q)continue;if($.type==="file"&&Q)continue;if(iQ.matchesPattern(A,$.pattern))return!0}return!1}static addCustomPattern(A){iQ.customPatterns.push(A)}static clearCustomPatterns(){iQ.customPatterns=[]}static getAllPatterns(){return[...iQ.DEFAULT_PATTERNS,...iQ.customPatterns]}static matchesPattern(A,Q){let $=A.replace(/\\/g,"/").split("/"),J=$[$.length-1];if(Q.includes("*"))return iQ.matchesGlob(J??"",Q);return $.some((Y)=>Y===Q)}static matchesGlob(A,Q){let B=Q.replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${B}$`).test(A)}}var Yf4=500000,Wt0=1e4;class Ht0{async scanDirectory(A,Q={respectIgnorePatterns:!0}){let B=Date.now(),$=oH5(A),{respectIgnorePatterns:J=!0,maxDepth:Y=20,maxFiles:Z=1e5,onProgress:F,signal:X,forceNodeJS:D=!1,strategy:G="auto",followSymlinks:V=!1,alwaysIncludePaths:U=[]}=Q,K=U.length>0?Zf4.default(U,{dot:!0}):void 0,E="nodejs",z=[],W=!1,H=0,q=await Jf4($).catch(()=>$),N=new Set;try{if(D||G==="nodejs")E="nodejs";else{let L=await this.tryExternalTools($,G,X,{followSymlinks:V,alwaysIncludeMatcher:K});if(L)z=L.entries,E=L.strategy,W=!0;else E="nodejs"}if(E==="nodejs"){let L=await this.scanWithNodeJS($,{respectIgnorePatterns:J,maxDepth:Y,maxFiles:Z,onProgress:F||(()=>{}),signal:X||new AbortController().signal,alwaysIncludeMatcher:K},{followSymlinks:V,rootRealPath:q,visitedRealDirs:N});z=L.entries,H=L.skippedPaths}if(E!=="nodejs"){if(isFinite(Z))z=z.slice(0,Z);if(F){let L=z.filter((T)=>T.kind==="file").length,P=z.filter((T)=>T.kind==="directory").length;F({scannedFiles:L,scannedDirectories:P,currentPath:$})}if(U.length>0){let L=await this.scanAlwaysIncludePaths($,U,K,z,{followSymlinks:V,rootRealPath:q,visitedRealDirs:N});z=[...z,...L]}}}catch(L){if(L instanceof Error&&(L.name==="AbortError"||L.message==="Scan aborted"))throw L;j.warn("Directory scan completed with errors",{error:L})}let I=Date.now()-B,w=z.filter((L)=>L.kind==="file").length,O=z.filter((L)=>L.kind==="directory").length;return{entries:z,stats:{totalFiles:w,totalDirectories:O,scanDuration:I,skippedPaths:H,strategy:E,externalToolsAvailable:W}}}async tryExternalTools(A,Q,B,$){let J=[];if(Q==="auto")if($.followSymlinks)J.push("ripgrep");else J.push("git","ripgrep");else if(Q==="git"){if(!$.followSymlinks)J.push("git")}else if(Q==="ripgrep")J.push("ripgrep");for(let Y of J)try{let Z=await this.runExternalTool(Y,A,B,{followSymlinks:$.followSymlinks,alwaysIncludeMatcher:$.alwaysIncludeMatcher});if(Z.length>0)return{entries:Z,strategy:Y};else j.debug("External tool returned no entries, trying next",{tool:Y})}catch(Z){j.debug("External tool failed, trying next",{tool:Y,error:Z})}return j.debug("All external tools failed, falling back to Node.js scanning"),null}async runExternalTool(A,Q,B,$){let J=A==="git"?"git":await Eq(),Y=A==="git"?["ls-files","--exclude-standard","--cached","--others"]:$.followSymlinks?["--files","--follow","--hidden","--glob","!.git/","--glob","!.jj/"]:["--files","--hidden","--glob","!.git/","--glob","!.jj/"];return new Promise((Z,F)=>{let X=nH5(J,Y,{cwd:Q,stdio:["ignore","pipe","pipe"]}),D=[],G="",V="",U=!1,K=(E)=>{if(!E||U)return;if(D.push(E),D.length>=Yf4){if(!U)j.warn("External directory scan limit reached. Returning partial results.",{tool:A,rootPath:Q,limit:Yf4}),U=!0,X.kill()}};if(X.stdout?.on("data",(E)=>{if(U)return;G+=E.toString("utf8");let z;while((z=G.indexOf(`
4727
4727
  `))!==-1){let W=G.slice(0,z).replace(/\r$/,"");if(G=G.slice(z+1),K(W),U)break}}),X.stderr?.on("data",(E)=>{if(V.length>=Wt0)return;let z=E.toString("utf8");if(V.length+z.length>Wt0)V+=z.slice(0,Wt0-V.length);else V+=z}),B){let E=()=>{if(!U)X.kill("SIGTERM"),F(Error("Scan aborted"))};if(B.aborted)E();else B.addEventListener("abort",E,{once:!0})}X.on("close",(E)=>{if(!U&&G){let z=G.replace(/\r$/,"");K(z)}if(!U&&E!==0){if(!V.trim().split(`
4728
- `).filter((H)=>H.length>0).every((H)=>H.includes("No such file or directory"))){j.debug("External tool failed",{command:J,code:E,stderr:V}),F(Error(`${J} exited with code ${E}: ${V}`));return}}try{let z=new Set,W={rootPath:Q,alwaysIncludeMatcher:$.alwaysIncludeMatcher},H=D.map((I)=>{let w=this.createEntryFromPath(Go(Q,I),{size:0,mtime:new Date,isDirectory:!1,isFile:!0,isSymlink:!1},W),O=I;while(O!==""&&O!==".")if(O=nH5(O),O&&O!=="."&&!z.has(O))z.add(O);return w}),q=Array.from(z).map((I)=>{return this.createEntryFromPath(Go(Q,I),{size:0,mtime:new Date,isDirectory:!0,isFile:!1,isSymlink:!1},W)}),N=[...H,...q];Z(N)}catch(z){F(z)}}),X.on("error",(E)=>{F(E)})})}async scanWithNodeJS(A,Q,B){if(Q.signal?.aborted)throw Error("Scan aborted");let $=[],J={scannedFiles:0,scannedDirectories:0,skippedPaths:0};return await this.scanDirectoryRecursive(A,A,0,Q,$,J,B),{entries:$,skippedPaths:J.skippedPaths}}async scanDirectoryRecursive(A,Q,B,$,J,Y,Z){if($.signal?.aborted)throw Error("Scan aborted");if(B>$.maxDepth)return;if(J.length>=$.maxFiles)return;let F=Vo(Q,A);if($.respectIgnorePatterns&&F){if(!($.alwaysIncludeMatcher?.(F)??!1)&&iQ.shouldIgnore(F,!0)){Y.skippedPaths++;return}}let X;try{X=await Cj.readdir(A,{withFileTypes:!0})}catch(D){if(D instanceof Error){if("code"in D&&(D.code==="EACCES"||D.code==="EPERM")){Y.skippedPaths++;return}if("code"in D&&D.code==="ENOENT")return}throw D}for(let D of X){if($.signal?.aborted)throw Error("Scan aborted");if(J.length>=$.maxFiles)break;let G=Go(A,D.name),V=Vo(Q,G);if($.respectIgnorePatterns){if(!($.alwaysIncludeMatcher?.(V)??!1)&&iQ.shouldIgnore(V,D.isDirectory())){Y.skippedPaths++;continue}}try{let U,K=!1,E={rootPath:Q,alwaysIncludeMatcher:$.alwaysIncludeMatcher};if(D.isDirectory())U=this.createEntryFromPath(G,{size:0,mtime:new Date,isDirectory:!0,isFile:!1,isSymlink:!1},E),Y.scannedDirectories++,K=!0;else if(D.isSymbolicLink()&&Z.followSymlinks){let z=await Cj.stat(G).catch(()=>null);if(z&&z.isDirectory())U=this.createEntryFromPath(G,{size:0,mtime:z.mtime,isDirectory:!0,isFile:!1,isSymlink:!0},E),Y.scannedDirectories++,K=!0;else if(z)U=this.createEntryFromPath(G,{size:z.size,mtime:z.mtime,isDirectory:!1,isFile:!0,isSymlink:!0},E),Y.scannedFiles++;else{Y.skippedPaths++;continue}}else{let z=await Cj.stat(G);U=this.createEntryFromPath(G,{size:z.size,mtime:z.mtime,isDirectory:!1,isFile:!0,isSymlink:z.isSymbolicLink()},E),Y.scannedFiles++}if(J.push(U),$.onProgress&&J.length%100===0)$.onProgress({scannedFiles:Y.scannedFiles,scannedDirectories:Y.scannedDirectories,currentPath:G});if(K){let z=await Jf4(G).catch(()=>null);if(!z){Y.skippedPaths++;continue}if(Z.visitedRealDirs.has(z))continue;Z.visitedRealDirs.add(z),await this.scanDirectoryRecursive(G,Q,B+1,$,J,Y,Z)}}catch(U){if(U instanceof Error){if("code"in U&&(U.code==="EACCES"||U.code==="EPERM"||U.code==="ENOENT")){Y.skippedPaths++;continue}}j.warn("Error processing file",{error:U}),Y.skippedPaths++}}}async scanAlwaysIncludePaths(A,Q,B,$,J){let Y=[],Z=new Set($.map((X)=>X.path)),F=new Set;for(let X of Q){let D=X.split("/"),G="";for(let V of D){if(V.includes("*")||V.includes("?")||V.includes("["))break;G=G?`${G}/${V}`:V}if(G)F.add(G)}for(let X of F){let D=Go(A,X);try{let G=await Cj.stat(D);if(G.isDirectory())await this.scanAlwaysIncludeDir(D,A,B,Z,Y,J);else if(!Z.has(D)){let V=Vo(A,D);if(B?.(V))Y.push(this.createEntryFromPath(D,{size:G.size,mtime:G.mtime,isDirectory:!1,isFile:!0,isSymlink:G.isSymbolicLink()},{rootPath:A,alwaysIncludeMatcher:B}))}}catch{}}return Y}async scanAlwaysIncludeDir(A,Q,B,$,J,Y){let Z;try{Z=await Cj.readdir(A,{withFileTypes:!0})}catch{return}for(let F of Z){let X=Go(A,F.name),D=Vo(Q,X);if($.has(X))continue;if(!(B?.(D)??!1))continue;try{if(F.isDirectory())J.push(this.createEntryFromPath(X,{size:0,mtime:new Date,isDirectory:!0,isFile:!1,isSymlink:!1},{rootPath:Q,alwaysIncludeMatcher:B})),await this.scanAlwaysIncludeDir(X,Q,B,$,J,Y);else if(F.isSymbolicLink()&&Y.followSymlinks){let V=await Cj.stat(X).catch(()=>null);if(V){if(J.push(this.createEntryFromPath(X,{size:V.size,mtime:V.mtime,isDirectory:V.isDirectory(),isFile:V.isFile(),isSymlink:!0},{rootPath:Q,alwaysIncludeMatcher:B})),V.isDirectory())await this.scanAlwaysIncludeDir(X,Q,B,$,J,Y)}}else{let V=await Cj.stat(X);J.push(this.createEntryFromPath(X,{size:V.size,mtime:V.mtime,isDirectory:!1,isFile:!0,isSymlink:V.isSymbolicLink()},{rootPath:Q,alwaysIncludeMatcher:B}))}}catch{}}}createEntryFromPath(A,Q,B){let $;if(Q.isDirectory)$="directory";else $="file";let J={size:Q.size,mtime:Q.mtime.getTime(),isSymlink:Q.isSymlink},Y=A,Z=o0.file(A),F=!1;if(B?.alwaysIncludeMatcher&&B?.rootPath){let X=Vo(B.rootPath,A);F=B.alwaysIncludeMatcher(X)}return new ZI({id:Y,kind:$,path:A,uri:Z,metadata:J,isAlwaysIncluded:F})}}var oH5={minScore:400,caseSensitive:!1,penalizeLengthDifference:!0,maxResults:50,smartCase:!0},nQ={EXACT_FILENAME:1000,PREFIX_FILENAME:950,SEGMENT_ORDERED_EXACT:900,SUFFIX_FILENAME:850,SEGMENT_ORDERED_PARTIAL:840,SUBSTRING_FILENAME:800,SEGMENT_EXACT:650,SEGMENT_SUBSTRING:600,PATH_SUBSTRING:500,FUZZY:250},rH5=["test","story"],sH5=30;class Ff4{config;queryChars;queryLower;constructor(A,Q={}){this.config={...oH5,...Q};let B=A.replace(/^[@#]+/,"");if(this.queryChars=Array.from(B),this.queryLower=Array.from(B.toLowerCase()),this.config.smartCase)this.config.caseSensitive=B!==B.toLowerCase()}match(A){if(this.queryChars.length===0)return A.filter((B)=>B.shouldIncludeInResults()).map((B)=>{let $=this.config.openFiles?.includes(B.path)?500:0,J=this.config.dirtyFiles?.includes(B.path)?300:0,Y=B.getImportanceBoost()+$+J-this.getTestAndStoryPathPenalty(B.path);return{entry:B,score:Y,matchPositions:[],highlightedPath:B.path}}).sort((B,$)=>$.score-B.score).slice(0,this.config.maxResults);let Q=this.matchWithSemanticScoring(A);if(Q.length>0)return Q;return this.matchWithFuzzyScoring(A)}matchWithSemanticScoring(A){let Q=[],B=0,$=50000,J=this.queryChars.join(""),Y=A.filter((F)=>F.shouldIncludeInResults()&&this.passesCharBagFilter(J,F)),Z=(F)=>{let X=this.matchEntrySemantic(F);if(X&&X.score>=this.config.minScore)Q.push(X);return B++,B>=$};for(let F of Y)if(F.isDirectory()){if(Z(F))break}if(B<$){for(let F of Y)if(!F.isDirectory()){if(Z(F))break}}return Q.sort((F,X)=>{let D=X.score-F.score;if(Math.abs(D)>0.001)return D;return F.entry.path.length-X.entry.path.length}),Q.slice(0,this.config.maxResults)}matchWithFuzzyScoring(A){let Q=[],B=0,$=50000,J=this.queryChars.join(""),Y=A.filter((F)=>F.shouldIncludeInResults()&&this.passesCharBagFilter(J,F)),Z=(F)=>{let X=this.matchEntryFuzzy(F);if(X)Q.push(X);return B++,B>=$};for(let F of Y)if(F.isDirectory()){if(Z(F))break}if(B<$){for(let F of Y)if(!F.isDirectory()){if(Z(F))break}}return Q.sort((F,X)=>{let D=X.score-F.score;if(Math.abs(D)>0.001)return D;return F.entry.path.length-X.entry.path.length}),Q.slice(0,this.config.maxResults)}matchEntrySemantic(A){let Q=A.path,B=this.queryLower.join(""),$=this.calculateSemanticScore(B,A);if($===0)return null;let J=this.applyTieBreakers($,B,A),Y=this.findMatchPositions(B,Q),Z=this.createHighlightedPath(Q,Y);return{entry:A,score:J,matchPositions:Y,highlightedPath:Z}}matchEntryFuzzy(A){let Q=A.path,B=this.queryLower.join(""),$=this.calculateFuzzyScore(B,A);if($===0)return null;let J=this.applyTieBreakers($,B,A),Y=this.findMatchPositions(B,Q),Z=this.createHighlightedPath(Q,Y);return{entry:A,score:J,matchPositions:Y,highlightedPath:Z}}calculateSemanticScore(A,Q){let B=A.toLowerCase(),$=Q.path,J=$.toLowerCase(),Y=this.normalizeMatchString(B),Z=this.getFilename($),F=this.removeExtension(Z).toLowerCase(),X=this.splitPathSegments(J);if(A.endsWith("/")&&Q.isDirectory()){let U=B.slice(0,-1);if(J===U||J.endsWith("/"+U))return nQ.EXACT_FILENAME+100;if(J.includes(U))return nQ.SUBSTRING_FILENAME+50}if(F===B||Z.toLowerCase()===B)return nQ.EXACT_FILENAME;if(F.startsWith(B))return nQ.PREFIX_FILENAME;if(F.endsWith(B))return nQ.SUFFIX_FILENAME;if(F.includes(B))return nQ.SUBSTRING_FILENAME;if(Y.length>6&&(A.includes("/")||A.includes("\\"))){let U=this.progressiveSegmentMatch(Y,X);if(U)return U}let D=this.simpleTokens(B);if(D.length>1){let U=this.matchTokensToSegments(D,X);if(U)return U}if(D.length===1&&B.length>6){let U=this.progressiveSegmentMatch(B,X);if(U)return U}if(X.includes(B))return nQ.SEGMENT_EXACT;if(X.some((U)=>U.includes(B)))return nQ.SEGMENT_SUBSTRING;let G=X.join("");if(Y&&G.includes(Y))return nQ.SEGMENT_SUBSTRING;let V=this.normalizeMatchString(J);if(Y&&V.includes(Y))return nQ.PATH_SUBSTRING;if(Y&&this.fuzzyIn(Y,V))return nQ.PATH_SUBSTRING;return 0}calculateFuzzyScore(A,Q){let B=A.toLowerCase(),$=Q.path.toLowerCase();if(this.fuzzyIn(B,$))return nQ.FUZZY;return 0}applyTieBreakers(A,Q,B){let $=A,J=Math.abs(B.path.length-Q.length);$-=0.01*J;let Y=B.path.split(/[/\\]/).length-1;$-=0.1*Y;let Z=this.getFilename(B.path),F=this.removeExtension(Z).toLowerCase();if(/^(license|readme|copy(ing|left))$/i.test(F)&&Y===1)$-=200;if(B.metadata.mtime){let D=(Date.now()-B.metadata.mtime)/86400000;if(D<30){let G=Math.max(0,1-D/30);$+=50*G}}if(this.config.openFiles?.includes(B.path))$+=500;if(this.config.dirtyFiles?.includes(B.path))$+=300;return $-=this.getTestAndStoryPathPenalty(B.path),$}getTestAndStoryPathPenalty(A){if(!this.config.downrankTestAndStoryPaths)return 0;return rH5.some((Q)=>A.includes(Q))?sH5:0}simpleTokens(A){return A.replace(/([a-z])([A-Z0-9])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}normalizeMatchString(A){return A.replace(/[^a-z0-9]+/g,"")}splitPathSegments(A){return A.split(/[/\\]/).flatMap((Q)=>Q.split(/[^a-z0-9]+/).filter(Boolean))}progressiveSegmentMatch(A,Q){let B=0,$=0,J=0;for(let Z of Q){if(B>=A.length)break;let F="",X="none";if(B+Z.length<=A.length){if(A.slice(B,B+Z.length)===Z)F=Z,X="exact"}if(!F&&Z.length>=3){if(A.slice(B).startsWith(Z))F=Z,X="prefix"}if(!F&&Z.length>=3){let D=A.slice(B);if(D.includes(Z)&&D.indexOf(Z)===0)F=Z,X="substring"}if(!F){let D=A.slice(B);if(D.length>=3&&Z.includes(D))F=D,X="substring"}if(F){if(B+=F.length,$++,X==="exact")J++}}if(B/A.length>=0.8&&$>=2)return J>=2?nQ.SEGMENT_ORDERED_EXACT:nQ.SEGMENT_ORDERED_PARTIAL;return 0}matchTokensToSegments(A,Q){let B=this.findTokenMatches(A,Q),$=this.getWorstMatchType(B);return this.scoreFromMatchType($)}findTokenMatches(A,Q){let B=0,$=[];for(let J of A){let Y=!1;for(let Z=B;Z<Q.length;Z++){let F=Q[Z];if(!F)continue;if(J===F){$.push("exact"),B=Z+1,Y=!0;break}else if(F.startsWith(J)||J.startsWith(F)||F.endsWith(J)||F.includes(J)||J.includes(F)){$.push("partial"),B=Z+1,Y=!0;break}}if(!Y)return[]}return $}getWorstMatchType(A){if(A.length===0)return"none";if(A.includes("partial"))return"partial";return"exact"}scoreFromMatchType(A){switch(A){case"exact":return nQ.SEGMENT_ORDERED_EXACT;case"partial":return nQ.SEGMENT_ORDERED_PARTIAL;default:return 0}}fuzzyIn(A,Q){let B=0;for(let $=0;$<Q.length&&B<A.length;$++)if(Q[$]===A[B])B++;return B===A.length}getFilename(A){return A.split(/[/\\]/).pop()||A}removeExtension(A){let Q=A.lastIndexOf(".");return Q>0?A.substring(0,Q):A}findMatchPositions(A,Q){let B=[],$=Q.toLowerCase(),J=A.toLowerCase();if($.includes(J)){let Z=$.indexOf(J);for(let F=0;F<J.length;F++)B.push(Z+F);return B}let Y=0;for(let Z of J){let F=$.indexOf(Z,Y);if(F!==-1)B.push(F),Y=F+1}return B}passesCharBagFilter(A,Q){if(A.includes("/")||A.includes("\\")){let B=A.split(/[/\\]/);for(let $ of B){if($.trim()==="")continue;let J=sB.fromString($);if(!Q.charBag.hasChars(J))return!1}return!0}else{let B=sB.fromString(A);return Q.charBag.hasChars(B)}}createHighlightedPath(A,Q){if(Q.length===0)return A;let B="",$=0;for(let J of Q){if(J>=A.length)continue;B+=A.slice($,J),B+=`**${A[J]}**`,$=J+1}return B+=A.slice($),B}}function Xf4(A,Q,B){return new Ff4(A,B).match(Q)}class Uo{metadata;entries;entriesByPath;entriesById;constructor(A,Q=[],B,$){if(this.metadata=A,this.entries=Q,B&&$)this.entriesByPath=B,this.entriesById=$;else{let J=new Map,Y=new Map;for(let Z of Q)J.set(Z.path,Z),Y.set(Z.id,Z);this.entriesByPath=J,this.entriesById=Y}this.cachedArray=Array.from(this.entriesByPath.values()),this.entriesArrayDirty=!1}static create(A){let Q=Date.now();return new Uo({id:Q,createdAt:Q,rootPath:A,entryCount:0,scanStatus:"scanning"},[])}static fromEntries(A,Q){let B=Date.now(),$={id:B,createdAt:B,rootPath:A,entryCount:Q.length,scanStatus:"complete"};return new Uo($,Q)}entriesArrayDirty=!1;cachedArray=[];getAllEntries(){if(this.entriesArrayDirty)this.cachedArray=[...this.entriesByPath.values()],this.entriesArrayDirty=!1;return this.cachedArray}getEntryByPath(A){return this.entriesByPath.get(A)??null}getEntryById(A){return this.entriesById.get(A)??null}applyChanges(A){let{added:Q=[],removed:B=[],modified:$=[]}=A;for(let J of B){let Y=this.entriesByPath.get(J);if(Y){if(this.entriesByPath.delete(J),this.entriesById.delete(Y.id),!this.entriesArrayDirty){let Z=this.cachedArray.findIndex((F)=>F.path===J);if(Z>=0)this.cachedArray.splice(Z,1)}}}for(let J of[...Q,...$])if(this.entriesByPath.set(J.path,J),this.entriesById.set(J.id,J),!this.entriesArrayDirty){let Y=this.cachedArray.findIndex((Z)=>Z.path===J.path);if(Y>=0)this.cachedArray.splice(Y,1);this.cachedArray.unshift(J)}this.metadata.entryCount=this.entriesByPath.size}findEntries(A){return this.entries.filter(A)}getFiles(){return this.findEntries((A)=>A.kind==="file")}getDirectories(){return this.findEntries((A)=>A.kind==="directory")}getInDirectory(A){let Q=A.endsWith("/")?A:A+"/";return this.findEntries((B)=>B.path.startsWith(Q)&&B.path!==A)}hasPath(A){return this.entriesByPath.has(A)}getStats(){let A=this.metadata.entryCount||this.entries.length,Q=this.getFiles().length,B=A-Q,$=A*250;return{totalEntries:A,fileEntries:Q,directoryEntries:B,memoryUsage:$}}}class qt0 extends tH5{rootPath;currentSnapshot=null;fileWatcher;scanner;isScanning=!1;stats;alwaysIncludeMatcher;constructor(A,Q){super();this.rootPath=A;this.fileWatcher=Q??cF0(),this.scanner=new Ht0,this.stats={totalFiles:0,totalDirectories:0,lastScanDuration:0,lastScanTime:0,memoryUsage:0,status:"idle"},this.fileWatcher.onFileSystemEvent(this.handleFileSystemEvents.bind(this))}async initialize(A){if(this.isScanning)throw Error("Index is already being initialized");let Q=A?.alwaysIncludePaths??[];this.alwaysIncludeMatcher=Q.length>0?Df4.default(Q,{dot:!0}):void 0;try{await this.performFullScan(A),await this.fileWatcher.watch(this.rootPath)}catch(B){throw this.updateStatus("error"),B}}async rescan(A){await this.performFullScan(A)}getCurrentSnapshot(){return this.currentSnapshot}getStats(){return{...this.stats}}search(A,Q={}){if(this.fileWatcher.triggerScan)this.fileWatcher.triggerScan(this.rootPath).catch(()=>{});if(!this.currentSnapshot)return[];let{limit:B=50,minScore:$=0.1,includeDirectories:J=!0,includeIgnored:Y=!1}=Q,Z=this.currentSnapshot.getAllEntries(),F=A.replace(/[@/]/g,"");if(F.length>2){if(Z.some((V)=>V.path.includes(F))){let V=Z.find((U)=>U.path.includes(F));j.debug("Search for existing file",{query:A,matchingFile:V?.path,entryIndex:Z.findIndex((U)=>U===V)})}}Z=Z.filter((G)=>{if(!Y&&G.isIgnored)return!1;if(!J&&G.isDirectory())return!1;return G.shouldIncludeInMentions()});let X=Xf4(A,Z,{minScore:$,openFiles:Q.openFiles,dirtyFiles:Q.dirtyFiles,downrankTestAndStoryPaths:Q.downrankTestAndStoryPaths});return X.sort((G,V)=>V.score-G.score),X.slice(0,B)}dispose(){this.fileWatcher.dispose(),this.removeAllListeners()}async performFullScan(A){this.isScanning=!0,this.updateStatus("scanning");let Q=Date.now();try{let B=await this.scanner.scanDirectory(this.rootPath,{respectIgnorePatterns:!0,...A});this.currentSnapshot=Uo.fromEntries(this.rootPath,B.entries);let $=Date.now()-Q;this.stats={...this.stats,totalFiles:B.stats.totalFiles,totalDirectories:B.stats.totalDirectories,lastScanDuration:$,lastScanTime:Q,memoryUsage:this.currentSnapshot.getStats().memoryUsage,status:"idle"},this.emit("scan-complete",{entries:B.entries.length,duration:$}),this.emit("status-changed",this.getStats())}catch(B){throw this.updateStatus("error"),this.emit("scan-error",B),B}finally{this.isScanning=!1}}async handleFileSystemEvents(A){if(!this.currentSnapshot||this.isScanning)return;this.updateStatus("updating");try{let Q=[],B=[],$=[];for(let J of A){let Y=J.path;switch(J.type){case"deleted":Q.push(Y);break;case"created":await this.processCreatedEvent(J,B);break;case"modified":await this.processModifiedEvent(J,$);break;case"renamed":if(J.oldPath)Q.push(J.oldPath);await this.processCreatedEvent(J,B);break}}if(this.currentSnapshot.applyChanges({removed:Q,added:B,modified:$}),Q.length>0||B.length>0||$.length>0)j.debug("Incremental snapshot update",{removed:Q.length,added:B.length,modified:$.length,totalEntries:this.currentSnapshot.metadata.entryCount,sampleAdded:B.slice(0,3).map((J)=>J.path),sampleRemoved:Q.slice(0,3)});this.stats={...this.stats,memoryUsage:this.currentSnapshot.getStats().memoryUsage,status:"idle"},this.emit("files-updated",{added:B.length,removed:Q.length,modified:$.length}),this.emit("status-changed",this.getStats())}catch(Q){this.updateStatus("error"),this.emit("scan-error",Q)}}async processCreatedEvent(A,Q){let B=A.path;try{let $=A.stat||(A.isDirectory?null:await eH5.lstat(B)),J=A.isDirectory,Y=Aq5(this.rootPath,B),Z=this.alwaysIncludeMatcher?.(Y)??!1;if(!Z&&iQ.shouldIgnore(Y,J))return;if(J)Q.push(new ZI({id:B,kind:"directory",path:B,uri:o0.file(B),metadata:{size:0,mtime:Date.now(),isSymlink:!1},isIgnored:!1,isAlwaysIncluded:Z}));else if($)Q.push(new ZI({id:B,kind:"file",path:B,uri:o0.file(B),metadata:{size:$.size,mtime:$.mtimeMs,isSymlink:$.isSymbolicLink()},isIgnored:!1,isAlwaysIncluded:Z}))}catch{}}async processModifiedEvent(A,Q){let B=this.currentSnapshot?.getEntryByPath(A.path);if(B){let $=B.withUpdates({metadata:{...B.metadata,mtime:A.timestamp}});Q.push($)}}updateStatus(A){this.stats={...this.stats,status:A},this.emit("status-changed",this.getStats())}}d0();import{execFile as Qq5}from"node:child_process";import{EventEmitter as Bq5}from"node:events";import{promises as lF0,watch as $q5}from"node:fs";import{join as Nt0,resolve as Jq5}from"node:path";import{promisify as Yq5}from"node:util";var Gf4=Yq5(Qq5);class It0 extends Bq5{repoRoot;pollInterval;on(A,Q){return super.on(A,Q)}emit(A,...Q){return super.emit(A,...Q)}currentSha;disposed=!1;started=!1;running=!1;pendingForce=!1;watchers=new Set;currentRefWatcher;timer;constructor(A,Q=30000){super();this.repoRoot=A;this.pollInterval=Q;this.repoRoot=this.validateRepoRoot(A)}static async isRepo(A){try{let Q=Nt0(A,".git");return await lF0.access(Q),!0}catch{try{let Q=Nt0(A,"HEAD");return await lF0.access(Q),!0}catch{return!1}}}async start(){if(this.disposed)throw Error("GitHeadWatcher has been disposed");if(this.started)throw Error("GitHeadWatcher has already been started");this.started=!0,this.currentSha=await this.getCurrentSha();let A=await this.getGitPath("HEAD");this.watch(A,async()=>{await this.updateRefWatcher(),this.scheduleCheck()}),await this.updateRefWatcher();let Q=await this.getGitPath("logs/HEAD");try{await lF0.access(Q),this.watch(Q,()=>this.scheduleCheck(!0))}catch{}this.timer=setInterval(()=>this.scheduleCheck(),this.pollInterval),j.debug("GitHeadWatcher started",{repoRoot:this.repoRoot,headPath:A})}stop(){for(let A of Array.from(this.watchers))this.cleanupWatcher(A);if(this.timer)clearInterval(this.timer),this.timer=void 0;this.currentRefWatcher=void 0,this.started=!1,this.running=!1,this.pendingForce=!1}dispose(){if(this.disposed)return;this.stop(),this.disposed=!0,this.removeAllListeners()}watch(A,Q){let B=$q5(A);return B.on("change",Q),B.on("rename",()=>{this.cleanupWatcher(B),setTimeout(()=>{if(!this.disposed)this.watch(A,Q),this.scheduleCheck(!0)},50)}),B.on("error",($)=>{j.debug("Git file watcher error",{filePath:A,error:$}),this.cleanupWatcher(B)}),this.watchers.add(B),B}cleanupWatcher(A){try{A.removeAllListeners(),A.close()}catch(Q){j.debug("Error during watcher cleanup",{error:Q})}this.watchers.delete(A)}async updateRefWatcher(){if(this.currentRefWatcher)this.cleanupWatcher(this.currentRefWatcher),this.currentRefWatcher=void 0;try{let A=await this.getGitPath("HEAD"),Q=await lF0.readFile(A,"utf8");if(!Q)return;let B=Q.trim();if(B.startsWith("ref: ")){let $=B.slice(5),J=await this.getGitPath($);this.currentRefWatcher=this.watch(J,()=>this.scheduleCheck())}}catch(A){j.debug("Failed to update ref watcher",{repoRoot:this.repoRoot,error:A})}}scheduleCheck(A=!1){if(this.disposed)return;if(this.pendingForce||=A,this.running)return;this.running=!0,queueMicrotask(async()=>{if(this.disposed)return;let Q=this.pendingForce;this.pendingForce=!1;try{await this.performCheck(Q)}finally{this.running=!1}})}async checkForChanges(A=!1){this.scheduleCheck(A)}async performCheck(A){if(this.disposed)return;try{let Q=await this.getCurrentSha();if(!Q&&this.currentSha){j.warn("Failed to get current SHA, keeping previous value",{repoRoot:this.repoRoot,previousSha:this.currentSha.slice(0,7)});return}if(Q&&Q!==this.currentSha&&this.currentSha||A){let B=this.currentSha;this.currentSha=Q??this.currentSha,this.emit("head-change",{oldSha:B,newSha:this.currentSha,repoRoot:this.repoRoot,force:A})}else if(Q!==this.currentSha)this.currentSha=Q}catch(Q){j.warn("Error checking for git HEAD changes",{repoRoot:this.repoRoot,error:Q})}}async getCurrentSha(){try{let{stdout:A}=await Gf4("git",["rev-parse","HEAD"],{cwd:this.repoRoot});return A.trim()}catch(A){return}}async getGitPath(A){try{let{stdout:Q}=await Gf4("git",["rev-parse","--git-path",A],{cwd:this.repoRoot}),B=Q.trim();if(B.includes(`
4729
- `))throw Error("Unexpected newline in git path output");return Jq5(this.repoRoot,B)}catch(Q){return Nt0(this.repoRoot,".git",A)}}validateRepoRoot(A){if(!A||typeof A!=="string")throw Error("Repository root must be a valid string path");if(!A.startsWith("/")&&!A.match(/^[A-Za-z]:\\/))throw Error("Repository root must be an absolute path");return A}}async function Vf4(A,Q){if(!await It0.isRepo(A))return null;return new It0(A,Q?.pollInterval)}class iF0{indexes=new Map;headWatchers=new Map;reindexingWorkspaces=new Set;config;disposed=!1;static forWorkspace(A){return new iF0({workspaceRoots:[A],scanOnStartup:!0,maxIndexedFiles:500000,enableFileWatching:!0,usePollingFallback:!1,enableHeadWatching:!0,followSymlinkDirs:!0})}constructor(A){this.config={...A}}async initialize(){if(this.disposed)throw Error("Service has been disposed");if(this.config.scanOnStartup){let A=this.config.workspaceRoots.map((Q)=>this.indexWorkspace(Q));await Promise.allSettled(A)}}async indexWorkspace(A){if(this.disposed)throw Error("Service has been disposed");if(this.indexes.has(A)){await this.indexes.get(A).rescan();return}let Q=this.config.enableFileWatching?cF0({rootPath:A,usePolling:this.config.usePollingFallback}):void 0,B=new qt0(A,Q);B.on("scan-error",(J)=>{j.error("Scan error in workspace",{rootPath:A,error:J})});let $={respectIgnorePatterns:!0,maxFiles:this.config.maxIndexedFiles,followSymlinks:this.config.followSymlinkDirs,alwaysIncludePaths:this.config.alwaysIncludePaths};try{if(await B.initialize($),this.indexes.set(A,B),this.config.enableHeadWatching)await this.setupHeadWatching(A,B,Q)}catch(J){B.dispose();let Y=this.headWatchers.get(A);if(Y)Y.dispose(),this.headWatchers.delete(A);throw J}}async removeWorkspace(A){let Q=this.indexes.get(A);if(Q)Q.dispose(),this.indexes.delete(A);let B=this.headWatchers.get(A);if(B)B.dispose(),this.headWatchers.delete(A)}searchAll(A,Q){let B=[];for(let $ of this.indexes.values())try{let J=$.search(A,Q);B.push(...J)}catch(J){}return B.sort(($,J)=>J.score-$.score),Q?.limit?B.slice(0,Q.limit):B}searchWorkspace(A,Q,B){let $=this.indexes.get(A);if(!$)return[];try{return $.search(Q,B)}catch(J){return j.error(`Search error in workspace ${A}:`,J),[]}}getIndexStats(A){if(A){let B=this.indexes.get(A);if(B)return[{...B.getStats(),rootPath:A}];return[]}let Q=[];for(let[B,$]of this.indexes.entries())Q.push({...$.getStats(),rootPath:B});return Q}getConfig(){return{...this.config}}updateConfig(A){this.config={...this.config,...A}}async rescanAll(){let A=[];for(let[Q,B]of this.indexes.entries())A.push(B.rescan().catch(($)=>{j.error(`Rescan error in workspace ${Q}:`,$)}));await Promise.allSettled(A)}getIndexedWorkspaces(){return Array.from(this.indexes.keys())}isWorkspaceIndexed(A){return this.indexes.has(A)}dispose(){if(this.disposed)return;for(let[,A]of this.indexes.entries())A.dispose();for(let[,A]of this.headWatchers.entries())A.dispose();this.indexes.clear(),this.headWatchers.clear(),this.disposed=!0}isDisposed(){return this.disposed}async setupHeadWatching(A,Q,B){try{let $=await Vf4(A);if(!$)return;$.on("head-change",async({oldSha:J,newSha:Y})=>{if(this.reindexingWorkspaces.has(A)){j.debug("Re-index already in progress, skipping",{rootPath:A});return}this.reindexingWorkspaces.add(A);try{if(await Q.rescan(),B&&B instanceof Lx)await B.reset(A)}catch(Z){j.error("Failed to re-index after change",{rootPath:A,error:Z})}finally{this.reindexingWorkspaces.delete(A)}}),await $.start(),this.headWatchers.set(A,$),j.debug("Git HEAD watching enabled",{rootPath:A})}catch($){j.warn("Failed to setup git HEAD watching",{rootPath:A,error:$})}}}function wt0(A,Q){let B={workspaceRoots:A,scanOnStartup:!0,maxIndexedFiles:500000,enableFileWatching:!0,usePollingFallback:!1,enableHeadWatching:!0,followSymlinkDirs:!0,...Q};return new iF0(B)}var Fq5=4096,Xq5=["test","story"],Dq5="AMP_EXPERIMENT_PERFSORT",Gq5="AMP_LEGACY_CORE_FUZZY_INDEX",Vq5=4,Uq5=50,Kq5=5,Eq5=3.25,zq5=3,Wq5=6,Hq5=1.5,qq5=1,Nq5=1.5,Iq5=1,wq5=0.75,Cq5=5.5,Mq5=0.5;function Ef4(){return process.env[Dq5]==="1"}function Lq5(){return process.env[Gq5]==="1"}class nF0{implementation;workspaceRoot;constructor(A=process.cwd(),Q={},B=!1){this.workspaceRoot=A,this.implementation=Lq5()?new Ct0(A,Q,B):new zf4(A,Q,B)}async start(){return this.implementation.start()}async query(A,Q=50,B,$){return this.implementation.query(A,Q,B,$)}async queryCompletions(A,Q=50,B,$){return this.implementation.queryCompletions(A,Q,B,$)}getStats(){return this.implementation.getStats()}dispose(){this.implementation.dispose()}}class Ct0{opts;fuzzyService=null;state="unstarted";initPromise=null;workspaceRoot;constructor(A=process.cwd(),Q={},B=!1){this.opts=Q;if(this.workspaceRoot=A,B)this.start().catch(($)=>{j.debug("Fuzzy service background initialization failed",$)})}async start(){if(this.initPromise!==null)return this.initPromise;return this.initPromise=this.init(),this.initPromise}async init(){if(FI.resolve(this.workspaceRoot)===FI.resolve(Kf4.homedir())){this.state="ready";return}this.state="initializing";try{this.fuzzyService=wt0([this.workspaceRoot],{scanOnStartup:!0,enableFileWatching:!0,usePollingFallback:!1,...this.opts}),await this.fuzzyService.initialize(),this.state="ready"}catch(A){this.state="failed",j.warn("Failed to initialize legacy fuzzy service",{error:A instanceof Error?A.message:String(A)})}}async query(A,Q=50,B,$){return(await this.queryCompletions(A,Q,B,$)).map((J)=>("path"in J)?J.path:"").filter(Boolean)}async queryCompletions(A,Q=50,B,$){if(this.state==="unstarted")await this.start();else if(this.initPromise!==null)await this.initPromise;if(!this.fuzzyService)return[];try{let J=A.trim();return this.fuzzyService.searchAll(J,{limit:Q,minScore:J?0.1:void 0,openFiles:B,dirtyFiles:$,downrankTestAndStoryPaths:!0}).map((Z)=>({kind:Z.entry.isDirectory()?"folder":"file",path:FI.relative(this.workspaceRoot,Z.entry.path)}))}catch(J){return j.error("Fuzzy search failed",J),[]}}getStats(){return{state:this.state,stats:this.fuzzyService?.getIndexStats()??[]}}dispose(){this.fuzzyService?.dispose(),this.fuzzyService=null,this.state="unstarted",this.initPromise=null}}class zf4{opts;worker=null;fallbackClient=null;fallbackPromise=null;state="unstarted";stats=[];initPromise=null;initResolve=null;queryID=0;latestQueryID=0;workerGeneration=0;workerReadyResolvers=[];pendingQueries=new Map;workspaceRoot;constructor(A=process.cwd(),Q={},B=!1){this.opts=Q;if(this.workspaceRoot=A,B)this.start().catch(($)=>{j.debug("@ completion worker index background initialization failed",$)})}async start(){if(this.fallbackClient)return this.fallbackClient.start();if(this.initPromise!==null)return this.initPromise;return this.initPromise=this.init(),this.initPromise}async init(){if(FI.resolve(this.workspaceRoot)===FI.resolve(Kf4.homedir())){this.state="ready";return}this.state="initializing",this.stats=[Rq5(this.workspaceRoot,{status:"scanning"})];let A;try{let B=await Eq(),$=Date.now();A=new Zq5(Oq5,{eval:!0,workerData:{rg:B,workspaceRoot:this.workspaceRoot,alwaysIncludePaths:this.opts.alwaysIncludePaths?.filter(Boolean)??[],startedAt:$}})}catch(B){await this.switchToFallback(B);return}this.worker=A;let Q=++this.workerGeneration;this.resolveWorkerReady(),A.on("message",(B)=>{if(Q===this.workerGeneration)this.handleWorkerMessage(B)}),A.on("error",(B)=>{if(Q===this.workerGeneration)this.handleWorkerFailure(B)}),A.on("exit",(B)=>{if(Q===this.workerGeneration&&B!==0&&this.state!=="failed")this.handleWorkerFailure(Error(`@ completion worker exited with code ${B}`))}),await new Promise((B)=>{this.initResolve=B})}async query(A,Q=50,B,$){return(await this.queryCompletions(A,Q,B,$)).filter((J)=>("path"in J)).map((J)=>J.path)}async queryCompletions(A,Q=50,B,$){if(this.fallbackClient)return this.fallbackClient.queryCompletions(A,Q,B,$);if(this.state==="unstarted")this.start().catch((Z)=>{j.debug("@ completion worker index lazy initialization failed",Z)});if(!this.worker)await this.waitForWorkerReady(Uq5);let J=this.getFallbackClient();if(J)return J.queryCompletions(A,Q,B,$);if(!this.worker||this.state==="failed")return[];let Y=++this.queryID;return this.latestQueryID=Y,new Promise((Z,F)=>{this.pendingQueries.set(Y,{text:A,limit:Q,openFiles:B,dirtyFiles:$,resolve:Z,reject:F}),this.worker?.postMessage({type:"query",id:Y,text:A.trim(),limit:Q,openFiles:[...Uf4(this.workspaceRoot,B)],dirtyFiles:[...Uf4(this.workspaceRoot,$)]})})}getStats(){if(this.fallbackClient)return this.fallbackClient.getStats();return{state:this.state,stats:this.stats}}dispose(){this.workerGeneration++,this.worker?.terminate().catch(()=>{}),this.worker=null,this.fallbackClient?.dispose(),this.fallbackClient=null,this.fallbackPromise=null,this.state="unstarted",this.stats=[],this.initPromise=null,this.resolveWorkerReady();for(let{resolve:A}of this.pendingQueries.values())A([]);this.pendingQueries.clear()}handleWorkerMessage(A){if(A.type==="state"){if(A.state==="failed"){this.switchToFallback(Error(A.error??"@ completion worker failed"));return}if(this.state=A.state,this.stats=A.stats,A.state==="ready")this.initResolve?.(),this.initResolve=null;return}let Q=this.pendingQueries.get(A.id);if(!Q)return;if(this.pendingQueries.delete(A.id),A.type==="queryError"){Q.reject(Error(A.error));return}Q.resolve(A.id===this.latestQueryID?A.results:[])}handleWorkerFailure(A){this.switchToFallback(A)}async switchToFallback(A){if(this.fallbackPromise){await this.fallbackPromise;return}let Q=A instanceof Error?A.message:String(A);j.warn("Falling back to legacy fuzzy service after @ completion worker failure",{error:Q}),this.workerGeneration++,this.worker?.terminate().catch(()=>{}),this.worker=null,this.resolveWorkerReady();let B=new Ct0(this.workspaceRoot,this.opts);this.fallbackClient=B,this.fallbackPromise=B.start().then(async()=>{let $=B.getStats();this.state=$.state,this.stats=$.stats,this.initResolve?.(),this.initResolve=null;let J=[...this.pendingQueries.values()];this.pendingQueries.clear(),await Promise.all(J.map(async(Y)=>{try{Y.resolve(await B.queryCompletions(Y.text,Y.limit,Y.openFiles,Y.dirtyFiles))}catch(Z){Y.reject(Z instanceof Error?Z:Error(String(Z)))}}))}),await this.fallbackPromise}async waitForWorkerReady(A){await Promise.race([new Promise((Q)=>this.workerReadyResolvers.push(Q)),new Promise((Q)=>setTimeout(Q,A))])}resolveWorkerReady(){let A=this.workerReadyResolvers.splice(0);for(let Q of A)Q()}getFallbackClient(){return this.fallbackClient}}var Oq5=String.raw`
4728
+ `).filter((H)=>H.length>0).every((H)=>H.includes("No such file or directory"))){j.debug("External tool failed",{command:J,code:E,stderr:V}),F(Error(`${J} exited with code ${E}: ${V}`));return}}try{let z=new Set,W={rootPath:Q,alwaysIncludeMatcher:$.alwaysIncludeMatcher},H=D.map((I)=>{let w=this.createEntryFromPath(Go(Q,I),{size:0,mtime:new Date,isDirectory:!1,isFile:!0,isSymlink:!1},W),O=I;while(O!==""&&O!==".")if(O=aH5(O),O&&O!=="."&&!z.has(O))z.add(O);return w}),q=Array.from(z).map((I)=>{return this.createEntryFromPath(Go(Q,I),{size:0,mtime:new Date,isDirectory:!0,isFile:!1,isSymlink:!1},W)}),N=[...H,...q];Z(N)}catch(z){F(z)}}),X.on("error",(E)=>{F(E)})})}async scanWithNodeJS(A,Q,B){if(Q.signal?.aborted)throw Error("Scan aborted");let $=[],J={scannedFiles:0,scannedDirectories:0,skippedPaths:0};return await this.scanDirectoryRecursive(A,A,0,Q,$,J,B),{entries:$,skippedPaths:J.skippedPaths}}async scanDirectoryRecursive(A,Q,B,$,J,Y,Z){if($.signal?.aborted)throw Error("Scan aborted");if(B>$.maxDepth)return;if(J.length>=$.maxFiles)return;let F=Vo(Q,A);if($.respectIgnorePatterns&&F){if(!($.alwaysIncludeMatcher?.(F)??!1)&&iQ.shouldIgnore(F,!0)){Y.skippedPaths++;return}}let X;try{X=await Cj.readdir(A,{withFileTypes:!0})}catch(D){if(D instanceof Error){if("code"in D&&(D.code==="EACCES"||D.code==="EPERM")){Y.skippedPaths++;return}if("code"in D&&D.code==="ENOENT")return}throw D}for(let D of X){if($.signal?.aborted)throw Error("Scan aborted");if(J.length>=$.maxFiles)break;let G=Go(A,D.name),V=Vo(Q,G);if($.respectIgnorePatterns){if(!($.alwaysIncludeMatcher?.(V)??!1)&&iQ.shouldIgnore(V,D.isDirectory())){Y.skippedPaths++;continue}}try{let U,K=!1,E={rootPath:Q,alwaysIncludeMatcher:$.alwaysIncludeMatcher};if(D.isDirectory())U=this.createEntryFromPath(G,{size:0,mtime:new Date,isDirectory:!0,isFile:!1,isSymlink:!1},E),Y.scannedDirectories++,K=!0;else if(D.isSymbolicLink()&&Z.followSymlinks){let z=await Cj.stat(G).catch(()=>null);if(z&&z.isDirectory())U=this.createEntryFromPath(G,{size:0,mtime:z.mtime,isDirectory:!0,isFile:!1,isSymlink:!0},E),Y.scannedDirectories++,K=!0;else if(z)U=this.createEntryFromPath(G,{size:z.size,mtime:z.mtime,isDirectory:!1,isFile:!0,isSymlink:!0},E),Y.scannedFiles++;else{Y.skippedPaths++;continue}}else{let z=await Cj.stat(G);U=this.createEntryFromPath(G,{size:z.size,mtime:z.mtime,isDirectory:!1,isFile:!0,isSymlink:z.isSymbolicLink()},E),Y.scannedFiles++}if(J.push(U),$.onProgress&&J.length%100===0)$.onProgress({scannedFiles:Y.scannedFiles,scannedDirectories:Y.scannedDirectories,currentPath:G});if(K){let z=await Jf4(G).catch(()=>null);if(!z){Y.skippedPaths++;continue}if(Z.visitedRealDirs.has(z))continue;Z.visitedRealDirs.add(z),await this.scanDirectoryRecursive(G,Q,B+1,$,J,Y,Z)}}catch(U){if(U instanceof Error){if("code"in U&&(U.code==="EACCES"||U.code==="EPERM"||U.code==="ENOENT")){Y.skippedPaths++;continue}}j.warn("Error processing file",{error:U}),Y.skippedPaths++}}}async scanAlwaysIncludePaths(A,Q,B,$,J){let Y=[],Z=new Set($.map((X)=>X.path)),F=new Set;for(let X of Q){let D=X.split("/"),G="";for(let V of D){if(V.includes("*")||V.includes("?")||V.includes("["))break;G=G?`${G}/${V}`:V}if(G)F.add(G)}for(let X of F){let D=Go(A,X);try{let G=await Cj.stat(D);if(G.isDirectory())await this.scanAlwaysIncludeDir(D,A,B,Z,Y,J);else if(!Z.has(D)){let V=Vo(A,D);if(B?.(V))Y.push(this.createEntryFromPath(D,{size:G.size,mtime:G.mtime,isDirectory:!1,isFile:!0,isSymlink:G.isSymbolicLink()},{rootPath:A,alwaysIncludeMatcher:B}))}}catch{}}return Y}async scanAlwaysIncludeDir(A,Q,B,$,J,Y){let Z;try{Z=await Cj.readdir(A,{withFileTypes:!0})}catch{return}for(let F of Z){let X=Go(A,F.name),D=Vo(Q,X);if($.has(X))continue;if(!(B?.(D)??!1))continue;try{if(F.isDirectory())J.push(this.createEntryFromPath(X,{size:0,mtime:new Date,isDirectory:!0,isFile:!1,isSymlink:!1},{rootPath:Q,alwaysIncludeMatcher:B})),await this.scanAlwaysIncludeDir(X,Q,B,$,J,Y);else if(F.isSymbolicLink()&&Y.followSymlinks){let V=await Cj.stat(X).catch(()=>null);if(V){if(J.push(this.createEntryFromPath(X,{size:V.size,mtime:V.mtime,isDirectory:V.isDirectory(),isFile:V.isFile(),isSymlink:!0},{rootPath:Q,alwaysIncludeMatcher:B})),V.isDirectory())await this.scanAlwaysIncludeDir(X,Q,B,$,J,Y)}}else{let V=await Cj.stat(X);J.push(this.createEntryFromPath(X,{size:V.size,mtime:V.mtime,isDirectory:!1,isFile:!0,isSymlink:V.isSymbolicLink()},{rootPath:Q,alwaysIncludeMatcher:B}))}}catch{}}}createEntryFromPath(A,Q,B){let $;if(Q.isDirectory)$="directory";else $="file";let J={size:Q.size,mtime:Q.mtime.getTime(),isSymlink:Q.isSymlink},Y=A,Z=o0.file(A),F=!1;if(B?.alwaysIncludeMatcher&&B?.rootPath){let X=Vo(B.rootPath,A);F=B.alwaysIncludeMatcher(X)}return new ZI({id:Y,kind:$,path:A,uri:Z,metadata:J,isAlwaysIncluded:F})}}var rH5={minScore:400,caseSensitive:!1,penalizeLengthDifference:!0,maxResults:50,smartCase:!0},nQ={EXACT_FILENAME:1000,PREFIX_FILENAME:950,SEGMENT_ORDERED_EXACT:900,SUFFIX_FILENAME:850,SEGMENT_ORDERED_PARTIAL:840,SUBSTRING_FILENAME:800,SEGMENT_EXACT:650,SEGMENT_SUBSTRING:600,PATH_SUBSTRING:500,FUZZY:250},sH5=["test","story"],tH5=30;class Ff4{config;queryChars;queryLower;constructor(A,Q={}){this.config={...rH5,...Q};let B=A.replace(/^[@#]+/,"");if(this.queryChars=Array.from(B),this.queryLower=Array.from(B.toLowerCase()),this.config.smartCase)this.config.caseSensitive=B!==B.toLowerCase()}match(A){if(this.queryChars.length===0)return A.filter((B)=>B.shouldIncludeInResults()).map((B)=>{let $=this.config.openFiles?.includes(B.path)?500:0,J=this.config.dirtyFiles?.includes(B.path)?300:0,Y=B.getImportanceBoost()+$+J-this.getTestAndStoryPathPenalty(B.path);return{entry:B,score:Y,matchPositions:[],highlightedPath:B.path}}).sort((B,$)=>$.score-B.score).slice(0,this.config.maxResults);let Q=this.matchWithSemanticScoring(A);if(Q.length>0)return Q;return this.matchWithFuzzyScoring(A)}matchWithSemanticScoring(A){let Q=[],B=0,$=50000,J=this.queryChars.join(""),Y=A.filter((F)=>F.shouldIncludeInResults()&&this.passesCharBagFilter(J,F)),Z=(F)=>{let X=this.matchEntrySemantic(F);if(X&&X.score>=this.config.minScore)Q.push(X);return B++,B>=$};for(let F of Y)if(F.isDirectory()){if(Z(F))break}if(B<$){for(let F of Y)if(!F.isDirectory()){if(Z(F))break}}return Q.sort((F,X)=>{let D=X.score-F.score;if(Math.abs(D)>0.001)return D;return F.entry.path.length-X.entry.path.length}),Q.slice(0,this.config.maxResults)}matchWithFuzzyScoring(A){let Q=[],B=0,$=50000,J=this.queryChars.join(""),Y=A.filter((F)=>F.shouldIncludeInResults()&&this.passesCharBagFilter(J,F)),Z=(F)=>{let X=this.matchEntryFuzzy(F);if(X)Q.push(X);return B++,B>=$};for(let F of Y)if(F.isDirectory()){if(Z(F))break}if(B<$){for(let F of Y)if(!F.isDirectory()){if(Z(F))break}}return Q.sort((F,X)=>{let D=X.score-F.score;if(Math.abs(D)>0.001)return D;return F.entry.path.length-X.entry.path.length}),Q.slice(0,this.config.maxResults)}matchEntrySemantic(A){let Q=A.path,B=this.queryLower.join(""),$=this.calculateSemanticScore(B,A);if($===0)return null;let J=this.applyTieBreakers($,B,A),Y=this.findMatchPositions(B,Q),Z=this.createHighlightedPath(Q,Y);return{entry:A,score:J,matchPositions:Y,highlightedPath:Z}}matchEntryFuzzy(A){let Q=A.path,B=this.queryLower.join(""),$=this.calculateFuzzyScore(B,A);if($===0)return null;let J=this.applyTieBreakers($,B,A),Y=this.findMatchPositions(B,Q),Z=this.createHighlightedPath(Q,Y);return{entry:A,score:J,matchPositions:Y,highlightedPath:Z}}calculateSemanticScore(A,Q){let B=A.toLowerCase(),$=Q.path,J=$.toLowerCase(),Y=this.normalizeMatchString(B),Z=this.getFilename($),F=this.removeExtension(Z).toLowerCase(),X=this.splitPathSegments(J);if(A.endsWith("/")&&Q.isDirectory()){let U=B.slice(0,-1);if(J===U||J.endsWith("/"+U))return nQ.EXACT_FILENAME+100;if(J.includes(U))return nQ.SUBSTRING_FILENAME+50}if(F===B||Z.toLowerCase()===B)return nQ.EXACT_FILENAME;if(F.startsWith(B))return nQ.PREFIX_FILENAME;if(F.endsWith(B))return nQ.SUFFIX_FILENAME;if(F.includes(B))return nQ.SUBSTRING_FILENAME;if(Y.length>6&&(A.includes("/")||A.includes("\\"))){let U=this.progressiveSegmentMatch(Y,X);if(U)return U}let D=this.simpleTokens(B);if(D.length>1){let U=this.matchTokensToSegments(D,X);if(U)return U}if(D.length===1&&B.length>6){let U=this.progressiveSegmentMatch(B,X);if(U)return U}if(X.includes(B))return nQ.SEGMENT_EXACT;if(X.some((U)=>U.includes(B)))return nQ.SEGMENT_SUBSTRING;let G=X.join("");if(Y&&G.includes(Y))return nQ.SEGMENT_SUBSTRING;let V=this.normalizeMatchString(J);if(Y&&V.includes(Y))return nQ.PATH_SUBSTRING;if(Y&&this.fuzzyIn(Y,V))return nQ.PATH_SUBSTRING;return 0}calculateFuzzyScore(A,Q){let B=A.toLowerCase(),$=Q.path.toLowerCase();if(this.fuzzyIn(B,$))return nQ.FUZZY;return 0}applyTieBreakers(A,Q,B){let $=A,J=Math.abs(B.path.length-Q.length);$-=0.01*J;let Y=B.path.split(/[/\\]/).length-1;$-=0.1*Y;let Z=this.getFilename(B.path),F=this.removeExtension(Z).toLowerCase();if(/^(license|readme|copy(ing|left))$/i.test(F)&&Y===1)$-=200;if(B.metadata.mtime){let D=(Date.now()-B.metadata.mtime)/86400000;if(D<30){let G=Math.max(0,1-D/30);$+=50*G}}if(this.config.openFiles?.includes(B.path))$+=500;if(this.config.dirtyFiles?.includes(B.path))$+=300;return $-=this.getTestAndStoryPathPenalty(B.path),$}getTestAndStoryPathPenalty(A){if(!this.config.downrankTestAndStoryPaths)return 0;return sH5.some((Q)=>A.includes(Q))?tH5:0}simpleTokens(A){return A.replace(/([a-z])([A-Z0-9])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}normalizeMatchString(A){return A.replace(/[^a-z0-9]+/g,"")}splitPathSegments(A){return A.split(/[/\\]/).flatMap((Q)=>Q.split(/[^a-z0-9]+/).filter(Boolean))}progressiveSegmentMatch(A,Q){let B=0,$=0,J=0;for(let Z of Q){if(B>=A.length)break;let F="",X="none";if(B+Z.length<=A.length){if(A.slice(B,B+Z.length)===Z)F=Z,X="exact"}if(!F&&Z.length>=3){if(A.slice(B).startsWith(Z))F=Z,X="prefix"}if(!F&&Z.length>=3){let D=A.slice(B);if(D.includes(Z)&&D.indexOf(Z)===0)F=Z,X="substring"}if(!F){let D=A.slice(B);if(D.length>=3&&Z.includes(D))F=D,X="substring"}if(F){if(B+=F.length,$++,X==="exact")J++}}if(B/A.length>=0.8&&$>=2)return J>=2?nQ.SEGMENT_ORDERED_EXACT:nQ.SEGMENT_ORDERED_PARTIAL;return 0}matchTokensToSegments(A,Q){let B=this.findTokenMatches(A,Q),$=this.getWorstMatchType(B);return this.scoreFromMatchType($)}findTokenMatches(A,Q){let B=0,$=[];for(let J of A){let Y=!1;for(let Z=B;Z<Q.length;Z++){let F=Q[Z];if(!F)continue;if(J===F){$.push("exact"),B=Z+1,Y=!0;break}else if(F.startsWith(J)||J.startsWith(F)||F.endsWith(J)||F.includes(J)||J.includes(F)){$.push("partial"),B=Z+1,Y=!0;break}}if(!Y)return[]}return $}getWorstMatchType(A){if(A.length===0)return"none";if(A.includes("partial"))return"partial";return"exact"}scoreFromMatchType(A){switch(A){case"exact":return nQ.SEGMENT_ORDERED_EXACT;case"partial":return nQ.SEGMENT_ORDERED_PARTIAL;default:return 0}}fuzzyIn(A,Q){let B=0;for(let $=0;$<Q.length&&B<A.length;$++)if(Q[$]===A[B])B++;return B===A.length}getFilename(A){return A.split(/[/\\]/).pop()||A}removeExtension(A){let Q=A.lastIndexOf(".");return Q>0?A.substring(0,Q):A}findMatchPositions(A,Q){let B=[],$=Q.toLowerCase(),J=A.toLowerCase();if($.includes(J)){let Z=$.indexOf(J);for(let F=0;F<J.length;F++)B.push(Z+F);return B}let Y=0;for(let Z of J){let F=$.indexOf(Z,Y);if(F!==-1)B.push(F),Y=F+1}return B}passesCharBagFilter(A,Q){if(A.includes("/")||A.includes("\\")){let B=A.split(/[/\\]/);for(let $ of B){if($.trim()==="")continue;let J=sB.fromString($);if(!Q.charBag.hasChars(J))return!1}return!0}else{let B=sB.fromString(A);return Q.charBag.hasChars(B)}}createHighlightedPath(A,Q){if(Q.length===0)return A;let B="",$=0;for(let J of Q){if(J>=A.length)continue;B+=A.slice($,J),B+=`**${A[J]}**`,$=J+1}return B+=A.slice($),B}}function Xf4(A,Q,B){return new Ff4(A,B).match(Q)}class Uo{metadata;entries;entriesByPath;entriesById;constructor(A,Q=[],B,$){if(this.metadata=A,this.entries=Q,B&&$)this.entriesByPath=B,this.entriesById=$;else{let J=new Map,Y=new Map;for(let Z of Q)J.set(Z.path,Z),Y.set(Z.id,Z);this.entriesByPath=J,this.entriesById=Y}this.cachedArray=Array.from(this.entriesByPath.values()),this.entriesArrayDirty=!1}static create(A){let Q=Date.now();return new Uo({id:Q,createdAt:Q,rootPath:A,entryCount:0,scanStatus:"scanning"},[])}static fromEntries(A,Q){let B=Date.now(),$={id:B,createdAt:B,rootPath:A,entryCount:Q.length,scanStatus:"complete"};return new Uo($,Q)}entriesArrayDirty=!1;cachedArray=[];getAllEntries(){if(this.entriesArrayDirty)this.cachedArray=[...this.entriesByPath.values()],this.entriesArrayDirty=!1;return this.cachedArray}getEntryByPath(A){return this.entriesByPath.get(A)??null}getEntryById(A){return this.entriesById.get(A)??null}applyChanges(A){let{added:Q=[],removed:B=[],modified:$=[]}=A;for(let J of B){let Y=this.entriesByPath.get(J);if(Y){if(this.entriesByPath.delete(J),this.entriesById.delete(Y.id),!this.entriesArrayDirty){let Z=this.cachedArray.findIndex((F)=>F.path===J);if(Z>=0)this.cachedArray.splice(Z,1)}}}for(let J of[...Q,...$])if(this.entriesByPath.set(J.path,J),this.entriesById.set(J.id,J),!this.entriesArrayDirty){let Y=this.cachedArray.findIndex((Z)=>Z.path===J.path);if(Y>=0)this.cachedArray.splice(Y,1);this.cachedArray.unshift(J)}this.metadata.entryCount=this.entriesByPath.size}findEntries(A){return this.entries.filter(A)}getFiles(){return this.findEntries((A)=>A.kind==="file")}getDirectories(){return this.findEntries((A)=>A.kind==="directory")}getInDirectory(A){let Q=A.endsWith("/")?A:A+"/";return this.findEntries((B)=>B.path.startsWith(Q)&&B.path!==A)}hasPath(A){return this.entriesByPath.has(A)}getStats(){let A=this.metadata.entryCount||this.entries.length,Q=this.getFiles().length,B=A-Q,$=A*250;return{totalEntries:A,fileEntries:Q,directoryEntries:B,memoryUsage:$}}}class qt0 extends eH5{rootPath;currentSnapshot=null;fileWatcher;scanner;isScanning=!1;stats;alwaysIncludeMatcher;constructor(A,Q){super();this.rootPath=A;this.fileWatcher=Q??cF0(),this.scanner=new Ht0,this.stats={totalFiles:0,totalDirectories:0,lastScanDuration:0,lastScanTime:0,memoryUsage:0,status:"idle"},this.fileWatcher.onFileSystemEvent(this.handleFileSystemEvents.bind(this))}async initialize(A){if(this.isScanning)throw Error("Index is already being initialized");let Q=A?.alwaysIncludePaths??[];this.alwaysIncludeMatcher=Q.length>0?Df4.default(Q,{dot:!0}):void 0;try{await this.performFullScan(A),await this.fileWatcher.watch(this.rootPath)}catch(B){throw this.updateStatus("error"),B}}async rescan(A){await this.performFullScan(A)}getCurrentSnapshot(){return this.currentSnapshot}getStats(){return{...this.stats}}search(A,Q={}){if(this.fileWatcher.triggerScan)this.fileWatcher.triggerScan(this.rootPath).catch(()=>{});if(!this.currentSnapshot)return[];let{limit:B=50,minScore:$=0.1,includeDirectories:J=!0,includeIgnored:Y=!1}=Q,Z=this.currentSnapshot.getAllEntries(),F=A.replace(/[@/]/g,"");if(F.length>2){if(Z.some((V)=>V.path.includes(F))){let V=Z.find((U)=>U.path.includes(F));j.debug("Search for existing file",{query:A,matchingFile:V?.path,entryIndex:Z.findIndex((U)=>U===V)})}}Z=Z.filter((G)=>{if(!Y&&G.isIgnored)return!1;if(!J&&G.isDirectory())return!1;return G.shouldIncludeInMentions()});let X=Xf4(A,Z,{minScore:$,openFiles:Q.openFiles,dirtyFiles:Q.dirtyFiles,downrankTestAndStoryPaths:Q.downrankTestAndStoryPaths});return X.sort((G,V)=>V.score-G.score),X.slice(0,B)}dispose(){this.fileWatcher.dispose(),this.removeAllListeners()}async performFullScan(A){this.isScanning=!0,this.updateStatus("scanning");let Q=Date.now();try{let B=await this.scanner.scanDirectory(this.rootPath,{respectIgnorePatterns:!0,...A});this.currentSnapshot=Uo.fromEntries(this.rootPath,B.entries);let $=Date.now()-Q;this.stats={...this.stats,totalFiles:B.stats.totalFiles,totalDirectories:B.stats.totalDirectories,lastScanDuration:$,lastScanTime:Q,memoryUsage:this.currentSnapshot.getStats().memoryUsage,status:"idle"},this.emit("scan-complete",{entries:B.entries.length,duration:$}),this.emit("status-changed",this.getStats())}catch(B){throw this.updateStatus("error"),this.emit("scan-error",B),B}finally{this.isScanning=!1}}async handleFileSystemEvents(A){if(!this.currentSnapshot||this.isScanning)return;this.updateStatus("updating");try{let Q=[],B=[],$=[];for(let J of A){let Y=J.path;switch(J.type){case"deleted":Q.push(Y);break;case"created":await this.processCreatedEvent(J,B);break;case"modified":await this.processModifiedEvent(J,$);break;case"renamed":if(J.oldPath)Q.push(J.oldPath);await this.processCreatedEvent(J,B);break}}if(this.currentSnapshot.applyChanges({removed:Q,added:B,modified:$}),Q.length>0||B.length>0||$.length>0)j.debug("Incremental snapshot update",{removed:Q.length,added:B.length,modified:$.length,totalEntries:this.currentSnapshot.metadata.entryCount,sampleAdded:B.slice(0,3).map((J)=>J.path),sampleRemoved:Q.slice(0,3)});this.stats={...this.stats,memoryUsage:this.currentSnapshot.getStats().memoryUsage,status:"idle"},this.emit("files-updated",{added:B.length,removed:Q.length,modified:$.length}),this.emit("status-changed",this.getStats())}catch(Q){this.updateStatus("error"),this.emit("scan-error",Q)}}async processCreatedEvent(A,Q){let B=A.path;try{let $=A.stat||(A.isDirectory?null:await Aq5.lstat(B)),J=A.isDirectory,Y=Qq5(this.rootPath,B),Z=this.alwaysIncludeMatcher?.(Y)??!1;if(!Z&&iQ.shouldIgnore(Y,J))return;if(J)Q.push(new ZI({id:B,kind:"directory",path:B,uri:o0.file(B),metadata:{size:0,mtime:Date.now(),isSymlink:!1},isIgnored:!1,isAlwaysIncluded:Z}));else if($)Q.push(new ZI({id:B,kind:"file",path:B,uri:o0.file(B),metadata:{size:$.size,mtime:$.mtimeMs,isSymlink:$.isSymbolicLink()},isIgnored:!1,isAlwaysIncluded:Z}))}catch{}}async processModifiedEvent(A,Q){let B=this.currentSnapshot?.getEntryByPath(A.path);if(B){let $=B.withUpdates({metadata:{...B.metadata,mtime:A.timestamp}});Q.push($)}}updateStatus(A){this.stats={...this.stats,status:A},this.emit("status-changed",this.getStats())}}d0();import{execFile as Bq5}from"node:child_process";import{EventEmitter as $q5}from"node:events";import{promises as lF0,watch as Jq5}from"node:fs";import{join as Nt0,resolve as Yq5}from"node:path";import{promisify as Zq5}from"node:util";var Gf4=Zq5(Bq5);class It0 extends $q5{repoRoot;pollInterval;on(A,Q){return super.on(A,Q)}emit(A,...Q){return super.emit(A,...Q)}currentSha;disposed=!1;started=!1;running=!1;pendingForce=!1;watchers=new Set;currentRefWatcher;timer;constructor(A,Q=30000){super();this.repoRoot=A;this.pollInterval=Q;this.repoRoot=this.validateRepoRoot(A)}static async isRepo(A){try{let Q=Nt0(A,".git");return await lF0.access(Q),!0}catch{try{let Q=Nt0(A,"HEAD");return await lF0.access(Q),!0}catch{return!1}}}async start(){if(this.disposed)throw Error("GitHeadWatcher has been disposed");if(this.started)throw Error("GitHeadWatcher has already been started");this.started=!0,this.currentSha=await this.getCurrentSha();let A=await this.getGitPath("HEAD");this.watch(A,async()=>{await this.updateRefWatcher(),this.scheduleCheck()}),await this.updateRefWatcher();let Q=await this.getGitPath("logs/HEAD");try{await lF0.access(Q),this.watch(Q,()=>this.scheduleCheck(!0))}catch{}this.timer=setInterval(()=>this.scheduleCheck(),this.pollInterval),j.debug("GitHeadWatcher started",{repoRoot:this.repoRoot,headPath:A})}stop(){for(let A of Array.from(this.watchers))this.cleanupWatcher(A);if(this.timer)clearInterval(this.timer),this.timer=void 0;this.currentRefWatcher=void 0,this.started=!1,this.running=!1,this.pendingForce=!1}dispose(){if(this.disposed)return;this.stop(),this.disposed=!0,this.removeAllListeners()}watch(A,Q){let B=Jq5(A);return B.on("change",Q),B.on("rename",()=>{this.cleanupWatcher(B),setTimeout(()=>{if(!this.disposed)this.watch(A,Q),this.scheduleCheck(!0)},50)}),B.on("error",($)=>{j.debug("Git file watcher error",{filePath:A,error:$}),this.cleanupWatcher(B)}),this.watchers.add(B),B}cleanupWatcher(A){try{A.removeAllListeners(),A.close()}catch(Q){j.debug("Error during watcher cleanup",{error:Q})}this.watchers.delete(A)}async updateRefWatcher(){if(this.currentRefWatcher)this.cleanupWatcher(this.currentRefWatcher),this.currentRefWatcher=void 0;try{let A=await this.getGitPath("HEAD"),Q=await lF0.readFile(A,"utf8");if(!Q)return;let B=Q.trim();if(B.startsWith("ref: ")){let $=B.slice(5),J=await this.getGitPath($);this.currentRefWatcher=this.watch(J,()=>this.scheduleCheck())}}catch(A){j.debug("Failed to update ref watcher",{repoRoot:this.repoRoot,error:A})}}scheduleCheck(A=!1){if(this.disposed)return;if(this.pendingForce||=A,this.running)return;this.running=!0,queueMicrotask(async()=>{if(this.disposed)return;let Q=this.pendingForce;this.pendingForce=!1;try{await this.performCheck(Q)}finally{this.running=!1}})}async checkForChanges(A=!1){this.scheduleCheck(A)}async performCheck(A){if(this.disposed)return;try{let Q=await this.getCurrentSha();if(!Q&&this.currentSha){j.warn("Failed to get current SHA, keeping previous value",{repoRoot:this.repoRoot,previousSha:this.currentSha.slice(0,7)});return}if(Q&&Q!==this.currentSha&&this.currentSha||A){let B=this.currentSha;this.currentSha=Q??this.currentSha,this.emit("head-change",{oldSha:B,newSha:this.currentSha,repoRoot:this.repoRoot,force:A})}else if(Q!==this.currentSha)this.currentSha=Q}catch(Q){j.warn("Error checking for git HEAD changes",{repoRoot:this.repoRoot,error:Q})}}async getCurrentSha(){try{let{stdout:A}=await Gf4("git",["rev-parse","HEAD"],{cwd:this.repoRoot});return A.trim()}catch(A){return}}async getGitPath(A){try{let{stdout:Q}=await Gf4("git",["rev-parse","--git-path",A],{cwd:this.repoRoot}),B=Q.trim();if(B.includes(`
4729
+ `))throw Error("Unexpected newline in git path output");return Yq5(this.repoRoot,B)}catch(Q){return Nt0(this.repoRoot,".git",A)}}validateRepoRoot(A){if(!A||typeof A!=="string")throw Error("Repository root must be a valid string path");if(!A.startsWith("/")&&!A.match(/^[A-Za-z]:\\/))throw Error("Repository root must be an absolute path");return A}}async function Vf4(A,Q){if(!await It0.isRepo(A))return null;return new It0(A,Q?.pollInterval)}class iF0{indexes=new Map;headWatchers=new Map;reindexingWorkspaces=new Set;config;disposed=!1;static forWorkspace(A){return new iF0({workspaceRoots:[A],scanOnStartup:!0,maxIndexedFiles:500000,enableFileWatching:!0,usePollingFallback:!1,enableHeadWatching:!0,followSymlinkDirs:!0})}constructor(A){this.config={...A}}async initialize(){if(this.disposed)throw Error("Service has been disposed");if(this.config.scanOnStartup){let A=this.config.workspaceRoots.map((Q)=>this.indexWorkspace(Q));await Promise.allSettled(A)}}async indexWorkspace(A){if(this.disposed)throw Error("Service has been disposed");if(this.indexes.has(A)){await this.indexes.get(A).rescan();return}let Q=this.config.enableFileWatching?cF0({rootPath:A,usePolling:this.config.usePollingFallback}):void 0,B=new qt0(A,Q);B.on("scan-error",(J)=>{j.error("Scan error in workspace",{rootPath:A,error:J})});let $={respectIgnorePatterns:!0,maxFiles:this.config.maxIndexedFiles,followSymlinks:this.config.followSymlinkDirs,alwaysIncludePaths:this.config.alwaysIncludePaths};try{if(await B.initialize($),this.indexes.set(A,B),this.config.enableHeadWatching)await this.setupHeadWatching(A,B,Q)}catch(J){B.dispose();let Y=this.headWatchers.get(A);if(Y)Y.dispose(),this.headWatchers.delete(A);throw J}}async removeWorkspace(A){let Q=this.indexes.get(A);if(Q)Q.dispose(),this.indexes.delete(A);let B=this.headWatchers.get(A);if(B)B.dispose(),this.headWatchers.delete(A)}searchAll(A,Q){let B=[];for(let $ of this.indexes.values())try{let J=$.search(A,Q);B.push(...J)}catch(J){}return B.sort(($,J)=>J.score-$.score),Q?.limit?B.slice(0,Q.limit):B}searchWorkspace(A,Q,B){let $=this.indexes.get(A);if(!$)return[];try{return $.search(Q,B)}catch(J){return j.error(`Search error in workspace ${A}:`,J),[]}}getIndexStats(A){if(A){let B=this.indexes.get(A);if(B)return[{...B.getStats(),rootPath:A}];return[]}let Q=[];for(let[B,$]of this.indexes.entries())Q.push({...$.getStats(),rootPath:B});return Q}getConfig(){return{...this.config}}updateConfig(A){this.config={...this.config,...A}}async rescanAll(){let A=[];for(let[Q,B]of this.indexes.entries())A.push(B.rescan().catch(($)=>{j.error(`Rescan error in workspace ${Q}:`,$)}));await Promise.allSettled(A)}getIndexedWorkspaces(){return Array.from(this.indexes.keys())}isWorkspaceIndexed(A){return this.indexes.has(A)}dispose(){if(this.disposed)return;for(let[,A]of this.indexes.entries())A.dispose();for(let[,A]of this.headWatchers.entries())A.dispose();this.indexes.clear(),this.headWatchers.clear(),this.disposed=!0}isDisposed(){return this.disposed}async setupHeadWatching(A,Q,B){try{let $=await Vf4(A);if(!$)return;$.on("head-change",async({oldSha:J,newSha:Y})=>{if(this.reindexingWorkspaces.has(A)){j.debug("Re-index already in progress, skipping",{rootPath:A});return}this.reindexingWorkspaces.add(A);try{if(await Q.rescan(),B&&B instanceof Lx)await B.reset(A)}catch(Z){j.error("Failed to re-index after change",{rootPath:A,error:Z})}finally{this.reindexingWorkspaces.delete(A)}}),await $.start(),this.headWatchers.set(A,$),j.debug("Git HEAD watching enabled",{rootPath:A})}catch($){j.warn("Failed to setup git HEAD watching",{rootPath:A,error:$})}}}function wt0(A,Q){let B={workspaceRoots:A,scanOnStartup:!0,maxIndexedFiles:500000,enableFileWatching:!0,usePollingFallback:!1,enableHeadWatching:!0,followSymlinkDirs:!0,...Q};return new iF0(B)}var Xq5=4096,Dq5=["test","story"],Gq5="AMP_EXPERIMENT_PERFSORT",Vq5="AMP_LEGACY_CORE_FUZZY_INDEX",Uq5=4,Kq5=50,Eq5=5,zq5=3.25,Wq5=3,Hq5=6,qq5=1.5,Nq5=1,Iq5=1.5,wq5=1,Cq5=0.75,Mq5=5.5,Lq5=0.5;function Ef4(){return process.env[Gq5]==="1"}function Oq5(){return process.env[Vq5]==="1"}class nF0{implementation;workspaceRoot;constructor(A=process.cwd(),Q={},B=!1){this.workspaceRoot=A,this.implementation=Oq5()?new Ct0(A,Q,B):new zf4(A,Q,B)}async start(){return this.implementation.start()}async query(A,Q=50,B,$){return this.implementation.query(A,Q,B,$)}async queryCompletions(A,Q=50,B,$){return this.implementation.queryCompletions(A,Q,B,$)}getStats(){return this.implementation.getStats()}dispose(){this.implementation.dispose()}}class Ct0{opts;fuzzyService=null;state="unstarted";initPromise=null;workspaceRoot;constructor(A=process.cwd(),Q={},B=!1){this.opts=Q;if(this.workspaceRoot=A,B)this.start().catch(($)=>{j.debug("Fuzzy service background initialization failed",$)})}async start(){if(this.initPromise!==null)return this.initPromise;return this.initPromise=this.init(),this.initPromise}async init(){if(FI.resolve(this.workspaceRoot)===FI.resolve(Kf4.homedir())){this.state="ready";return}this.state="initializing";try{this.fuzzyService=wt0([this.workspaceRoot],{scanOnStartup:!0,enableFileWatching:!0,usePollingFallback:!1,...this.opts}),await this.fuzzyService.initialize(),this.state="ready"}catch(A){this.state="failed",j.warn("Failed to initialize legacy fuzzy service",{error:A instanceof Error?A.message:String(A)})}}async query(A,Q=50,B,$){return(await this.queryCompletions(A,Q,B,$)).map((J)=>("path"in J)?J.path:"").filter(Boolean)}async queryCompletions(A,Q=50,B,$){if(this.state==="unstarted")await this.start();else if(this.initPromise!==null)await this.initPromise;if(!this.fuzzyService)return[];try{let J=A.trim();return this.fuzzyService.searchAll(J,{limit:Q,minScore:J?0.1:void 0,openFiles:B,dirtyFiles:$,downrankTestAndStoryPaths:!0}).map((Z)=>({kind:Z.entry.isDirectory()?"folder":"file",path:FI.relative(this.workspaceRoot,Z.entry.path)}))}catch(J){return j.error("Fuzzy search failed",J),[]}}getStats(){return{state:this.state,stats:this.fuzzyService?.getIndexStats()??[]}}dispose(){this.fuzzyService?.dispose(),this.fuzzyService=null,this.state="unstarted",this.initPromise=null}}class zf4{opts;worker=null;fallbackClient=null;fallbackPromise=null;state="unstarted";stats=[];initPromise=null;initResolve=null;queryID=0;latestQueryID=0;workerGeneration=0;workerReadyResolvers=[];pendingQueries=new Map;workspaceRoot;constructor(A=process.cwd(),Q={},B=!1){this.opts=Q;if(this.workspaceRoot=A,B)this.start().catch(($)=>{j.debug("@ completion worker index background initialization failed",$)})}async start(){if(this.fallbackClient)return this.fallbackClient.start();if(this.initPromise!==null)return this.initPromise;return this.initPromise=this.init(),this.initPromise}async init(){if(FI.resolve(this.workspaceRoot)===FI.resolve(Kf4.homedir())){this.state="ready";return}this.state="initializing",this.stats=[Pq5(this.workspaceRoot,{status:"scanning"})];let A;try{let B=await Eq(),$=Date.now();A=new Fq5(jq5,{eval:!0,workerData:{rg:B,workspaceRoot:this.workspaceRoot,alwaysIncludePaths:this.opts.alwaysIncludePaths?.filter(Boolean)??[],startedAt:$}})}catch(B){await this.switchToFallback(B);return}this.worker=A;let Q=++this.workerGeneration;this.resolveWorkerReady(),A.on("message",(B)=>{if(Q===this.workerGeneration)this.handleWorkerMessage(B)}),A.on("error",(B)=>{if(Q===this.workerGeneration)this.handleWorkerFailure(B)}),A.on("exit",(B)=>{if(Q===this.workerGeneration&&B!==0&&this.state!=="failed")this.handleWorkerFailure(Error(`@ completion worker exited with code ${B}`))}),await new Promise((B)=>{this.initResolve=B})}async query(A,Q=50,B,$){return(await this.queryCompletions(A,Q,B,$)).filter((J)=>("path"in J)).map((J)=>J.path)}async queryCompletions(A,Q=50,B,$){if(this.fallbackClient)return this.fallbackClient.queryCompletions(A,Q,B,$);if(this.state==="unstarted")this.start().catch((Z)=>{j.debug("@ completion worker index lazy initialization failed",Z)});if(!this.worker)await this.waitForWorkerReady(Kq5);let J=this.getFallbackClient();if(J)return J.queryCompletions(A,Q,B,$);if(!this.worker||this.state==="failed")return[];let Y=++this.queryID;return this.latestQueryID=Y,new Promise((Z,F)=>{this.pendingQueries.set(Y,{text:A,limit:Q,openFiles:B,dirtyFiles:$,resolve:Z,reject:F}),this.worker?.postMessage({type:"query",id:Y,text:A.trim(),limit:Q,openFiles:[...Uf4(this.workspaceRoot,B)],dirtyFiles:[...Uf4(this.workspaceRoot,$)]})})}getStats(){if(this.fallbackClient)return this.fallbackClient.getStats();return{state:this.state,stats:this.stats}}dispose(){this.workerGeneration++,this.worker?.terminate().catch(()=>{}),this.worker=null,this.fallbackClient?.dispose(),this.fallbackClient=null,this.fallbackPromise=null,this.state="unstarted",this.stats=[],this.initPromise=null,this.resolveWorkerReady();for(let{resolve:A}of this.pendingQueries.values())A([]);this.pendingQueries.clear()}handleWorkerMessage(A){if(A.type==="state"){if(A.state==="failed"){this.switchToFallback(Error(A.error??"@ completion worker failed"));return}if(this.state=A.state,this.stats=A.stats,A.state==="ready")this.initResolve?.(),this.initResolve=null;return}let Q=this.pendingQueries.get(A.id);if(!Q)return;if(this.pendingQueries.delete(A.id),A.type==="queryError"){Q.reject(Error(A.error));return}Q.resolve(A.id===this.latestQueryID?A.results:[])}handleWorkerFailure(A){this.switchToFallback(A)}async switchToFallback(A){if(this.fallbackPromise){await this.fallbackPromise;return}let Q=A instanceof Error?A.message:String(A);j.warn("Falling back to legacy fuzzy service after @ completion worker failure",{error:Q}),this.workerGeneration++,this.worker?.terminate().catch(()=>{}),this.worker=null,this.resolveWorkerReady();let B=new Ct0(this.workspaceRoot,this.opts);this.fallbackClient=B,this.fallbackPromise=B.start().then(async()=>{let $=B.getStats();this.state=$.state,this.stats=$.stats,this.initResolve?.(),this.initResolve=null;let J=[...this.pendingQueries.values()];this.pendingQueries.clear(),await Promise.all(J.map(async(Y)=>{try{Y.resolve(await B.queryCompletions(Y.text,Y.limit,Y.openFiles,Y.dirtyFiles))}catch(Z){Y.reject(Z instanceof Error?Z:Error(String(Z)))}}))}),await this.fallbackPromise}async waitForWorkerReady(A){await Promise.race([new Promise((Q)=>this.workerReadyResolvers.push(Q)),new Promise((Q)=>setTimeout(Q,A))])}resolveWorkerReady(){let A=this.workerReadyResolvers.splice(0);for(let Q of A)Q()}getFallbackClient(){return this.fallbackClient}}var jq5=String.raw`
4730
4730
  const { spawn } = require('node:child_process')
4731
4731
  const { readdir } = require('node:fs/promises')
4732
4732
  const path = require('node:path')
@@ -4734,20 +4734,20 @@ const { StringDecoder } = require('node:string_decoder')
4734
4734
  const { parentPort, workerData } = require('node:worker_threads')
4735
4735
  const { setImmediate: setImmediateAsync } = require('node:timers/promises')
4736
4736
 
4737
- const TEST_AND_STORY_PATH_TERMS = ${JSON.stringify(Xq5)}
4738
- const BASENAME_SCORE_WEIGHT = ${Kq5}
4739
- const PATH_SCORE_WEIGHT = ${Eq5}
4740
- const EXACT_BASENAME_BONUS = ${zq5}
4741
- const EXACT_PATH_BONUS = ${Wq5}
4742
- const PREFIX_BASENAME_BONUS = ${Hq5}
4743
- const PREFIX_PATH_BONUS = ${qq5}
4744
- const OPEN_FILE_BONUS = ${Nq5}
4745
- const DIRTY_FILE_BONUS = ${Iq5}
4746
- const FOLDER_MULTI_TERM_QUERY_BONUS = ${wq5}
4747
- const TRAILING_FOLDER_QUERY_BONUS = ${Cq5}
4748
- const TEST_AND_STORY_PATH_PENALTY = ${Mq5}
4749
- const STREAMING_QUERY_SLICE_BUDGET_MS = ${Vq5}
4750
- const MAX_STDERR_CHARS = ${Fq5}
4737
+ const TEST_AND_STORY_PATH_TERMS = ${JSON.stringify(Dq5)}
4738
+ const BASENAME_SCORE_WEIGHT = ${Eq5}
4739
+ const PATH_SCORE_WEIGHT = ${zq5}
4740
+ const EXACT_BASENAME_BONUS = ${Wq5}
4741
+ const EXACT_PATH_BONUS = ${Hq5}
4742
+ const PREFIX_BASENAME_BONUS = ${qq5}
4743
+ const PREFIX_PATH_BONUS = ${Nq5}
4744
+ const OPEN_FILE_BONUS = ${Iq5}
4745
+ const DIRTY_FILE_BONUS = ${wq5}
4746
+ const FOLDER_MULTI_TERM_QUERY_BONUS = ${Cq5}
4747
+ const TRAILING_FOLDER_QUERY_BONUS = ${Mq5}
4748
+ const TEST_AND_STORY_PATH_PENALTY = ${Lq5}
4749
+ const STREAMING_QUERY_SLICE_BUDGET_MS = ${Uq5}
4750
+ const MAX_STDERR_CHARS = ${Xq5}
4751
4751
 
4752
4752
  let entries = []
4753
4753
  const entriesByPath = new Set()
@@ -5143,21 +5143,21 @@ parentPort.on('message', async (message) => {
5143
5143
  })
5144
5144
  }
5145
5145
  })()
5146
- `;function jq5(A){return FI.normalize(A)}function Rq5(A,Q={}){return{rootPath:A,totalFiles:0,totalDirectories:0,lastScanDuration:0,lastScanTime:0,memoryUsage:0,status:"idle",...Q}}function Uf4(A,Q){if(!Q||Q.length===0)return new Set;return new Set(Q.map((B)=>{let $=FI.isAbsolute(B)?FI.relative(A,B):B;return jq5($)}))}d0();import*as Wf4 from"node:readline";async function Pq5(){let A=Wf4.createInterface({input:process.stdin}),Q={};try{for await(let B of A){if(B==="")break;let $=B.indexOf("=");if($!==-1){let J=B.slice(0,$),Y=B.slice($+1);Q[J]=Y}}}finally{A.close()}return Q}async function _q5(A,Q){let B=await fetch(`${A}/api/internal`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Q}`},body:JSON.stringify({method:"getGitHubGitAccessToken",params:{host:"github.com",protocol:"https"}})});if(!B.ok)return j.error("Failed to fetch GitHub git token",{status:B.status}),process.stderr.write(`Unable to fetch GitHub credentials.
5146
+ `;function Rq5(A){return FI.normalize(A)}function Pq5(A,Q={}){return{rootPath:A,totalFiles:0,totalDirectories:0,lastScanDuration:0,lastScanTime:0,memoryUsage:0,status:"idle",...Q}}function Uf4(A,Q){if(!Q||Q.length===0)return new Set;return new Set(Q.map((B)=>{let $=FI.isAbsolute(B)?FI.relative(A,B):B;return Rq5($)}))}d0();import*as Wf4 from"node:readline";async function _q5(){let A=Wf4.createInterface({input:process.stdin}),Q={};try{for await(let B of A){if(B==="")break;let $=B.indexOf("=");if($!==-1){let J=B.slice(0,$),Y=B.slice($+1);Q[J]=Y}}}finally{A.close()}return Q}async function Tq5(A,Q){let B=await fetch(`${A}/api/internal`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Q}`},body:JSON.stringify({method:"getGitHubGitAccessToken",params:{host:"github.com",protocol:"https"}})});if(!B.ok)return j.error("Failed to fetch GitHub git token",{status:B.status}),process.stderr.write(`Unable to fetch GitHub credentials.
5147
5147
  `),null;let $=await B.json();if(!$.ok||!$.result?.accessToken){if(j.debug("GitHub git token not available",{error:$.error}),$.error?.message)process.stderr.write(`${$.error.message}
5148
- `);return null}return $.result.accessToken}async function Hf4(A,Q,B){if(A!=="get")return;let $=await Pq5();if($.protocol!=="https"||$.host!=="github.com")return;let J=await B.get("apiKey",Q);if(!J){j.error("No API key found. Run `amp login` first."),process.exitCode=1;return}let Y=await _q5(Q,J);if(!Y){process.exitCode=1;return}process.stdout.write(`protocol=https
5148
+ `);return null}return $.result.accessToken}async function Hf4(A,Q,B){if(A!=="get")return;let $=await _q5();if($.protocol!=="https"||$.host!=="github.com")return;let J=await B.get("apiKey",Q);if(!J){j.error("No API key found. Run `amp login` first."),process.exitCode=1;return}let Y=await Tq5(Q,J);if(!Y){process.exitCode=1;return}process.stdout.write(`protocol=https
5149
5149
  host=github.com
5150
5150
  username=x-access-token
5151
5151
  password=${Y}
5152
5152
 
5153
- `)}d0();async function Tq5(A,Q,B){let $=await fetch(`${A}/api/internal`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Q}`},body:JSON.stringify({method:"signCommit",params:{commitObject:B}})});if(!$.ok)return j.error("Failed to fetch commit signature",{status:$.status}),null;let J=await $.json();if(!J.ok||!J.result?.signature)return j.error("Commit signing failed",{error:J.error}),null;return J.result.signature}async function qf4(A,Q){let B=await Q.get("apiKey",A);if(!B){j.error("No API key found. Run `amp login` first."),process.exitCode=1;return}let $=[];for await(let Z of process.stdin)$.push(Z);let J=Buffer.concat($).toString("utf-8"),Y=await Tq5(A,B,J);if(!Y){process.exitCode=1;return}process.stdout.write(Y),process.stdout.write(`
5153
+ `)}d0();async function kq5(A,Q,B){let $=await fetch(`${A}/api/internal`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Q}`},body:JSON.stringify({method:"signCommit",params:{commitObject:B}})});if(!$.ok)return j.error("Failed to fetch commit signature",{status:$.status}),null;let J=await $.json();if(!J.ok||!J.result?.signature)return j.error("Commit signing failed",{error:J.error}),null;return J.result.signature}async function qf4(A,Q){let B=await Q.get("apiKey",A);if(!B){j.error("No API key found. Run `amp login` first."),process.exitCode=1;return}let $=[];for await(let Z of process.stdin)$.push(Z);let J=Buffer.concat($).toString("utf-8"),Y=await kq5(A,B,J);if(!Y){process.exitCode=1;return}process.stdout.write(Y),process.stdout.write(`
5154
5154
  `),process.stderr.write(`
5155
5155
  [GNUPG:] SIG_CREATED
5156
- `)}d0();L2();function Mt0(A){return async()=>{let Q=await DA.loadPlugins({},{config:A});if(!Q.ok)throw j.debug("Failed to load global plugins from internal API",{error:Q.error}),Error(Q.error.message);return Q.result}}d0();n7();wY0();Cc();function aF0(A){return A.toolUseId}function Nf4(A){let Q=aF0(A);return{id:A.id||Q,toolCallId:Q,toolName:A.toolName,args:A.args,reason:A.reason,toAllow:A.toAllow,context:A.context,timestamp:A.timestamp,matchedRule:A.matchedRule,ruleSource:A.ruleSource}}class Lt0{options;constructor(A){this.options=A}onConnectionChanged(A){let B={role:A.role??"unclaimed"};if(A.state==="reconnecting"&&A.reconnectCause)Object.assign(B,kq5(A.reconnectCause));this.options.logInfo(`${this.options.clientID} connection: ${A.state}`,B),this.options.overrides?.onConnectionChanged?.(A)}onDelta(A){this.log({eventType:"delta",...A}),this.options.overrides?.onDelta?.(A)}onAgentState(A){this.log(A),this.options.overrides?.onAgentState?.(A)}onMessageAdded(A){this.log(A),this.options.overrides?.onMessageAdded?.(A)}onMessageUpdated(A){this.log(A),this.options.overrides?.onMessageUpdated?.(A)}onEditRejected(A){this.log(A),this.options.overrides?.onEditRejected?.(A)}onQueuedMessages(A){this.log(A),this.options.overrides?.onQueuedMessages?.(A)}onRetryEvent(A){this.log(A),this.options.overrides?.onRetryEvent?.(A)}onErrorNotice(A){this.log(A),this.options.logError(`${this.options.clientID} error`,A.message),this.options.overrides?.onErrorNotice?.(A)}onActiveError(A){this.log(A),this.options.overrides?.onActiveError?.(A)}onCancelled(A){this.log(A),this.options.overrides?.onCancelled?.(A)}onToolApprovalQueue(A){this.log(A),this.options.overrides?.onToolApprovalQueue?.(A)}onExecutorToolApprovalResponse(A){this.log(A),this.options.overrides?.onExecutorToolApprovalResponse?.(A)}onToolProgress(A){this.log(A),this.options.overrides?.onToolProgress?.(A)}onExecutorError(A){this.log(A),this.options.logError(`${this.options.clientID} executor error`,A.message),this.options.overrides?.onExecutorError?.(A)}onExecutorConnected(A){this.log(A),this.options.overrides?.onExecutorConnected?.(A)}onObservers(A){this.log(A),this.options.overrides?.onObservers?.(A)}onExecutorStatus(A){this.log(A),this.options.overrides?.onExecutorStatus?.(A)}onEnvironmentUpdate(A){this.log(A),this.options.overrides?.onEnvironmentUpdate?.(A)}onArtifactEvent(A){this.log(A),this.options.overrides?.onArtifactEvent?.(A)}onThreadTitle(A){this.log(A),this.options.overrides?.onThreadTitle?.(A)}onThreadRelationships(A){this.log(A),this.options.overrides?.onThreadRelationships?.(A)}onCompactionEvent(A){this.log(A),this.options.overrides?.onCompactionEvent?.(A)}onPluginMessage(A){this.log(A),this.options.overrides?.onPluginMessage?.(A)}log(A){this.options.logWsMessage("RECV",this.options.clientID,A)}}function kq5(A){let Q={reconnectCauseType:A.type,reconnectCauseAt:new Date(A.at).toISOString()};if(A.code!==void 0)Q.reconnectCode=A.code;if(A.reason)Q.reconnectReason=A.reason;if(A.error)Q.reconnectError=A.error;return Q}var Ko=j.getChild("headless-executor");function jt0(){return new Date().toISOString()}var Rt0=process.stderr.isTTY,If4=3000;function Sq5(A){let Q=A.trim();if(!(Q.startsWith("{")&&Q.endsWith("}")||Q.startsWith("[")&&Q.endsWith("]")))return null;try{return JSON.parse(Q)}catch{return null}}var oF0=2000;function Pt0(A){let Q;if(A instanceof Error)Q=A.stack??A.message;else if(typeof A==="string"){let B=Sq5(A);Q=B!==null?JSON.stringify(B,null,2):A}else if(A===void 0)return"";else try{Q=JSON.stringify(A,null,2)}catch{Q=String(A)}if(Q.length>oF0)return Q.slice(0,oF0)+n0.dim(`
5156
+ `)}d0();L2();function Mt0(A){return async()=>{let Q=await DA.loadPlugins({},{config:A});if(!Q.ok)throw j.debug("Failed to load global plugins from internal API",{error:Q.error}),Error(Q.error.message);return Q.result}}d0();n7();wY0();Cc();function aF0(A){return A.toolUseId}function Nf4(A){let Q=aF0(A);return{id:A.id||Q,toolCallId:Q,toolName:A.toolName,args:A.args,reason:A.reason,toAllow:A.toAllow,context:A.context,timestamp:A.timestamp,matchedRule:A.matchedRule,ruleSource:A.ruleSource}}class Lt0{options;constructor(A){this.options=A}onConnectionChanged(A){let B={role:A.role??"unclaimed"};if(A.state==="reconnecting"&&A.reconnectCause)Object.assign(B,Sq5(A.reconnectCause));this.options.logInfo(`${this.options.clientID} connection: ${A.state}`,B),this.options.overrides?.onConnectionChanged?.(A)}onDelta(A){this.log({eventType:"delta",...A}),this.options.overrides?.onDelta?.(A)}onAgentState(A){this.log(A),this.options.overrides?.onAgentState?.(A)}onMessageAdded(A){this.log(A),this.options.overrides?.onMessageAdded?.(A)}onMessageUpdated(A){this.log(A),this.options.overrides?.onMessageUpdated?.(A)}onEditRejected(A){this.log(A),this.options.overrides?.onEditRejected?.(A)}onQueuedMessages(A){this.log(A),this.options.overrides?.onQueuedMessages?.(A)}onRetryEvent(A){this.log(A),this.options.overrides?.onRetryEvent?.(A)}onErrorNotice(A){this.log(A),this.options.logError(`${this.options.clientID} error`,A.message),this.options.overrides?.onErrorNotice?.(A)}onActiveError(A){this.log(A),this.options.overrides?.onActiveError?.(A)}onCancelled(A){this.log(A),this.options.overrides?.onCancelled?.(A)}onToolApprovalQueue(A){this.log(A),this.options.overrides?.onToolApprovalQueue?.(A)}onExecutorToolApprovalResponse(A){this.log(A),this.options.overrides?.onExecutorToolApprovalResponse?.(A)}onToolProgress(A){this.log(A),this.options.overrides?.onToolProgress?.(A)}onExecutorError(A){this.log(A),this.options.logError(`${this.options.clientID} executor error`,A.message),this.options.overrides?.onExecutorError?.(A)}onExecutorConnected(A){this.log(A),this.options.overrides?.onExecutorConnected?.(A)}onObservers(A){this.log(A),this.options.overrides?.onObservers?.(A)}onExecutorStatus(A){this.log(A),this.options.overrides?.onExecutorStatus?.(A)}onEnvironmentUpdate(A){this.log(A),this.options.overrides?.onEnvironmentUpdate?.(A)}onArtifactEvent(A){this.log(A),this.options.overrides?.onArtifactEvent?.(A)}onThreadTitle(A){this.log(A),this.options.overrides?.onThreadTitle?.(A)}onThreadRelationships(A){this.log(A),this.options.overrides?.onThreadRelationships?.(A)}onCompactionEvent(A){this.log(A),this.options.overrides?.onCompactionEvent?.(A)}onPluginMessage(A){this.log(A),this.options.overrides?.onPluginMessage?.(A)}log(A){this.options.logWsMessage("RECV",this.options.clientID,A)}}function Sq5(A){let Q={reconnectCauseType:A.type,reconnectCauseAt:new Date(A.at).toISOString()};if(A.code!==void 0)Q.reconnectCode=A.code;if(A.reason)Q.reconnectReason=A.reason;if(A.error)Q.reconnectError=A.error;return Q}var Ko=j.getChild("headless-executor");function jt0(){return new Date().toISOString()}var Rt0=process.stderr.isTTY,If4=3000;function vq5(A){let Q=A.trim();if(!(Q.startsWith("{")&&Q.endsWith("}")||Q.startsWith("[")&&Q.endsWith("]")))return null;try{return JSON.parse(Q)}catch{return null}}var oF0=2000;function Pt0(A){let Q;if(A instanceof Error)Q=A.stack??A.message;else if(typeof A==="string"){let B=vq5(A);Q=B!==null?JSON.stringify(B,null,2):A}else if(A===void 0)return"";else try{Q=JSON.stringify(A,null,2)}catch{Q=String(A)}if(Q.length>oF0)return Q.slice(0,oF0)+n0.dim(`
5157
5157
  ... (truncated ${Q.length-oF0} chars)`);return Q}function Ot0(A){if(typeof A!=="object"||A===null)return A;if(Array.isArray(A))return A.map(Ot0);let Q={};for(let[B,$]of Object.entries(A))if(typeof $==="string"&&$.length>oF0)Q[B]=`<${$.length} chars>`;else if(typeof $==="object"&&$!==null)Q[B]=Ot0($);else Q[B]=$;return Q}function Mj(A,Q,B){let $=Ot0(B);if(Ko.info("websocket message",{direction:A,clientId:Q,...typeof $==="object"&&$!==null?$:{message:$}}),!Rt0)return;let J=n0.dim(`[${jt0()}]`),Y=n0.magenta(`[${Q}]`),Z=A==="SEND"?n0.green(">>>"):n0.yellow("<<<"),F=Pt0($);process.stderr.write(`${J} ${Y} ${Z} ${F}
5158
5158
  `)}function Y9(A,Q){if(Q)Ko.info(A,Q);else Ko.info(A);if(!Rt0)return;let B=n0.dim(`[${jt0()}]`),$=n0.cyan("[INFO]"),J=Q?` ${Pt0(Q)}`:"";process.stderr.write(`${B} ${$} ${A}${J}
5159
5159
  `)}function kz(A,Q){if(Q!==void 0)Ko.error(A,{error:Q});else Ko.error(A);if(!Rt0)return;let B=n0.dim(`[${jt0()}]`),$=n0.red("[ERROR]"),J=Pt0(Q);process.stderr.write(`${B} ${$} ${A} ${J}
5160
- `)}function vq5(A,Q){let B=new URL(A);if(!B.pathname.endsWith("/"))B.pathname+="/";return new URL(`threads/${Q}`,B).toString()}class wf4{options;client=null;disposed=!1;pluginsBootstrapped=!1;pendingExitCode=null;resolveRunLoop=null;constructor(A){this.options=A}bindClientThread(A,Q){let B=A.threadId!==Q;if(A.threadId=Q,A.fsTracker&&!B)return;let $=this.options.fileSystem??j3,J=new ML($);A.fsTracker=IY0({fileChangeTrackerStorage:J},$,Q)}async connectTransport(A,Q,B){let $=await A.ensureConnected({maxAttempts:1,waitForConnectedTimeoutMs:If4});if(!$){let J=A.getConnectionInfo();Y9(`${Q} waiting for reconnect during ${B}`,{connectionState:J.state,reconnectCauseType:J.reconnectCause?.type,reconnectCauseCode:J.reconnectCause?.code,reconnectCauseReason:J.reconnectCause?.reason,waitedMs:If4})}return $}async recoverTransport(A,Q,B,$){let J=this.client;if(!J||J.recoveringTransport||this.disposed)return;J.recoveringTransport=!0,Y9(`${A} recovering transport after send failure`,{messageType:Q,error:B.message,...$});try{let Y=J.transport.getConnectionInfo();if(Y.state==="connecting"||Y.state==="authenticating"||Y.state==="reconnecting"){Y9(`${A} recovery waiting for in-flight connection`,{connectionState:Y.state,reconnectCauseType:Y.reconnectCause?.type,reconnectCauseCode:Y.reconnectCause?.code,reconnectCauseReason:Y.reconnectCause?.reason});return}if(Y.state==="connected")J.transport.disconnect();let Z=await this.connectTransport(J.transport,A,"recovery"),F=J.transport.getThreadId();if(F)this.bindClientThread(J,F);if(!Z)return;let X=J.transport.getConnectionInfo();Y9(`${A} requesting executor handshake after transport recovery`,{trigger:"retry",connectionState:X.state,role:X.role,transportClientId:X.clientId}),J.executorRuntime.ensureHandshake("retry")}catch(Y){kz(`${A} transport recovery failed`,Y)}finally{J.recoveringTransport=!1}}async start(){Y9("Starting Headless DTW Harness",{ampURL:this.options.ampURL,workspaceRoot:this.options.workspaceRoot,threadId:this.options.threadId??null});try{let A=await this.createClient(this.options.threadId);Y9("Initial client created",{clientId:A.id,threadId:A.threadId}),this.logThreadURL(A.threadId);let Q=await this.runLoop();if(Q!==0)throw Error(`Headless DTW harness exited with code ${Q}`)}catch(A){throw kz("Failed to start harness",A),A}}logThreadURL(A){if(!A)return;let Q=vq5(this.options.ampURL,A);Y9(`Thread URL: ${n0.blue.underline(Q)}`)}async shutdown(A,Q){if(this.pendingExitCode===null||A>this.pendingExitCode)this.pendingExitCode=A;let B=this.resolveRunLoop;if(B)this.resolveRunLoop=null;if(!this.disposed){if(A===0)Y9(Q);else kz(Q);await this.dispose()}if(B){let $=this.pendingExitCode??A;this.pendingExitCode=null,B($)}}async invokeToolForClient(A,Q){let{toolService:B,configService:$,mcpService:J,skillService:Y}=this.options;if(!B||!$||!J)throw Error("Tool service not available");let{toolName:Z,toolCallId:F,args:X}=Q,D=typeof X==="object"&&X!==null?X:{},V=await YI({toolName:Z,dtwArtifactSyncService:{upsertArtifact:(U,K)=>{let E=l3.safeParse(K);A.transport.sendExecutorArtifactUpsert(U,E.success?E.data:void 0)},deleteArtifact:(U)=>{A.transport.sendExecutorArtifactDelete(U)}},configService:$,toolService:B,mcpService:J,skillService:Y,fsTracker:A.fsTracker??void 0,toolUseID:F,discoveredGuidanceFileURIs:A.toolRunner.discoveredGuidanceFileURIs,threadId:A.threadId});return B.invokeTool(Z,{args:D},V)}async createClient(A){let Q=`cli-headless-${crypto.randomUUID()}`,B={current:null},$=()=>{let N=B.current;if(!N)throw Error("Headless client callbacks invoked before initialization");return N},J=process.env.RIVET_PUBLIC_ENDPOINT??uF(this.options.ampURL);Y9(`Creating client ${Q}`,{threadId:A,rivetPublicEndpoint:J,options:this.options});let Y=OU({endpoint:J}),Z={threadId:A,webSocketProvider:async()=>{return{webSocket:await Y.threadActor.getOrCreate([A],{params:{apiKey:this.options.apiKey,threadId:A,executorClientId:Q},...this.options.ownerUserId&&typeof this.options.threadVersion==="number"?{createWithInput:{threadId:A,ownerUserId:this.options.ownerUserId,threadVersion:this.options.threadVersion}}:{}}).webSocket("/",void 0,{skipReadyWait:!0}),threadId:A}},maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000},F=null,{toolService:X}=this.options,D=new Lt0({clientID:Q,logWsMessage:Mj,logInfo:Y9,logError:kz,overrides:{onConnectionChanged:(N)=>{let I=$();Y9(`${Q} forwarding connection change to executor runtime`,{...N});let w=U.getThreadId();if(N.state==="connected"&&w)this.bindClientThread(I,w);I.executorRuntime.handleConnectionChange(N)},onExecutorToolApprovalResponse:(N)=>{if(!X){kz(`${Q} received approval response without tool service`);return}Y9(`${Q} approval resolved`,{toolCallId:N.toolCallId,accepted:N.accepted}),X.resolveApproval(N.toolCallId,N.accepted,N.input?.denyFeedback)}}}),G=null,V=this.options.pluginService?bF0({pluginService:this.options.pluginService,sendPluginMessage:(N)=>G?.(N)}):void 0,U=new PU({transport:Z,threadHistoryLoader:async()=>null,observerCallbacks:D,executorCallbacks:{onToolLease:(N)=>{F?.onToolLeaseMessage(N)},onToolLeaseRevoked:(N)=>{F?.onToolLeaseRevokedMessage(N)},onFileSystemReadDirectoryRequest:(N)=>{F?.onExecutorFileSystemReadDirectoryRequestMessage(N)},onFileSystemReadFileRequest:(N)=>{F?.onExecutorFileSystemReadFileRequestMessage(N)},...V?{onPluginMessage:V}:{}}});G=(N)=>U.sendPluginMessage(N);let K=(N)=>({...N??{},threadId:A}),E={info:(N,I)=>{Y9(N,K(I))},error:(N,I)=>{kz(N,I)},wsMessage:(N,I,w)=>{Mj(N,I,K(typeof w==="object"&&w!==null?w:{message:w}))}};F=new wj({transport:U,toolService:this.options.toolService,configService:this.options.configService,clientID:Q,threadId:A,invokeTool:(N)=>this.invokeToolForClient($(),N),skillService:this.options.skillService,fileSystem:this.options.fileSystem,bootstrapLogMessage:(N,I)=>{Mj(N,Q,I)},initialToolDiscovery:this.options.initialToolDiscovery,onBootstrapSuccess:async()=>{let N=$();if(!N.hasLoggedPostBootstrapThreadURL&&N.threadId)this.logThreadURL(N.threadId),N.hasLoggedPostBootstrapThreadURL=!0;this.setNotifyForwarder(N),this.bootstrapPluginsAfterExecutorConnect(N)},sendGitSnapshot:!0,executorType:"sandbox",workspaceRoot:this.options.workspaceRoot,handshakeManagerOptions:{onError:({error:N,attempt:I,delayMs:w})=>{kz(`${Q} executor handshake failed`,{error:N,attempt:I,delayMs:w})},onExhausted:({error:N,maxAttempts:I})=>{this.shutdown(1,`${Q} executor handshake failed after ${I} attempts: ${N instanceof Error?N.message:String(N)}`)}},captureGitStatus:()=>gF0(this.options.workspaceRoot),batchGuidanceFiles:bx4,renderToolRunError:hh0,onTransportSendFailure:(N,I,w,O)=>{this.recoverTransport(N,I,w,O)},log:E,autoResolvePendingApprovals:!1,handleExecutorFileSystemReadDirectoryRequest:async(N)=>{let I=$();await this.handleExecutorFileSystemReadDirectoryRequest(I,N)},handleExecutorFileSystemReadFileRequest:async(N)=>{let I=$();await this.handleExecutorFileSystemReadFileRequest(I,N)},logInboundExecutorMessages:!0});let z={id:Q,transport:U,threadId:A,hasLoggedPostBootstrapThreadURL:!1,executorRuntime:F,toolRunner:F.toolRunner,fsTracker:null,recoveringTransport:!1};B.current=z,this.client=z;let W=U.getConnectionInfo();Y9(`${Q} seeding executor runtime with initial connection info`,{connectionState:W.state,role:W.role,transportClientId:W.clientId,reconnectCauseType:W.reconnectCause?.type,reconnectCauseCode:W.reconnectCause?.code,reconnectCauseReason:W.reconnectCause?.reason}),F.handleConnectionChange(W),this.subscribeToApprovalRequests(z),Y9(`Connecting ${Q}...`);let H=await this.connectTransport(U,Q,"startup"),q=U.getThreadId();if(q)this.bindClientThread(z,q);if(H)Y9(`Connected ${Q}`,{threadId:q});if(H)z.executorRuntime.ensureHandshake("connect");return z}setNotifyForwarder(A){let Q=this.options.pluginPlatform;if(!Q)return;Q.setNotifyForwarder(async(B)=>{let $={type:"event",event:"ui.notify",data:{message:B}};try{Mj("SEND",A.id,{type:"executor_plugin_message",message:$}),A.transport.sendPluginMessage($)}catch(J){kz(`${A.id} failed to forward plugin notification`,J)}})}bootstrapPluginsAfterExecutorConnect(A){let Q=this.options.pluginService;if(!Q)return;if(!this.pluginsBootstrapped)this.pluginsBootstrapped=!0,Y9(`${A.id} reloading plugins after executor bootstrap`),Q.reload();try{A.transport.sendPluginMessage({type:"event",event:"plugins.ready",data:{}})}catch(B){kz(`${A.id} failed to advertise plugin readiness`,B)}}syncApprovalRequests(A,Q){if(!A.threadId)return;let B=Q.filter((J)=>J.threadId===A.threadId||J.mainThreadId===A.threadId),$=new Set(B.map(aF0));for(let J of[...A.toolRunner.sentApprovalRequests])if(!$.has(J))A.toolRunner.sentApprovalRequests.delete(J);for(let J of B){let Y=aF0(J);if(A.toolRunner.sentApprovalRequests.has(Y))continue;let Z=Nf4(J);Mj("SEND",A.id,{type:"executor_tool_approval_request",toolCallId:Z.toolCallId,toolName:Z.toolName}),A.transport.sendExecutorToolApprovalRequest(Z),A.toolRunner.sentApprovalRequests.add(Y)}}subscribeToApprovalRequests(A){let{toolService:Q}=this.options;if(Q)Q.pendingApprovals$.subscribe((B)=>{this.syncApprovalRequests(A,B)})}async handleExecutorFileSystemReadDirectoryRequest(A,Q){let B=await qx({fileSystem:this.options.fileSystem??j3,workspaceRoot:this.options.workspaceRoot},Q.uri);Mj("SEND",A.id,{type:"executor_filesystem_read_directory_result",requestId:Q.requestId,...B}),A.transport.sendExecutorFileSystemReadDirectoryResult(Q.requestId,B)}async handleExecutorFileSystemReadFileRequest(A,Q){let B=await qx4({fileSystem:this.options.fileSystem??j3,workspaceRoot:this.options.workspaceRoot},Q.uri);Mj("SEND",A.id,{type:"executor_filesystem_read_file_result",requestId:Q.requestId,...B}),A.transport.sendExecutorFileSystemReadFileResult(Q.requestId,B)}async runLoop(){if(Y9("Harness running. Press Ctrl+C to exit."),this.pendingExitCode!==null)return this.pendingExitCode;return await new Promise((A)=>{let Q=!1,B=(Y)=>{if(Q){Y9(`Received ${Y} while shutdown is already in progress`);return}Q=!0,this.shutdown(0,`Received ${Y}, shutting down harness...`)},$=()=>B("SIGINT"),J=()=>B("SIGTERM");this.resolveRunLoop=(Y)=>{process.off("SIGINT",$),process.off("SIGTERM",J),A(Y)},process.on("SIGINT",$),process.on("SIGTERM",J)})}async dispose(){this.disposed=!0,this.options.pluginPlatform?.setNotifyForwarder(null);let A=this.client;if(A){if((await A.transport.disconnectAndWait()).status==="timeout")Y9(`${A.id} timed out waiting for close acknowledgement before dispose`);A.transport.dispose(),A.executorRuntime.dispose()}this.client=null}}async function Cf4(A){let Q=await nY(A.threadId,A.configService,A.apiKey);await new wf4({...A,threadId:Q.threadId,ownerUserId:Q.ownerUserId,threadVersion:Q.threadVersion,agentMode:Q.agentMode}).start()}import{stderr as vD,stdin as yq5}from"node:process";import{createInterface as xq5}from"node:readline";import{stdout as _t0}from"node:process";function Mf4(){return!!(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)}function rF0(){return _t0.isTTY&&Mf4()}function sF0(A=_t0){A.write("\x07")}function Lf4(){if(!_t0.isTTY)return!0;if(Mf4())return!0;if(process.platform!=="darwin"&&process.platform!=="win32"&&!process.env.DISPLAY)return!0;return!1}var tF0=[],Tt0=null;function kt0(A){if(Tt0=A,A&&tF0.length>0){for(let Q of tF0)A(Q);tF0=[]}}function Of4(A){return async(Q,B)=>{return new Promise(($,J)=>{let Y={serverName:A,authorizationUrl:Q,redirectUrl:B,resolve:$,reject:J};if(Tt0)Tt0(Y);else tF0.push(Y)})}}function jf4(){return async(A,Q)=>{return vD.write(`
5160
+ `)}function yq5(A,Q){let B=new URL(A);if(!B.pathname.endsWith("/"))B.pathname+="/";return new URL(`threads/${Q}`,B).toString()}class wf4{options;client=null;disposed=!1;pluginsBootstrapped=!1;pendingExitCode=null;resolveRunLoop=null;constructor(A){this.options=A}bindClientThread(A,Q){let B=A.threadId!==Q;if(A.threadId=Q,A.fsTracker&&!B)return;let $=this.options.fileSystem??j3,J=new ML($);A.fsTracker=IY0({fileChangeTrackerStorage:J},$,Q)}async connectTransport(A,Q,B){let $=await A.ensureConnected({maxAttempts:1,waitForConnectedTimeoutMs:If4});if(!$){let J=A.getConnectionInfo();Y9(`${Q} waiting for reconnect during ${B}`,{connectionState:J.state,reconnectCauseType:J.reconnectCause?.type,reconnectCauseCode:J.reconnectCause?.code,reconnectCauseReason:J.reconnectCause?.reason,waitedMs:If4})}return $}async recoverTransport(A,Q,B,$){let J=this.client;if(!J||J.recoveringTransport||this.disposed)return;J.recoveringTransport=!0,Y9(`${A} recovering transport after send failure`,{messageType:Q,error:B.message,...$});try{let Y=J.transport.getConnectionInfo();if(Y.state==="connecting"||Y.state==="authenticating"||Y.state==="reconnecting"){Y9(`${A} recovery waiting for in-flight connection`,{connectionState:Y.state,reconnectCauseType:Y.reconnectCause?.type,reconnectCauseCode:Y.reconnectCause?.code,reconnectCauseReason:Y.reconnectCause?.reason});return}if(Y.state==="connected")J.transport.disconnect();let Z=await this.connectTransport(J.transport,A,"recovery"),F=J.transport.getThreadId();if(F)this.bindClientThread(J,F);if(!Z)return;let X=J.transport.getConnectionInfo();Y9(`${A} requesting executor handshake after transport recovery`,{trigger:"retry",connectionState:X.state,role:X.role,transportClientId:X.clientId}),J.executorRuntime.ensureHandshake("retry")}catch(Y){kz(`${A} transport recovery failed`,Y)}finally{J.recoveringTransport=!1}}async start(){Y9("Starting Headless DTW Harness",{ampURL:this.options.ampURL,workspaceRoot:this.options.workspaceRoot,threadId:this.options.threadId??null});try{let A=await this.createClient(this.options.threadId);Y9("Initial client created",{clientId:A.id,threadId:A.threadId}),this.logThreadURL(A.threadId);let Q=await this.runLoop();if(Q!==0)throw Error(`Headless DTW harness exited with code ${Q}`)}catch(A){throw kz("Failed to start harness",A),A}}logThreadURL(A){if(!A)return;let Q=yq5(this.options.ampURL,A);Y9(`Thread URL: ${n0.blue.underline(Q)}`)}async shutdown(A,Q){if(this.pendingExitCode===null||A>this.pendingExitCode)this.pendingExitCode=A;let B=this.resolveRunLoop;if(B)this.resolveRunLoop=null;if(!this.disposed){if(A===0)Y9(Q);else kz(Q);await this.dispose()}if(B){let $=this.pendingExitCode??A;this.pendingExitCode=null,B($)}}async invokeToolForClient(A,Q){let{toolService:B,configService:$,mcpService:J,skillService:Y}=this.options;if(!B||!$||!J)throw Error("Tool service not available");let{toolName:Z,toolCallId:F,args:X}=Q,D=typeof X==="object"&&X!==null?X:{},V=await YI({toolName:Z,dtwArtifactSyncService:{upsertArtifact:(U,K)=>{let E=l3.safeParse(K);A.transport.sendExecutorArtifactUpsert(U,E.success?E.data:void 0)},deleteArtifact:(U)=>{A.transport.sendExecutorArtifactDelete(U)}},configService:$,toolService:B,mcpService:J,skillService:Y,fsTracker:A.fsTracker??void 0,toolUseID:F,discoveredGuidanceFileURIs:A.toolRunner.discoveredGuidanceFileURIs,threadId:A.threadId});return B.invokeTool(Z,{args:D},V)}async createClient(A){let Q=`cli-headless-${crypto.randomUUID()}`,B={current:null},$=()=>{let N=B.current;if(!N)throw Error("Headless client callbacks invoked before initialization");return N},J=process.env.RIVET_PUBLIC_ENDPOINT??uF(this.options.ampURL);Y9(`Creating client ${Q}`,{threadId:A,rivetPublicEndpoint:J,options:this.options});let Y=OU({endpoint:J}),Z={threadId:A,webSocketProvider:async()=>{return{webSocket:await Y.threadActor.getOrCreate([A],{params:{apiKey:this.options.apiKey,threadId:A,executorClientId:Q},...this.options.ownerUserId&&typeof this.options.threadVersion==="number"?{createWithInput:{threadId:A,ownerUserId:this.options.ownerUserId,threadVersion:this.options.threadVersion}}:{}}).webSocket("/",void 0,{skipReadyWait:!0}),threadId:A}},maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000},F=null,{toolService:X}=this.options,D=new Lt0({clientID:Q,logWsMessage:Mj,logInfo:Y9,logError:kz,overrides:{onConnectionChanged:(N)=>{let I=$();Y9(`${Q} forwarding connection change to executor runtime`,{...N});let w=U.getThreadId();if(N.state==="connected"&&w)this.bindClientThread(I,w);I.executorRuntime.handleConnectionChange(N)},onExecutorToolApprovalResponse:(N)=>{if(!X){kz(`${Q} received approval response without tool service`);return}Y9(`${Q} approval resolved`,{toolCallId:N.toolCallId,accepted:N.accepted}),X.resolveApproval(N.toolCallId,N.accepted,N.input?.denyFeedback)}}}),G=null,V=this.options.pluginService?bF0({pluginService:this.options.pluginService,sendPluginMessage:(N)=>G?.(N)}):void 0,U=new PU({transport:Z,threadHistoryLoader:async()=>null,observerCallbacks:D,executorCallbacks:{onToolLease:(N)=>{F?.onToolLeaseMessage(N)},onToolLeaseRevoked:(N)=>{F?.onToolLeaseRevokedMessage(N)},onFileSystemReadDirectoryRequest:(N)=>{F?.onExecutorFileSystemReadDirectoryRequestMessage(N)},onFileSystemReadFileRequest:(N)=>{F?.onExecutorFileSystemReadFileRequestMessage(N)},...V?{onPluginMessage:V}:{}}});G=(N)=>U.sendPluginMessage(N);let K=(N)=>({...N??{},threadId:A}),E={info:(N,I)=>{Y9(N,K(I))},error:(N,I)=>{kz(N,I)},wsMessage:(N,I,w)=>{Mj(N,I,K(typeof w==="object"&&w!==null?w:{message:w}))}};F=new wj({transport:U,toolService:this.options.toolService,configService:this.options.configService,clientID:Q,threadId:A,invokeTool:(N)=>this.invokeToolForClient($(),N),skillService:this.options.skillService,fileSystem:this.options.fileSystem,bootstrapLogMessage:(N,I)=>{Mj(N,Q,I)},initialToolDiscovery:this.options.initialToolDiscovery,onBootstrapSuccess:async()=>{let N=$();if(!N.hasLoggedPostBootstrapThreadURL&&N.threadId)this.logThreadURL(N.threadId),N.hasLoggedPostBootstrapThreadURL=!0;this.setNotifyForwarder(N),this.bootstrapPluginsAfterExecutorConnect(N)},sendGitSnapshot:!0,executorType:"sandbox",workspaceRoot:this.options.workspaceRoot,handshakeManagerOptions:{onError:({error:N,attempt:I,delayMs:w})=>{kz(`${Q} executor handshake failed`,{error:N,attempt:I,delayMs:w})},onExhausted:({error:N,maxAttempts:I})=>{this.shutdown(1,`${Q} executor handshake failed after ${I} attempts: ${N instanceof Error?N.message:String(N)}`)}},captureGitStatus:()=>gF0(this.options.workspaceRoot),batchGuidanceFiles:bx4,renderToolRunError:hh0,onTransportSendFailure:(N,I,w,O)=>{this.recoverTransport(N,I,w,O)},log:E,autoResolvePendingApprovals:!1,handleExecutorFileSystemReadDirectoryRequest:async(N)=>{let I=$();await this.handleExecutorFileSystemReadDirectoryRequest(I,N)},handleExecutorFileSystemReadFileRequest:async(N)=>{let I=$();await this.handleExecutorFileSystemReadFileRequest(I,N)},logInboundExecutorMessages:!0});let z={id:Q,transport:U,threadId:A,hasLoggedPostBootstrapThreadURL:!1,executorRuntime:F,toolRunner:F.toolRunner,fsTracker:null,recoveringTransport:!1};B.current=z,this.client=z;let W=U.getConnectionInfo();Y9(`${Q} seeding executor runtime with initial connection info`,{connectionState:W.state,role:W.role,transportClientId:W.clientId,reconnectCauseType:W.reconnectCause?.type,reconnectCauseCode:W.reconnectCause?.code,reconnectCauseReason:W.reconnectCause?.reason}),F.handleConnectionChange(W),this.subscribeToApprovalRequests(z),Y9(`Connecting ${Q}...`);let H=await this.connectTransport(U,Q,"startup"),q=U.getThreadId();if(q)this.bindClientThread(z,q);if(H)Y9(`Connected ${Q}`,{threadId:q});if(H)z.executorRuntime.ensureHandshake("connect");return z}setNotifyForwarder(A){let Q=this.options.pluginPlatform;if(!Q)return;Q.setNotifyForwarder(async(B)=>{let $={type:"event",event:"ui.notify",data:{message:B}};try{Mj("SEND",A.id,{type:"executor_plugin_message",message:$}),A.transport.sendPluginMessage($)}catch(J){kz(`${A.id} failed to forward plugin notification`,J)}})}bootstrapPluginsAfterExecutorConnect(A){let Q=this.options.pluginService;if(!Q)return;if(!this.pluginsBootstrapped)this.pluginsBootstrapped=!0,Y9(`${A.id} reloading plugins after executor bootstrap`),Q.reload();try{A.transport.sendPluginMessage({type:"event",event:"plugins.ready",data:{}})}catch(B){kz(`${A.id} failed to advertise plugin readiness`,B)}}syncApprovalRequests(A,Q){if(!A.threadId)return;let B=Q.filter((J)=>J.threadId===A.threadId||J.mainThreadId===A.threadId),$=new Set(B.map(aF0));for(let J of[...A.toolRunner.sentApprovalRequests])if(!$.has(J))A.toolRunner.sentApprovalRequests.delete(J);for(let J of B){let Y=aF0(J);if(A.toolRunner.sentApprovalRequests.has(Y))continue;let Z=Nf4(J);Mj("SEND",A.id,{type:"executor_tool_approval_request",toolCallId:Z.toolCallId,toolName:Z.toolName}),A.transport.sendExecutorToolApprovalRequest(Z),A.toolRunner.sentApprovalRequests.add(Y)}}subscribeToApprovalRequests(A){let{toolService:Q}=this.options;if(Q)Q.pendingApprovals$.subscribe((B)=>{this.syncApprovalRequests(A,B)})}async handleExecutorFileSystemReadDirectoryRequest(A,Q){let B=await qx({fileSystem:this.options.fileSystem??j3,workspaceRoot:this.options.workspaceRoot},Q.uri);Mj("SEND",A.id,{type:"executor_filesystem_read_directory_result",requestId:Q.requestId,...B}),A.transport.sendExecutorFileSystemReadDirectoryResult(Q.requestId,B)}async handleExecutorFileSystemReadFileRequest(A,Q){let B=await qx4({fileSystem:this.options.fileSystem??j3,workspaceRoot:this.options.workspaceRoot},Q.uri);Mj("SEND",A.id,{type:"executor_filesystem_read_file_result",requestId:Q.requestId,...B}),A.transport.sendExecutorFileSystemReadFileResult(Q.requestId,B)}async runLoop(){if(Y9("Harness running. Press Ctrl+C to exit."),this.pendingExitCode!==null)return this.pendingExitCode;return await new Promise((A)=>{let Q=!1,B=(Y)=>{if(Q){Y9(`Received ${Y} while shutdown is already in progress`);return}Q=!0,this.shutdown(0,`Received ${Y}, shutting down harness...`)},$=()=>B("SIGINT"),J=()=>B("SIGTERM");this.resolveRunLoop=(Y)=>{process.off("SIGINT",$),process.off("SIGTERM",J),A(Y)},process.on("SIGINT",$),process.on("SIGTERM",J)})}async dispose(){this.disposed=!0,this.options.pluginPlatform?.setNotifyForwarder(null);let A=this.client;if(A){if((await A.transport.disconnectAndWait()).status==="timeout")Y9(`${A.id} timed out waiting for close acknowledgement before dispose`);A.transport.dispose(),A.executorRuntime.dispose()}this.client=null}}async function Cf4(A){let Q=await nY(A.threadId,A.configService,A.apiKey);await new wf4({...A,threadId:Q.threadId,ownerUserId:Q.ownerUserId,threadVersion:Q.threadVersion,agentMode:Q.agentMode}).start()}import{stderr as vD,stdin as xq5}from"node:process";import{createInterface as fq5}from"node:readline";import{stdout as _t0}from"node:process";function Mf4(){return!!(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)}function rF0(){return _t0.isTTY&&Mf4()}function sF0(A=_t0){A.write("\x07")}function Lf4(){if(!_t0.isTTY)return!0;if(Mf4())return!0;if(process.platform!=="darwin"&&process.platform!=="win32"&&!process.env.DISPLAY)return!0;return!1}var tF0=[],Tt0=null;function kt0(A){if(Tt0=A,A&&tF0.length>0){for(let Q of tF0)A(Q);tF0=[]}}function Of4(A){return async(Q,B)=>{return new Promise(($,J)=>{let Y={serverName:A,authorizationUrl:Q,redirectUrl:B,resolve:$,reject:J};if(Tt0)Tt0(Y);else tF0.push(Y)})}}function jf4(){return async(A,Q)=>{return vD.write(`
5161
5161
  `),vD.write(n0.yellow.bold(`OAuth Authorization Required
5162
5162
  `)),vD.write(n0.dim("─".repeat(60)+`
5163
5163
  `)),vD.write(`
@@ -5169,12 +5169,12 @@ password=${Y}
5169
5169
  `)),vD.write(n0.dim(`The redirect will fail - this is expected in headless mode.
5170
5170
  `)),vD.write(n0.dim(`Copy the full URL from your browser address bar and paste it below.
5171
5171
  `)),vD.write(`
5172
- `),await fq5("Paste the callback URL or authorization code: ")}}async function fq5(A){let Q=xq5({input:yq5,output:vD});return new Promise((B,$)=>{Q.on("SIGINT",()=>{Q.close(),$(Error("OAuth authorization cancelled"))}),Q.question(A,(J)=>{Q.close(),B(J.trim())})})}function Rf4(){if(process.env.AMP_HEADLESS_OAUTH==="1"||process.env.AMP_HEADLESS_OAUTH==="true")return!0;return Lf4()}pZ();d0();import{readFileSync as bq5,rmSync as uq5}from"node:fs";import{mkdir as hq5,readFile as gq5,rm as St0,writeFile as mq5}from"node:fs/promises";import Pf4 from"node:path";var pq5=Pf4.join(x$,"pids");function dq5(A){try{return process.kill(A,0),!0}catch(Q){return Q.code==="EPERM"}}function _f4(A){let Q=A.trim();if(!/^\d+$/.test(Q))return;let B=Number.parseInt(Q,10);return Number.isSafeInteger(B)&&B>0?B:void 0}function vt0(A,Q){return A.code===Q}async function Tf4(A){try{let Q=await gq5(A,"utf-8"),B=_f4(Q);if(B===void 0)return{kind:"invalid",value:Q.trim()};return{kind:"valid",pid:B}}catch(Q){if(vt0(Q,"ENOENT"))return{kind:"missing"};throw Q}}async function cq5(A,Q){let B=await Tf4(A);if(B.kind!=="valid"||B.pid!==Q)return;await St0(A,{force:!0}),j.info("Removed headless PID file",{currentPID:Q,pidFilePath:A})}function lq5(A,Q){try{let B=bq5(A,"utf-8");if(_f4(B)!==Q)return}catch(B){if(vt0(B,"ENOENT"))return;throw B}uq5(A,{force:!0})}async function kf4(A,Q={}){let B=Q.pidDir??pq5,$=Q.currentPID??process.pid,J=Q.isProcessRunning??dq5,Y=Pf4.join(B,`${A}.pid`);await hq5(B,{recursive:!0});while(!0){let Z=await Tf4(Y);if(Z.kind==="valid"){if(J(Z.pid))return j.info("Headless instance already running for thread, exiting",{pidFilePath:Y,runningPID:Z.pid,threadID:A}),{status:"already-running",pidFilePath:Y,runningPID:Z.pid};j.info("Replacing stale headless PID file",{pidFilePath:Y,stalePID:Z.pid,threadID:A}),await St0(Y,{force:!0})}if(Z.kind==="invalid")j.warn("Replacing invalid headless PID file content",{invalidPID:Z.value,pidFilePath:Y,threadID:A}),await St0(Y,{force:!0});try{await mq5(Y,`${$}
5173
- `,{encoding:"utf-8",flag:"wx",mode:384}),j.info("Claimed headless PID file",{currentPID:$,pidFilePath:Y,threadID:A});let F=!1,X=()=>{if(F)return;F=!0,lq5(Y,$)},D=(U)=>{if(X(),process.off("SIGINT",G),process.off("SIGTERM",V),process.listenerCount(U)===0)process.kill(process.pid,U)},G=()=>D("SIGINT"),V=()=>D("SIGTERM");return process.once("exit",X),process.on("SIGINT",G),process.on("SIGTERM",V),{status:"claimed",pidFilePath:Y,release:async()=>{if(F)return;await cq5(Y,$),F=!0,process.off("exit",X),process.off("SIGINT",G),process.off("SIGTERM",V)}}}catch(F){if(vt0(F,"EEXIST"))continue;throw F}}}BV();d0();M1();import yt0,{promises as Wo}from"node:fs";import{homedir as yf4}from"node:os";import aY from"node:path";k50();d0();jT();import{promises as XI}from"node:fs";import Eo from"node:path";async function zo(A,Q,B){let $=await XI.realpath(A).catch((G)=>G.code==="ENOENT"?A:Promise.reject(G)),J=await XI.readFile($,"utf-8").catch((G)=>G.code==="ENOENT"?"{}":Promise.reject(G)),Y=Q(J);if(J===Y.newContent)return;let F=Eo.dirname($);await XI.mkdir(F,{recursive:!0});let X=await XI.mkdtemp(Eo.join(F,".amp-temp-")),D=Eo.join(X,Eo.basename(A));try{await XI.writeFile(D,Y.newContent,{encoding:"utf-8",flush:!0,...B?.mode!==void 0&&process.platform!=="win32"?{mode:B.mode}:{}}),await XI.rename(D,$),await iq5(Eo.dirname($));return}finally{await XI.rm(X,{recursive:!0,force:!0})}}async function iq5(A){if(process.platform==="win32")return;let Q=await XI.open(A,"r");try{await Q.sync()}catch(B){if(B.code==="EPERM"||B.code==="EINVAL");else throw B}finally{await Q.close()}}d0();ZE();function nq5(A,Q){let{default:B,global:$,workspace:J}=Q;if(!ok0(A))return;let Y=[];for(let F of[J,$,B])if(Array.isArray(F))Y.push(...F);else if(F!==void 0)j.warn("Expected array value for merged array key",{key:A,value:F});let Z=new Map;for(let F of Y){let X=JSON.stringify(F);if(!Z.has(X))Z.set(X,F)}return Z.size>0?Array.from(Z.values()):void 0}function eF0(A){let Q={};if(A.default&&typeof A.default==="object")for(let[B,$]of Object.entries(A.default))Q[B]={...$,_target:"default"};else if(A.default!==void 0)j.warn("Expected object for mcpServers default",{value:A.default});if(A.global&&typeof A.global==="object")for(let[B,$]of Object.entries(A.global))Q[B]={...$,_target:"global"};else if(A.global!==void 0)j.warn("Expected object for mcpServers global",{value:A.global});if(A.workspace&&typeof A.workspace==="object")for(let[B,$]of Object.entries(A.workspace))Q[B]={...$,_target:"workspace"};else if(A.workspace!==void 0)j.warn("Expected object for mcpServers workspace",{value:A.workspace});if(A.override&&typeof A.override==="object")for(let[B,$]of Object.entries(A.override))Q[B]={...$};else if(A.override!==void 0)j.warn("Expected object for mcpServers override",{value:A.override});return Object.keys(Q).length>0?Q:void 0}function Sf4(A,Q){if(A==="mcpServers")return eF0(Q);if(ok0(A))return nq5(A,Q);return Q.workspace??Q.global??Q.default}ZE();var jx=aY.join(TH||aY.join(yf4(),".local/share"),"amp"),mF=aY.join(MT||aY.join(yf4(),".config"),"amp","settings.json");async function xf4(A,Q){try{return await Wo.access(A),A}catch{if(A===Q){let B=aY.join(aY.dirname(A),"settings.jsonc");try{return await Wo.access(B),j.info("Settings file not found, falling back to .jsonc",{jsonPath:A,jsoncPath:B}),B}catch{return A}}return A}}async function vf4(A){try{return await Wo.access(A),!0}catch{return!1}}async function aq5(A){let B=fy(A)||A,$=A,J=100;for(let Z=0;Z<J;Z++){let F=aY.join($,".amp","settings.json"),X=aY.join($,".amp","settings.jsonc");if(await vf4(F))return{workspaceRootPath:$,workspaceSettingsPath:F};if(await vf4(X))return{workspaceRootPath:$,workspaceSettingsPath:X};if($===B)break;$=aY.dirname($)}let Y=aY.join(B,".amp","settings.json");return{workspaceRootPath:B,workspaceSettingsPath:Y}}function Ox(A,Q){if(Q==="admin")throw Error("Cannot set admin settings in file storage");if(Q==="global")return;if(pr1[`amp.${A}`]?.scope==="application")throw Error(`Unable to write ${String(A)} to Workspace Settings. This setting can be written only into User settings.`)}function ff4(A,Q){let B=[];if(A){for(let $ of Object.keys(Q))if(!dZ(A[$],Q[$]))B.push($);for(let $ of Object.keys(A))if(!($ in Q)&&!B.includes($))B.push($)}else B.push(...Object.keys(Q));return B}var oq5=(A,Q)=>yt0.watch(A,Q),rq5=(A,Q)=>{return yt0.watchFile(A,{interval:1000},Q),{close(){yt0.unwatchFile(A,Q)}}},AX0=new pY;async function bf4(A){let Q=await xf4(A.settingsFile??mF,mF),B=A.watchFactory??oq5,$=A.fallbackWatchFactory??rq5,J=A.debounceMs??100,Y=A.fileReadDelayMs??10,Z=A.fileReadRetryCount??2,F=A.fileReadRetryDelayMs??50,X=new m4,D=new m4,G=new m0((h)=>{I();let f=D.subscribe(h);return()=>f.unsubscribe()}),V,U,K,E=Promise.resolve(),z=!1,W;async function H(){try{let h=aY.dirname(Q);await Wo.mkdir(h,{recursive:!0})}catch(h){throw j.error(`Failed to create config directory: ${h}`),h}}async function q(h=!1){if(V&&!h)return V;I();try{let f=await Wo.readFile(Q,"utf-8"),S=[],u=p50(f,S,{allowTrailingComma:!0});if(S.length>0){let c=S.map((g)=>{return f.substring(0,g.offset).split(`
5174
- `).length-1});throw new $4(`Invalid JSON in settings file ${Q}`,1,`Fix the JSON syntax errors. Errors found on lines [${c.join(", ")}].`)}j.debug("readSettings",{settingsPath:Q,rawConfig:u});let d={};for(let[c,g]of Object.entries(u))if(c.startsWith("amp.")){let l=c.substring(4);d[l]=g}return V=d,d}catch(f){if(f.code==="ENOENT")return V={},V;throw j.error(`Failed to read settings: ${f}`),f}}async function N(h){await AX0.acquire();try{await H(),await zo(Q,(f)=>{let S=f;for(let[u,d]of Object.entries(h)){let c=aT0(S,[`amp.${u}`],d,{formattingOptions:{tabSize:2,insertSpaces:!0}});if(c.length>0)S=oT0(S,c)}return{newContent:S}},{mode:384}),V=h}catch(f){throw j.error(`Failed to write settings: ${f}`),f}finally{AX0.release()}}function I(){if(z)return;if(process.versions.bun){try{W=$(Q,(h,f)=>{j.debug("Settings file change detected (fallback watcher)",{settingsPath:Q,curr:h,prev:f}),w()}),z=!0,j.debug("Started watching settings file with fallback watcher (Bun)",{settingsPath:Q})}catch(h){j.error("Failed to start fallback file watcher",{settingsPath:Q,error:h})}return}try{let h=aY.dirname(Q),f=aY.basename(Q);U=B(h,(S,u)=>{if(u!==f)return;j.debug("Settings file change detected",{eventType:S,filename:u,settingsPath:Q}),w()}),U.on("error",(S)=>{j.debug("transient file watcher error",{error:S}),w()}),j.debug("Started watching settings directory",{dir:h,targetFilename:f})}catch(h){if(h.code==="ENOENT"){if(!W)W=$(Q,(f,S)=>{if(f.ino===0)return;j.debug("Settings file created, starting file watcher",{settingsPath:Q}),W?.close(),W=void 0,z=!1,I(),w()})}else j.warn("Failed to start watching settings directory",{settingsPath:Q,error:h})}z=!0}function w(){if(K)clearTimeout(K);K=setTimeout(()=>{K=void 0,O()},J)}function O(){return E=E.then(k),E}function L(h){return new Promise((f)=>setTimeout(f,h))}async function P(){for(let h=0;;h++)try{return await q(!0)}catch(f){if(h>=Z)throw f;await L(F)}}function T(h){return h instanceof $4?"invalid-json":"read-error"}async function k(){let h=V;try{await L(Y);let f=await P(),S=ff4(h,f);if(S.length>0)D.next({type:"succeeded",changedKeys:S,path:Q}),X.next(S),j.info("Settings reloaded",{changedKeys:S})}catch(f){D.next({type:"failed",reason:T(f),message:f instanceof Error?f.message:String(f),path:Q}),j.warn("Failed to handle settings file change",{settingsPath:Q,error:f})}}function x(){if(U)U.close(),U=void 0;if(W)W.close(),W=void 0;if(K)clearTimeout(K),K=void 0;z=!1,j.debug("Stopped watching settings directory",{settingsPath:Q})}return{async get(h){return(await q())[h]},async set(h,f,S){let u=await q();u[h]=f,await N(u),X.next([h])},async delete(h,f){await AX0.acquire();try{await zo(Q,(u)=>{let d=`amp.${h}`,c=aT0(u,[d],void 0,{formattingOptions:{tabSize:2,insertSpaces:!0}});return{newContent:c.length>0?oT0(u,c):u}},{mode:384});let S=await q();delete S[h],V=S,X.next([h])}catch(S){throw j.error(`Failed to delete setting: ${S}`),S}finally{AX0.release()}},async keys(){let h=await q();return Object.keys(h)},getSettingsFilePath(){return Q},changes:X,reloadEvents:G,[Symbol.dispose](){x()}}}async function sq5(A){let Q=await xf4(A.settingsFile??mF,mF),B=await bf4({...A,settingsFile:Q});return{...B,async set($,J){return Ox($,"global"),B.set($,J)},async delete($){return Ox($,"global"),B.delete($)}}}async function tq5(A){let{workspaceRootPath:Q,workspaceSettingsPath:B}=await aq5(A.cwd),$=await bf4({...A,settingsFile:B}),J=new m4,Y=$.changes.subscribe((X)=>J.next(X)),Z=A.workspaceTrust?.current??!1,F=A.workspaceTrust?.changes?.subscribe(async(X)=>{let D=Z;if(Z=X,!D&&X){let V=(await $.keys()).filter((U)=>S30.includes(U));if(V.length>0)J.next(V)}});return{...$,changes:J,getWorkspaceRootPath(){return Q},async get(X){if(!Z&&S30.includes(X))return;return $.get(X)},async set(X,D){return Ox(X,"workspace"),$.set(X,D)},async delete(X){return Ox(X,"workspace"),$.delete(X)},async keys(){let X=await $.keys();if(!Z)return X.filter((D)=>!S30.includes(D));return X},[Symbol.dispose](){Y.unsubscribe(),F?.unsubscribe(),$[Symbol.dispose]()}}}async function uf4(A){let Q=A.getHook,B=new m4,$=await sq5(A),J=await tq5({...A,cwd:A.cwd||process.cwd()});j.info("Using settings file",{settingsPath:$.getSettingsFilePath(),workspaceSettingsPath:J.getSettingsFilePath(),workspaceRootPath:J.getWorkspaceRootPath()});let Y=$.changes.subscribe((X)=>B.next(X)),Z=J.changes.subscribe((X)=>B.next(X)),F=new m0((X)=>{let D=$.reloadEvents.subscribe(X),G=J.reloadEvents.subscribe(X);return()=>{D.unsubscribe(),G.unsubscribe()}});return{async get(X,D){let G=async()=>{switch(D){case"global":return $.get(X);case"workspace":return J.get(X);case"admin":throw Error("Cannot get admin settings from file storage");case void 0:break}let[V,U]=await Promise.all([$.get(X),J.get(X)]);return Sf4(X,{global:V,workspace:U})};return Q?Q(X,G):G()},async set(X,D,G="workspace"){switch(Ox(X,G),G){case"workspace":await J.set(X,D);break;case"global":await $.set(X,D);break;default:}},async delete(X,D="workspace"){switch(Ox(X,D),D){case"workspace":await J.delete(X);break;case"global":await $.delete(X);break;default:}},async keys(){let X=await $.keys(),D=await J.keys(),G=new Set([...X,...D]);return Array.from(G)},getSettingsFilePath(){return $.getSettingsFilePath()},getWorkspaceRootPath(){return J.getWorkspaceRootPath()},getWorkspaceSettingsPath(){return J.getSettingsFilePath()},changes:B,reloadEvents:F,[Symbol.dispose](){Y.unsubscribe(),Z.unsubscribe(),$[Symbol.dispose](),J[Symbol.dispose]()}}}d0();BV();import eq5,{promises as QX0}from"node:fs";import AN5 from"node:path";import{stderr as hf4,stdout as QN5}from"node:process";M1();var BN5="secrets.json";function gf4(A){return AN5.join(A.dataDir,BN5)}function mf4(A){let Q=j.getChild("secrets.file"),B=new m4,$,J=gf4(A),Y=new pY;async function Z(){try{await QX0.mkdir(A.dataDir,{recursive:!0})}catch(D){throw Q.error(`Failed to create data directory: ${D}`),D}}async function F(){if($)return $;try{await Z();let D=await QX0.readFile(J,"utf-8");return $=JSON.parse(D),$}catch(D){if(D.code==="ENOENT")return $={},$;throw Q.error("Failed to read secrets",{secretsPath:J,error:D}),D}}async function X(D){await Y.acquire();try{await Z(),await zo(J,()=>({newContent:JSON.stringify(D,null,2)}),{mode:384}),$=D}catch(G){throw Q.error("Failed to write secrets",{secretsPath:J,error:G}),G}finally{Y.release()}}return{async get(D,G){let V=await F(),U=yT(G);return V[`${D}@${U}`]},async set(D,G,V){let U=yT(V),K=`${D}@${U}`,E=await F();E[K]=G,await X(E),B.next(K)},changes:B}}async function pf4(A,Q){let B=j.getChild("secrets.file.migrate"),$=gf4(A);if(!eq5.existsSync($))return;let J=await QX0.readFile($,"utf-8"),Y=JSON.parse(J);if(Object.keys(Y).length===0)return;if(!A.quiet)QN5.write(`Migrating secrets from file storage to native secret storage...
5172
+ `),await bq5("Paste the callback URL or authorization code: ")}}async function bq5(A){let Q=fq5({input:xq5,output:vD});return new Promise((B,$)=>{Q.on("SIGINT",()=>{Q.close(),$(Error("OAuth authorization cancelled"))}),Q.question(A,(J)=>{Q.close(),B(J.trim())})})}function Rf4(){if(process.env.AMP_HEADLESS_OAUTH==="1"||process.env.AMP_HEADLESS_OAUTH==="true")return!0;return Lf4()}pZ();d0();import{readFileSync as uq5,rmSync as hq5}from"node:fs";import{mkdir as gq5,readFile as mq5,rm as St0,writeFile as pq5}from"node:fs/promises";import Pf4 from"node:path";var dq5=Pf4.join(x$,"pids");function cq5(A){try{return process.kill(A,0),!0}catch(Q){return Q.code==="EPERM"}}function _f4(A){let Q=A.trim();if(!/^\d+$/.test(Q))return;let B=Number.parseInt(Q,10);return Number.isSafeInteger(B)&&B>0?B:void 0}function vt0(A,Q){return A.code===Q}async function Tf4(A){try{let Q=await mq5(A,"utf-8"),B=_f4(Q);if(B===void 0)return{kind:"invalid",value:Q.trim()};return{kind:"valid",pid:B}}catch(Q){if(vt0(Q,"ENOENT"))return{kind:"missing"};throw Q}}async function lq5(A,Q){let B=await Tf4(A);if(B.kind!=="valid"||B.pid!==Q)return;await St0(A,{force:!0}),j.info("Removed headless PID file",{currentPID:Q,pidFilePath:A})}function iq5(A,Q){try{let B=uq5(A,"utf-8");if(_f4(B)!==Q)return}catch(B){if(vt0(B,"ENOENT"))return;throw B}hq5(A,{force:!0})}async function kf4(A,Q={}){let B=Q.pidDir??dq5,$=Q.currentPID??process.pid,J=Q.isProcessRunning??cq5,Y=Pf4.join(B,`${A}.pid`);await gq5(B,{recursive:!0});while(!0){let Z=await Tf4(Y);if(Z.kind==="valid"){if(J(Z.pid))return j.info("Headless instance already running for thread, exiting",{pidFilePath:Y,runningPID:Z.pid,threadID:A}),{status:"already-running",pidFilePath:Y,runningPID:Z.pid};j.info("Replacing stale headless PID file",{pidFilePath:Y,stalePID:Z.pid,threadID:A}),await St0(Y,{force:!0})}if(Z.kind==="invalid")j.warn("Replacing invalid headless PID file content",{invalidPID:Z.value,pidFilePath:Y,threadID:A}),await St0(Y,{force:!0});try{await pq5(Y,`${$}
5173
+ `,{encoding:"utf-8",flag:"wx",mode:384}),j.info("Claimed headless PID file",{currentPID:$,pidFilePath:Y,threadID:A});let F=!1,X=()=>{if(F)return;F=!0,iq5(Y,$)},D=(U)=>{if(X(),process.off("SIGINT",G),process.off("SIGTERM",V),process.listenerCount(U)===0)process.kill(process.pid,U)},G=()=>D("SIGINT"),V=()=>D("SIGTERM");return process.once("exit",X),process.on("SIGINT",G),process.on("SIGTERM",V),{status:"claimed",pidFilePath:Y,release:async()=>{if(F)return;await lq5(Y,$),F=!0,process.off("exit",X),process.off("SIGINT",G),process.off("SIGTERM",V)}}}catch(F){if(vt0(F,"EEXIST"))continue;throw F}}}BV();d0();M1();import yt0,{promises as Wo}from"node:fs";import{homedir as yf4}from"node:os";import aY from"node:path";k50();d0();jT();import{promises as XI}from"node:fs";import Eo from"node:path";async function zo(A,Q,B){let $=await XI.realpath(A).catch((G)=>G.code==="ENOENT"?A:Promise.reject(G)),J=await XI.readFile($,"utf-8").catch((G)=>G.code==="ENOENT"?"{}":Promise.reject(G)),Y=Q(J);if(J===Y.newContent)return;let F=Eo.dirname($);await XI.mkdir(F,{recursive:!0});let X=await XI.mkdtemp(Eo.join(F,".amp-temp-")),D=Eo.join(X,Eo.basename(A));try{await XI.writeFile(D,Y.newContent,{encoding:"utf-8",flush:!0,...B?.mode!==void 0&&process.platform!=="win32"?{mode:B.mode}:{}}),await XI.rename(D,$),await nq5(Eo.dirname($));return}finally{await XI.rm(X,{recursive:!0,force:!0})}}async function nq5(A){if(process.platform==="win32")return;let Q=await XI.open(A,"r");try{await Q.sync()}catch(B){if(B.code==="EPERM"||B.code==="EINVAL");else throw B}finally{await Q.close()}}d0();ZE();function aq5(A,Q){let{default:B,global:$,workspace:J}=Q;if(!ok0(A))return;let Y=[];for(let F of[J,$,B])if(Array.isArray(F))Y.push(...F);else if(F!==void 0)j.warn("Expected array value for merged array key",{key:A,value:F});let Z=new Map;for(let F of Y){let X=JSON.stringify(F);if(!Z.has(X))Z.set(X,F)}return Z.size>0?Array.from(Z.values()):void 0}function eF0(A){let Q={};if(A.default&&typeof A.default==="object")for(let[B,$]of Object.entries(A.default))Q[B]={...$,_target:"default"};else if(A.default!==void 0)j.warn("Expected object for mcpServers default",{value:A.default});if(A.global&&typeof A.global==="object")for(let[B,$]of Object.entries(A.global))Q[B]={...$,_target:"global"};else if(A.global!==void 0)j.warn("Expected object for mcpServers global",{value:A.global});if(A.workspace&&typeof A.workspace==="object")for(let[B,$]of Object.entries(A.workspace))Q[B]={...$,_target:"workspace"};else if(A.workspace!==void 0)j.warn("Expected object for mcpServers workspace",{value:A.workspace});if(A.override&&typeof A.override==="object")for(let[B,$]of Object.entries(A.override))Q[B]={...$};else if(A.override!==void 0)j.warn("Expected object for mcpServers override",{value:A.override});return Object.keys(Q).length>0?Q:void 0}function Sf4(A,Q){if(A==="mcpServers")return eF0(Q);if(ok0(A))return aq5(A,Q);return Q.workspace??Q.global??Q.default}ZE();var jx=aY.join(TH||aY.join(yf4(),".local/share"),"amp"),mF=aY.join(MT||aY.join(yf4(),".config"),"amp","settings.json");async function xf4(A,Q){try{return await Wo.access(A),A}catch{if(A===Q){let B=aY.join(aY.dirname(A),"settings.jsonc");try{return await Wo.access(B),j.info("Settings file not found, falling back to .jsonc",{jsonPath:A,jsoncPath:B}),B}catch{return A}}return A}}async function vf4(A){try{return await Wo.access(A),!0}catch{return!1}}async function oq5(A){let B=fy(A)||A,$=A,J=100;for(let Z=0;Z<J;Z++){let F=aY.join($,".amp","settings.json"),X=aY.join($,".amp","settings.jsonc");if(await vf4(F))return{workspaceRootPath:$,workspaceSettingsPath:F};if(await vf4(X))return{workspaceRootPath:$,workspaceSettingsPath:X};if($===B)break;$=aY.dirname($)}let Y=aY.join(B,".amp","settings.json");return{workspaceRootPath:B,workspaceSettingsPath:Y}}function Ox(A,Q){if(Q==="admin")throw Error("Cannot set admin settings in file storage");if(Q==="global")return;if(pr1[`amp.${A}`]?.scope==="application")throw Error(`Unable to write ${String(A)} to Workspace Settings. This setting can be written only into User settings.`)}function ff4(A,Q){let B=[];if(A){for(let $ of Object.keys(Q))if(!dZ(A[$],Q[$]))B.push($);for(let $ of Object.keys(A))if(!($ in Q)&&!B.includes($))B.push($)}else B.push(...Object.keys(Q));return B}var rq5=(A,Q)=>yt0.watch(A,Q),sq5=(A,Q)=>{return yt0.watchFile(A,{interval:1000},Q),{close(){yt0.unwatchFile(A,Q)}}},AX0=new pY;async function bf4(A){let Q=await xf4(A.settingsFile??mF,mF),B=A.watchFactory??rq5,$=A.fallbackWatchFactory??sq5,J=A.debounceMs??100,Y=A.fileReadDelayMs??10,Z=A.fileReadRetryCount??2,F=A.fileReadRetryDelayMs??50,X=new m4,D=new m4,G=new m0((h)=>{I();let f=D.subscribe(h);return()=>f.unsubscribe()}),V,U,K,E=Promise.resolve(),z=!1,W;async function H(){try{let h=aY.dirname(Q);await Wo.mkdir(h,{recursive:!0})}catch(h){throw j.error(`Failed to create config directory: ${h}`),h}}async function q(h=!1){if(V&&!h)return V;I();try{let f=await Wo.readFile(Q,"utf-8"),S=[],u=p50(f,S,{allowTrailingComma:!0});if(S.length>0){let c=S.map((g)=>{return f.substring(0,g.offset).split(`
5174
+ `).length-1});throw new $4(`Invalid JSON in settings file ${Q}`,1,`Fix the JSON syntax errors. Errors found on lines [${c.join(", ")}].`)}j.debug("readSettings",{settingsPath:Q,rawConfig:u});let d={};for(let[c,g]of Object.entries(u))if(c.startsWith("amp.")){let l=c.substring(4);d[l]=g}return V=d,d}catch(f){if(f.code==="ENOENT")return V={},V;throw j.error(`Failed to read settings: ${f}`),f}}async function N(h){await AX0.acquire();try{await H(),await zo(Q,(f)=>{let S=f;for(let[u,d]of Object.entries(h)){let c=aT0(S,[`amp.${u}`],d,{formattingOptions:{tabSize:2,insertSpaces:!0}});if(c.length>0)S=oT0(S,c)}return{newContent:S}},{mode:384}),V=h}catch(f){throw j.error(`Failed to write settings: ${f}`),f}finally{AX0.release()}}function I(){if(z)return;if(process.versions.bun){try{W=$(Q,(h,f)=>{j.debug("Settings file change detected (fallback watcher)",{settingsPath:Q,curr:h,prev:f}),w()}),z=!0,j.debug("Started watching settings file with fallback watcher (Bun)",{settingsPath:Q})}catch(h){j.error("Failed to start fallback file watcher",{settingsPath:Q,error:h})}return}try{let h=aY.dirname(Q),f=aY.basename(Q);U=B(h,(S,u)=>{if(u!==f)return;j.debug("Settings file change detected",{eventType:S,filename:u,settingsPath:Q}),w()}),U.on("error",(S)=>{j.debug("transient file watcher error",{error:S}),w()}),j.debug("Started watching settings directory",{dir:h,targetFilename:f})}catch(h){if(h.code==="ENOENT"){if(!W)W=$(Q,(f,S)=>{if(f.ino===0)return;j.debug("Settings file created, starting file watcher",{settingsPath:Q}),W?.close(),W=void 0,z=!1,I(),w()})}else j.warn("Failed to start watching settings directory",{settingsPath:Q,error:h})}z=!0}function w(){if(K)clearTimeout(K);K=setTimeout(()=>{K=void 0,O()},J)}function O(){return E=E.then(k),E}function L(h){return new Promise((f)=>setTimeout(f,h))}async function P(){for(let h=0;;h++)try{return await q(!0)}catch(f){if(h>=Z)throw f;await L(F)}}function T(h){return h instanceof $4?"invalid-json":"read-error"}async function k(){let h=V;try{await L(Y);let f=await P(),S=ff4(h,f);if(S.length>0)D.next({type:"succeeded",changedKeys:S,path:Q}),X.next(S),j.info("Settings reloaded",{changedKeys:S})}catch(f){D.next({type:"failed",reason:T(f),message:f instanceof Error?f.message:String(f),path:Q}),j.warn("Failed to handle settings file change",{settingsPath:Q,error:f})}}function x(){if(U)U.close(),U=void 0;if(W)W.close(),W=void 0;if(K)clearTimeout(K),K=void 0;z=!1,j.debug("Stopped watching settings directory",{settingsPath:Q})}return{async get(h){return(await q())[h]},async set(h,f,S){let u=await q();u[h]=f,await N(u),X.next([h])},async delete(h,f){await AX0.acquire();try{await zo(Q,(u)=>{let d=`amp.${h}`,c=aT0(u,[d],void 0,{formattingOptions:{tabSize:2,insertSpaces:!0}});return{newContent:c.length>0?oT0(u,c):u}},{mode:384});let S=await q();delete S[h],V=S,X.next([h])}catch(S){throw j.error(`Failed to delete setting: ${S}`),S}finally{AX0.release()}},async keys(){let h=await q();return Object.keys(h)},getSettingsFilePath(){return Q},changes:X,reloadEvents:G,[Symbol.dispose](){x()}}}async function tq5(A){let Q=await xf4(A.settingsFile??mF,mF),B=await bf4({...A,settingsFile:Q});return{...B,async set($,J){return Ox($,"global"),B.set($,J)},async delete($){return Ox($,"global"),B.delete($)}}}async function eq5(A){let{workspaceRootPath:Q,workspaceSettingsPath:B}=await oq5(A.cwd),$=await bf4({...A,settingsFile:B}),J=new m4,Y=$.changes.subscribe((X)=>J.next(X)),Z=A.workspaceTrust?.current??!1,F=A.workspaceTrust?.changes?.subscribe(async(X)=>{let D=Z;if(Z=X,!D&&X){let V=(await $.keys()).filter((U)=>S30.includes(U));if(V.length>0)J.next(V)}});return{...$,changes:J,getWorkspaceRootPath(){return Q},async get(X){if(!Z&&S30.includes(X))return;return $.get(X)},async set(X,D){return Ox(X,"workspace"),$.set(X,D)},async delete(X){return Ox(X,"workspace"),$.delete(X)},async keys(){let X=await $.keys();if(!Z)return X.filter((D)=>!S30.includes(D));return X},[Symbol.dispose](){Y.unsubscribe(),F?.unsubscribe(),$[Symbol.dispose]()}}}async function uf4(A){let Q=A.getHook,B=new m4,$=await tq5(A),J=await eq5({...A,cwd:A.cwd||process.cwd()});j.info("Using settings file",{settingsPath:$.getSettingsFilePath(),workspaceSettingsPath:J.getSettingsFilePath(),workspaceRootPath:J.getWorkspaceRootPath()});let Y=$.changes.subscribe((X)=>B.next(X)),Z=J.changes.subscribe((X)=>B.next(X)),F=new m0((X)=>{let D=$.reloadEvents.subscribe(X),G=J.reloadEvents.subscribe(X);return()=>{D.unsubscribe(),G.unsubscribe()}});return{async get(X,D){let G=async()=>{switch(D){case"global":return $.get(X);case"workspace":return J.get(X);case"admin":throw Error("Cannot get admin settings from file storage");case void 0:break}let[V,U]=await Promise.all([$.get(X),J.get(X)]);return Sf4(X,{global:V,workspace:U})};return Q?Q(X,G):G()},async set(X,D,G="workspace"){switch(Ox(X,G),G){case"workspace":await J.set(X,D);break;case"global":await $.set(X,D);break;default:}},async delete(X,D="workspace"){switch(Ox(X,D),D){case"workspace":await J.delete(X);break;case"global":await $.delete(X);break;default:}},async keys(){let X=await $.keys(),D=await J.keys(),G=new Set([...X,...D]);return Array.from(G)},getSettingsFilePath(){return $.getSettingsFilePath()},getWorkspaceRootPath(){return J.getWorkspaceRootPath()},getWorkspaceSettingsPath(){return J.getSettingsFilePath()},changes:B,reloadEvents:F,[Symbol.dispose](){Y.unsubscribe(),Z.unsubscribe(),$[Symbol.dispose](),J[Symbol.dispose]()}}}d0();BV();import AN5,{promises as QX0}from"node:fs";import QN5 from"node:path";import{stderr as hf4,stdout as BN5}from"node:process";M1();var $N5="secrets.json";function gf4(A){return QN5.join(A.dataDir,$N5)}function mf4(A){let Q=j.getChild("secrets.file"),B=new m4,$,J=gf4(A),Y=new pY;async function Z(){try{await QX0.mkdir(A.dataDir,{recursive:!0})}catch(D){throw Q.error(`Failed to create data directory: ${D}`),D}}async function F(){if($)return $;try{await Z();let D=await QX0.readFile(J,"utf-8");return $=JSON.parse(D),$}catch(D){if(D.code==="ENOENT")return $={},$;throw Q.error("Failed to read secrets",{secretsPath:J,error:D}),D}}async function X(D){await Y.acquire();try{await Z(),await zo(J,()=>({newContent:JSON.stringify(D,null,2)}),{mode:384}),$=D}catch(G){throw Q.error("Failed to write secrets",{secretsPath:J,error:G}),G}finally{Y.release()}}return{async get(D,G){let V=await F(),U=yT(G);return V[`${D}@${U}`]},async set(D,G,V){let U=yT(V),K=`${D}@${U}`,E=await F();E[K]=G,await X(E),B.next(K)},changes:B}}async function pf4(A,Q){let B=j.getChild("secrets.file.migrate"),$=gf4(A);if(!AN5.existsSync($))return;let J=await QX0.readFile($,"utf-8"),Y=JSON.parse(J);if(Object.keys(Y).length===0)return;if(!A.quiet)BN5.write(`Migrating secrets from file storage to native secret storage...
5175
5175
  `);let Z=[];for(let[F,X]of Object.entries(Y))if(typeof X==="string"){let D=F.match(/^(.+)@(.+)$/);if(D){let[,G,V]=D;if(G&&V)try{await Q.set(G,X,V),Z.push(F),B.debug(`Successfully migrated secret: ${F}`)}catch(U){throw hf4.write(`Failed to migrate secret ${F} to native secret storage
5176
5176
  `),U}}}if(Z.length>0)try{await QX0.rm($),B.info("Successfully migrated secrets and removed file storage",{migratedKeys:Z,removed:$})}catch(F){throw hf4.write(`Failed to remove file storage after migration
5177
- `),F}}d0();BV();M1();function $N5(A){return typeof A==="function"}async function JN5(){let A=Reflect.get(globalThis,"__AMP_KEYRING_ENTRY_CLASS__");if($N5(A))return A;return(await import("@napi-rs/keyring")).Entry}async function df4(){let A=j.getChild("secrets.native"),Q=new m4,B={},$=await JN5();async function J(Y,Z){let F;try{F=new URL(Z).hostname}catch{F=Z}return new $(`amp.cli.${Y}`,F)}return{async get(Y,Z){let F=yT(Z),X=`${Y}@${F}`;if(X in B)return B[X];let D=await J(Y,F);try{let V=D.getPassword()||void 0;return B[X]=V,V}catch(G){A.warn("failed to get secret",{name:Y,url:Z,error:G}),B[X]=void 0;return}},async set(Y,Z,F){let X=yT(F),D=await J(Y,X);if(Z)D.setPassword(Z);else D.deleteCredential();let G=`${Y}@${X}`;B[G]=Z,Q.next(G)},changes:Q}}async function xt0(A,Q){let B={dataDir:A.dataDir||jx};if(!await Q.get("experimental.cli.nativeSecretsStorage.enabled","global"))return j.info("using file-based secrets storage",B),mf4(B);j.info("using native secrets storage");let $;try{$=await df4()}catch(J){throw j.error("failed to initialize native secrets storage",{error:J,platform:process.platform}),Error("Native secret storage is not supported on this machine")}return await pf4(B,$),$}async function cf4(A){return uf4(A)}var lf4={"agent.skipTitleGenerationIfMessageContains":{value:[],visible:!1,description:"List of strings that, if present in a message, will skip title generation"},"anthropic.interleavedThinking.enabled":{value:!1,visible:!1,description:"Enable interleaved thinking for Claude 4 models (allows reasoning between tool calls)"},"anthropic.provider":{value:"anthropic",visible:!1,description:'Which provider to use for Anthropic Claude inference: "anthropic" or "vertex"'},"anthropic.temperature":{value:1,visible:!1,description:"Temperature setting for Anthropic models (0.0 = deterministic, 1.0 = creative). Note: Only takes effect when thinking is disabled. Internal use only."},"anthropic.thinking.enabled":{value:!1,visible:!1,description:"Enable Claude thinking process output for debugging"},bitbucketToken:{value:void 0,visible:!0,description:"Personal access token for Bitbucket Enterprise. Used with a workspace-level Bitbucket connection configured by an admin."},dangerouslyAllowAll:{value:!1,visible:!0,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},defaultVisibility:{value:{"github.com/sourcegraph/amp":"workspace"},visible:!0,description:["Define default thread visibility per repository origin using mappings like ",'"github.com/org/repo": "workspace". Values: private, public, workspace, group.'].join("")},"experimental.cli.nativeSecretsStorage.enabled":{value:!1,visible:!1,description:"Use native secret storage instead of the plain-text secrets configuration file"},"experimental.modes":{value:[],visible:!0,description:"Enable experimental agent modes by name. Available modes: deep"},"experimental.tools":{value:[],visible:!1,description:"Enable experimental tools by name"},"fuzzy.alwaysIncludePaths":{value:[],visible:!0,description:"Glob patterns for paths that should always be included in fuzzy file search, even if gitignored"},"gemini.thinkingLevel":{value:void 0,visible:!1,description:"Thinking level for Gemini models (minimal, low, medium, high, or undefined)"},"git.commit.ampThread.enabled":{value:!0,visible:!0,description:"Enable adding Amp-Thread trailer in git commits"},"git.commit.coauthor.enabled":{value:!0,visible:!0,description:"Enable adding Amp as co-author in git commits"},"guardedFiles.allowlist":{value:[],visible:!0,description:"Array of file glob patterns that are allowed to be accessed without confirmation. Takes precedence over the built-in denylist."},hooks:{value:[],visible:!1,description:"Custom hooks for extending Amp functionality"},"jetbrains.skipInstall":{value:!1,visible:!1,description:"Skip JetBrains plugin installation"},mcpServers:{value:{filesystem:{command:"npx",args:["@modelcontextprotocol/server-filesystem","/path/to/allowed/dir"]}},visible:!0,description:"Model Context Protocol servers to connect to for additional tools"},"network.timeout":{value:30,visible:!0,description:"How many seconds to wait for network requests to the Amp server before timing out"},"notifications.enabled":{value:!0,visible:!0,description:"Enable notification alerts when the agent completes tasks. Over SSH, this sends a terminal bell."},"notifications.system.enabled":{value:!0,visible:!0,description:"Enable system notifications when terminal is not focused"},"openai.speed":{value:void 0,visible:!1,description:"Fast speed toggle for deep/internal modes (OpenAI priority tier)"},"painter.model":{value:"gemini-3-pro-image",visible:!1,description:"Experimental internal painter backend override."},permissions:{value:[{tool:"Bash",action:"ask",matches:{cmd:["git push*","git commit*","git branch -D*","git checkout HEAD*"]}}],visible:!0,description:"Permission rules for tool calls. See amp permissions --help"},proxy:{value:void 0,visible:!0,description:"Proxy URL used for both HTTP and HTTPS requests to the Amp server"},showCosts:{value:!0,visible:!0,description:"Set to false to hide costs while working on a thread"},gauge:{value:"cost",visible:!1,description:"Controls the usage gauge in the prompt editor border: 'tokens', 'cost', or false to hide."},"skills.disableClaudeCodeSkills":{value:!1,visible:!0,description:"Disable loading skills from Claude Code directories (.claude/skills/, ~/.claude/skills/, ~/.claude/plugins/cache/). Amp-native skill directories are not affected."},"skills.path":{value:void 0,visible:!0,description:"Path to additional directories containing skills. Supports colon-separated paths (semicolon on Windows). Use ~ for home directory."},submitOnEnter:{value:!0,visible:!1,description:"Whether to submit messages on Enter (true) or require Ctrl+Enter (false)"},systemPrompt:{value:void 0,visible:!1,description:"Custom system prompt text to append (SDK use only)"},"terminal.animation":{value:!0,visible:!0,description:"Set to false to disable terminal animations (or use the equivalent NO_ANIMATION=1 env var)"},"terminal.theme":{value:"terminal",visible:!0,description:"Color theme for the CLI. Built-in: terminal, dark, light, catppuccin-mocha, solarized-dark, solarized-light, gruvbox-dark-hard, nord. Custom themes: ~/.config/amp/themes/<name>/colors.toml"},"terminal.copyOnSelect":{value:!0,visible:!0,description:"Automatically copy selection to clipboard."},"toolbox.path":{value:void 0,visible:!0,description:"Path to the directory containing toolbox scripts. Supports colon-separated paths."},"tools.disable":{value:["browser_navigate","builtin:edit_file"],visible:!0,description:"Array of tool names to disable. Use 'builtin:toolname' to disable only the builtin tool with that name (allowing an MCP server to provide a tool by that name)."},"tools.enable":{value:void 0,visible:!0,description:"Array of tool name patterns to enable. Supports glob patterns (e.g., 'mcp__metabase__*'). If not set, all tools are enabled. If set, only matching tools are enabled."},"tools.inactivityTimeout":{value:300,visible:!1,description:"How many seconds of no output to wait before canceling bash commands"},"tools.stopTimeout":{value:300,visible:!1,description:"Timeout for stopping tools"},"updates.mode":{value:"auto",visible:!0,description:'Control update checking behavior: "warn" shows update notifications, "disabled" turns off checking, "auto" automatically runs update.'},url:{value:"https://ampcode.com",visible:!1,description:"The Amp server URL to connect to"}},YN5=Object.fromEntries(Object.entries(lf4).filter(([,A])=>A.visible).map(([A,Q])=>[`amp.${A}`,Q.value])),Ho={examples:[{description:"Start an interactive session:",command:"amp"},{description:"Start an interactive session with a user message:",command:'echo "commit all my unstaged changes" | amp'},{description:"Use execute mode (--execute or -x) to send a command to an agent, have it execute it, print only the agent's last message, and then exit:",command:'amp -x "what file in this folder is in markdown format?"',output:`All Markdown files in this folder:
5177
+ `),F}}d0();BV();M1();function JN5(A){return typeof A==="function"}async function YN5(){let A=Reflect.get(globalThis,"__AMP_KEYRING_ENTRY_CLASS__");if(JN5(A))return A;return(await import("@napi-rs/keyring")).Entry}async function df4(){let A=j.getChild("secrets.native"),Q=new m4,B={},$=await YN5();async function J(Y,Z){let F;try{F=new URL(Z).hostname}catch{F=Z}return new $(`amp.cli.${Y}`,F)}return{async get(Y,Z){let F=yT(Z),X=`${Y}@${F}`;if(X in B)return B[X];let D=await J(Y,F);try{let V=D.getPassword()||void 0;return B[X]=V,V}catch(G){A.warn("failed to get secret",{name:Y,url:Z,error:G}),B[X]=void 0;return}},async set(Y,Z,F){let X=yT(F),D=await J(Y,X);if(Z)D.setPassword(Z);else D.deleteCredential();let G=`${Y}@${X}`;B[G]=Z,Q.next(G)},changes:Q}}async function xt0(A,Q){let B={dataDir:A.dataDir||jx};if(!await Q.get("experimental.cli.nativeSecretsStorage.enabled","global"))return j.info("using file-based secrets storage",B),mf4(B);j.info("using native secrets storage");let $;try{$=await df4()}catch(J){throw j.error("failed to initialize native secrets storage",{error:J,platform:process.platform}),Error("Native secret storage is not supported on this machine")}return await pf4(B,$),$}async function cf4(A){return uf4(A)}var lf4={"agent.skipTitleGenerationIfMessageContains":{value:[],visible:!1,description:"List of strings that, if present in a message, will skip title generation"},"anthropic.interleavedThinking.enabled":{value:!1,visible:!1,description:"Enable interleaved thinking for Claude 4 models (allows reasoning between tool calls)"},"anthropic.provider":{value:"anthropic",visible:!1,description:'Which provider to use for Anthropic Claude inference: "anthropic" or "vertex"'},"anthropic.temperature":{value:1,visible:!1,description:"Temperature setting for Anthropic models (0.0 = deterministic, 1.0 = creative). Note: Only takes effect when thinking is disabled. Internal use only."},"anthropic.thinking.enabled":{value:!1,visible:!1,description:"Enable Claude thinking process output for debugging"},bitbucketToken:{value:void 0,visible:!0,description:"Personal access token for Bitbucket Enterprise. Used with a workspace-level Bitbucket connection configured by an admin."},dangerouslyAllowAll:{value:!1,visible:!0,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},defaultVisibility:{value:{"github.com/sourcegraph/amp":"workspace"},visible:!0,description:["Define default thread visibility per repository origin using mappings like ",'"github.com/org/repo": "workspace". Values: private, public, workspace, group.'].join("")},"experimental.cli.nativeSecretsStorage.enabled":{value:!1,visible:!1,description:"Use native secret storage instead of the plain-text secrets configuration file"},"experimental.modes":{value:[],visible:!0,description:"Enable experimental agent modes by name. Available modes: deep"},"experimental.tools":{value:[],visible:!1,description:"Enable experimental tools by name"},"fuzzy.alwaysIncludePaths":{value:[],visible:!0,description:"Glob patterns for paths that should always be included in fuzzy file search, even if gitignored"},"gemini.thinkingLevel":{value:void 0,visible:!1,description:"Thinking level for Gemini models (minimal, low, medium, high, or undefined)"},"git.commit.ampThread.enabled":{value:!0,visible:!0,description:"Enable adding Amp-Thread trailer in git commits"},"git.commit.coauthor.enabled":{value:!0,visible:!0,description:"Enable adding Amp as co-author in git commits"},"guardedFiles.allowlist":{value:[],visible:!0,description:"Array of file glob patterns that are allowed to be accessed without confirmation. Takes precedence over the built-in denylist."},hooks:{value:[],visible:!1,description:"Custom hooks for extending Amp functionality"},"jetbrains.skipInstall":{value:!1,visible:!1,description:"Skip JetBrains plugin installation"},mcpServers:{value:{filesystem:{command:"npx",args:["@modelcontextprotocol/server-filesystem","/path/to/allowed/dir"]}},visible:!0,description:"Model Context Protocol servers to connect to for additional tools"},"network.timeout":{value:30,visible:!0,description:"How many seconds to wait for network requests to the Amp server before timing out"},"notifications.enabled":{value:!0,visible:!0,description:"Enable notification alerts when the agent completes tasks. Over SSH, this sends a terminal bell."},"notifications.system.enabled":{value:!0,visible:!0,description:"Enable system notifications when terminal is not focused"},"openai.speed":{value:void 0,visible:!1,description:"Fast speed toggle for deep/internal modes (OpenAI priority tier)"},"painter.model":{value:"gemini-3-pro-image",visible:!1,description:"Experimental internal painter backend override."},permissions:{value:[{tool:"Bash",action:"ask",matches:{cmd:["git push*","git commit*","git branch -D*","git checkout HEAD*"]}}],visible:!0,description:"Permission rules for tool calls. See amp permissions --help"},proxy:{value:void 0,visible:!0,description:"Proxy URL used for both HTTP and HTTPS requests to the Amp server"},showCosts:{value:!0,visible:!0,description:"Set to false to hide costs while working on a thread"},gauge:{value:"cost",visible:!1,description:"Controls the usage gauge in the prompt editor border: 'tokens', 'cost', or false to hide."},"skills.disableClaudeCodeSkills":{value:!1,visible:!0,description:"Disable loading skills from Claude Code directories (.claude/skills/, ~/.claude/skills/, ~/.claude/plugins/cache/). Amp-native skill directories are not affected."},"skills.path":{value:void 0,visible:!0,description:"Path to additional directories containing skills. Supports colon-separated paths (semicolon on Windows). Use ~ for home directory."},submitOnEnter:{value:!0,visible:!1,description:"Whether to submit messages on Enter (true) or require Ctrl+Enter (false)"},systemPrompt:{value:void 0,visible:!1,description:"Custom system prompt text to append (SDK use only)"},"terminal.animation":{value:!0,visible:!0,description:"Set to false to disable terminal animations (or use the equivalent NO_ANIMATION=1 env var)"},"terminal.theme":{value:"terminal",visible:!0,description:"Color theme for the CLI. Built-in: terminal, dark, light, catppuccin-mocha, solarized-dark, solarized-light, gruvbox-dark-hard, nord. Custom themes: ~/.config/amp/themes/<name>/colors.toml"},"terminal.copyOnSelect":{value:!0,visible:!0,description:"Automatically copy selection to clipboard."},"toolbox.path":{value:void 0,visible:!0,description:"Path to the directory containing toolbox scripts. Supports colon-separated paths."},"tools.disable":{value:["browser_navigate","builtin:edit_file"],visible:!0,description:"Array of tool names to disable. Use 'builtin:toolname' to disable only the builtin tool with that name (allowing an MCP server to provide a tool by that name)."},"tools.enable":{value:void 0,visible:!0,description:"Array of tool name patterns to enable. Supports glob patterns (e.g., 'mcp__metabase__*'). If not set, all tools are enabled. If set, only matching tools are enabled."},"tools.inactivityTimeout":{value:300,visible:!1,description:"How many seconds of no output to wait before canceling bash commands"},"tools.stopTimeout":{value:300,visible:!1,description:"Timeout for stopping tools"},"updates.mode":{value:"auto",visible:!0,description:'Control update checking behavior: "warn" shows update notifications, "disabled" turns off checking, "auto" automatically runs update.'},url:{value:"https://ampcode.com",visible:!1,description:"The Amp server URL to connect to"}},ZN5=Object.fromEntries(Object.entries(lf4).filter(([,A])=>A.visible).map(([A,Q])=>[`amp.${A}`,Q.value])),Ho={examples:[{description:"Start an interactive session:",command:"amp"},{description:"Start an interactive session with a user message:",command:'echo "commit all my unstaged changes" | amp'},{description:"Use execute mode (--execute or -x) to send a command to an agent, have it execute it, print only the agent's last message, and then exit:",command:'amp -x "what file in this folder is in markdown format?"',output:`All Markdown files in this folder:
5178
5178
 
5179
5179
  - README.md (root)
5180
5180
  - AGENT.md (root)
@@ -5183,13 +5183,13 @@ password=${Y}
5183
5183
 
5184
5184
  Total: **13 Markdown files** found across the project.
5185
5185
  `},{description:"Stream JSON output and extract assistant text blocks with jq:",command:`amp -x "what file in this folder is in markdown format?" --stream-json | jq -r 'select(.type=="assistant") | .message.content[] | select(.type=="text") | .text'`},{description:"Stream JSON output with thinking blocks and extract them with jq:",command:`amp -x "what file in this folder is in markdown format?" --stream-json-thinking | jq -r 'select(.type=="assistant") | .message.content[] | select(.type=="thinking") | .thinking'`},{description:"Use execute mode and allow agent to use tools that would require approval:",command:'amp --dangerously-allow-all -x "Rename all .markdown files to .md. Only print list of renamed files."',output:`- readme.markdown → readme.md
5186
- - ghostty.markdown → ghostty.md`},{description:"Pipe a command to the agent and use execute mode:",command:'echo "commit all my unstaged changes" | amp -x --dangerously-allow-all',output:"Done. I have committed all your unstaged changes."},{description:"Pipe data to the agent and send along a prompt in execute mode:",command:`cat ~/.zshrc | amp -x "what does the 'beautiful' function do?"`,output:'The `beautiful` function creates an infinite loop that prints the letter "o" in cycling colors every 0.2 seconds.'},{description:"Execute a prompt from a file and store final assistant message output in a file (redirecting stdout is equivalent to providing -x/--execute):",command:"amp < prompt.txt > output.txt"},{description:"Add an MCP server with a local command:",command:"amp mcp add context7 -- npx -y @upstash/context7-mcp"},{description:"Add an MCP server with environment variables:",command:"amp mcp add postgres --env PGUSER=orb -- npx -y @modelcontextprotocol/server-postgres postgresql://localhost/orbing"},{description:"Add a remote MCP server:",command:"amp mcp add hugging-face https://huggingface.co/mcp"}],configuration:{description:`Amp can be configured using a JSON settings file located at ${mF}. All settings use the "amp." prefix.`,sampleConfig:JSON.stringify(YN5,null,2),keyDescriptions:Object.entries(lf4).filter(([,A])=>A.visible).map(([A,Q])=>({key:`amp.${A}`,description:Q.description}))}};function ft0({onlyFirst:A=!1}={}){let B=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(B,A?void 0:"g")}var ZN5=ft0();function qo(A){if(typeof A!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof A}\``);return A.replace(ZN5,"")}function if4(A){return A===161||A===164||A===167||A===168||A===170||A===173||A===174||A>=176&&A<=180||A>=182&&A<=186||A>=188&&A<=191||A===198||A===208||A===215||A===216||A>=222&&A<=225||A===230||A>=232&&A<=234||A===236||A===237||A===240||A===242||A===243||A>=247&&A<=250||A===252||A===254||A===257||A===273||A===275||A===283||A===294||A===295||A===299||A>=305&&A<=307||A===312||A>=319&&A<=322||A===324||A>=328&&A<=331||A===333||A===338||A===339||A===358||A===359||A===363||A===462||A===464||A===466||A===468||A===470||A===472||A===474||A===476||A===593||A===609||A===708||A===711||A>=713&&A<=715||A===717||A===720||A>=728&&A<=731||A===733||A===735||A>=768&&A<=879||A>=913&&A<=929||A>=931&&A<=937||A>=945&&A<=961||A>=963&&A<=969||A===1025||A>=1040&&A<=1103||A===1105||A===8208||A>=8211&&A<=8214||A===8216||A===8217||A===8220||A===8221||A>=8224&&A<=8226||A>=8228&&A<=8231||A===8240||A===8242||A===8243||A===8245||A===8251||A===8254||A===8308||A===8319||A>=8321&&A<=8324||A===8364||A===8451||A===8453||A===8457||A===8467||A===8470||A===8481||A===8482||A===8486||A===8491||A===8531||A===8532||A>=8539&&A<=8542||A>=8544&&A<=8555||A>=8560&&A<=8569||A===8585||A>=8592&&A<=8601||A===8632||A===8633||A===8658||A===8660||A===8679||A===8704||A===8706||A===8707||A===8711||A===8712||A===8715||A===8719||A===8721||A===8725||A===8730||A>=8733&&A<=8736||A===8739||A===8741||A>=8743&&A<=8748||A===8750||A>=8756&&A<=8759||A===8764||A===8765||A===8776||A===8780||A===8786||A===8800||A===8801||A>=8804&&A<=8807||A===8810||A===8811||A===8814||A===8815||A===8834||A===8835||A===8838||A===8839||A===8853||A===8857||A===8869||A===8895||A===8978||A>=9312&&A<=9449||A>=9451&&A<=9547||A>=9552&&A<=9587||A>=9600&&A<=9615||A>=9618&&A<=9621||A===9632||A===9633||A>=9635&&A<=9641||A===9650||A===9651||A===9654||A===9655||A===9660||A===9661||A===9664||A===9665||A>=9670&&A<=9672||A===9675||A>=9678&&A<=9681||A>=9698&&A<=9701||A===9711||A===9733||A===9734||A===9737||A===9742||A===9743||A===9756||A===9758||A===9792||A===9794||A===9824||A===9825||A>=9827&&A<=9829||A>=9831&&A<=9834||A===9836||A===9837||A===9839||A===9886||A===9887||A===9919||A>=9926&&A<=9933||A>=9935&&A<=9939||A>=9941&&A<=9953||A===9955||A===9960||A===9961||A>=9963&&A<=9969||A===9972||A>=9974&&A<=9977||A===9979||A===9980||A===9982||A===9983||A===10045||A>=10102&&A<=10111||A>=11094&&A<=11097||A>=12872&&A<=12879||A>=57344&&A<=63743||A>=65024&&A<=65039||A===65533||A>=127232&&A<=127242||A>=127248&&A<=127277||A>=127280&&A<=127337||A>=127344&&A<=127373||A===127375||A===127376||A>=127387&&A<=127404||A>=917760&&A<=917999||A>=983040&&A<=1048573||A>=1048576&&A<=1114109}function nf4(A){return A===12288||A>=65281&&A<=65376||A>=65504&&A<=65510}function af4(A){return A>=4352&&A<=4447||A===8986||A===8987||A===9001||A===9002||A>=9193&&A<=9196||A===9200||A===9203||A===9725||A===9726||A===9748||A===9749||A>=9776&&A<=9783||A>=9800&&A<=9811||A===9855||A>=9866&&A<=9871||A===9875||A===9889||A===9898||A===9899||A===9917||A===9918||A===9924||A===9925||A===9934||A===9940||A===9962||A===9970||A===9971||A===9973||A===9978||A===9981||A===9989||A===9994||A===9995||A===10024||A===10060||A===10062||A>=10067&&A<=10069||A===10071||A>=10133&&A<=10135||A===10160||A===10175||A===11035||A===11036||A===11088||A===11093||A>=11904&&A<=11929||A>=11931&&A<=12019||A>=12032&&A<=12245||A>=12272&&A<=12287||A>=12289&&A<=12350||A>=12353&&A<=12438||A>=12441&&A<=12543||A>=12549&&A<=12591||A>=12593&&A<=12686||A>=12688&&A<=12773||A>=12783&&A<=12830||A>=12832&&A<=12871||A>=12880&&A<=42124||A>=42128&&A<=42182||A>=43360&&A<=43388||A>=44032&&A<=55203||A>=63744&&A<=64255||A>=65040&&A<=65049||A>=65072&&A<=65106||A>=65108&&A<=65126||A>=65128&&A<=65131||A>=94176&&A<=94180||A===94192||A===94193||A>=94208&&A<=100343||A>=100352&&A<=101589||A>=101631&&A<=101640||A>=110576&&A<=110579||A>=110581&&A<=110587||A===110589||A===110590||A>=110592&&A<=110882||A===110898||A>=110928&&A<=110930||A===110933||A>=110948&&A<=110951||A>=110960&&A<=111355||A>=119552&&A<=119638||A>=119648&&A<=119670||A===126980||A===127183||A===127374||A>=127377&&A<=127386||A>=127488&&A<=127490||A>=127504&&A<=127547||A>=127552&&A<=127560||A===127568||A===127569||A>=127584&&A<=127589||A>=127744&&A<=127776||A>=127789&&A<=127797||A>=127799&&A<=127868||A>=127870&&A<=127891||A>=127904&&A<=127946||A>=127951&&A<=127955||A>=127968&&A<=127984||A===127988||A>=127992&&A<=128062||A===128064||A>=128066&&A<=128252||A>=128255&&A<=128317||A>=128331&&A<=128334||A>=128336&&A<=128359||A===128378||A===128405||A===128406||A===128420||A>=128507&&A<=128591||A>=128640&&A<=128709||A===128716||A>=128720&&A<=128722||A>=128725&&A<=128727||A>=128732&&A<=128735||A===128747||A===128748||A>=128756&&A<=128764||A>=128992&&A<=129003||A===129008||A>=129292&&A<=129338||A>=129340&&A<=129349||A>=129351&&A<=129535||A>=129648&&A<=129660||A>=129664&&A<=129673||A>=129679&&A<=129734||A>=129742&&A<=129756||A>=129759&&A<=129769||A>=129776&&A<=129784||A>=131072&&A<=196605||A>=196608&&A<=262141}function FN5(A){if(!Number.isSafeInteger(A))throw TypeError(`Expected a code point, got \`${typeof A}\`.`)}function of4(A,{ambiguousAsWide:Q=!1}={}){if(FN5(A),nf4(A)||af4(A)||Q&&if4(A))return 2;return 1}var tf4=v4(sf4(),1),XN5=new Intl.Segmenter,DN5=/^\p{Default_Ignorable_Code_Point}$/u;function Lj(A,Q={}){if(typeof A!=="string"||A.length===0)return 0;let{ambiguousIsNarrow:B=!0,countAnsiEscapeCodes:$=!1}=Q;if(!$)A=qo(A);if(A.length===0)return 0;let J=0,Y={ambiguousAsWide:!B};for(let{segment:Z}of XN5.segment(A)){let F=Z.codePointAt(0);if(F<=31||F>=127&&F<=159)continue;if(F>=8203&&F<=8207||F===65279)continue;if(F>=768&&F<=879||F>=6832&&F<=6911||F>=7616&&F<=7679||F>=8400&&F<=8447||F>=65056&&F<=65071)continue;if(F>=55296&&F<=57343)continue;if(F>=65024&&F<=65039)continue;if(DN5.test(Z))continue;if(tf4.default().test(Z)){J+=2;continue}J+=of4(F,Y)}return J}var ef4=(A=0)=>(Q)=>`\x1B[${Q+A}m`,Ab4=(A=0)=>(Q)=>`\x1B[${38+A};5;${Q}m`,Qb4=(A=0)=>(Q,B,$)=>`\x1B[${38+A};2;${Q};${B};${$}m`,C8={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},Bw8=Object.keys(C8.modifier),GN5=Object.keys(C8.color),VN5=Object.keys(C8.bgColor),$w8=[...GN5,...VN5];function UN5(){let A=new Map;for(let[Q,B]of Object.entries(C8)){for(let[$,J]of Object.entries(B))C8[$]={open:`\x1B[${J[0]}m`,close:`\x1B[${J[1]}m`},B[$]=C8[$],A.set(J[0],J[1]);Object.defineProperty(C8,Q,{value:B,enumerable:!1})}return Object.defineProperty(C8,"codes",{value:A,enumerable:!1}),C8.color.close="\x1B[39m",C8.bgColor.close="\x1B[49m",C8.color.ansi=ef4(),C8.color.ansi256=Ab4(),C8.color.ansi16m=Qb4(),C8.bgColor.ansi=ef4(10),C8.bgColor.ansi256=Ab4(10),C8.bgColor.ansi16m=Qb4(10),Object.defineProperties(C8,{rgbToAnsi256:{value:(Q,B,$)=>{if(Q===B&&B===$){if(Q<8)return 16;if(Q>248)return 231;return Math.round((Q-8)/247*24)+232}return 16+36*Math.round(Q/255*5)+6*Math.round(B/255*5)+Math.round($/255*5)},enumerable:!1},hexToRgb:{value:(Q)=>{let B=/[a-f\d]{6}|[a-f\d]{3}/i.exec(Q.toString(16));if(!B)return[0,0,0];let[$]=B;if($.length===3)$=[...$].map((Y)=>Y+Y).join("");let J=Number.parseInt($,16);return[J>>16&255,J>>8&255,J&255]},enumerable:!1},hexToAnsi256:{value:(Q)=>C8.rgbToAnsi256(...C8.hexToRgb(Q)),enumerable:!1},ansi256ToAnsi:{value:(Q)=>{if(Q<8)return 30+Q;if(Q<16)return 90+(Q-8);let B,$,J;if(Q>=232)B=((Q-232)*10+8)/255,$=B,J=B;else{Q-=16;let F=Q%36;B=Math.floor(Q/36)/5,$=Math.floor(F/6)/5,J=F%6/5}let Y=Math.max(B,$,J)*2;if(Y===0)return 30;let Z=30+(Math.round(J)<<2|Math.round($)<<1|Math.round(B));if(Y===2)Z+=60;return Z},enumerable:!1},rgbToAnsi:{value:(Q,B,$)=>C8.ansi256ToAnsi(C8.rgbToAnsi256(Q,B,$)),enumerable:!1},hexToAnsi:{value:(Q)=>C8.ansi256ToAnsi(C8.hexToAnsi256(Q)),enumerable:!1}}),C8}var KN5=UN5(),Bb4=KN5;var $X0=new Set(["\x1B","›"]),EN5=39,ut0="\x07",Yb4="[",zN5="]",Zb4="m",BX0=`${zN5}8;;`,$b4=(A)=>`${$X0.values().next().value}${Yb4}${A}${Zb4}`,Jb4=(A)=>`${$X0.values().next().value}${BX0}${A}${ut0}`,WN5=(A)=>A.split(" ").map((Q)=>Lj(Q)),bt0=(A,Q,B)=>{let $=[...Q],J=!1,Y=!1,Z=Lj(qo(A.at(-1)));for(let[F,X]of $.entries()){let D=Lj(X);if(Z+D<=B)A[A.length-1]+=X;else A.push(X),Z=0;if($X0.has(X))J=!0,Y=$.slice(F+1,F+1+BX0.length).join("")===BX0;if(J){if(Y){if(X===ut0)J=!1,Y=!1}else if(X===Zb4)J=!1;continue}if(Z+=D,Z===B&&F<$.length-1)A.push(""),Z=0}if(!Z&&A.at(-1).length>0&&A.length>1)A[A.length-2]+=A.pop()},HN5=(A)=>{let Q=A.split(" "),B=Q.length;while(B>0){if(Lj(Q[B-1])>0)break;B--}if(B===Q.length)return A;return Q.slice(0,B).join(" ")+Q.slice(B).join("")},qN5=(A,Q,B={})=>{if(B.trim!==!1&&A.trim()==="")return"";let $="",J,Y,Z=WN5(A),F=[""];for(let[V,U]of A.split(" ").entries()){if(B.trim!==!1)F[F.length-1]=F.at(-1).trimStart();let K=Lj(F.at(-1));if(V!==0){if(K>=Q&&(B.wordWrap===!1||B.trim===!1))F.push(""),K=0;if(K>0||B.trim===!1)F[F.length-1]+=" ",K++}if(B.hard&&Z[V]>Q){let E=Q-K,z=1+Math.floor((Z[V]-E-1)/Q);if(Math.floor((Z[V]-1)/Q)<z)F.push("");bt0(F,U,Q);continue}if(K+Z[V]>Q&&K>0&&Z[V]>0){if(B.wordWrap===!1&&K<Q){bt0(F,U,Q);continue}F.push("")}if(K+Z[V]>Q&&B.wordWrap===!1){bt0(F,U,Q);continue}F[F.length-1]+=U}if(B.trim!==!1)F=F.map((V)=>HN5(V));let X=F.join(`
5187
- `),D=[...X],G=0;for(let[V,U]of D.entries()){if($+=U,$X0.has(U)){let{groups:E}=new RegExp(`(?:\\${Yb4}(?<code>\\d+)m|\\${BX0}(?<uri>.*)${ut0})`).exec(X.slice(G))||{groups:{}};if(E.code!==void 0){let z=Number.parseFloat(E.code);J=z===EN5?void 0:z}else if(E.uri!==void 0)Y=E.uri.length===0?void 0:E.uri}let K=Bb4.codes.get(Number(J));if(D[V+1]===`
5186
+ - ghostty.markdown → ghostty.md`},{description:"Pipe a command to the agent and use execute mode:",command:'echo "commit all my unstaged changes" | amp -x --dangerously-allow-all',output:"Done. I have committed all your unstaged changes."},{description:"Pipe data to the agent and send along a prompt in execute mode:",command:`cat ~/.zshrc | amp -x "what does the 'beautiful' function do?"`,output:'The `beautiful` function creates an infinite loop that prints the letter "o" in cycling colors every 0.2 seconds.'},{description:"Execute a prompt from a file and store final assistant message output in a file (redirecting stdout is equivalent to providing -x/--execute):",command:"amp < prompt.txt > output.txt"},{description:"Add an MCP server with a local command:",command:"amp mcp add context7 -- npx -y @upstash/context7-mcp"},{description:"Add an MCP server with environment variables:",command:"amp mcp add postgres --env PGUSER=orb -- npx -y @modelcontextprotocol/server-postgres postgresql://localhost/orbing"},{description:"Add a remote MCP server:",command:"amp mcp add hugging-face https://huggingface.co/mcp"}],configuration:{description:`Amp can be configured using a JSON settings file located at ${mF}. All settings use the "amp." prefix.`,sampleConfig:JSON.stringify(ZN5,null,2),keyDescriptions:Object.entries(lf4).filter(([,A])=>A.visible).map(([A,Q])=>({key:`amp.${A}`,description:Q.description}))}};function ft0({onlyFirst:A=!1}={}){let B=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(B,A?void 0:"g")}var FN5=ft0();function qo(A){if(typeof A!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof A}\``);return A.replace(FN5,"")}function if4(A){return A===161||A===164||A===167||A===168||A===170||A===173||A===174||A>=176&&A<=180||A>=182&&A<=186||A>=188&&A<=191||A===198||A===208||A===215||A===216||A>=222&&A<=225||A===230||A>=232&&A<=234||A===236||A===237||A===240||A===242||A===243||A>=247&&A<=250||A===252||A===254||A===257||A===273||A===275||A===283||A===294||A===295||A===299||A>=305&&A<=307||A===312||A>=319&&A<=322||A===324||A>=328&&A<=331||A===333||A===338||A===339||A===358||A===359||A===363||A===462||A===464||A===466||A===468||A===470||A===472||A===474||A===476||A===593||A===609||A===708||A===711||A>=713&&A<=715||A===717||A===720||A>=728&&A<=731||A===733||A===735||A>=768&&A<=879||A>=913&&A<=929||A>=931&&A<=937||A>=945&&A<=961||A>=963&&A<=969||A===1025||A>=1040&&A<=1103||A===1105||A===8208||A>=8211&&A<=8214||A===8216||A===8217||A===8220||A===8221||A>=8224&&A<=8226||A>=8228&&A<=8231||A===8240||A===8242||A===8243||A===8245||A===8251||A===8254||A===8308||A===8319||A>=8321&&A<=8324||A===8364||A===8451||A===8453||A===8457||A===8467||A===8470||A===8481||A===8482||A===8486||A===8491||A===8531||A===8532||A>=8539&&A<=8542||A>=8544&&A<=8555||A>=8560&&A<=8569||A===8585||A>=8592&&A<=8601||A===8632||A===8633||A===8658||A===8660||A===8679||A===8704||A===8706||A===8707||A===8711||A===8712||A===8715||A===8719||A===8721||A===8725||A===8730||A>=8733&&A<=8736||A===8739||A===8741||A>=8743&&A<=8748||A===8750||A>=8756&&A<=8759||A===8764||A===8765||A===8776||A===8780||A===8786||A===8800||A===8801||A>=8804&&A<=8807||A===8810||A===8811||A===8814||A===8815||A===8834||A===8835||A===8838||A===8839||A===8853||A===8857||A===8869||A===8895||A===8978||A>=9312&&A<=9449||A>=9451&&A<=9547||A>=9552&&A<=9587||A>=9600&&A<=9615||A>=9618&&A<=9621||A===9632||A===9633||A>=9635&&A<=9641||A===9650||A===9651||A===9654||A===9655||A===9660||A===9661||A===9664||A===9665||A>=9670&&A<=9672||A===9675||A>=9678&&A<=9681||A>=9698&&A<=9701||A===9711||A===9733||A===9734||A===9737||A===9742||A===9743||A===9756||A===9758||A===9792||A===9794||A===9824||A===9825||A>=9827&&A<=9829||A>=9831&&A<=9834||A===9836||A===9837||A===9839||A===9886||A===9887||A===9919||A>=9926&&A<=9933||A>=9935&&A<=9939||A>=9941&&A<=9953||A===9955||A===9960||A===9961||A>=9963&&A<=9969||A===9972||A>=9974&&A<=9977||A===9979||A===9980||A===9982||A===9983||A===10045||A>=10102&&A<=10111||A>=11094&&A<=11097||A>=12872&&A<=12879||A>=57344&&A<=63743||A>=65024&&A<=65039||A===65533||A>=127232&&A<=127242||A>=127248&&A<=127277||A>=127280&&A<=127337||A>=127344&&A<=127373||A===127375||A===127376||A>=127387&&A<=127404||A>=917760&&A<=917999||A>=983040&&A<=1048573||A>=1048576&&A<=1114109}function nf4(A){return A===12288||A>=65281&&A<=65376||A>=65504&&A<=65510}function af4(A){return A>=4352&&A<=4447||A===8986||A===8987||A===9001||A===9002||A>=9193&&A<=9196||A===9200||A===9203||A===9725||A===9726||A===9748||A===9749||A>=9776&&A<=9783||A>=9800&&A<=9811||A===9855||A>=9866&&A<=9871||A===9875||A===9889||A===9898||A===9899||A===9917||A===9918||A===9924||A===9925||A===9934||A===9940||A===9962||A===9970||A===9971||A===9973||A===9978||A===9981||A===9989||A===9994||A===9995||A===10024||A===10060||A===10062||A>=10067&&A<=10069||A===10071||A>=10133&&A<=10135||A===10160||A===10175||A===11035||A===11036||A===11088||A===11093||A>=11904&&A<=11929||A>=11931&&A<=12019||A>=12032&&A<=12245||A>=12272&&A<=12287||A>=12289&&A<=12350||A>=12353&&A<=12438||A>=12441&&A<=12543||A>=12549&&A<=12591||A>=12593&&A<=12686||A>=12688&&A<=12773||A>=12783&&A<=12830||A>=12832&&A<=12871||A>=12880&&A<=42124||A>=42128&&A<=42182||A>=43360&&A<=43388||A>=44032&&A<=55203||A>=63744&&A<=64255||A>=65040&&A<=65049||A>=65072&&A<=65106||A>=65108&&A<=65126||A>=65128&&A<=65131||A>=94176&&A<=94180||A===94192||A===94193||A>=94208&&A<=100343||A>=100352&&A<=101589||A>=101631&&A<=101640||A>=110576&&A<=110579||A>=110581&&A<=110587||A===110589||A===110590||A>=110592&&A<=110882||A===110898||A>=110928&&A<=110930||A===110933||A>=110948&&A<=110951||A>=110960&&A<=111355||A>=119552&&A<=119638||A>=119648&&A<=119670||A===126980||A===127183||A===127374||A>=127377&&A<=127386||A>=127488&&A<=127490||A>=127504&&A<=127547||A>=127552&&A<=127560||A===127568||A===127569||A>=127584&&A<=127589||A>=127744&&A<=127776||A>=127789&&A<=127797||A>=127799&&A<=127868||A>=127870&&A<=127891||A>=127904&&A<=127946||A>=127951&&A<=127955||A>=127968&&A<=127984||A===127988||A>=127992&&A<=128062||A===128064||A>=128066&&A<=128252||A>=128255&&A<=128317||A>=128331&&A<=128334||A>=128336&&A<=128359||A===128378||A===128405||A===128406||A===128420||A>=128507&&A<=128591||A>=128640&&A<=128709||A===128716||A>=128720&&A<=128722||A>=128725&&A<=128727||A>=128732&&A<=128735||A===128747||A===128748||A>=128756&&A<=128764||A>=128992&&A<=129003||A===129008||A>=129292&&A<=129338||A>=129340&&A<=129349||A>=129351&&A<=129535||A>=129648&&A<=129660||A>=129664&&A<=129673||A>=129679&&A<=129734||A>=129742&&A<=129756||A>=129759&&A<=129769||A>=129776&&A<=129784||A>=131072&&A<=196605||A>=196608&&A<=262141}function XN5(A){if(!Number.isSafeInteger(A))throw TypeError(`Expected a code point, got \`${typeof A}\`.`)}function of4(A,{ambiguousAsWide:Q=!1}={}){if(XN5(A),nf4(A)||af4(A)||Q&&if4(A))return 2;return 1}var tf4=v4(sf4(),1),DN5=new Intl.Segmenter,GN5=/^\p{Default_Ignorable_Code_Point}$/u;function Lj(A,Q={}){if(typeof A!=="string"||A.length===0)return 0;let{ambiguousIsNarrow:B=!0,countAnsiEscapeCodes:$=!1}=Q;if(!$)A=qo(A);if(A.length===0)return 0;let J=0,Y={ambiguousAsWide:!B};for(let{segment:Z}of DN5.segment(A)){let F=Z.codePointAt(0);if(F<=31||F>=127&&F<=159)continue;if(F>=8203&&F<=8207||F===65279)continue;if(F>=768&&F<=879||F>=6832&&F<=6911||F>=7616&&F<=7679||F>=8400&&F<=8447||F>=65056&&F<=65071)continue;if(F>=55296&&F<=57343)continue;if(F>=65024&&F<=65039)continue;if(GN5.test(Z))continue;if(tf4.default().test(Z)){J+=2;continue}J+=of4(F,Y)}return J}var ef4=(A=0)=>(Q)=>`\x1B[${Q+A}m`,Ab4=(A=0)=>(Q)=>`\x1B[${38+A};5;${Q}m`,Qb4=(A=0)=>(Q,B,$)=>`\x1B[${38+A};2;${Q};${B};${$}m`,C8={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},Bw8=Object.keys(C8.modifier),VN5=Object.keys(C8.color),UN5=Object.keys(C8.bgColor),$w8=[...VN5,...UN5];function KN5(){let A=new Map;for(let[Q,B]of Object.entries(C8)){for(let[$,J]of Object.entries(B))C8[$]={open:`\x1B[${J[0]}m`,close:`\x1B[${J[1]}m`},B[$]=C8[$],A.set(J[0],J[1]);Object.defineProperty(C8,Q,{value:B,enumerable:!1})}return Object.defineProperty(C8,"codes",{value:A,enumerable:!1}),C8.color.close="\x1B[39m",C8.bgColor.close="\x1B[49m",C8.color.ansi=ef4(),C8.color.ansi256=Ab4(),C8.color.ansi16m=Qb4(),C8.bgColor.ansi=ef4(10),C8.bgColor.ansi256=Ab4(10),C8.bgColor.ansi16m=Qb4(10),Object.defineProperties(C8,{rgbToAnsi256:{value:(Q,B,$)=>{if(Q===B&&B===$){if(Q<8)return 16;if(Q>248)return 231;return Math.round((Q-8)/247*24)+232}return 16+36*Math.round(Q/255*5)+6*Math.round(B/255*5)+Math.round($/255*5)},enumerable:!1},hexToRgb:{value:(Q)=>{let B=/[a-f\d]{6}|[a-f\d]{3}/i.exec(Q.toString(16));if(!B)return[0,0,0];let[$]=B;if($.length===3)$=[...$].map((Y)=>Y+Y).join("");let J=Number.parseInt($,16);return[J>>16&255,J>>8&255,J&255]},enumerable:!1},hexToAnsi256:{value:(Q)=>C8.rgbToAnsi256(...C8.hexToRgb(Q)),enumerable:!1},ansi256ToAnsi:{value:(Q)=>{if(Q<8)return 30+Q;if(Q<16)return 90+(Q-8);let B,$,J;if(Q>=232)B=((Q-232)*10+8)/255,$=B,J=B;else{Q-=16;let F=Q%36;B=Math.floor(Q/36)/5,$=Math.floor(F/6)/5,J=F%6/5}let Y=Math.max(B,$,J)*2;if(Y===0)return 30;let Z=30+(Math.round(J)<<2|Math.round($)<<1|Math.round(B));if(Y===2)Z+=60;return Z},enumerable:!1},rgbToAnsi:{value:(Q,B,$)=>C8.ansi256ToAnsi(C8.rgbToAnsi256(Q,B,$)),enumerable:!1},hexToAnsi:{value:(Q)=>C8.ansi256ToAnsi(C8.hexToAnsi256(Q)),enumerable:!1}}),C8}var EN5=KN5(),Bb4=EN5;var $X0=new Set(["\x1B","›"]),zN5=39,ut0="\x07",Yb4="[",WN5="]",Zb4="m",BX0=`${WN5}8;;`,$b4=(A)=>`${$X0.values().next().value}${Yb4}${A}${Zb4}`,Jb4=(A)=>`${$X0.values().next().value}${BX0}${A}${ut0}`,HN5=(A)=>A.split(" ").map((Q)=>Lj(Q)),bt0=(A,Q,B)=>{let $=[...Q],J=!1,Y=!1,Z=Lj(qo(A.at(-1)));for(let[F,X]of $.entries()){let D=Lj(X);if(Z+D<=B)A[A.length-1]+=X;else A.push(X),Z=0;if($X0.has(X))J=!0,Y=$.slice(F+1,F+1+BX0.length).join("")===BX0;if(J){if(Y){if(X===ut0)J=!1,Y=!1}else if(X===Zb4)J=!1;continue}if(Z+=D,Z===B&&F<$.length-1)A.push(""),Z=0}if(!Z&&A.at(-1).length>0&&A.length>1)A[A.length-2]+=A.pop()},qN5=(A)=>{let Q=A.split(" "),B=Q.length;while(B>0){if(Lj(Q[B-1])>0)break;B--}if(B===Q.length)return A;return Q.slice(0,B).join(" ")+Q.slice(B).join("")},NN5=(A,Q,B={})=>{if(B.trim!==!1&&A.trim()==="")return"";let $="",J,Y,Z=HN5(A),F=[""];for(let[V,U]of A.split(" ").entries()){if(B.trim!==!1)F[F.length-1]=F.at(-1).trimStart();let K=Lj(F.at(-1));if(V!==0){if(K>=Q&&(B.wordWrap===!1||B.trim===!1))F.push(""),K=0;if(K>0||B.trim===!1)F[F.length-1]+=" ",K++}if(B.hard&&Z[V]>Q){let E=Q-K,z=1+Math.floor((Z[V]-E-1)/Q);if(Math.floor((Z[V]-1)/Q)<z)F.push("");bt0(F,U,Q);continue}if(K+Z[V]>Q&&K>0&&Z[V]>0){if(B.wordWrap===!1&&K<Q){bt0(F,U,Q);continue}F.push("")}if(K+Z[V]>Q&&B.wordWrap===!1){bt0(F,U,Q);continue}F[F.length-1]+=U}if(B.trim!==!1)F=F.map((V)=>qN5(V));let X=F.join(`
5187
+ `),D=[...X],G=0;for(let[V,U]of D.entries()){if($+=U,$X0.has(U)){let{groups:E}=new RegExp(`(?:\\${Yb4}(?<code>\\d+)m|\\${BX0}(?<uri>.*)${ut0})`).exec(X.slice(G))||{groups:{}};if(E.code!==void 0){let z=Number.parseFloat(E.code);J=z===zN5?void 0:z}else if(E.uri!==void 0)Y=E.uri.length===0?void 0:E.uri}let K=Bb4.codes.get(Number(J));if(D[V+1]===`
5188
5188
  `){if(Y)$+=Jb4("");if(J&&K)$+=$b4(K)}else if(U===`
5189
5189
  `){if(J&&K)$+=$b4(J);if(Y)$+=Jb4(Y)}G+=U.length}return $};function ht0(A,Q,B){return String(A).normalize().replaceAll(`\r
5190
5190
  `,`
5191
5191
  `).split(`
5192
- `).map(($)=>qN5($,Q,B)).join(`
5192
+ `).map(($)=>NN5($,Q,B)).join(`
5193
5193
  `)}function Fb4(A,Q){return ht0(A,Q,{hard:!0,wordWrap:!0,trim:!0})}function gt0(A,Q={}){let B={baseIndent:" ",firstColumnColor:n0.green},{baseIndent:$,firstColumnColor:J}={...B,...Q};if(A.length===0)return"";let Z=A.reduce((F,[X])=>Math.max(F,X.length),0)+2;return A.map(([F,X])=>{let D=F.padEnd(Z),G=J(D),V=$+" ".repeat(Z),K=(process.stdout.columns||120)-V.length,W=Fb4(X,K).split(`
5194
5194
  `).map((H,q)=>q===0?H:V+H).join(`
5195
5195
  `);return $+G+W}).join(`
@@ -5234,14 +5234,14 @@ Total: **13 Markdown files** found across the project.
5234
5234
 
5235
5235
  `;let F=A.commands.filter((X)=>!X._hidden);if(F.length>0)$+=n0.bold("Commands:")+`
5236
5236
 
5237
- `,$+=NN5(F),$+=`
5238
- `;if($+=B(A.options.filter((X)=>!X.hidden),"Options:"),A.parent){let X=A.parent;while(X.parent)X=X.parent;let D=new Set(A.options.map((G)=>G.flags));$+=B(X.options.filter((G)=>!G.hidden).filter((G)=>!D.has(G.flags)).filter((G)=>{let V=G.flags.includes("--execute"),U=G.flags.includes("--interactive");return!V&&!U}),"Global options:")}return $}function Gb4(A,Q=0){let B=[];for(let $ of A){B.push({cmd:$,level:Q});let J=$.commands.filter((Y)=>!Y._hidden);if(J.length>0)B.push(...Gb4(J,Q+1))}return B}function NN5(A,Q=" "){let $=Gb4(A).map(({cmd:J,level:Y})=>{let Z=Q.repeat(Y),F=J.aliases(),X=J.summary()||J.description(),D=F.length>0?`[alias: ${F.join(", ")}] `:"";return[Z+J.name(),D+X]});return gt0($)}function Z9(){return process.env.TERMINAL_EMULATOR?.includes("JetBrains")??!1}function Vb4(){return process.env.TERM_PROGRAM!==void 0&&process.env.TERM_PROGRAM==="vscode"}function Ub4(){return process.env.NVIM!==void 0}import{mkdir as MN5,writeFile as LN5}from"node:fs/promises";import Oj from"node:os";import oY from"node:path";import{stdout as Io}from"node:process";import{chmodSync as ON5,existsSync as Nb4,mkdirSync as jN5,writeFileSync as qb4}from"fs";import{spawn as IN5}from"node:child_process";import{constants as Kb4}from"node:fs";import{access as wN5}from"node:fs/promises";import*as zb4 from"node:os";import{join as pt0}from"node:path";function No(){return process.platform==="win32"&&Boolean(process.env.MSYSTEM||process.env.MINGW_PREFIX)}function _U(A){let Q=zb4.homedir();if(A.startsWith(Q))return A.replace(Q,"~");return A}async function Wb4(){let A=process.env.PATH||"",Q=No(),B=A.split(process.platform==="win32"&&!Q?";":":").filter((Z)=>Z.trim()),$=process.platform==="win32"&&!Q,J=B.flatMap((Z)=>{if($)return[pt0(Z,"amp.bat"),pt0(Z,"amp.exe")];else return[pt0(Z,"amp")]});return(await Promise.all(J.map(async(Z)=>{try{let F=$?Kb4.F_OK:Kb4.X_OK;return await wN5(Z,F),Z}catch{return null}}))).filter((Z)=>Z!==null)}function yD(A,Q,B=1e4){return new Promise(($)=>{let J=IN5(A,Q,{stdio:["ignore","pipe","pipe"],timeout:B,shell:process.platform==="win32"}),Y="";J.stdout.on("data",(Z)=>{Y+=Z.toString()}),J.stderr.on("data",(Z)=>{Y+=Z.toString()}),J.on("close",(Z,F)=>{if(F==="SIGTERM")$({reason:"fail",output:(Y+`
5237
+ `,$+=IN5(F),$+=`
5238
+ `;if($+=B(A.options.filter((X)=>!X.hidden),"Options:"),A.parent){let X=A.parent;while(X.parent)X=X.parent;let D=new Set(A.options.map((G)=>G.flags));$+=B(X.options.filter((G)=>!G.hidden).filter((G)=>!D.has(G.flags)).filter((G)=>{let V=G.flags.includes("--execute"),U=G.flags.includes("--interactive");return!V&&!U}),"Global options:")}return $}function Gb4(A,Q=0){let B=[];for(let $ of A){B.push({cmd:$,level:Q});let J=$.commands.filter((Y)=>!Y._hidden);if(J.length>0)B.push(...Gb4(J,Q+1))}return B}function IN5(A,Q=" "){let $=Gb4(A).map(({cmd:J,level:Y})=>{let Z=Q.repeat(Y),F=J.aliases(),X=J.summary()||J.description(),D=F.length>0?`[alias: ${F.join(", ")}] `:"";return[Z+J.name(),D+X]});return gt0($)}function Z9(){return process.env.TERMINAL_EMULATOR?.includes("JetBrains")??!1}function Vb4(){return process.env.TERM_PROGRAM!==void 0&&process.env.TERM_PROGRAM==="vscode"}function Ub4(){return process.env.NVIM!==void 0}import{mkdir as LN5,writeFile as ON5}from"node:fs/promises";import Oj from"node:os";import oY from"node:path";import{stdout as Io}from"node:process";import{chmodSync as jN5,existsSync as Nb4,mkdirSync as RN5,writeFileSync as qb4}from"fs";import{spawn as wN5}from"node:child_process";import{constants as Kb4}from"node:fs";import{access as CN5}from"node:fs/promises";import*as zb4 from"node:os";import{join as pt0}from"node:path";function No(){return process.platform==="win32"&&Boolean(process.env.MSYSTEM||process.env.MINGW_PREFIX)}function _U(A){let Q=zb4.homedir();if(A.startsWith(Q))return A.replace(Q,"~");return A}async function Wb4(){let A=process.env.PATH||"",Q=No(),B=A.split(process.platform==="win32"&&!Q?";":":").filter((Z)=>Z.trim()),$=process.platform==="win32"&&!Q,J=B.flatMap((Z)=>{if($)return[pt0(Z,"amp.bat"),pt0(Z,"amp.exe")];else return[pt0(Z,"amp")]});return(await Promise.all(J.map(async(Z)=>{try{let F=$?Kb4.F_OK:Kb4.X_OK;return await CN5(Z,F),Z}catch{return null}}))).filter((Z)=>Z!==null)}function yD(A,Q,B=1e4){return new Promise(($)=>{let J=wN5(A,Q,{stdio:["ignore","pipe","pipe"],timeout:B,shell:process.platform==="win32"}),Y="";J.stdout.on("data",(Z)=>{Y+=Z.toString()}),J.stderr.on("data",(Z)=>{Y+=Z.toString()}),J.on("close",(Z,F)=>{if(F==="SIGTERM")$({reason:"fail",output:(Y+`
5239
5239
  timeout`).trim()});else if(Z===0)$({reason:"success",output:Y.trim()});else $({reason:"fail",output:(Y+`
5240
- Exit code ${Z}`).trim()})}),J.on("error",(Z)=>{$({reason:"missing",output:Z.message.trim()})})})}function Eb4(A){let Q=A.replace(/\\/g,"/");return process.platform==="win32"?Q.toLowerCase():Q}function Hb4(){return process.platform==="win32"?"where amp":"which amp"}async function CN5(A,Q){let B=await Wb4(),[$]=B;if(!$)return{status:"missing",warning:"[WARN] amp not accessible via PATH"};if(Eb4($)===Eb4(Q))return{status:"same"};let J=`[WARN] Found amp at ${_U($)} in PATH, but expected version ${A} from ${_U(Q)}. Another version may be installed.`;if(B.length>0){J+=`
5240
+ Exit code ${Z}`).trim()})}),J.on("error",(Z)=>{$({reason:"missing",output:Z.message.trim()})})})}function Eb4(A){let Q=A.replace(/\\/g,"/");return process.platform==="win32"?Q.toLowerCase():Q}function Hb4(){return process.platform==="win32"?"where amp":"which amp"}async function MN5(A,Q){let B=await Wb4(),[$]=B;if(!$)return{status:"missing",warning:"[WARN] amp not accessible via PATH"};if(Eb4($)===Eb4(Q))return{status:"same"};let J=`[WARN] Found amp at ${_U($)} in PATH, but expected version ${A} from ${_U(Q)}. Another version may be installed.`;if(B.length>0){J+=`
5241
5241
  [WARN] Found amp executables at these locations:`;for(let Y of B)J+=`
5242
5242
  ${_U(Y)}`}return J+=`
5243
5243
  [WARN] To resolve this, ensure the correct amp is at the front of your PATH.`,J+=`
5244
- [WARN] Run "${Hb4()}" in your shell to see which amp executable is currently being used.`,{status:"different",warning:J}}async function Sz(A,Q={}){if(Q.currentExecutablePath)return CN5(A,Q.currentExecutablePath);let{reason:B,output:$}=await yD("amp",["--version"]);switch(B){case"success":{let Y=$.trim().split(" ")[0];if(Y===A)return{status:"same"};else{let Z=await Wb4(),F=`[WARN] Found amp ${Y} in PATH, but expected ${A}. Another version is installed.`;if(Z.length>0){F+=`
5244
+ [WARN] Run "${Hb4()}" in your shell to see which amp executable is currently being used.`,{status:"different",warning:J}}async function Sz(A,Q={}){if(Q.currentExecutablePath)return MN5(A,Q.currentExecutablePath);let{reason:B,output:$}=await yD("amp",["--version"]);switch(B){case"success":{let Y=$.trim().split(" ")[0];if(Y===A)return{status:"same"};else{let Z=await Wb4(),F=`[WARN] Found amp ${Y} in PATH, but expected ${A}. Another version is installed.`;if(Z.length>0){F+=`
5245
5245
  [WARN] Found amp executables at these locations:`;for(let X of Z)F+=`
5246
5246
  ${_U(X)}`}return F+=`
5247
5247
  [WARN] To resolve this, ensure the correct amp is at the front of your PATH.`,F+=`
@@ -5251,7 +5251,7 @@ ${$.trim()}`;return{status:"fail",warning:J}}}}var aQ={blue:(A)=>Io.write(n0.blu
5251
5251
  `),red:(A)=>Io.write(n0.red(A)+`
5252
5252
  `),yellow:(A)=>Io.write(n0.yellow(A)+`
5253
5253
  `),bold:(A)=>Io.write(n0.bold(A)+`
5254
- `)};function RN5(){let A=process.env.AMP_HOME;if(!A)return{ripgrepTargetDir:null,installLocalBin:!1,checkVersion:!0};let Q=oY.join(A,"bin"),B=oY.join(Oj.homedir(),".amp");if(A!==B)return aQ.blue("[INFO] Custom AMP_HOME detected - skipping installation of ~/.local/bin/amp (assuming testing mode)"),{ripgrepTargetDir:Q,installLocalBin:!1,checkVersion:!1};return{ripgrepTargetDir:Q,installLocalBin:!0,checkVersion:!0}}async function PN5(A,Q,B){if(await MN5(A,{recursive:!0}),await k74(A,Q)){if(B)aQ.green("✓ ripgrep spell successfully conjured")}else{aQ.red("✗ Failed to install ripgrep"),process.exitCode=1;return}}async function _N5(){let A=process.platform==="win32"&&!No(),Q=oY.join(Oj.homedir(),".local","bin");if(!Nb4(Q))jN5(Q,{recursive:!0});if(A){let $=oY.join(Q,"amp.bat"),J=`@echo off
5254
+ `)};function PN5(){let A=process.env.AMP_HOME;if(!A)return{ripgrepTargetDir:null,installLocalBin:!1,checkVersion:!0};let Q=oY.join(A,"bin"),B=oY.join(Oj.homedir(),".amp");if(A!==B)return aQ.blue("[INFO] Custom AMP_HOME detected - skipping installation of ~/.local/bin/amp (assuming testing mode)"),{ripgrepTargetDir:Q,installLocalBin:!1,checkVersion:!1};return{ripgrepTargetDir:Q,installLocalBin:!0,checkVersion:!0}}async function _N5(A,Q,B){if(await LN5(A,{recursive:!0}),await k74(A,Q)){if(B)aQ.green("✓ ripgrep spell successfully conjured")}else{aQ.red("✗ Failed to install ripgrep"),process.exitCode=1;return}}async function TN5(){let A=process.platform==="win32"&&!No(),Q=oY.join(Oj.homedir(),".local","bin");if(!Nb4(Q))RN5(Q,{recursive:!0});if(A){let $=oY.join(Q,"amp.bat"),J=`@echo off
5255
5255
  REM Amp CLI PATH wrapper - simply execs the main script
5256
5256
  if defined AMP_HOME (
5257
5257
  "%AMP_HOME%\\bin\\amp.bat" %*
@@ -5271,29 +5271,29 @@ exec "\${AMP_HOME:-$HOME/.amp}/bin/amp" "$@"
5271
5271
  `;qb4($,`#!/usr/bin/env bash
5272
5272
  # Amp CLI PATH wrapper - simply execs the main script
5273
5273
  exec "\${AMP_HOME:-$HOME/.amp}/bin/amp" "$@"
5274
- `);try{ON5($,493)}catch{}}let B=A?oY.join(Q,"amp.bat"):oY.join(Q,"amp");aQ.green(`✓ The wizard's staff is ready at ${_U(B)}`)}async function TN5(){let A=process.platform==="darwin"?"zsh":"bash",Q=oY.basename(process.env.SHELL||A),$={fish:{configPaths:[oY.join(Oj.homedir(),".config","fish","config.fish")],command:'fish_add_path "~/.local/bin"',refreshCommand:"source ~/.config/fish/config.fish"},nu:{configPaths:[oY.join(Oj.homedir(),".config","nushell","env.nu")],command:"$env.PATH ++= ['~/.local/bin']",refreshCommand:"source ~/.config/nushell/env.nu"},zsh:{configPaths:[oY.join(Oj.homedir(),".zshrc")],command:'export PATH="$HOME/.local/bin:$PATH"',refreshCommand:"exec $SHELL"},bash:{configPaths:[oY.join(Oj.homedir(),".bashrc"),oY.join(Oj.homedir(),".bash_profile")],command:'export PATH="$HOME/.local/bin:$PATH"',refreshCommand:"source ~/.bashrc"}}[Q];if(!$){aQ.yellow("Manually add the directory to your shell configuration:"),aQ.bold(' export PATH="$HOME/.local/bin:$PATH"');return}if(await kN5($))aQ.blue(`
5274
+ `);try{jN5($,493)}catch{}}let B=A?oY.join(Q,"amp.bat"):oY.join(Q,"amp");aQ.green(`✓ The wizard's staff is ready at ${_U(B)}`)}async function kN5(){let A=process.platform==="darwin"?"zsh":"bash",Q=oY.basename(process.env.SHELL||A),$={fish:{configPaths:[oY.join(Oj.homedir(),".config","fish","config.fish")],command:'fish_add_path "~/.local/bin"',refreshCommand:"source ~/.config/fish/config.fish"},nu:{configPaths:[oY.join(Oj.homedir(),".config","nushell","env.nu")],command:"$env.PATH ++= ['~/.local/bin']",refreshCommand:"source ~/.config/nushell/env.nu"},zsh:{configPaths:[oY.join(Oj.homedir(),".zshrc")],command:'export PATH="$HOME/.local/bin:$PATH"',refreshCommand:"exec $SHELL"},bash:{configPaths:[oY.join(Oj.homedir(),".bashrc"),oY.join(Oj.homedir(),".bash_profile")],command:'export PATH="$HOME/.local/bin:$PATH"',refreshCommand:"source ~/.bashrc"}}[Q];if(!$){aQ.yellow("Manually add the directory to your shell configuration:"),aQ.bold(' export PATH="$HOME/.local/bin:$PATH"');return}if(await SN5($))aQ.blue(`
5275
5275
  To awaken the orb, run:
5276
5276
  `),aQ.bold(` ${$.refreshCommand}`),aQ.bold(" amp --help");else aQ.yellow(`
5277
- Manually weave this spell into your shell configuration:`),aQ.bold(` ${$.command}`)}async function kN5(A){for(let Q of A.configPaths){let B=_U(Q);if(Nb4(Q))try{return aQ.blue(`[INFO] Adding PATH to "${B}"`),await LN5(Q,`
5277
+ Manually weave this spell into your shell configuration:`),aQ.bold(` ${$.command}`)}async function SN5(A){for(let Q of A.configPaths){let B=_U(Q);if(Nb4(Q))try{return aQ.blue(`[INFO] Adding PATH to "${B}"`),await ON5(Q,`
5278
5278
  # amp
5279
5279
  `+A.command+`
5280
- `,{flag:"a"}),aQ.green(`✓ Added "~/.local/bin" to PATH in "${B}"`),!0}catch($){aQ.red(`[WARN] Failed to update ${B}: ${$ instanceof Error?$.message:String($)}`)}}return!1}async function dt0(A,Q,B){let $=RN5();if($.ripgrepTargetDir)await PN5($.ripgrepTargetDir,A,Q);if($.installLocalBin)await _N5();let J=!1;if($.checkVersion){let Y=await Sz(B);if(Q)aQ.blue(`[INFO] "amp --version" state is ${Y.status}`);if(Y.warning)aQ.yellow(Y.warning);J=Y.status==="missing"}if(J&&$.installLocalBin)await TN5()}d0();import{realpath as SN5,stat as vN5}from"node:fs/promises";import{dirname as Ib4,join as yN5}from"node:path";async function xN5(A){switch(A){case"npm":{let B=await yD("npm",["list","-g","-p"]);if(B.reason!=="success")return j.debug("Failed to get npm global path",{result:B}),["/usr/local/lib/node_modules/"];if(!B.output)return["/usr/local/lib/node_modules/"];let $=`/usr/local/lib/node_modules/
5280
+ `,{flag:"a"}),aQ.green(`✓ Added "~/.local/bin" to PATH in "${B}"`),!0}catch($){aQ.red(`[WARN] Failed to update ${B}: ${$ instanceof Error?$.message:String($)}`)}}return!1}async function dt0(A,Q,B){let $=PN5();if($.ripgrepTargetDir)await _N5($.ripgrepTargetDir,A,Q);if($.installLocalBin)await TN5();let J=!1;if($.checkVersion){let Y=await Sz(B);if(Q)aQ.blue(`[INFO] "amp --version" state is ${Y.status}`);if(Y.warning)aQ.yellow(Y.warning);J=Y.status==="missing"}if(J&&$.installLocalBin)await kN5()}d0();import{realpath as vN5,stat as yN5}from"node:fs/promises";import{dirname as Ib4,join as xN5}from"node:path";async function fN5(A){switch(A){case"npm":{let B=await yD("npm",["list","-g","-p"]);if(B.reason!=="success")return j.debug("Failed to get npm global path",{result:B}),["/usr/local/lib/node_modules/"];if(!B.output)return["/usr/local/lib/node_modules/"];let $=`/usr/local/lib/node_modules/
5281
5281
  ${B.output}`.split(`
5282
- `).map((Y)=>Y.trim()).filter((Y)=>Y).sort();return $.filter((Y,Z)=>{let F=$[Z+1];return!F||!F.includes(Y)})}case"pnpm":{let Q=await yD("pnpm",["list","-g","--json"]);if(Q.reason!=="success")return j.debug("Failed to get pnpm global path",{result:Q}),[];let B=JSON.parse(Q.output);if(Array.isArray(B)&&B[0]?.path)return[B[0].path];return[]}case"yarn":{let Q=await yD("yarn",["global","dir"]);if(Q.reason!=="success")return j.debug("Failed to get yarn global path",{result:Q}),[];return Q.output?[Q.output]:[]}case"bun":return["/.bun/install/global/"];case"brew":return[];case"bootstrap":return[];case"binary":return[]}}function jj(){if(process.env.AMP_HOME)return!1;if(!process.versions.bun)return!1;let A=process.execPath;if(A.includes("/node_modules/")||A.includes("\\node_modules\\"))return!1;if(ct0(A))return!1;return!0}function ct0(A){return["/opt/homebrew/Cellar/ampcode/","/usr/local/Cellar/ampcode/","/home/linuxbrew/.linuxbrew/Cellar/ampcode/"].some((B)=>A.includes(B))}async function DI(){if(ct0(process.execPath))return"brew";if(jj())return"binary";if(process.env.AMP_HOME)return"bootstrap";try{let A=process.argv[1]||"";j.debug("Detecting package manager from script path",{currentScript:A});let Q=A;try{Q=await SN5(A),j.debug("Resolved path",{from:A,to:Q})}catch(Y){j.debug("Error resolving path",{error:Y})}if(j.debug("Resolved installation path",{actualPath:Q}),ct0(Q))return"brew";let B=["pnpm","yarn","bun","npm"];for(let Y of B)try{let Z=await xN5(Y);if(Z.length===0)continue;if(j.debug("package manager global paths found",{packageManager:Y,globalPaths:Z}),Z.some((F)=>Q.includes(F)))return Y}catch(Z){j.debug("Failed to query package manager global path",{packageManager:Y,error:Z})}j.debug("Checking installation directory for lockfiles");let $=Ib4(Ib4(Q));j.debug("Checking installation directory",{installDir:$});let J=[{file:"pnpm-lock.yaml",manager:"pnpm"},{file:"yarn.lock",manager:"yarn"},{file:"bun.lockb",manager:"bun"},{file:"package-lock.json",manager:"npm"}];for(let{file:Y,manager:Z}of J)try{let F=yN5($,Y);return j.debug("Checking for lockfile",{filePath:F}),await vN5(F),j.debug("Found package manager lockfile",{file:Y,manager:Z,filePath:F}),Z}catch(F){j.debug("Lockfile not found",{file:Y,error:F})}return j.debug("Could not determine package manager from node_modules path"),null}catch(A){return j.debug("Error detecting installed package manager",{error:A}),null}}async function wb4(){let A=process.env.npm_config_user_agent;if(A){if(A.includes("pnpm"))return"pnpm";if(A.includes("yarn"))return"yarn";if(A.includes("bun"))return"bun";if(A.includes("npm"))return"npm"}if(process.env.PNPM_HOME||process.env.PNPM_SCRIPT_SRC_DIR)return"pnpm";if(process.env.YARN_WRAP_OUTPUT||process.env.YARNPKG_LOCKFILE_VERSION)return"yarn";if(process.env.BUN_INSTALL)return"bun";let[Q,B,$,J]=await Promise.allSettled([JX0("pnpm"),JX0("yarn"),JX0("bun"),JX0("npm")]);if(Q.status==="fulfilled"&&Q.value)return"pnpm";if(B.status==="fulfilled"&&B.value)return"yarn";if($.status==="fulfilled"&&$.value)return"bun";if(J.status==="fulfilled"&&J.value)return"npm";return null}async function JX0(A){j.debug("Checking command existence",{command:A});let Q=await yD(A,["--version"]);if(Q.reason==="success")return j.debug("Command found",{command:A,version:Q.output}),!0;else return j.debug("Command not found or failed",{command:A,result:Q}),!1}function Cb4(A,Q){let $=Q?`@sourcegraph/amp@${Q}`:"@sourcegraph/amp";switch(A){case"npm":return["npm",["install","-g",$]];case"pnpm":return["pnpm",["add","-g",$]];case"yarn":return["yarn",["global","add",$]];case"bun":return["bun",["add","-g",$]];case"brew":return["brew",["upgrade","ampcode/tap/ampcode"]];case"bootstrap":throw Error("Bootstrap updates are handled separately");case"binary":throw Error("Binary updates are handled separately")}}d0();zE();import*as Ae0 from"node:os";import{execSync as fN5}from"node:child_process";import{createHash as bN5}from"node:crypto";import{chmodSync as Rb4,existsSync as at0,mkdirSync as uN5,readFileSync as Pb4,renameSync as wo,unlinkSync as ot0,writeFileSync as hN5}from"node:fs";import{homedir as gN5}from"node:os";import{basename as mN5,extname as pN5,join as Co}from"node:path";import{gunzipSync as dN5}from"node:zlib";M3();var Mb4=["KB","MB","GB","TB","PB"];function lt0(A,Q){let B=Q?.decimalPlaces??2;if(A<1024)return`${A} ${V4(A,"byte")}`;let $=A/1024,J=0;while($>=1024&&J<Mb4.length-1)$/=1024,J+=1;let Y=Mb4[J];if(!Y)throw Error(`(bug) missing byte size unit for index ${J}`);return`${$.toFixed(B)} ${Y}`}function Lb4(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}`}d0();var it0="https://static.ampcode.com/cli";function cN5(A){if(!A)return;let Q=Number(A);if(!Number.isFinite(Q)||Q<=0)return;return Q}function lN5(A,Q){let B=lt0(A,{decimalPlaces:2});if(Q===void 0)return`(${B})`;let $=lt0(Q,{decimalPlaces:2});return`(${B}/${$})`}async function iN5(A,Q){let B=cN5(A.headers?.get?.("content-length")??null),$=A.body?.getReader();if(!$){let X=new Uint8Array(await A.arrayBuffer());return Q?.(X.byteLength,B),X}let J=[],Y=0;while(!0){let{done:X,value:D}=await $.read();if(X)break;if(!D)continue;J.push(D),Y+=D.byteLength,Q?.(Y,B)}if(J.length===1){let[X]=J;if(X)return X}let Z=new Uint8Array(Y),F=0;for(let X of J)Z.set(X,F),F+=X.byteLength;return Z}function _b4(){if(process.env.AMP_HOME)return process.env.AMP_HOME;let A=gN5();if(!A)throw Error("Cannot determine home directory");return Co(A,".amp")}function Ob4(A){if(uN5(A,{recursive:!0,mode:448}),process.platform!=="win32")Rb4(A,448)}function nN5(){try{if(process.platform==="linux")return Pb4("/proc/cpuinfo","utf8").includes("avx2");if(process.platform==="darwin")return fN5("sysctl -a 2>/dev/null",{encoding:"utf8"}).includes("AVX2")}catch{}return!1}function aN5(){let{platform:A,arch:Q}=process;if(A==="darwin"){if(Q==="arm64")return"darwin-arm64";return"darwin-x64"}if(A==="win32")return"windows-x64";if(A==="linux"){if(Q==="arm64")return"linux-arm64";return nN5()?"linux-x64":"linux-x64-baseline"}return"linux-x64"}async function nt0(A,Q=300000){let B=new AbortController,$=setTimeout(()=>B.abort(),Q);try{let J=await fetch(A,{signal:B.signal});return clearTimeout($),J}catch(J){if(clearTimeout($),J instanceof Error&&J.name==="AbortError")throw Error(`Network timeout after ${Q}ms while fetching: ${A}`);throw J}}function oN5(A,Q){let B=Pb4(A),$=bN5("sha256");$.update(B);let J=$.digest("hex");if(J!==Q)throw Error(`Checksum verification failed for ${A}
5282
+ `).map((Y)=>Y.trim()).filter((Y)=>Y).sort();return $.filter((Y,Z)=>{let F=$[Z+1];return!F||!F.includes(Y)})}case"pnpm":{let Q=await yD("pnpm",["list","-g","--json"]);if(Q.reason!=="success")return j.debug("Failed to get pnpm global path",{result:Q}),[];let B=JSON.parse(Q.output);if(Array.isArray(B)&&B[0]?.path)return[B[0].path];return[]}case"yarn":{let Q=await yD("yarn",["global","dir"]);if(Q.reason!=="success")return j.debug("Failed to get yarn global path",{result:Q}),[];return Q.output?[Q.output]:[]}case"bun":return["/.bun/install/global/"];case"brew":return[];case"bootstrap":return[];case"binary":return[]}}function jj(){if(process.env.AMP_HOME)return!1;if(!process.versions.bun)return!1;let A=process.execPath;if(A.includes("/node_modules/")||A.includes("\\node_modules\\"))return!1;if(ct0(A))return!1;return!0}function ct0(A){return["/opt/homebrew/Cellar/ampcode/","/usr/local/Cellar/ampcode/","/home/linuxbrew/.linuxbrew/Cellar/ampcode/"].some((B)=>A.includes(B))}async function DI(){if(ct0(process.execPath))return"brew";if(jj())return"binary";if(process.env.AMP_HOME)return"bootstrap";try{let A=process.argv[1]||"";j.debug("Detecting package manager from script path",{currentScript:A});let Q=A;try{Q=await vN5(A),j.debug("Resolved path",{from:A,to:Q})}catch(Y){j.debug("Error resolving path",{error:Y})}if(j.debug("Resolved installation path",{actualPath:Q}),ct0(Q))return"brew";let B=["pnpm","yarn","bun","npm"];for(let Y of B)try{let Z=await fN5(Y);if(Z.length===0)continue;if(j.debug("package manager global paths found",{packageManager:Y,globalPaths:Z}),Z.some((F)=>Q.includes(F)))return Y}catch(Z){j.debug("Failed to query package manager global path",{packageManager:Y,error:Z})}j.debug("Checking installation directory for lockfiles");let $=Ib4(Ib4(Q));j.debug("Checking installation directory",{installDir:$});let J=[{file:"pnpm-lock.yaml",manager:"pnpm"},{file:"yarn.lock",manager:"yarn"},{file:"bun.lockb",manager:"bun"},{file:"package-lock.json",manager:"npm"}];for(let{file:Y,manager:Z}of J)try{let F=xN5($,Y);return j.debug("Checking for lockfile",{filePath:F}),await yN5(F),j.debug("Found package manager lockfile",{file:Y,manager:Z,filePath:F}),Z}catch(F){j.debug("Lockfile not found",{file:Y,error:F})}return j.debug("Could not determine package manager from node_modules path"),null}catch(A){return j.debug("Error detecting installed package manager",{error:A}),null}}async function wb4(){let A=process.env.npm_config_user_agent;if(A){if(A.includes("pnpm"))return"pnpm";if(A.includes("yarn"))return"yarn";if(A.includes("bun"))return"bun";if(A.includes("npm"))return"npm"}if(process.env.PNPM_HOME||process.env.PNPM_SCRIPT_SRC_DIR)return"pnpm";if(process.env.YARN_WRAP_OUTPUT||process.env.YARNPKG_LOCKFILE_VERSION)return"yarn";if(process.env.BUN_INSTALL)return"bun";let[Q,B,$,J]=await Promise.allSettled([JX0("pnpm"),JX0("yarn"),JX0("bun"),JX0("npm")]);if(Q.status==="fulfilled"&&Q.value)return"pnpm";if(B.status==="fulfilled"&&B.value)return"yarn";if($.status==="fulfilled"&&$.value)return"bun";if(J.status==="fulfilled"&&J.value)return"npm";return null}async function JX0(A){j.debug("Checking command existence",{command:A});let Q=await yD(A,["--version"]);if(Q.reason==="success")return j.debug("Command found",{command:A,version:Q.output}),!0;else return j.debug("Command not found or failed",{command:A,result:Q}),!1}function Cb4(A,Q){let $=Q?`@sourcegraph/amp@${Q}`:"@sourcegraph/amp";switch(A){case"npm":return["npm",["install","-g",$]];case"pnpm":return["pnpm",["add","-g",$]];case"yarn":return["yarn",["global","add",$]];case"bun":return["bun",["add","-g",$]];case"brew":return["brew",["upgrade","ampcode/tap/ampcode"]];case"bootstrap":throw Error("Bootstrap updates are handled separately");case"binary":throw Error("Binary updates are handled separately")}}d0();zE();import*as Ae0 from"node:os";import{execSync as bN5}from"node:child_process";import{createHash as uN5}from"node:crypto";import{chmodSync as Rb4,existsSync as at0,mkdirSync as hN5,readFileSync as Pb4,renameSync as wo,unlinkSync as ot0,writeFileSync as gN5}from"node:fs";import{homedir as mN5}from"node:os";import{extname as pN5,join as Co}from"node:path";import{gunzipSync as dN5}from"node:zlib";M3();var Mb4=["KB","MB","GB","TB","PB"];function lt0(A,Q){let B=Q?.decimalPlaces??2;if(A<1024)return`${A} ${V4(A,"byte")}`;let $=A/1024,J=0;while($>=1024&&J<Mb4.length-1)$/=1024,J+=1;let Y=Mb4[J];if(!Y)throw Error(`(bug) missing byte size unit for index ${J}`);return`${$.toFixed(B)} ${Y}`}function Lb4(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}`}d0();var it0="https://static.ampcode.com/cli";function cN5(A){if(!A)return;let Q=Number(A);if(!Number.isFinite(Q)||Q<=0)return;return Q}function lN5(A,Q){let B=lt0(A,{decimalPlaces:2});if(Q===void 0)return`(${B})`;let $=lt0(Q,{decimalPlaces:2});return`(${B}/${$})`}async function iN5(A,Q){let B=cN5(A.headers?.get?.("content-length")??null),$=A.body?.getReader();if(!$){let X=new Uint8Array(await A.arrayBuffer());return Q?.(X.byteLength,B),X}let J=[],Y=0;while(!0){let{done:X,value:D}=await $.read();if(X)break;if(!D)continue;J.push(D),Y+=D.byteLength,Q?.(Y,B)}if(J.length===1){let[X]=J;if(X)return X}let Z=new Uint8Array(Y),F=0;for(let X of J)Z.set(X,F),F+=X.byteLength;return Z}function _b4(){if(process.env.AMP_HOME)return process.env.AMP_HOME;let A=mN5();if(!A)throw Error("Cannot determine home directory");return Co(A,".amp")}function Ob4(A){if(hN5(A,{recursive:!0,mode:448}),process.platform!=="win32")Rb4(A,448)}function nN5(){try{if(process.platform==="linux")return Pb4("/proc/cpuinfo","utf8").includes("avx2");if(process.platform==="darwin")return bN5("sysctl -a 2>/dev/null",{encoding:"utf8"}).includes("AVX2")}catch{}return!1}function aN5(){let{platform:A,arch:Q}=process;if(A==="darwin"){if(Q==="arm64")return"darwin-arm64";return"darwin-x64"}if(A==="win32")return"windows-x64";if(A==="linux"){if(Q==="arm64")return"linux-arm64";return nN5()?"linux-x64":"linux-x64-baseline"}return"linux-x64"}async function nt0(A,Q=300000){let B=new AbortController,$=setTimeout(()=>B.abort(),Q);try{let J=await fetch(A,{signal:B.signal});return clearTimeout($),J}catch(J){if(clearTimeout($),J instanceof Error&&J.name==="AbortError")throw Error(`Network timeout after ${Q}ms while fetching: ${A}`);throw J}}function oN5(A,Q){let B=Pb4(A),$=uN5("sha256");$.update(B);let J=$.digest("hex");if(J!==Q)throw Error(`Checksum verification failed for ${A}
5283
5283
  Expected: ${Q}
5284
- Actual: ${J}`)}function Mo(){let A=_b4(),Q=Co(A,"bin"),B=process.platform==="win32";return Co(Q,B?"amp.exe":"amp")}async function rN5(){let A=`${it0}/cli-version.txt`,Q=await nt0(A);if(!Q.ok)throw Error(`Failed to fetch latest version: ${Q.status}`);return(await Q.text()).trim()}function jb4(A){return process.platform==="win32"?A.replace(/\\/g,"/").toLowerCase():A}function Tb4(A){let Q=pN5(A);return`${Q?A.slice(0,A.length-Q.length):A}.old${Q}`}function sN5(A){return jb4(process.execPath)===jb4(A)}function tN5(A,Q){let B=Tb4(A);if(at0(B))ot0(B);wo(A,B);try{wo(Q,A)}catch($){try{wo(B,A)}catch(J){throw Error(`Failed to install Windows binary update and restore original binary: ${J instanceof Error?J.message:String(J)}`)}throw $}j.info("Binary updated successfully",{binaryPath:A,oldBinaryPath:B})}function kb4(){if(process.platform!=="win32")return;let A=Tb4(process.execPath);if(!at0(A))return;try{ot0(A),j.debug("Removed previous Windows binary after successful restart",{oldBinaryPath:A})}catch(Q){j.debug("Failed to remove previous Windows binary after restart",{oldBinaryPath:A,error:Q})}}async function Sb4(A,Q){let B=aN5(),$=_b4();Ob4($);let J=Co($,"bin");Ob4(J);let Y=A||await rN5(),Z=B.startsWith("windows"),F=Z?`amp-${B}.exe`:`amp-${B}`,X=`${B}-amp.sha256`,D=process.env.USE_GZIPPED_BINARIES==="1"||mN5(process.cwd()).startsWith("amp"),G=`${it0}/${Y}/${F}${D?".gz":""}`,V=`${it0}/${Y}/${X}`,U=Mo(),K=Co(J,Z?"amp.download.tmp.exe":"amp.download.tmp");j.debug("Downloading binary update",{platform:B,version:Y,binaryUrl:G});try{let E=await nt0(V);if(!E.ok)throw Error(`Failed to fetch checksum: ${E.status}`);let z=(await E.text()).trim();j.debug("Downloading binary",{binaryUrl:G});let W=await nt0(G);if(!W.ok)throw Error(`Failed to download binary: ${W.status}`);let H=await iN5(W,(N,I)=>{Q?.(`Downloading update ${lN5(N,I)}`)}),q=D?dN5(H):H;if(hN5(K,q),oN5(K,z),!Z)Rb4(K,493);if(Z){if(sN5(U)){tN5(U,K);return}wo(K,U),j.info("Binary updated successfully",{binaryPath:U});return}wo(K,U),j.info("Binary updated successfully",{binaryPath:U})}catch(E){if(at0(K))try{ot0(K)}catch{}throw Error(`Binary update failed: ${E instanceof Error?E.message:String(E)}`)}}d0();import{execSync as st0}from"node:child_process";import{createHash as AI5}from"node:crypto";import{existsSync as GI,mkdirSync as QI5,readFileSync as xb4,renameSync as yb4,rmSync as Oo,writeFileSync as BI5}from"node:fs";import{homedir as $I5}from"node:os";import{join as TU}from"node:path";d0();import{spawn as eN5}from"node:child_process";function rt0(A){if(A=A.replace(/\/$/,""),!A.startsWith("http://")&&!A.startsWith("https://"))A=`https://${A}`;try{return new URL(A),A}catch{return j.warn(`Invalid registry URL: ${A}, falling back to npmjs.org`),"https://registry.npmjs.org"}}var YX0=null,Lo=null;function vb4(A){return new Promise((Q)=>{let B=eN5("npm",["config","get",A],{stdio:["ignore","pipe","ignore"],timeout:5000,shell:process.platform==="win32"}),$="";B.stdout.on("data",(J)=>{$+=J.toString()}),B.on("close",(J,Y)=>{if(J!==0||Y==="SIGTERM"){Q(null);return}let Z=$.trim();Q(Z&&Z!=="undefined"?Z:null)}),B.on("error",()=>{Q(null)})})}async function Rj(){if(YX0)return YX0;if(Lo)return Lo;Lo=(async()=>{let A=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(A)return rt0(A);let Q=await vb4("@sourcegraph:registry");if(Q)return rt0(Q);let B=await vb4("registry");if(B)return rt0(B);return"https://registry.npmjs.org"})();try{return YX0=await Lo,YX0}finally{Lo=null}}function JI5(){if(process.env.AMP_HOME)return process.env.AMP_HOME;let A=$I5();if(!A)throw Error("Cannot determine home directory. Set AMP_HOME environment variable to ~/.amp and try again.");return TU(A,".amp")}async function tt0(A,Q=300000){let B=new AbortController,$=setTimeout(()=>B.abort(),Q);try{let J=await fetch(A,{signal:B.signal});return clearTimeout($),J}catch(J){if(clearTimeout($),J instanceof Error&&J.name==="AbortError")throw Error(`Network timeout after ${Q}ms while fetching: ${A}`);throw J}}async function YI5(){let A=process.env.AMP_VERSION;if(A)return A;let Q=await Rj(),B=await tt0(`${Q}/@sourcegraph%2Famp`);if(!B.ok)throw Error("Failed to fetch package metadata from npm registry");let J=(await B.json())["dist-tags"]?.latest;if(!J)throw Error("Failed to find latest version in npm registry");return J}async function ZI5(A){let Q=await Rj(),B=await tt0(`${Q}/@sourcegraph%2Famp/${A}`);if(!B.ok)throw Error(`Failed to fetch metadata for version ${A}`);let $=await B.json(),J=$.dist?.tarball,Y=$.dist?.integrity;if(!J)throw Error(`Failed to find tarball URL for version ${A}`);return{tarballUrl:J,integrity:Y}}function FI5(A){if(!A)return null;let Q=A.match(/sha256-([A-Za-z0-9+/=]+)/);if(Q?.[1]){let $=Q[1];return{algorithm:"sha256",hash:Buffer.from($,"base64").toString("hex")}}let B=A.match(/sha512-([A-Za-z0-9+/=]+)/);if(B?.[1]){let $=B[1];return{algorithm:"sha512",hash:Buffer.from($,"base64").toString("hex")}}return null}function XI5(A,Q){if(!Q)return;let B=xb4(A),$=AI5(Q.algorithm);$.update(B);let J=$.digest("hex");if(J!==Q.hash)throw Error(`Checksum verification failed for ${A}
5284
+ Actual: ${J}`)}function Mo(){let A=_b4(),Q=Co(A,"bin"),B=process.platform==="win32";return Co(Q,B?"amp.exe":"amp")}async function rN5(){let A=`${it0}/cli-version.txt`,Q=await nt0(A);if(!Q.ok)throw Error(`Failed to fetch latest version: ${Q.status}`);return(await Q.text()).trim()}function jb4(A){return process.platform==="win32"?A.replace(/\\/g,"/").toLowerCase():A}function Tb4(A){let Q=pN5(A);return`${Q?A.slice(0,A.length-Q.length):A}.old${Q}`}function sN5(A){return jb4(process.execPath)===jb4(A)}function tN5(A,Q){let B=Tb4(A);if(at0(B))ot0(B);wo(A,B);try{wo(Q,A)}catch($){try{wo(B,A)}catch(J){throw Error(`Failed to install Windows binary update and restore original binary: ${J instanceof Error?J.message:String(J)}`)}throw $}j.info("Binary updated successfully",{binaryPath:A,oldBinaryPath:B})}function kb4(){if(process.platform!=="win32")return;let A=Tb4(process.execPath);if(!at0(A))return;try{ot0(A),j.debug("Removed previous Windows binary after successful restart",{oldBinaryPath:A})}catch(Q){j.debug("Failed to remove previous Windows binary after restart",{oldBinaryPath:A,error:Q})}}async function Sb4(A,Q){let B=aN5(),$=_b4();Ob4($);let J=Co($,"bin");Ob4(J);let Y=A||await rN5(),Z=B.startsWith("windows"),F=Z?`amp-${B}.exe`:`amp-${B}`,X=`${B}-amp.sha256`,D=`${it0}/${Y}/${F}.gz`,G=`${it0}/${Y}/${X}`,V=Mo(),U=Co(J,Z?"amp.download.tmp.exe":"amp.download.tmp");j.debug("Downloading binary update",{platform:B,version:Y,binaryUrl:D});try{let K=await nt0(G);if(!K.ok)throw Error(`Failed to fetch checksum: ${K.status}`);let E=(await K.text()).trim();j.debug("Downloading binary",{binaryUrl:D});let z=await nt0(D);if(!z.ok)throw Error(`Failed to download binary: ${z.status}`);let W=await iN5(z,(q,N)=>{Q?.(`Downloading update ${lN5(q,N)}`)}),H=dN5(W);if(gN5(U,H),oN5(U,E),!Z)Rb4(U,493);if(Z){if(sN5(V)){tN5(V,U);return}wo(U,V),j.info("Binary updated successfully",{binaryPath:V});return}wo(U,V),j.info("Binary updated successfully",{binaryPath:V})}catch(K){if(at0(U))try{ot0(U)}catch{}throw Error(`Binary update failed: ${K instanceof Error?K.message:String(K)}`)}}d0();import{execSync as st0}from"node:child_process";import{createHash as AI5}from"node:crypto";import{existsSync as GI,mkdirSync as QI5,readFileSync as xb4,renameSync as yb4,rmSync as Oo,writeFileSync as BI5}from"node:fs";import{homedir as $I5}from"node:os";import{join as TU}from"node:path";d0();import{spawn as eN5}from"node:child_process";function rt0(A){if(A=A.replace(/\/$/,""),!A.startsWith("http://")&&!A.startsWith("https://"))A=`https://${A}`;try{return new URL(A),A}catch{return j.warn(`Invalid registry URL: ${A}, falling back to npmjs.org`),"https://registry.npmjs.org"}}var YX0=null,Lo=null;function vb4(A){return new Promise((Q)=>{let B=eN5("npm",["config","get",A],{stdio:["ignore","pipe","ignore"],timeout:5000,shell:process.platform==="win32"}),$="";B.stdout.on("data",(J)=>{$+=J.toString()}),B.on("close",(J,Y)=>{if(J!==0||Y==="SIGTERM"){Q(null);return}let Z=$.trim();Q(Z&&Z!=="undefined"?Z:null)}),B.on("error",()=>{Q(null)})})}async function Rj(){if(YX0)return YX0;if(Lo)return Lo;Lo=(async()=>{let A=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(A)return rt0(A);let Q=await vb4("@sourcegraph:registry");if(Q)return rt0(Q);let B=await vb4("registry");if(B)return rt0(B);return"https://registry.npmjs.org"})();try{return YX0=await Lo,YX0}finally{Lo=null}}function JI5(){if(process.env.AMP_HOME)return process.env.AMP_HOME;let A=$I5();if(!A)throw Error("Cannot determine home directory. Set AMP_HOME environment variable to ~/.amp and try again.");return TU(A,".amp")}async function tt0(A,Q=300000){let B=new AbortController,$=setTimeout(()=>B.abort(),Q);try{let J=await fetch(A,{signal:B.signal});return clearTimeout($),J}catch(J){if(clearTimeout($),J instanceof Error&&J.name==="AbortError")throw Error(`Network timeout after ${Q}ms while fetching: ${A}`);throw J}}async function YI5(){let A=process.env.AMP_VERSION;if(A)return A;let Q=await Rj(),B=await tt0(`${Q}/@sourcegraph%2Famp`);if(!B.ok)throw Error("Failed to fetch package metadata from npm registry");let J=(await B.json())["dist-tags"]?.latest;if(!J)throw Error("Failed to find latest version in npm registry");return J}async function ZI5(A){let Q=await Rj(),B=await tt0(`${Q}/@sourcegraph%2Famp/${A}`);if(!B.ok)throw Error(`Failed to fetch metadata for version ${A}`);let $=await B.json(),J=$.dist?.tarball,Y=$.dist?.integrity;if(!J)throw Error(`Failed to find tarball URL for version ${A}`);return{tarballUrl:J,integrity:Y}}function FI5(A){if(!A)return null;let Q=A.match(/sha256-([A-Za-z0-9+/=]+)/);if(Q?.[1]){let $=Q[1];return{algorithm:"sha256",hash:Buffer.from($,"base64").toString("hex")}}let B=A.match(/sha512-([A-Za-z0-9+/=]+)/);if(B?.[1]){let $=B[1];return{algorithm:"sha512",hash:Buffer.from($,"base64").toString("hex")}}return null}function XI5(A,Q){if(!Q)return;let B=xb4(A),$=AI5(Q.algorithm);$.update(B);let J=$.digest("hex");if(J!==Q.hash)throw Error(`Checksum verification failed for ${A}
5285
5285
  Expected: ${Q.hash}
5286
5286
  Actual: ${J}`)}async function DI5(A,Q,B){let $=TU(Q,"package.tgz");j.debug("Downloading package from npm registry",{tarballUrl:A});let J=await tt0(A);if(!J.ok)throw Error("Failed to download package from npm registry");let Y=await J.arrayBuffer();BI5($,new Uint8Array(Y));let Z=FI5(B);XI5($,Z);let F=process.platform==="win32"&&!No();try{if(F)st0("where tar",{stdio:"pipe"});else st0("which tar",{stdio:"pipe"})}catch{throw Error("tar command not found. Please install tar to extract packages.")}try{st0(`tar -xzf "${$}" -C "${Q}"`,{stdio:"pipe"})}catch(X){throw Error(`Failed to extract tarball: ${X instanceof Error?X.message:String(X)}`)}Oo($)}function GI5(A,Q){let B=TU(A,"package"),$=TU(B,"dist","main.js"),J=TU(B,"package.json");if(!GI($)||!GI(J))return!0;try{return JSON.parse(xb4(J,"utf8")).version!==Q}catch{return!0}}async function fb4(A){let Q=JI5(),B=TU(Q,"package"),$=A||await YI5();if(!GI5(Q,$)){j.debug("Bootstrap installation is already up to date",{version:$});return}j.debug("Updating bootstrap installation",{version:$,ampHome:Q});let{tarballUrl:J,integrity:Y}=await ZI5($),Z=TU(Q,".package.staging");try{if(GI(Z))Oo(Z,{recursive:!0});QI5(Z,{recursive:!0}),await DI5(J,Z,Y);let F=TU(Z,"package");if(!GI(F))throw Error("package/ directory not found in npm tarball");let X=TU(F,"dist","main.js");if(!GI(X))throw Error("dist/main.js not found in extracted package");if(GI(B)){let D=TU(Q,".package.backup");if(GI(D))Oo(D,{recursive:!0});yb4(B,D)}yb4(F,B),Oo(Z,{recursive:!0}),j.debug("Bootstrap installation updated successfully",{version:$})}catch(F){if(GI(Z))Oo(Z,{recursive:!0});throw F}}d0();var et0="v1.3.8";function ub4(A){let Q=A.replace(/^v/,""),[B,$,J]=Q.split(".").map(Number);if(B===void 0||$===void 0||J===void 0)return;if(Number.isNaN(B)||Number.isNaN($)||Number.isNaN(J))return;return[B,$,J]}async function bb4(A){let{reason:Q,output:B}=await yD(A,["--version"]);if(Q!=="success"){j.error("Failed to get current Bun version",{output:B});return}let $=B.trim(),J=ub4($);if(!J){j.error("Failed to parse Bun version from output",{output:B});return}return J}function VI5(A,Q){for(let B=0;B<A.length;B++){if(A[B]<Q[B])return-1;if(A[B]>Q[B])return 1}return 0}function UI5(A,Q){return VI5(A,Q)<0}async function KI5(A,Q=300000){j.info("Running bun upgrade",{bunPath:A});let{reason:B,output:$}=await yD(A,["upgrade"],Q);if(B==="success"){j.info("Bun upgrade completed successfully");return}throw j.error("Failed to upgrade Bun",{reason:B,output:$}),Error(`Failed to upgrade Bun: ${B}`)}async function hb4(A){try{let Q=process.env.AMP_HOME;if(!Q)throw Error("AMP_HOME environment variable is not set");let B=`${Q}/bin/bun`,$=await bb4(B);if(!$)return j.warn("Unable to determine Bun version, skipping update"),!1;let J=ub4(et0);if(!J)throw Error(`Invalid EXPECTED_BUN_VERSION: ${et0}`);if(j.debug("Checking Bun version",{currentVersion:$,expectedVersion:J}),!UI5($,J))return!1;j.info("Updating Bun",{currentVersion:$.join("."),expectedMinimum:et0}),A?.("bun upgrade"),await KI5(B);let Y=await bb4(B);return j.info("Bun updated",{newVersion:Y}),!0}catch(Q){return j.warn("Failed to update Bun",{error:Q instanceof Error?Q.message:String(Q)}),!1}}async function jo(A,Q,B,$){let J=Q??null;if(!J)J=await DI();if(!J)J=await wb4();if(!J){if((process.argv[1]||"").includes("/nix/store/"))throw Error("Cannot update amp: this installation was not installed via npm/pnpm/yarn/bun and cannot be updated using the update command. Please use your system package manager or installation method to update amp.");throw Error("Could not detect which package manager was used to install Amp. Please specify one explicitly or ensure the package manager is available in PATH.")}if(j.debug("Using package manager for update",{packageManager:J,targetVersion:A}),J==="binary")try{await Sb4(A,$);return}catch(F){throw Error(`Binary update failed: ${F instanceof Error?F.message:String(F)}`)}if(J==="bootstrap")try{await fb4(A),await hb4(B);return}catch(F){throw Error(`Bootstrap update failed: ${F instanceof Error?F.message:String(F)}`)}if(J==="brew")return B?.("brew upgrade ampcode/tap/ampcode"),new Promise((F,X)=>{j.debug("Running update command",{packageManager:J,command:"brew"});let D=EE("brew",["upgrade","ampcode/tap/ampcode"],{stdio:["ignore","pipe","pipe"],shell:Ae0.platform()==="win32"}),G="",V="",U=!1;D.subscribe({next:(K)=>{if(K.stdout)V=K.stdout;if(K.stderr)G=K.stderr;if(K.exited&&!U)if(U=!0,K.exitCode===0)F();else{let E=G||V||"No output";X(Error(`brew upgrade ampcode/tap/ampcode failed with code ${K.exitCode}:
5287
5287
  ${E}`))}},error:(K)=>{if(!U)U=!0,X(Error(`Failed to spawn brew: ${K.message}`))},complete:()=>{if(!U)U=!0,F()}})});let[Y,Z]=Cb4(J,A);return B?.(`${Y} ${Z.join(" ")}`),new Promise((F,X)=>{j.debug("Running update command",{packageManager:J,command:Y,args:Z});let D="",G="",V=!1;EE(Y,Z,{stdio:["ignore","pipe","pipe"],shell:Ae0.platform()==="win32"}).subscribe({next:(K)=>{if(K.stdout)G=K.stdout;if(K.stderr)D=K.stderr;if(K.exited&&!V)if(V=!0,K.exitCode===0)F();else{let E=D||G||"No output",z=`${Y} ${Z.join(" ")} failed with code ${K.exitCode}:
5288
5288
  ${E}`;if(Y==="pnpm"&&E.includes("Unable to find the global bin directory"))z+=`
5289
5289
 
5290
5290
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
5291
- npm install -g @sourcegraph/amp`;X(Error(z))}},error:(K)=>{if(!V)V=!0,X(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,F()}})})}d0();d0();EN();async function ZX0(A,Q){let J=`${Q||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,Y=new AbortController,Z=setTimeout(()=>Y.abort(),5000);try{let F=await fetch(J,{signal:Y.signal});if(!F.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let X=await F.json(),D=X.version??X["dist-tags"]?.latest;if(!D)return{hasUpdate:!1,currentVersion:A,source:"npm"};let G=Ro(A,D),V=G<0,U,K;if(X.time){let E=X.time[A],z=X.time[D],W=Date.now();if(E)U=Math.floor((W-new Date(E).getTime())/3600000);if(z)K=Math.floor((W-new Date(z).getTime())/3600000)}return j.info("NPM version comparison",{currentVersion:A,latestVersion:D,compareResult:G,hasUpdate:V,currentVersionAge:U,latestVersionAge:K}),{hasUpdate:V,latestVersion:D,currentVersion:A,currentVersionAge:U,latestVersionAge:K,source:"npm"}}catch(F){return j.debug("Error checking npm version",{error:F}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var EI5="https://static.ampcode.com/cli/cli-version.txt";async function FX0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${EI5}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!$.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let J=(await $.text()).trim();if(!J||!/^\d+\.\d+\.\d+/.test(J))return{hasUpdate:!1,currentVersion:A,source:"bin"};let Y=Ro(A,J),Z=Y<0;return j.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return j.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var zI5=604800000;function gb4(A){if(!A)return null;let Q=typeof A==="number"?A:new Date(A).getTime();if(isNaN(Q))return null;let B=Date.now()-Q;if(B>zI5)return{ageMs:B};return null}function Ro(A,Q){let B=(Z)=>{let[F,X]=Z.split("-");return{parts:F?.split(".").map(Number)||[],label:X}},$=B(A),J=B(Q),Y=Math.max($.parts.length,J.parts.length);for(let Z=0;Z<Y;Z++){let F=$.parts[Z]||0,X=J.parts[Z]||0;if(F<X)return-1;if(F>X)return 1}if($.label===J.label)return 0;if(!$.label&&J.label)return 1;if($.label&&!J.label)return-1;if($.label&&J.label)return $.label<J.label?-1:1;return 0}function Qe0(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Q)return null;let B=parseInt(Q[1],10)*1000,$=Q[2],J=B!==0?oV(B):void 0;return{sha:$,age:J}}catch{return null}}M1();d0();import{readFile as WI5,realpath as HI5}from"node:fs/promises";import{homedir as qI5}from"node:os";import{dirname as mb4,join as Be0}from"node:path";async function pb4(A){switch(A){case"binary":case"brew":return NI5(Mo());case"npm":case"pnpm":case"yarn":case"bun":return II5();case"bootstrap":return wI5()}}async function NI5(A){let Q=await yD(A,["--version"],5000);if(Q.reason!=="success")return j.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function II5(){try{let A=process.argv[1];if(!A)return null;let Q=await HI5(A),B=mb4(mb4(Q));return await db4(Be0(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function wI5(){try{let A=process.env.AMP_HOME??Be0(qI5(),".amp");return await db4(Be0(A,"package","package.json"))}catch(A){return j.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function db4(A){let Q=await WI5(A,"utf8"),B=JSON.parse(Q);if(B.name!=="@sourcegraph/amp")return j.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var CI5=3600000,MI5=5000;function $e0(A,Q,B={}){let $=new m4,J=$.pipe(sA({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??CI5,F=!1,X=()=>{F=!0};return setImmediate(async()=>{let D=j.getChild("update");if(Y>0){if(await eV(Y),F)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!F){let U=await LI5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await eV(MI5),F)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!F){let z=Math.min(K,E);await eV(z),E-=z}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:X}}async function LI5(A,Q,B,$){let J={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return B.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),J.stop=!0,J;let Y=await Q.get("updates.mode");if(Y==="disabled")return B.debug("checking disabled"),J.stop=!0,J;let Z=await DI(),F=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:F});let X;if(F)X=await FX0(A);else{let V=await Rj();X=await ZX0(A,V)}if(!(X.latestVersion&&X.hasUpdate))return B.debug("no update available"),J;let D=(V)=>{$.next(V),J.emittedVisibleState=!0};if(Z){let V=await pb4(Z);if(V&&Ro(V,X.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:X.latestVersion}),J.updatedTo=V,Ro(A,V)<0){let U=await Sz(V),K={from:A,to:V,externallyUpdated:!0,...U};if(U.status==="same")B.info("on-disk already updated by another instance",K),D("updated");else B.warn("on-disk already updated by another instance, with PATH warning",K),D("updated-with-warning")}return J}}let G=()=>{if(X.currentVersionAge!==void 0&&X.latestVersionAge!==void 0){let V=X.currentVersionAge-X.latestVersionAge,U=0.5;if(Math.abs(V)<0.5)return B.debug("versions too close together, suppressing update warning",{currentVersionAge:X.currentVersionAge,latestVersionAge:X.latestVersionAge,ageDifferenceHours:V}),!0}return!1};if(!Y)Y=Z==="pnpm"?"warn":"auto",B.debug("no configured update mode; selected default based on package manager",{packageManager:Z,mode:Y});if(Z==="brew"){if(!G())D("update-available-brew");return J}if(Z==="binary"&&process.execPath!==Mo()){if(B.debug("non-standard binary path, showing warning"),!G())D("update-available-unrecognized-path");return J}if(Y==="warn"){if(!G())D("update-available");return J}if(!Z){if(B.debug("auto-update not supported, falling back to warn mode"),!G())D("update-available");return J}if(Z==="binary"&&process.platform==="win32"){if(B.debug("binary auto-update not supported on Windows, falling back to warn mode"),!G())D("update-available");return J}try{await jo(X.latestVersion,Z),J.updatedTo=X.latestVersion;let V=await Sz(X.latestVersion),U={from:X.currentVersion,to:X.latestVersion,...V};if(V.status==="same")B.info("success",U),D("updated");else B.warn("success with warning",U),D("updated-with-warning")}catch(V){D("update-error")}return J}catch(Y){return B.debug("check failed",{error:Y}),J}}EN();import{stderr as xD}from"node:process";function cb4(A){let Q=new pN().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($)=>{await dt0($.force||!1,$.verbose||!1,"0.0.1778476494-g8a21dc"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new pN("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($)=>{await jI5($.targetVersion)});A.addCommand(B)}function OI5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
5291
+ npm install -g @sourcegraph/amp`;X(Error(z))}},error:(K)=>{if(!V)V=!0,X(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,F()}})})}d0();d0();EN();async function ZX0(A,Q){let J=`${Q||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,Y=new AbortController,Z=setTimeout(()=>Y.abort(),5000);try{let F=await fetch(J,{signal:Y.signal});if(!F.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let X=await F.json(),D=X.version??X["dist-tags"]?.latest;if(!D)return{hasUpdate:!1,currentVersion:A,source:"npm"};let G=Ro(A,D),V=G<0,U,K;if(X.time){let E=X.time[A],z=X.time[D],W=Date.now();if(E)U=Math.floor((W-new Date(E).getTime())/3600000);if(z)K=Math.floor((W-new Date(z).getTime())/3600000)}return j.info("NPM version comparison",{currentVersion:A,latestVersion:D,compareResult:G,hasUpdate:V,currentVersionAge:U,latestVersionAge:K}),{hasUpdate:V,latestVersion:D,currentVersion:A,currentVersionAge:U,latestVersionAge:K,source:"npm"}}catch(F){return j.debug("Error checking npm version",{error:F}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var EI5="https://static.ampcode.com/cli/cli-version.txt";async function FX0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${EI5}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!$.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let J=(await $.text()).trim();if(!J||!/^\d+\.\d+\.\d+/.test(J))return{hasUpdate:!1,currentVersion:A,source:"bin"};let Y=Ro(A,J),Z=Y<0;return j.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return j.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var zI5=604800000;function gb4(A){if(!A)return null;let Q=typeof A==="number"?A:new Date(A).getTime();if(isNaN(Q))return null;let B=Date.now()-Q;if(B>zI5)return{ageMs:B};return null}function Ro(A,Q){let B=(Z)=>{let[F,X]=Z.split("-");return{parts:F?.split(".").map(Number)||[],label:X}},$=B(A),J=B(Q),Y=Math.max($.parts.length,J.parts.length);for(let Z=0;Z<Y;Z++){let F=$.parts[Z]||0,X=J.parts[Z]||0;if(F<X)return-1;if(F>X)return 1}if($.label===J.label)return 0;if(!$.label&&J.label)return 1;if($.label&&!J.label)return-1;if($.label&&J.label)return $.label<J.label?-1:1;return 0}function Qe0(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Q)return null;let B=parseInt(Q[1],10)*1000,$=Q[2],J=B!==0?oV(B):void 0;return{sha:$,age:J}}catch{return null}}M1();d0();import{readFile as WI5,realpath as HI5}from"node:fs/promises";import{homedir as qI5}from"node:os";import{dirname as mb4,join as Be0}from"node:path";async function pb4(A){switch(A){case"binary":case"brew":return NI5(Mo());case"npm":case"pnpm":case"yarn":case"bun":return II5();case"bootstrap":return wI5()}}async function NI5(A){let Q=await yD(A,["--version"],5000);if(Q.reason!=="success")return j.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function II5(){try{let A=process.argv[1];if(!A)return null;let Q=await HI5(A),B=mb4(mb4(Q));return await db4(Be0(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function wI5(){try{let A=process.env.AMP_HOME??Be0(qI5(),".amp");return await db4(Be0(A,"package","package.json"))}catch(A){return j.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function db4(A){let Q=await WI5(A,"utf8"),B=JSON.parse(Q);if(B.name!=="@sourcegraph/amp")return j.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var CI5=3600000,MI5=5000;function $e0(A,Q,B={}){let $=new m4,J=$.pipe(sA({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??CI5,F=!1,X=()=>{F=!0};return setImmediate(async()=>{let D=j.getChild("update");if(Y>0){if(await eV(Y),F)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!F){let U=await LI5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await eV(MI5),F)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!F){let z=Math.min(K,E);await eV(z),E-=z}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:X}}async function LI5(A,Q,B,$){let J={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return B.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),J.stop=!0,J;let Y=await Q.get("updates.mode");if(Y==="disabled")return B.debug("checking disabled"),J.stop=!0,J;let Z=await DI(),F=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:F});let X;if(F)X=await FX0(A);else{let V=await Rj();X=await ZX0(A,V)}if(!(X.latestVersion&&X.hasUpdate))return B.debug("no update available"),J;let D=(V)=>{$.next(V),J.emittedVisibleState=!0};if(Z){let V=await pb4(Z);if(V&&Ro(V,X.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:X.latestVersion}),J.updatedTo=V,Ro(A,V)<0){let U=await Sz(V),K={from:A,to:V,externallyUpdated:!0,...U};if(U.status==="same")B.info("on-disk already updated by another instance",K),D("updated");else B.warn("on-disk already updated by another instance, with PATH warning",K),D("updated-with-warning")}return J}}let G=()=>{if(X.currentVersionAge!==void 0&&X.latestVersionAge!==void 0){let V=X.currentVersionAge-X.latestVersionAge,U=0.5;if(Math.abs(V)<0.5)return B.debug("versions too close together, suppressing update warning",{currentVersionAge:X.currentVersionAge,latestVersionAge:X.latestVersionAge,ageDifferenceHours:V}),!0}return!1};if(!Y)Y=Z==="pnpm"?"warn":"auto",B.debug("no configured update mode; selected default based on package manager",{packageManager:Z,mode:Y});if(Z==="brew"){if(!G())D("update-available-brew");return J}if(Z==="binary"&&process.execPath!==Mo()){if(B.debug("non-standard binary path, showing warning"),!G())D("update-available-unrecognized-path");return J}if(Y==="warn"){if(!G())D("update-available");return J}if(!Z){if(B.debug("auto-update not supported, falling back to warn mode"),!G())D("update-available");return J}if(Z==="binary"&&process.platform==="win32"){if(B.debug("binary auto-update not supported on Windows, falling back to warn mode"),!G())D("update-available");return J}try{await jo(X.latestVersion,Z),J.updatedTo=X.latestVersion;let V=await Sz(X.latestVersion),U={from:X.currentVersion,to:X.latestVersion,...V};if(V.status==="same")B.info("success",U),D("updated");else B.warn("success with warning",U),D("updated-with-warning")}catch(V){D("update-error")}return J}catch(Y){return B.debug("check failed",{error:Y}),J}}EN();import{stderr as xD}from"node:process";function cb4(A){let Q=new pN().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($)=>{await dt0($.force||!1,$.verbose||!1,"0.0.1778480457-g5efd50"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new pN("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($)=>{await jI5($.targetVersion)});A.addCommand(B)}function OI5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
5292
5292
  `),$=!1,B=0}function Y(Z){if(!Q)return;let F=Z.padEnd(B," ");A.write(`\r${F}`),$=!0,B=F.length}return{flushProgressLine:J,renderProgress:Y}}async function jI5(A){let B=process.platform==="win32"&&jj()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:$,renderProgress:J}=OI5(xD);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")xD.write(n0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
5293
5293
 
5294
5294
  `));try{if(!A){xD.write(n0.blue(`Checking for updates...
5295
- `));let F=!1,X;if(jj()){let D=await FX0("0.0.1778476494-g8a21dc");F=D.hasUpdate,X=D.latestVersion}else{let D=await Rj(),G=await ZX0("0.0.1778476494-g8a21dc",D);F=G.hasUpdate,X=G.latestVersion}if(!F){let D=Qe0("0.0.1778476494-g8a21dc"),G=D?.age?`released ${D.age} ago`:`built ${oV(new Date("2026-05-11T05:19:01.767Z"))} ago`;xD.write(n0.green(`✓ Amp is already up to date on version ${"0.0.1778476494-g8a21dc"} (${G})
5296
- `));let V=await Sz("0.0.1778476494-g8a21dc",B);if(V.warning)xD.write(`
5295
+ `));let F=!1,X;if(jj()){let D=await FX0("0.0.1778480457-g5efd50");F=D.hasUpdate,X=D.latestVersion}else{let D=await Rj(),G=await ZX0("0.0.1778480457-g5efd50",D);F=G.hasUpdate,X=G.latestVersion}if(!F){let D=Qe0("0.0.1778480457-g5efd50"),G=D?.age?`released ${D.age} ago`:`built ${oV(new Date("2026-05-11T06:24:41.556Z"))} ago`;xD.write(n0.green(`✓ Amp is already up to date on version ${"0.0.1778480457-g5efd50"} (${G})
5296
+ `));let V=await Sz("0.0.1778480457-g5efd50",B);if(V.warning)xD.write(`
5297
5297
  `+n0.yellow(V.warning)+`
5298
5298
  `);process.exit(0)}if(!X)xD.write(n0.yellow("[WARN] could not find latest version")),process.exit(0);A=X}xD.write(n0.blue(`Updating to version ${A}...
5299
5299
  `)),await jo(A,void 0,(F)=>{$(),xD.write(n0.dim(`Running: ${F}
@@ -5700,7 +5700,7 @@ ${$}`).join(`
5700
5700
  `).length,J=new p({text:new C(A,new v({color:B}))});if($<=IG0)return J;return new U0({width:1/0,height:IG0,child:new ZQ({autofocus:!1,controller:Q,child:J})})}function Ny5(){return new Map([[C1.key("PageUp"),new wG0],[C1.key("PageDown"),new k41],[C1.ctrl("u"),new wG0],[C1.shift("Home"),new S41],[C1.shift("End"),new v41]])}function Iy5(A,Q,B){return Math.max(Q,Math.min(A,B))}var y41=8,ni4=1,ai4=y41-1;class x41 extends P4{}class f41 extends P4{}class CG0 extends P4{}class MG0 extends P4{}class b41 extends P4{}class u41 extends P4{}class h41 extends T0{props;constructor(A){super(A.key===void 0?{}:{key:A.key});this.props=A}createState(){return new oi4}}class oi4 extends _0{messageScroll=new hA;initState(){super.initState(),this.messageScroll.followMode=!1,this.messageScroll.jumpTo(0)}dispose(){this.messageScroll.dispose(),super.dispose()}build(A){let Q=this.widget.props,B=wy5(Q,this.messageScroll),$=Cy5(Q.options.message),J=$?new l4({actions:this.buildScrollActions(),child:new $5({debugLabel:"NeoSelectDialogScrollShortcuts",shortcuts:Ly5(),child:B})}):B,Y=[{keys:["↑/↓","j/k"],label:"move"},{keys:["Enter"],label:"select"}];if($)Y.push({keys:["Ctrl+E","Ctrl+Y"],label:"scroll"});return Y.push({keys:["Esc"],label:"cancel"}),new yA({header:Q.options.title,minWidth:64,maxWidth:80,footer:Y,autofocus:!1,onDismiss:Q.onCancel,child:J})}buildScrollActions(){let A=(Q)=>{let B=Oy5(this.messageScroll.offset+Q,0,this.messageScroll.maxScrollExtent);this.messageScroll.jumpTo(B)};return new Map([[x41,new d1(()=>A(-ni4))],[f41,new d1(()=>A(ni4))],[CG0,new d1(()=>A(-ai4))],[MG0,new d1(()=>A(ai4))],[b41,new d1(()=>this.messageScroll.jumpTo(0))],[u41,new d1(()=>this.messageScroll.jumpTo(this.messageScroll.maxScrollExtent))]])}}function wy5(A,Q){let B=A.options.options.map(($)=>({value:$,label:$}));return new F9({options:B,body:My5(A.options.message,Q),onSelect:($)=>{if($===null){A.onCancel();return}A.onSelect($)},padding:K0.all(0),showBorder:!1,showDismissalMessage:!1,enableMouseInteraction:!1})}function Cy5(A){if(A===void 0)return!1;return A.split(`
5701
5701
  `).length>y41}function My5(A,Q){if(A===void 0)return;let B=A.split(`
5702
5702
  `).length,$=Math.min(B,y41);return new U0({width:1/0,height:$,child:new ZQ({autofocus:!1,controller:Q,child:new p({text:new C(A)})})})}function Ly5(){return new Map([[C1.key("PageUp"),new CG0],[C1.key("PageDown"),new MG0],[C1.ctrl("u"),new CG0],[C1.ctrl("d"),new MG0],[C1.ctrl("y"),new x41],[C1.ctrl("e"),new f41],[C1.shift("Home"),new b41],[C1.shift("End"),new u41]])}function Oy5(A,Q,B){return Math.max(Q,Math.min(A,B))}class g41{options;unregisterPluginCommands=null;pluginCommandSubscriptions=[];pluginErrorToastKeys=new Set;activeDialog=null;queuedDialogs=[];statusItems=new Map;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.cancelPendingDialogs(),this.statusItems.clear(),this.clearPluginPlatformStatusHandlers()}hasBlockingDialog(){return this.activeDialog!==null}buildDialogLayers(){let A=this.activeDialog;if(!A)return[];switch(A.kind){case"input":return[new Vs({key:new xz(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 T41({key:new xz(A),options:A.options,onConfirm:()=>this.resolveConfirmDialog(A,!0),onCancel:()=>this.resolveConfirmDialog(A,!1)})];case"select":return[new h41({key:new xz(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.neoContext.pluginPlatform;if(!A)return;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.neoContext.observerOnly?async()=>{throw Error("thread.append is only available from an executor-owned plugin runtime")}:this.options.appendToThread,A.showInputDialog=this.showInputDialog,A.showConfirmDialog=this.showConfirmDialog,A.showSelectDialog=this.showSelectDialog,A.createStatusItemHandler=this.createStatusItem,A.updateStatusItemHandler=this.updateStatusItem,A.removeStatusItemHandler=this.removeStatusItem}clearPluginPlatformStatusHandlers(){let A=this.options.neoContext.pluginPlatform;if(!A)return;if(A.createStatusItemHandler===this.createStatusItem)A.createStatusItemHandler=null;if(A.updateStatusItemHandler===this.updateStatusItem)A.updateStatusItemHandler=null;if(A.removeStatusItemHandler===this.removeStatusItem)A.removeStatusItemHandler=null}subscribePluginCommands(){let A=this.options.neoContext.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 B=A.map(($)=>this.createPluginCommand($)).map(($)=>this.options.commandRegistry.register($));this.unregisterPluginCommands=()=>{for(let $ of B)$()}}showNewPluginErrorToasts(A){let Q=new Set;for(let B of A){if(B.status!=="error")continue;if(id(B.errorMessage))continue;let $=`${B.uri.toString()}
5703
- ${B.errorMessage??""}`;if(Q.add($),this.pluginErrorToastKeys.has($))continue;this.options.toastController.show(this.formatPluginErrorToast(B),"error",8000)}this.pluginErrorToastKeys=Q}removeInactivePluginStatusItems(A){let Q=new Set(A.filter(($)=>$.status==="active").map(($)=>$.uri.toString())),B=[];for(let[$,J]of this.statusItems){if(Q.has(J.pluginURI))continue;B.push($)}if(B.length===0)return;this.updateStatusItemState(()=>{for(let $ of B)this.statusItems.delete($)})}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.neoContext.logFilePath}`}createPluginCommand(A){return{noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,keywords:["plugin",A.pluginName,A.id],status:{type:"enabled"},run:async(Q,B,$)=>{$();try{await this.options.neoContext.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(J){j.error("Neo plugin command failed",{error:J,command:A}),this.options.toastController.show(J instanceof Error?J.message:String(J),"error",5000)}}}}showInputDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(void 0);return}this.enqueueDialog({kind:"input",options:A,resolve:Q})})};showConfirmDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(!1);return}this.enqueueDialog({kind:"confirm",options:A,resolve:Q})})};showSelectDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(void 0);return}this.enqueueDialog({kind:"select",options:A,resolve:Q})})};createStatusItem=(A,Q,B)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let $=this.statusItemKey(A,Q),J={pluginURI:A,id:Q};if(B!==void 0)J.value=B;this.statusItems.set($,J)})};updateStatusItem=(A,Q,B)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.set(this.statusItemKey(A,Q),{pluginURI:A,id:Q,value:B})})};removeStatusItem=(A,Q)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.delete(this.statusItemKey(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=[];for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}enqueueDialog(A){if(this.activeDialog){this.queuedDialogs.push(A);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A})}resolveInputDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}resolveConfirmDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}resolveSelectDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}}Wl();L2();import{readFile as jy5}from"node:fs/promises";import m41 from"node:os";function Ry5(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function ri4(A,Q){try{return{path:Q,contents:Sh0(await jy5(A,"utf8"))}}catch{return null}}async function si4(A,Q){let B=[],$=Ry5(),J=await DA.getThread({thread:Q},{config:A.configService}),Y=J.ok?J.result.thread.data:null;B.push({path:`${$}/thread.json`,contents:JSON.stringify($J(Y),null,2)});let Z=await ri4(Dx(Q),`${$}/logs/${Q}.log`);if(Z)B.push(Z);let F=await ri4(A.settingsFilePath,`${$}/settings/global.json`);if(F)B.push(F);let X=await DI()??"unknown",D=await DA.sendReport({threadID:Q,files:B,metadata:{clientVersion:"0.0.1778476494-g8a21dc",clientOS:`${m41.platform()} ${m41.release()} ${m41.arch()}`,installMethod:X}},{config:A.configService});if(!D.ok)throw Error(`Failed to submit report: ${D.error.message}`);return D.result.reportID}class p41{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 B=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.backStack.pop();this.forwardStack.push(Q)}}}}d0();E9();L2();async function ti4(A,Q,B){let $;switch(B){case"private":$="This thread's visibility has been updated to private";break;case"workspace":$="This thread's visibility has been updated to workspace";break;case"group":$="This thread's visibility has been updated to group";break;case"unlisted":$="This thread's visibility has been updated to unlisted. Anyone on the Internet with the link can view it.";break;case"public":$="This thread's visibility has been updated to public. Anyone on the Internet can see it on your public profile, and it is publicly searchable.";break}try{let J=await DA.setThreadMeta({thread:Q,meta:wJ(B)},{config:A.configService});if(!J.ok)throw Error(J.error.message);let Y=!1;if(B!=="private"){let F=PB(new URL(A.ampURL),Q).toString();try{await C4.instance.tuiInstance.clipboard.writeText(F),Y=!0}catch(X){j.error("Failed to copy thread URL after visibility update",{error:X})}}let Z=Y?`${$} Link copied to clipboard.`:$;return new tQ(Z)}catch(J){let Y=J instanceof Error?J.message:String(J);if(Y.includes("no-workspace"))return Error("You are not a member of any workspace.");if(Y.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(Y.includes("no-groups"))return Error("You are not a member of any groups.");return j.error("Unexpected failure to update thread visibility",{error:J}),Error(`Failed to update thread visibility for ${Q}`)}}class LG0 extends q5{offstage;constructor({key:A,offstage:Q=!0,child:B}){super({key:A,child:B});this.offstage=Q}createRenderObject(){return new d41(this.offstage)}updateRenderObject(A){if(A instanceof d41)A.offstage=this.offstage}}class d41 extends J4{_offstage;constructor(A){super();this._offstage=A}get offstage(){return this._offstage}set offstage(A){if(A===this._offstage)return;this._offstage=A,this.markNeedsLayout()}getMinIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicWidth(A)??0}getMaxIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicWidth(A)??0}getMinIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicHeight(A)??0}getMaxIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicHeight(A)??0}performLayout(){let A=this._lastConstraints;q4(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let B=A.constrain(Q.size.width,Q.size.height);this.setSize(B.width,B.height),Q.setOffset(0,0)}else{let B=A.smallest;this.setSize(B.width,B.height)}super.performLayout()}paint(A,Q,B){if(this._offstage)return;super.paint(A,Q,B)}hitTest(A,Q,B,$){if(this._offstage)return!1;return super.hitTest(A,Q,B,$)}}class c41{_state=null;_attach(A){this._state=A}_detach(){this._state=null}push(A){this._state?.push(A)}pushWithDismiss(A){this._state?.pushWithDismiss(A)}pop(){return this._state?.pop()??!1}get canPop(){return this._state?.canPop??!1}}class l41 extends T0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new ei4}}class ei4 extends _0{entries=[];initState(){this.widget.controller._attach(this)}didUpdateWidget(A){if(A.controller!==this.widget.controller)A.controller._detach(),this.widget.controller._attach(this)}dispose(){this.widget.controller._detach(),super.dispose()}push(A){let Q=new vj,B=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:B})})}pushWithDismiss(A){let Q=new vj,B=this.makeScopedDismiss(Q),$=A(B);this.setState(()=>{this.entries.push({key:Q,widget:$,dismiss:B})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new LG0({offstage:this.entries.length>0,child:this.widget.root}));for(let B=0;B<this.entries.length;B++){let $=this.entries[B],J=B===this.entries.length-1,Y=J?new n4({autofocus:!0,debugLabel:`ModalStackEntry[${B}]`,onKey:(Z)=>{if(Z.key!=="Escape")return"ignored";return $.dismiss(),"handled"},child:$.widget}):$.widget;Q.push(new LG0({key:$.key,offstage:!J,child:Y}))}return new QA({fit:"expand",children:Q})}}class n41 extends q1{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter(($)=>$.status.type!=="hidden"),B=Py5(Q);return new yA({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:K0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new u6({items:Q,showBorder:!1,getLabel:($)=>{let J=i41($);return $.keywords&&$.keywords.length>0?`${J} ${$.keywords.join(" ").toLowerCase()}`:J},sortItems:($,J,Y)=>{if(Y===""){let G=$.item.status.type==="disabled"?1:0,V=J.item.status.type==="disabled"?1:0;if(G!==V)return G-V;let U=$.item.sortBoost??0,K=J.item.sortBoost??0;if(U!==K)return K-U;let E=$.item.noun?.toLowerCase()??"",z=J.item.noun?.toLowerCase()??"";if(E!==z)return E<z?-1:1;return 0}let Z=tj($.item.verb.toLowerCase(),Y),F=tj(J.item.verb.toLowerCase(),Y);if(Z!==F)return F-Z;let X=tj(i41($.item),Y),D=tj(i41(J.item),Y);if(X!==D)return D-X;return J.score-$.score},isItemDisabled:($)=>$.status.type==="disabled",buildDisabledReasonWidget:($,J)=>{if($.status.type!=="disabled")return;let{colors:Y}=P0.of(J);return new p({text:new C($.status.reason,new v({color:Y.mutedForeground,dim:!0})),textAlign:"center"})},renderItem:($,J,Y,Z)=>new An4({command:$,isSelected:J,isDisabled:Y,categoryWidth:B,buildContext:Z}),onAccept:($)=>{this.props.onAccept($)},onDismiss:this.props.onDismiss})})}}class An4 extends q1{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:B,isDisabled:$,categoryWidth:J,buildContext:Y}=this.props,Z=P0.of(Y),{colors:F,app:X}=Z,D=B?X.selectionBackground:void 0,G=B?X.selectionForeground:F.foreground,V=B?G:F.mutedForeground,U=new p({text:new C(Q.noun?.toLowerCase()??"",new v({color:V,dim:$||!B})),textAlign:"right"}),K=[new C(Q.verb.toLowerCase(),new v({color:G,bold:!0,dim:$}))];if($)K.push(new C(" (unavailable)",new v({color:G,dim:!0})));let E=p.spans(K),z=[{child:U,fixedWidth:J},{child:E,expanded:!0}];if(Q.shortcut)z.push({child:_y5(Q.shortcut,Z,$)});return new Qn4({columns:z,padding:K0.horizontal(1),backgroundColor:D})}}function i41(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function Py5(A){return A.reduce((Q,B)=>{return B.noun?Math.max(Q,y4(B.noun)):Q},0)}function _y5(A,Q,B){let{colors:$,app:J}=Q,Y=new v({color:$.mutedForeground,dim:B}),Z=[];for(let F of A.modifiers()){if(Z.length>0)Z.push(new C(" ",Y));Z.push(new C(F,new v({color:J.keybind,bold:!0,dim:B})))}if(Z.length>0)Z.push(new C(" ",Y));return Z.push(new C(A.key,new v({color:J.keybind,bold:!0,dim:B}))),p.spans(Z)}class Qn4 extends q1{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:B=2,padding:$,backgroundColor:J}=this.props,Y=[];for(let F=0;F<Q.length;F++){let X=Q[F];if(F>0&&B>0)Y.push(new U0({width:B}));if(X.fixedWidth!==void 0)Y.push(new U0({width:X.fixedWidth,child:X.child}));else if(X.expanded)Y.push(new P1({child:X.child}));else Y.push(X.child)}let Z=new r0({crossAxisAlignment:"start",children:Y});if(!$&&!J)return Z;return new g0({decoration:J?{color:J}:void 0,padding:$,child:Z})}}class a41{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#B(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#B()}}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#B(){for(let A of this.#Q)A()}}class $Z extends H6{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=$Z.maybeOf(A);if(!Q)throw Error("No NeoCommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType($Z)?.commandRegistry??null}}class o41 extends T0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new Bn4}}class Bn4 extends _0{modalStack=new c41;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=$Z.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=$Z.of(A).commands,B=new n41({commands:Q,onAccept:($)=>{$.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new l41({root:B,controller:this.modalStack})}}var r41=[{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"]},{input:"S",keys:["Alt"]}]},{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"]}]}],s41=[{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 OG0 extends q1{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let B=s1.of(A).size.width,$=50,J=B<50,Y=[];for(let Z of this.items){let[F,X]=this.renderRow(Z),D;if(J)D=new x0({crossAxisAlignment:"start",mainAxisSize:"min",children:[F,new f0({padding:K0.only({left:4}),child:X})]});else D=new r0({crossAxisAlignment:"start",children:[new P1({flex:1,child:F}),new U0({width:1}),new P1({flex:1,child:X})]});Y.push(new f0({padding:K0.horizontal(6),child:D}))}return new x0({crossAxisAlignment:"start",mainAxisSize:"min",children:Y})}}class t41 extends T0{commands;submitOnEnter;constructor({key:A,commands:Q,submitOnEnter:B}){super(A?{key:A}:{});this.commands=Q,this.submitOnEnter=B??!0}createState(){return new $n4}}class $n4 extends _0{scrollController;initState(){this.scrollController=new hA,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0)}dispose(){}build(A){let B=j1.of(A).colorScheme,J=P0.of(A).app,Y=s1.of(A),Z=new v({color:B.primary,bold:!0}),F=new v({color:B.secondary,bold:!0}),X=new v({color:J.keybind}),D=new v({color:J.command}),G=new v({color:B.foreground}),V=new v({color:B.foreground}),U=Y.size.width,K=Y.size.height,E=U-4,z=K-4,W=Math.max(40,Math.min(80,E)),H=new Set(["permissions-disable"]),N=[...this.widget.commands.filter((L)=>{let P=L.noun?.toLowerCase();return P!=="dev"&&P!=="debug"&&!L.id.startsWith("debug-")&&!H.has(L.id)})].sort((L,P)=>{let T=(L.noun??"").toLowerCase(),k=(P.noun??"").toLowerCase(),x=T.localeCompare(k);if(x!==0)return x;let h=L.verb.toLowerCase(),f=P.verb.toLowerCase(),S=h.localeCompare(f);if(S!==0)return S;return L.id.localeCompare(P.id)}),I=new vA({autofocus:!0,controller:this.scrollController,child:new g0({constraints:new w1(W,W,0,Number.POSITIVE_INFINITY),child:new x0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new o1({child:new p({text:new C(`Amp CLI - Help & Keyboard Shortcuts
5703
+ ${B.errorMessage??""}`;if(Q.add($),this.pluginErrorToastKeys.has($))continue;this.options.toastController.show(this.formatPluginErrorToast(B),"error",8000)}this.pluginErrorToastKeys=Q}removeInactivePluginStatusItems(A){let Q=new Set(A.filter(($)=>$.status==="active").map(($)=>$.uri.toString())),B=[];for(let[$,J]of this.statusItems){if(Q.has(J.pluginURI))continue;B.push($)}if(B.length===0)return;this.updateStatusItemState(()=>{for(let $ of B)this.statusItems.delete($)})}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.neoContext.logFilePath}`}createPluginCommand(A){return{noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,keywords:["plugin",A.pluginName,A.id],status:{type:"enabled"},run:async(Q,B,$)=>{$();try{await this.options.neoContext.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(J){j.error("Neo plugin command failed",{error:J,command:A}),this.options.toastController.show(J instanceof Error?J.message:String(J),"error",5000)}}}}showInputDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(void 0);return}this.enqueueDialog({kind:"input",options:A,resolve:Q})})};showConfirmDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(!1);return}this.enqueueDialog({kind:"confirm",options:A,resolve:Q})})};showSelectDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(void 0);return}this.enqueueDialog({kind:"select",options:A,resolve:Q})})};createStatusItem=(A,Q,B)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let $=this.statusItemKey(A,Q),J={pluginURI:A,id:Q};if(B!==void 0)J.value=B;this.statusItems.set($,J)})};updateStatusItem=(A,Q,B)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.set(this.statusItemKey(A,Q),{pluginURI:A,id:Q,value:B})})};removeStatusItem=(A,Q)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.delete(this.statusItemKey(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=[];for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}enqueueDialog(A){if(this.activeDialog){this.queuedDialogs.push(A);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A})}resolveInputDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}resolveConfirmDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}resolveSelectDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}}Wl();L2();import{readFile as jy5}from"node:fs/promises";import m41 from"node:os";function Ry5(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function ri4(A,Q){try{return{path:Q,contents:Sh0(await jy5(A,"utf8"))}}catch{return null}}async function si4(A,Q){let B=[],$=Ry5(),J=await DA.getThread({thread:Q},{config:A.configService}),Y=J.ok?J.result.thread.data:null;B.push({path:`${$}/thread.json`,contents:JSON.stringify($J(Y),null,2)});let Z=await ri4(Dx(Q),`${$}/logs/${Q}.log`);if(Z)B.push(Z);let F=await ri4(A.settingsFilePath,`${$}/settings/global.json`);if(F)B.push(F);let X=await DI()??"unknown",D=await DA.sendReport({threadID:Q,files:B,metadata:{clientVersion:"0.0.1778480457-g5efd50",clientOS:`${m41.platform()} ${m41.release()} ${m41.arch()}`,installMethod:X}},{config:A.configService});if(!D.ok)throw Error(`Failed to submit report: ${D.error.message}`);return D.result.reportID}class p41{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 B=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.backStack.pop();this.forwardStack.push(Q)}}}}d0();E9();L2();async function ti4(A,Q,B){let $;switch(B){case"private":$="This thread's visibility has been updated to private";break;case"workspace":$="This thread's visibility has been updated to workspace";break;case"group":$="This thread's visibility has been updated to group";break;case"unlisted":$="This thread's visibility has been updated to unlisted. Anyone on the Internet with the link can view it.";break;case"public":$="This thread's visibility has been updated to public. Anyone on the Internet can see it on your public profile, and it is publicly searchable.";break}try{let J=await DA.setThreadMeta({thread:Q,meta:wJ(B)},{config:A.configService});if(!J.ok)throw Error(J.error.message);let Y=!1;if(B!=="private"){let F=PB(new URL(A.ampURL),Q).toString();try{await C4.instance.tuiInstance.clipboard.writeText(F),Y=!0}catch(X){j.error("Failed to copy thread URL after visibility update",{error:X})}}let Z=Y?`${$} Link copied to clipboard.`:$;return new tQ(Z)}catch(J){let Y=J instanceof Error?J.message:String(J);if(Y.includes("no-workspace"))return Error("You are not a member of any workspace.");if(Y.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(Y.includes("no-groups"))return Error("You are not a member of any groups.");return j.error("Unexpected failure to update thread visibility",{error:J}),Error(`Failed to update thread visibility for ${Q}`)}}class LG0 extends q5{offstage;constructor({key:A,offstage:Q=!0,child:B}){super({key:A,child:B});this.offstage=Q}createRenderObject(){return new d41(this.offstage)}updateRenderObject(A){if(A instanceof d41)A.offstage=this.offstage}}class d41 extends J4{_offstage;constructor(A){super();this._offstage=A}get offstage(){return this._offstage}set offstage(A){if(A===this._offstage)return;this._offstage=A,this.markNeedsLayout()}getMinIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicWidth(A)??0}getMaxIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicWidth(A)??0}getMinIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicHeight(A)??0}getMaxIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicHeight(A)??0}performLayout(){let A=this._lastConstraints;q4(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let B=A.constrain(Q.size.width,Q.size.height);this.setSize(B.width,B.height),Q.setOffset(0,0)}else{let B=A.smallest;this.setSize(B.width,B.height)}super.performLayout()}paint(A,Q,B){if(this._offstage)return;super.paint(A,Q,B)}hitTest(A,Q,B,$){if(this._offstage)return!1;return super.hitTest(A,Q,B,$)}}class c41{_state=null;_attach(A){this._state=A}_detach(){this._state=null}push(A){this._state?.push(A)}pushWithDismiss(A){this._state?.pushWithDismiss(A)}pop(){return this._state?.pop()??!1}get canPop(){return this._state?.canPop??!1}}class l41 extends T0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new ei4}}class ei4 extends _0{entries=[];initState(){this.widget.controller._attach(this)}didUpdateWidget(A){if(A.controller!==this.widget.controller)A.controller._detach(),this.widget.controller._attach(this)}dispose(){this.widget.controller._detach(),super.dispose()}push(A){let Q=new vj,B=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:B})})}pushWithDismiss(A){let Q=new vj,B=this.makeScopedDismiss(Q),$=A(B);this.setState(()=>{this.entries.push({key:Q,widget:$,dismiss:B})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new LG0({offstage:this.entries.length>0,child:this.widget.root}));for(let B=0;B<this.entries.length;B++){let $=this.entries[B],J=B===this.entries.length-1,Y=J?new n4({autofocus:!0,debugLabel:`ModalStackEntry[${B}]`,onKey:(Z)=>{if(Z.key!=="Escape")return"ignored";return $.dismiss(),"handled"},child:$.widget}):$.widget;Q.push(new LG0({key:$.key,offstage:!J,child:Y}))}return new QA({fit:"expand",children:Q})}}class n41 extends q1{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter(($)=>$.status.type!=="hidden"),B=Py5(Q);return new yA({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:K0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new u6({items:Q,showBorder:!1,getLabel:($)=>{let J=i41($);return $.keywords&&$.keywords.length>0?`${J} ${$.keywords.join(" ").toLowerCase()}`:J},sortItems:($,J,Y)=>{if(Y===""){let G=$.item.status.type==="disabled"?1:0,V=J.item.status.type==="disabled"?1:0;if(G!==V)return G-V;let U=$.item.sortBoost??0,K=J.item.sortBoost??0;if(U!==K)return K-U;let E=$.item.noun?.toLowerCase()??"",z=J.item.noun?.toLowerCase()??"";if(E!==z)return E<z?-1:1;return 0}let Z=tj($.item.verb.toLowerCase(),Y),F=tj(J.item.verb.toLowerCase(),Y);if(Z!==F)return F-Z;let X=tj(i41($.item),Y),D=tj(i41(J.item),Y);if(X!==D)return D-X;return J.score-$.score},isItemDisabled:($)=>$.status.type==="disabled",buildDisabledReasonWidget:($,J)=>{if($.status.type!=="disabled")return;let{colors:Y}=P0.of(J);return new p({text:new C($.status.reason,new v({color:Y.mutedForeground,dim:!0})),textAlign:"center"})},renderItem:($,J,Y,Z)=>new An4({command:$,isSelected:J,isDisabled:Y,categoryWidth:B,buildContext:Z}),onAccept:($)=>{this.props.onAccept($)},onDismiss:this.props.onDismiss})})}}class An4 extends q1{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:B,isDisabled:$,categoryWidth:J,buildContext:Y}=this.props,Z=P0.of(Y),{colors:F,app:X}=Z,D=B?X.selectionBackground:void 0,G=B?X.selectionForeground:F.foreground,V=B?G:F.mutedForeground,U=new p({text:new C(Q.noun?.toLowerCase()??"",new v({color:V,dim:$||!B})),textAlign:"right"}),K=[new C(Q.verb.toLowerCase(),new v({color:G,bold:!0,dim:$}))];if($)K.push(new C(" (unavailable)",new v({color:G,dim:!0})));let E=p.spans(K),z=[{child:U,fixedWidth:J},{child:E,expanded:!0}];if(Q.shortcut)z.push({child:_y5(Q.shortcut,Z,$)});return new Qn4({columns:z,padding:K0.horizontal(1),backgroundColor:D})}}function i41(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function Py5(A){return A.reduce((Q,B)=>{return B.noun?Math.max(Q,y4(B.noun)):Q},0)}function _y5(A,Q,B){let{colors:$,app:J}=Q,Y=new v({color:$.mutedForeground,dim:B}),Z=[];for(let F of A.modifiers()){if(Z.length>0)Z.push(new C(" ",Y));Z.push(new C(F,new v({color:J.keybind,bold:!0,dim:B})))}if(Z.length>0)Z.push(new C(" ",Y));return Z.push(new C(A.key,new v({color:J.keybind,bold:!0,dim:B}))),p.spans(Z)}class Qn4 extends q1{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:B=2,padding:$,backgroundColor:J}=this.props,Y=[];for(let F=0;F<Q.length;F++){let X=Q[F];if(F>0&&B>0)Y.push(new U0({width:B}));if(X.fixedWidth!==void 0)Y.push(new U0({width:X.fixedWidth,child:X.child}));else if(X.expanded)Y.push(new P1({child:X.child}));else Y.push(X.child)}let Z=new r0({crossAxisAlignment:"start",children:Y});if(!$&&!J)return Z;return new g0({decoration:J?{color:J}:void 0,padding:$,child:Z})}}class a41{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#B(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#B()}}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#B(){for(let A of this.#Q)A()}}class $Z extends H6{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=$Z.maybeOf(A);if(!Q)throw Error("No NeoCommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType($Z)?.commandRegistry??null}}class o41 extends T0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new Bn4}}class Bn4 extends _0{modalStack=new c41;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=$Z.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=$Z.of(A).commands,B=new n41({commands:Q,onAccept:($)=>{$.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new l41({root:B,controller:this.modalStack})}}var r41=[{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"]},{input:"S",keys:["Alt"]}]},{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"]}]}],s41=[{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 OG0 extends q1{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let B=s1.of(A).size.width,$=50,J=B<50,Y=[];for(let Z of this.items){let[F,X]=this.renderRow(Z),D;if(J)D=new x0({crossAxisAlignment:"start",mainAxisSize:"min",children:[F,new f0({padding:K0.only({left:4}),child:X})]});else D=new r0({crossAxisAlignment:"start",children:[new P1({flex:1,child:F}),new U0({width:1}),new P1({flex:1,child:X})]});Y.push(new f0({padding:K0.horizontal(6),child:D}))}return new x0({crossAxisAlignment:"start",mainAxisSize:"min",children:Y})}}class t41 extends T0{commands;submitOnEnter;constructor({key:A,commands:Q,submitOnEnter:B}){super(A?{key:A}:{});this.commands=Q,this.submitOnEnter=B??!0}createState(){return new $n4}}class $n4 extends _0{scrollController;initState(){this.scrollController=new hA,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0)}dispose(){}build(A){let B=j1.of(A).colorScheme,J=P0.of(A).app,Y=s1.of(A),Z=new v({color:B.primary,bold:!0}),F=new v({color:B.secondary,bold:!0}),X=new v({color:J.keybind}),D=new v({color:J.command}),G=new v({color:B.foreground}),V=new v({color:B.foreground}),U=Y.size.width,K=Y.size.height,E=U-4,z=K-4,W=Math.max(40,Math.min(80,E)),H=new Set(["permissions-disable"]),N=[...this.widget.commands.filter((L)=>{let P=L.noun?.toLowerCase();return P!=="dev"&&P!=="debug"&&!L.id.startsWith("debug-")&&!H.has(L.id)})].sort((L,P)=>{let T=(L.noun??"").toLowerCase(),k=(P.noun??"").toLowerCase(),x=T.localeCompare(k);if(x!==0)return x;let h=L.verb.toLowerCase(),f=P.verb.toLowerCase(),S=h.localeCompare(f);if(S!==0)return S;return L.id.localeCompare(P.id)}),I=new vA({autofocus:!0,controller:this.scrollController,child:new g0({constraints:new w1(W,W,0,Number.POSITIVE_INFINITY),child:new x0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new o1({child:new p({text:new C(`Amp CLI - Help & Keyboard Shortcuts
5704
5704
  `,Z)})}),new U0({height:1}),new f0({padding:K0.horizontal(2),child:new p({text:new C(`Editor Shortcuts
5705
5705
  `,F)})}),new OG0({items:r41.filter((L)=>L.submitOnEnterOnly===void 0||L.submitOnEnterOnly===this.widget.submitOnEnter),renderRow:(L)=>{let P=[];for(let k of L.methods){let x=this.buildCleanKeyCombination(k);P.push(x)}let T=P.join(", ");return[new p({text:new C(T,X)}),new p({text:new C(L.description,G)})]}}),new U0({height:1}),new f0({padding:K0.horizontal(2),child:new p({text:new C(`Scrolling & Navigation
5706
5706
  `,F)})}),new OG0({items:s41,renderRow:(L)=>{let P=[];for(let k of L.methods){let x=this.buildCleanKeyCombination(k);P.push(x)}let T=P.join(", ");return[new p({text:new C(T,X)}),new p({text:new C(L.description,G)})]}}),new U0({height:1}),new f0({padding:K0.horizontal(2),child:new p({text:new C(`Command Palette Commands
@@ -5801,7 +5801,7 @@ Ctrl-X, Y, Z to unlock`;if(E){let V0=G.text.replace(/`([^`]+)`/g,"$1")+`
5801
5801
  `))}function bh5(A,Q){let{colors:B,app:$}=Q;switch(A){case"pending":return{icon:"◌",color:B.warning};case"registered":return{icon:"•",color:B.mutedForeground};case"failed":return{icon:"✗",color:$.toolError};case"duplicate":return{icon:"◇",color:B.warning};default:return{icon:"?",color:B.foreground}}}function Sr4(A,Q){let B=A.replace(/\s+/g," ").trim();if(y4(B)<=Q)return B;let $="...",J=y4($);if(Q<=J)return WJ($,Q);return`${WJ(B,Q-J,!0,"")}${$}`}var v61="https://ampcode.com/news/neo",y61=[{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:v61,href:v61},"","",{text:"Need old Amp for a bit? Use ",keybind:"amp --take-me-back"}]}];function uh5(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:v61,textAfter:" you'll need to switch to the binary install:",linkWidget:!0},"",{codeBlock:["npm uninstall -g @sourcegraph/amp",A]}]}]}function hh5(){if(process.platform==="win32")return'powershell -c "irm https://ampcode.com/install.ps1 | iex"';return"curl -fsSL https://ampcode.com/install.sh | bash"}var uf=50,ER=40,k61=1000,gh5=420,mh5=760,ph5=-250,dh5=1100,$V0=33,fr4=0.999,ch5=2.1,lh5=720,ih5=420,cr4="Meet the new",lr4="Amp",ir4="CLI",x61=L4(cr4).length,nh5=L4(lr4).length,ah5=L4(ir4).length,JV0={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}},br4={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},ur4={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}},hr4=[JV0,br4,ur4,JV0,br4,ur4,JV0],oh5=JV0;class f61 extends T0{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??hh5(),this.introStages=this.variant==="npm-migration"?uh5(this.binaryInstallCommand):y61,this.dismissible=this.variant!=="npm-migration"}createState(){return new nr4}}class nr4 extends _0{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=k61;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 S9(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=JZ(this.widget.animationProgress),this.firstStageTitleVisible=this.animationProgress>=fr4,this.firstStageHintVisible=this.animationProgress>=fr4,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:k61,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=JZ(A/mh5);if(this.setState(()=>{this.dismissProgress=Q}),Q>=1)this.stopDismissAnimation(),this.widget.onDismiss()},$V0)}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 B=performance.now()-this.stageTransitionStartedAt,$=JZ(B/gh5);if(this.setState(()=>{if(this.stageTransitionProgress=$,$>=1)this.previousIntroStage=null}),$>=1)this.stopStageTransitionTimer()},$V0)}startProgressAnimation({from:A,to:Q,durationMs:B,onComplete:$}){this.stopAnimation(),this.startedAt=performance.now(),this.animationStartProgress=A,this.animationTargetProgress=Q,this.animationDurationMs=B,this.onAnimationComplete=$,this.animationProgress=A,this.animationTimer=setInterval(()=>{let J=performance.now()-this.startedAt,Y=JZ(J/this.animationDurationMs),Z=this.animationStartProgress+(this.animationTargetProgress-this.animationStartProgress)*hf(Y);if(this.setState(()=>{this.animationProgress=Z}),Y>=1)this.stopAnimation(),this.onAnimationComplete?.(),this.onAnimationComplete=null},$V0)}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,k61+ph5),Q=A+dh5;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?JZ((A-this.firstStageTitleRevealStartedAt)/lh5):this.firstStageTitleRevealProgress,B=this.firstStageHintRevealStartedAt?JZ((A-this.firstStageHintRevealStartedAt)/ih5):this.firstStageHintRevealProgress;if(this.setState(()=>{this.firstStageTitleRevealProgress=Q,this.firstStageHintRevealProgress=B}),Q>=1&&B>=1)this.stopFirstStageRevealTimer()},$V0)}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=gr4(this.introStage),Q=this.previousIntroStage===null||this.stageTransitionProgress>=1?A:mr4(gr4(this.previousIntroStage),A,hf(this.stageTransitionProgress));return this.dismissProgress>0?mr4(Q,oh5,hf(this.dismissProgress)):Q}build(A){let Q=j1.of(A).colorScheme,B=P0.of(A),$=this.currentOrbPalette(),J=sQ(1,"frontier",$),Y=s1.of(A).size,F=this.widget.animationProgress??this.animationProgress,X=Math.max(Y.width/uf,Y.height/ER)*ch5,D=X+(1-X)*F,G=hf(this.dismissProgress),V=Math.max(uf,Math.round(uf*D)),U=Math.max(ER,Math.round(ER*D)),K=Math.round((Y.width-V)/2),E=Math.round((Y.height-U)/2),z=Math.max(0,Math.floor((Y.width-uf)/2)),W=-Math.floor(ER/2),H=Math.round(K+(z-K)*F),q=Math.round(E+(W-E)*F),N=H+V/2,I=q+U/2,w=rh5({dismissProgress:this.dismissProgress,easedDismissProgress:G,introOrbScale:D,normalOrbCenterX:N,normalOrbCenterY:I,size:Y}),O=Math.max(uf,Math.round(uf*w.orbScale)),L=Math.max(ER,Math.round(ER*w.orbScale)),P=w.orbCenterX,T=w.orbCenterY,k=Math.round(P-O/2),x=Math.round(T-L/2),h=Math.max(3,Math.min(Y.height-5,Math.floor(ER/2)+2)),f=Math.max(h+3,Y.height-3),S=w.textDissolveProgress,u=this.isFinalIntroStage()?w.backdropDissolveProgress:0,d=this.firstStageTitleVisible&&S<1,c=d&&this.firstStageHintVisible,g=c&&this.widget.dismissible&&this.introStage>0&&!this.isFinalIntroStage(),l=this.introStage===0?this.firstStageTitleRevealProgress:1,s=this.introStage===0?this.firstStageHintRevealProgress:1,A0=Math.max(24,Math.min(74,Y.width-4)),H0=Math.min(12,Math.max(8,Y.height-h-6)),V0=Math.max(0,Math.floor((Y.width-A0)/2)),w0=Math.max(0,Math.min(Y.height-H0,Math.floor(Y.height*0.55-H0/2))),R0=this.widget.animationProgress!==void 0||!this.widget.animationsEnabled?new Sx({width:O,height:L,agentMode:"frontier",visualStyle:"neo",neoGlyphSet:"dotField",backgroundColor:Q.background,primaryColor:$.primary,secondaryColor:$.secondary,glow:this.splashOrbGlow,seed:42,fps:0,onClick:()=>{}}):new Sx({width:O,height:L,agentMode:"frontier",visualStyle:"neo",neoGlyphSet:"dotField",backgroundColor:Q.background,primaryColor:$.primary,secondaryColor:$.secondary,glow:this.splashOrbGlow,onClick:()=>{}});return new n4({autofocus:!0,canRequestFocus:!0,debugLabel:"NeoWelcomeTakeover",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 QA({fit:"expand",children:[new ar4({color:Q.background,dissolveProgress:u}),new QA({fit:"expand",children:[new k1({onClick:()=>{},child:U0.expand()}),new NA({left:k,top:x,width:O,height:L,child:R0}),...d?[new NA({left:V0,top:w0,width:A0,height:H0,child:th5({introStages:this.widget.introStages,stage:this.introStage,previousStage:this.previousIntroStage,progress:this.stageTransitionProgress,direction:this.stageTransitionDirection,width:A0,height:H0,foreground:Q.foreground,mutedForeground:Q.mutedForeground,accent:J,link:B.app.link,keybind:B.app.keybind,titleRevealProgress:l,dissolveProgress:S,context:A})})]:[],...c?[...g?[new NA({left:V0,top:Math.max(0,f-1),width:A0,height:1,child:new p({text:Jg5({stage:this.introStage,featureStageCount:Math.max(0,this.widget.introStages.length-2),foreground:Q.mutedForeground,dissolveProgress:S}),textAlign:"center"})})]:[],new NA({left:V0,top:f,width:A0,height:1,child:Zg5({finalStage:this.isFinalIntroStage(),dismissible:this.widget.dismissible,foreground:Q.mutedForeground,keybind:B.app.keybind,revealProgress:s,dissolveProgress:S,context:A})})]:[]]})]})})}}class ar4 extends Y8{color;dissolveProgress;constructor({color:A,dissolveProgress:Q}){super();this.color=A,this.dissolveProgress=Q}createRenderObject(){return new or4(this.color,this.dissolveProgress)}updateRenderObject(A){A.update(this.color,this.dissolveProgress)}}class or4 extends J4{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;q4(!!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,B=0){let $=Math.floor(Q+this.offset.x),J=Math.floor(B+this.offset.y),Y=Math.floor(this.size.width),Z=Math.floor(this.size.height),F={bg:this.color},X=JZ(this.dissolveProgress);if(X<=0){A.fill($,J,Y,Z," ",F);return}if(X>=1)return;for(let D=0;D<Z;D++)for(let G=0;G<Y;G++)if(!sh5(G,D,Y,Z,X))A.fill($+G,J+D,1,1," ",F)}}function JZ(A){return Math.min(1,Math.max(0,A))}function hf(A){return 1-(1-A)**3}function gr4(A){return hr4[A]??hr4[0]}function mr4(A,Q,B){return{primary:yj(A.primary,Q.primary,B),secondary:yj(A.secondary,Q.secondary,B)}}function rh5({dismissProgress:A,easedDismissProgress:Q,introOrbScale:B,normalOrbCenterX:$,normalOrbCenterY:J,size:Y}){return{orbScale:B+(B*0.86-B)*Q,orbCenterX:$+(Y.width*0.54-$)*Q,orbCenterY:J-Y.height*0.44*Q,textDissolveProgress:JZ(A/0.52),backdropDissolveProgress:hf(JZ((A-0.12)/0.88))}}function sh5(A,Q,B,$,J){let Y=$<=1?0:Q/($-1),Z=rr4(A+Q*Math.max(1,B));return(1-Y)*0.72+Z*0.28<J}function th5({introStages:A,stage:Q,previousStage:B,progress:$,direction:J,width:Y,height:Z,foreground:F,mutedForeground:X,accent:D,link:G,keybind:V,titleRevealProgress:U,dissolveProgress:K,context:E}){if(B===null||$>=1)return S61({introStages:A,stage:Q,foreground:F,mutedForeground:X,accent:D,link:G,keybind:V,titleRevealProgress:U,dissolveProgress:K,context:E});let z=hf($),W=J*Math.round((1-z)*Y),H=-J*Math.round(z*Y);return new hz(new QA({fit:"expand",children:[new NA({left:H,top:0,width:Y,height:Z,child:S61({introStages:A,stage:B,foreground:F,mutedForeground:X,accent:D,link:G,keybind:V,titleRevealProgress:B===0?1:U,dissolveProgress:K,context:E})}),new NA({left:W,top:0,width:Y,height:Z,child:S61({introStages:A,stage:Q,foreground:F,mutedForeground:X,accent:D,link:G,keybind:V,titleRevealProgress:U,dissolveProgress:K,context:E})})]}))}function S61({introStages:A,stage:Q,foreground:B,mutedForeground:$,accent:J,link:Y,keybind:Z,titleRevealProgress:F,dissolveProgress:X,context:D}){let G=A[Q]??A[0]??y61[0],V=new v({color:J,bold:!0}),U=new v({color:B}),K=A===y61&&Q===0,E=[...G.title===null?[]:[new p({text:K?YV0(Qg5({progress:F,foreground:J,pulseColor:J}),X):new C(Y$(G.title,X),V),textAlign:"center"})],...G.body.length>0?[eh5()]:[],...G.body.map((z)=>Ag5(z,U,$,Y,Z,X,D))];return new o1({child:new f0({padding:K0.horizontal(1),child:new x0({crossAxisAlignment:"stretch",mainAxisAlignment:"center",mainAxisSize:"min",children:E})})})}function eh5(){return U0.height(1)}function Ag5(A,Q,B,$,J,Y,Z){if(typeof A==="string")return new p({text:new C(Y$(A,Y),Q),textAlign:"center"});if("codeBlock"in A)return new $3({onCopy:(F,X)=>{if(X)d5.success(Z,"Copied to clipboard",2000)},child:new x0({mainAxisSize:"min",children:A.codeBlock.map((F)=>new p({text:new C(Y$(F,Y),new v({color:J})),textAlign:"center",selectable:!0}))})});if("keybind"in A){let F=new p({text:new C("",void 0,[new C(Y$(A.text,Y),new v({color:B,dim:!0})),new C(Y$(A.keybind,Y,L4(A.text).length),new v({color:J}))]),textAlign:"center",selectable:"selectable"in A?A.selectable:!1});if("selectable"in A)return new o1({child:new $3({child:F})});return F}if("highlightText"in A){let F=UA.createSpan(A.href,A.linkText,new v({color:$,underline:!0})),X=oD.of(Z),D=new C("",void 0,[new C(A.text,Q),new C(A.highlightText,new v({color:J})),new C(A.textAfterHighlight,Q),new C(F.text,F.style,F.children,F.hyperlink,()=>{nA(Z,A.href,{forceExternal:!1,onShowImagePreview:X})}),new C(A.textAfter,Q)]);return new p({text:YV0(D,Y),textAlign:"center"})}if("linkText"in A){if(A.linkWidget)return new x0({mainAxisSize:"min",children:[new p({text:new C(Y$(A.text,Y),Q),textAlign:"center"}),new o1({child:new r0({mainAxisSize:"min",children:[UA.createWidget(Z,A.href,Y$(A.linkText,Y),new v({color:$,underline:!0})),new p({text:new C(Y$(A.textAfter,Y),Q)})]})})]});let F=UA.createSpan(A.href,A.linkText,new v({color:$,underline:!0})),X=oD.of(Z),D=new C("",void 0,[new C(A.text,Q),new C(F.text,F.style,F.children,F.hyperlink,()=>{nA(Z,A.href,{forceExternal:!1,onShowImagePreview:X})}),new C(A.textAfter,Q)]);return new p({text:YV0(D,Y),textAlign:"center"})}if(Y>0)return new p({text:new C(Y$(A.text,Y),new v({color:$,underline:!0})),textAlign:"center"});return new o1({child:UA.createWidget(Z,A.href,A.text,new v({color:$,underline:!0}))})}function Qg5({progress:A,foreground:Q,pulseColor:B}){let $=new v({color:Q,bold:!0}),J=new v({color:$g5({progress:A,foreground:Q,pulseColor:B}),bold:!0});return new C("",void 0,[new C(Bg5(A).padEnd(x61," "),$),new C(" ",$),new C(pr4(lr4,nh5,A,0.72),$),new C(" ",$),new C(pr4(ir4,ah5,A,0.88),J)])}function Bg5(A){let Q=L4(cr4),B=Math.min(x61,Math.ceil(JZ(A/0.62)*x61));return Q.slice(0,B).join("")}function pr4(A,Q,B,$){return B>=$?A:"".padEnd(Q," ")}function $g5({progress:A,foreground:Q,pulseColor:B}){if(A<0.88||A>=1)return Q;let $=JZ((A-0.88)/0.12);return Math.cos($*Math.PI*4)*(1-$)>0.12?B:Q}function Jg5({stage:A,featureStageCount:Q,foreground:B,dissolveProgress:$}){return new C(Y$(`${A}/${Q}`,$),new v({color:B,dim:!0}))}function Yg5({finalStage:A,dismissible:Q,foreground:B,keybind:$,revealProgress:J,dissolveProgress:Y}){let Z=new v({color:$}),F=new v({color:B,dim:!0}),X=Q?A?"Enter":"Space":"Esc",D=Q?A?" to get started":" to continue":" to quit, or use ",G=Q?"":"amp --take-me-back",V=Q?"":" to use the old version",U=`${D}${G}${V}`;if(!Q)return new C("",void 0,[new C(X,Z),new C(D,F),new C(G,Z),new C(V,F)]);let K=dr4(X,J),E=dr4(U,JZ((J*(L4(X).length+L4(U).length)-L4(X).length)/L4(U).length));return new C("",void 0,[new C(Y$(K,Y),Z),new C(Y$(E.slice(0,D.length),Y),F),new C(Y$(E.slice(D.length,D.length+G.length),Y),Z),new C(Y$(E.slice(D.length+G.length),Y),F)])}function Zg5({finalStage:A,dismissible:Q,foreground:B,keybind:$,revealProgress:J,dissolveProgress:Y,context:Z}){if(Q)return new p({text:Yg5({finalStage:A,dismissible:Q,foreground:B,keybind:$,revealProgress:J,dissolveProgress:Y}),textAlign:"center"});let F=new v({color:$}),X=new v({color:B,dim:!0});return new $3({onCopy:(D,G)=>{if(G)d5.success(Z,"Copied to clipboard",2000)},child:new p({text:new C("",void 0,[new C("q",F),new C(" to quit, or use ",X),new C("amp --take-me-back",F),new C(" to use the old version",X)]),textAlign:"center",selectable:!0})})}function dr4(A,Q){let B=L4(A),$=Math.min(B.length,Math.ceil(JZ(Q)*B.length));return B.slice(0,$).join("").padEnd(B.length," ")}function YV0(A,Q,B=0){if(Q<=0)return A;let $=B+L4(A.text??"").length,J=A.children?.map((Y)=>{let Z=YV0(Y,Q,$);return $+=L4(Y.toPlainText()).length,Z});return new C(A.text?Y$(A.text,Q,B):A.text,A.style,J,A.hyperlink,A.onClick)}function Y$(A,Q,B=0){if(Q<=0)return A;return L4(A).map((J,Y)=>{if(J.trim()==="")return J;return rr4(B+Y)<Q?" ":J}).join("")}function rr4(A){let Q=Math.sin((A+1)*12.9898)*43758.5453;return Q-Math.floor(Q)}d0();L2();function aI(A,Q){let{colors:B,dim:$}=Q,J=[];if(A.totalCostUSD===null)return J;let Y=A.costBreakdown,Z=Y?.freeUSD??0,F=Y?.paidUSD??0;if(Z===0&&F===0)return J;let D={decimalPlaces:"more-if-tiny",intent:"cost"};if(F===0)J.push(new C(nU(Z,D),new v({color:B.foreground,dim:$}))),J.push(new C(" (free)",new v({color:B.foreground,dim:$})));else if(Z>0)J.push(new C(nU(Z,D),new v({color:B.foreground,dim:$}))),J.push(new C(" (free)",new v({color:B.foreground,dim:$}))),J.push(new C(" + ",new v({color:B.foreground,dim:$}))),J.push(new C(nU(F,D),new v({color:B.foreground,dim:$,bold:!$})));else J.push(new C(nU(F,D),new v({color:B.foreground,dim:$,bold:!$})));return J}class b61 extends P4{}class u61 extends P4{}function Fg5(A,Q){if(Q.code==="auth-required")return"You must be logged in to view thread usage. Run `amp login` first.";if(Q.code==="thread-not-found")return`Thread ${A} not found.`;return`Failed to load thread usage: ${Q.message??Q.code}`}function Xg5(A,Q){let B=P0.of(Q),{colors:$}=B,J=aI(A,{colors:{foreground:$.foreground}}),Y=[];if(J.length>0)Y.push(new C("Total: ",new v({color:$.mutedForeground}))),Y.push(...J);else if(A.totalCostUSD===null)Y.push(new C("Usage information is currently unavailable."));else Y.push(new C("No usage recorded for this thread yet."));if(A.costBreakdownURL)Y.push(new C(`
5802
5802
 
5803
5803
  `)),Y.push(new C("Details: ",new v({color:$.mutedForeground}))),Y.push(new C(A.costBreakdownURL,new v({color:B.app.link})));return new p({text:new C("",void 0,Y)})}function Dg5(A,Q,B){let $=Xg5(A,Q);if(!A.costBreakdownURL)return new yA({header:"Thread Cost",minWidth:80,maxWidth:100,onDismiss:B,child:$});let J=A.costBreakdownURL,Y=new d1(()=>{return l4.maybeInvoke(Q,new f9(J,"Cost breakdown URL copied to clipboard","Failed to copy cost breakdown URL")),"handled"}),Z=new d1(()=>{return nA(Q,J),"handled"});return new yA({header:"Thread Cost",minWidth:80,maxWidth:100,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["o"],label:"open in browser"},{keys:["y"],label:"copy url"}],onDismiss:B,child:new l4({actions:new Map([[b61,Y],[u61,Z]]),child:new $5({debugLabel:"ThreadCostShortcuts",shortcuts:new Map([[C1.key("o"),new u61],[C1.key("y"),new b61]]),child:new d4({autofocus:!0,debugLabel:"ThreadCostBody",child:$})})})})}function sr4(A){return{noun:"thread",verb:"show cost",description:"Show usage cost for the active thread",keywords:["usage","credits","billing","spend"],get status(){return A.getActiveThreadID()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(Q,B,$)=>{let J=A.getActiveThreadID();if(!J)return;try{let Y=await DA.threadDisplayCostInfo({threadID:J},{config:A.configService});if(!Y.ok){A.toastController.show(Fg5(J,Y.error),"error",5000),$();return}Q.push(Dg5(Y.result,B,$))}catch(Y){j.error("Failed to load Neo thread cost",{error:Y,threadID:J}),A.toastController.show(`Failed to show thread cost: ${Y instanceof Error?Y.message:String(Y)}`,"error",5000),$()}}}}function Gg5({ampURL:A,threadID:Q,logPath:B}){return[`Debug thread ${PB(new URL(A),Q).toString()} (cli log: ${B}). 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(`
5804
- `)}class h61 extends T0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;showNeoWelcome;neoWelcomeVariant;onNeoWelcomeDismissed;notificationService;onThreadArchived;initialUserInput;getDefaultNewThreadVisibility;openThreadPickerOnStart;neoContext;constructor(A){super();this.analyzeContextForThread=A.analyzeContextForThread,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.initialThreadID=A.initialThreadID,this.showNeoWelcome=A.showNeoWelcome??!1,this.neoWelcomeVariant=A.neoWelcomeVariant??"intro",this.onNeoWelcomeDismissed=A.onNeoWelcomeDismissed,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.initialUserInput=A.initialUserInput,this.getDefaultNewThreadVisibility=A.getDefaultNewThreadVisibility,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new er4}}class er4 extends _0{editorController=new L8;commandPalette=new Xr(this);commandRegistry=new a41;toastController=new z01;exitHintTimer=new rx(this,1000);ideStatus=new h8(this,{});threadNavigationHistory=new p41;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;agentStateSubscription=null;currentTitleText=void 0;currentAgentBusy=!1;currentTerminalTitle=void 0;terminalTitleSpinner=new W6;terminalTitleSpinnerTimer=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;pluginIntegration=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.connectToExistingThread(A,{recordNavigation:!0})};sendFeedbackReport=async(A)=>si4({configService:this.widget.configService,settingsFilePath:this.widget.neoContext.settingsFilePath},A);setThreadVisibility=(A,Q)=>{return ti4({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await md4({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await pd4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};removeThreadLabel=async(A,Q)=>{let B=await dd4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(tB.getInstance().interceptConsole(),this.widget.showNeoWelcome)this.neoWelcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:Q,error:B})=>{if(j.error("Neo failed to connect to thread",{threadID:Q,error:B}),!Q)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configSubscription=this.widget.configService.config.subscribe((Q)=>{this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(k30(Q.settings)))}),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID){let Q={};if(A)Q.initialUserInput=A;this.connectToExistingThread(this.widget.initialThreadID,Q)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.pluginIntegration=new g41({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,neoContext:this.widget.neoContext,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread}),this.pluginIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=C4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this,Q=this.widget.neoContext.pluginService?di4({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,logFilePath:this.widget.neoContext.logFilePath,toastController:this.toastController}):[],$=[{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(J,Y,Z)=>{J.pushWithDismiss((F)=>vA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:F,onThreadSelected:Z}))}},{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(J,Y,Z)=>{A.navigateBack(),Z()}},sr4({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(J,Y,Z)=>{A.navigateForward(),Z()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new ZA1({mcpServers:this.widget.neoContext.mcpServers,onDismiss:Z}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",keywords:["tools","toolbox"],status:{type:"enabled"},run:(J)=>{J.pushWithDismiss((Y)=>new T61({toolboxes:this.widget.neoContext.toolboxes,onDismiss:Y}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async(J,Y,Z)=>{try{await nA(Y,"https://ampcode.com/chronicle")}finally{Z()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{CJ(this.widget.neoContext.settingsFilePath).catch((J)=>{j.error("Failed to open settings file in editor",{error:J})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(J,Y,Z)=>{J.pushWithDismiss((F)=>new JA1({onCancel:F,onSelect:(X)=>{this.handleIdeSelection(X),Z()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new e41({commands:$Z.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(J,Y,Z)=>{Z(),A.showNeoWelcome()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new yA({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new p({text:new C(X01({version:"0.0.1778476494-g8a21dc",buildTimestamp:"2026-05-11T05:19:01.767Z",buildType:"'release'"}))})}))}},{noun:"amp",verb:"reconnect",description:"Disconnect and reconnect the active thread",keywords:["connection","disconnect","socket","debug"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: reconnect with no active thread"}},run:(J,Y,Z)=>{A.reconnectActiveThread(),Z()}},{noun:"amp",verb:"disconnect",description:"Disconnect the active thread without reconnecting",keywords:["connection","socket","debug","dev"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: disconnect with no active thread"}},run:(J,Y,Z)=>{A.disconnectActiveThread(),Z()}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:C1.ctrl("c"),status:{type:"enabled"},run:(J,Y)=>{l4.maybeInvoke(Y,new Of)}},...Q,...ki4(this.widget.neoContext.logFilePath)].map((J)=>this.commandRegistry.register(J));return()=>{for(let J of $)J()}}build(A){let Q=this.buildHints(),B=this.ideStatus.getValue(),$=new _61({initialAgentMode:this.widget.neoContext.sessionAgentMode,analyzeContextForThread:this.widget.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,sendFeedbackReport:this.sendFeedbackReport,setThreadVisibility:this.setThreadVisibility,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:B,statusItems:this.pluginIntegration?.getStatusItems()??[]}),J=s1.of(A),Y=J.capabilities.animationSupport!=="disabled",F=[new g0({constraints:w1.tight(J.size.width,J.size.height),child:$})];if(this.commandPalette.isEnabled())F.push(new n4({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new o41({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)F.push(vA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)F.push(new n4({debugLabel:"NeoWelcomeDialogOverlay",child:new f61({onDismiss:this.dismissNeoWelcome,onQuit:()=>C4.instance.stop(),animationsEnabled:Y,variant:this.widget.neoWelcomeVariant})}));if(F.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)F.push(new BA1({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:Ss.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)F.push(new $A1);return new _3({neoContext:this.widget.neoContext,child:new $Z({commandRegistry:this.commandRegistry,child:new uI({completionBuilder:this.widget.completionBuilder,child:new d5({controller:this.toastController,child:new l4({actions:this.buildActions(),child:new $5({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[C1.ctrl("c"),new KG0],[C1.ctrl("o"),new EG0],[C1.alt("i"),new WG0],[C1.alt("p"),new CI],[C1.ctrl("t"),new HG0]]),child:new d4({debugLabel:"AppShellFocus",child:new W01({controller:this.toastController,child:new AA1({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new QA({children:F})})})})})})})})})})}buildActions(){let A=new d1(()=>{if(IJ.hasAnyCopyableSelection())return IJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new d1(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new d1(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new d1(()=>{return this.startNewDraftThread(),"handled"}),J=new d1(()=>{return C4.instance.stop(),"handled"}),Y=new d1((U)=>{if(!U.text)return"ignored";return C4.instance.tuiInstance.clipboard.writeText(U.text).then((K)=>{if(K.ok)this.toastController.show(U.successMessage,"success",2000);else this.toastController.show(`${U.failureMessage}: ${K.userFacingErrorMessage}`,"error",4000)}).catch((K)=>{j.error("Failed to copy Neo text to clipboard",{error:K}),this.toastController.show(U.failureMessage,"error",2000)}),"handled"}),Z=new d1(()=>{return C4.instance.toggleFrameStatsOverlay(),"handled"}),F=new d1(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),X=new d1(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";let K=Dx(U);return C4.instance.tuiInstance.clipboard.writeText(K).then(()=>{this.toastController.show("Copied log path to clipboard","success",2000)}).catch((E)=>{j.error("Failed to copy thread log path",{error:E,threadID:U,logPath:K}),this.toastController.show("Failed to copy log path","error",2000)}),"handled"}),D=new d1(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";let U=this.activeThreadContext?.client.getThreadId();if(!U)return"handled";return this.prepareThreadIssueInvestigation(U),"handled"}),G=new d1(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";return this.toastController.show("Sending report...","success",2000),this.sendFeedbackReport(U).then(async(K)=>{try{await C4.instance.tuiInstance.clipboard.writeText(K),this.toastController.show("Sent report and copied report ID","success",3000)}catch(E){j.warn("Failed to copy report ID to clipboard",{error:E,reportID:K}),this.toastController.show(`Sent report ${K}`,"success",3000)}}).catch((K)=>{j.error("Failed to send report from debug overlay",{error:K,threadID:U}),this.toastController.show("Failed to send report","error",3000)}),"handled"}),V=new d1(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[KG0,A],[Bs,$],[Of,J],[f9,Y],[Ys,B],[EG0,Q],[WG0,F],[Zs,X],[Fs,D],[Xs,G],[CI,Z],[HG0,V]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=null,this.currentAgentBusy=!1,this.syncTerminalTitleSpinner(),this.clearTerminalTitle(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),A.prompt!==void 0)this.editorController.text=A.prompt}prepareThreadIssueInvestigation(A){try{this.startNewDraftThread({prompt:Gg5({ampURL:this.widget.neoContext.ampURL,threadID:A,logPath:Dx(A)}),hideDebugOverlay:!0})}catch(Q){j.error("Failed to prepare thread issue investigation",{error:Q,threadID:A})}}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 hx(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){j.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.neoContext.sessionAgentMode,B=A,$=eB(Q),J=hX0(this.widget.neoContext,Q);if($!==void 0&&J!==void 0)B={...B,[$]:J};return uX0(B,{agentMode:Q,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=tr4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(dZ(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=tr4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(bI);if(this.exitHintTimer.isActive())A.add(Nf);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),C4.instance.stop();else this.exitHintTimer.activate()};dismissNeoWelcome=()=>{if(!this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!1}),this.widget.onNeoWelcomeDismissed?.()};showNeoWelcome=()=>{if(this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!0})};closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,B=null,$)=>{await this.ensureDraftThreadSettingsInitialized();let J=this.activeThreadContext?.client.getThreadId(),Y=A.find((D)=>D.type==="text");if(Y&&Y.type==="text")this.widget.history.add(Y.text,Ss.cwd()),this.widget.history.reset();let Z=B?void 0:await this.widget.getDefaultNewThreadVisibility?.(),F=B??Z??null,X=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,F?wJ(F):void 0);this.sendUserMessage(X,A,Q,$),this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings),this.threadNavigationHistory.recordNavigation(J),this.setActiveClient(X)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.neoContext.sessionAgentMode=A;let B=Q["reasoning.effort"];if(B!==void 0)this.widget.neoContext.lastReasoningEffortByMode={...this.widget.neoContext.lastReasoningEffortByMode??{},[A]:B};let $=eB(A),J=$?Q[$]:void 0;if(J!==void 0)this.widget.neoContext.lastSpeedByMode={...this.widget.neoContext.lastSpeedByMode??{},[A]:J};NJ((Y)=>{let Z={...Y,agentMode:A};if(B!==void 0)Z={...Z,lastReasoningEffortByMode:{...Z.lastReasoningEffortByMode??{},[A]:B}};if(J!==void 0)Z={...Z,lastSpeedByMode:{...Z.lastSpeedByMode??{},[A]:J}};return Z}).catch((Y)=>{j.warn("Failed to persist Neo session defaults for new message",{error:Y instanceof Error?Y.message:String(Y)})})}sendUserMessage(A,Q,B,$){let J=CY0(this.ideStatus.getValue());if($===void 0){A.client.sendUserMessage(Q,B,{userState:J});return}A.client.sendUserMessage(Q,B,{reasoningEffort:$,userState:J})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};appendPluginMessagesToThread=async(A,Q)=>{let B=this.activeThreadContext;if(!B)throw Error("appendToThread is not available - no active thread");let $=B.client.getThreadId();if(Q&&$!==Q)throw Error("thread.append is only available for the active executor thread");for(let J of A)this.sendUserMessage(B,[{type:"text",text:J.content}])};async connectToExistingThread(A,Q={}){let B=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let $=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly});if(this.setActiveClient($),Q.recordNavigation&&B!==A)this.threadNavigationHistory.recordNavigation(B);if(Q.initialUserInput)this.sendUserMessage($,[{type:"text",text:Q.initialUserInput}])}catch($){if(j.error("Failed to load thread",{error:$,threadID:A}),this.toastController.show(`Failed to load ${A}: ${$ instanceof Error?$.message:String($)}`,"error",4000),Q.rethrowError)throw $}finally{this.setState(()=>{this.connectingToThreadID=null})}}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()}}async reconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to reconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Reconnecting ${Q}...`:"Reconnecting thread...","warning",60000);try{await A.client.reconnect(),this.toastController.update(B,Q?`Reconnected ${Q}`:"Reconnected thread","success",2000)}catch($){j.error("Failed to reconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Reconnect failed: ${J}`,"error",4000)}}async disconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to disconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Disconnecting ${Q}...`:"Disconnecting thread...","warning",60000);try{await A.client.disconnectAndWait(),this.toastController.update(B,Q?`Disconnected ${Q}`:"Disconnected thread","success",2000)}catch($){j.error("Failed to disconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Disconnect failed: ${J}`,"error",4000)}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q},this.subscribeTitleUpdates(Q),this.subscribeNotifications(Q)})}subscribeTitleUpdates(A){this.titleSubscription?.unsubscribe(),this.titleSubscription=A.title().subscribe({next:(Q)=>{this.currentTitleText=Q,this.updateTerminalTitle()}}),this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=A.agentState().subscribe({next:(Q)=>{let B=Q!=="idle"&&Q!=="error";if(B===this.currentAgentBusy)return;this.currentAgentBusy=B,this.syncTerminalTitleSpinner(),this.updateTerminalTitle()}})}subscribeNotifications(A){this.widget.notificationService.attach(A.agentState())}clearTerminalTitle(){this.currentTitleText=void 0,this.updateTerminalTitle()}updateTerminalTitle(){let A=Ss.cwd().replace(Ss.env.HOME||"","~"),Q=this.currentAgentBusy?`${this.terminalTitleSpinner.toBraille()} `:"",B=this.currentTitleText?`${Q}amp - ${this.currentTitleText} - ${A}`:this.currentAgentBusy?`${Q}amp - ${A}`:"";if(B===this.currentTerminalTitle)return;this.currentTerminalTitle=B,Ss.stdout.write(KI(B))}syncTerminalTitleSpinner(){if(this.currentAgentBusy){if(this.terminalTitleSpinnerTimer)return;this.terminalTitleSpinnerTimer=setInterval(()=>{this.terminalTitleSpinner.step(),this.updateTerminalTitle()},200);return}if(this.terminalTitleSpinnerTimer)clearInterval(this.terminalTitleSpinnerTimer),this.terminalTitleSpinnerTimer=null}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){j.error("Failed to connect to IDE",{error:Q});let B=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${B}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.titleSubscription?.unsubscribe(),this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=null,this.terminalTitleSpinnerTimer)clearInterval(this.terminalTitleSpinnerTimer),this.terminalTitleSpinnerTimer=null;this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.neoWelcomeVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function tr4(A,Q,B){let $={...A};for(let J of Vg5(Q,B)){if(!dZ(A[J],Q[J]))continue;let Y=B[J];if(Y===void 0)delete $[J];else $[J]=Y}return $}function Vg5(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}i4();function As4(A,Q,B,$){let J=tT(A),Y="\x1B[0m",Z="\x1B[34m",F="\x1B[90m",X="\x1B[2m",D=[];if(A.archived)D.push("\x1B[90m\x1B[2mArchived\x1B[0m");D.push(`${J}`),D.push(`\x1B[34m${Q}\x1B[0m`),D.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let G=14,V=7,U=new rY(G,V),K=new S9(42),E=new WI(G,V,G,V,G,V,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,E0.default(),K);E.layout(w1.tight(G,V)),E.paint(U,0,0);let z=U.getBuffer().getCells(),W=0;for(let P=0;P<V;P++)if(z[P].some((T)=>T.char!==" ")){W=P;break}let H=V-1;for(let P=V-1;P>=0;P--)if(z[P].some((T)=>T.char!==" ")){H=P;break}function q(P,T){if(!P)return"";if(P.type==="rgb"){let{r:k,g:x,b:h}=P.value;if(B.getColorDepth()>=24)return`\x1B[${T?38:48};2;${k};${x};${h}m`;let f=kj(k,x,h);return`\x1B[${T?38:48};5;${f}m`}return""}let N=[];if(H>=W)for(let P=W;P<=H;P++){let T="";for(let k=0;k<G;k++){let x=z[P][k],h=x.char,f=q(x.style.fg,!0);T+=f+h+"\x1B[0m"}N.push(T)}let I=N.length,w=Math.max(I,D.length),O=Math.floor((w-I)/2),L=Math.floor((w-D.length)/2);for(let P=0;P<w;P++){let T=" ".repeat(G);if(P>=O&&P<O+I)T=N[P-O];let k=" ",x="";if(P>=L&&P<L+D.length)x=D[P-L];B.write(T+k+x+`
5804
+ `)}class h61 extends T0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;showNeoWelcome;neoWelcomeVariant;onNeoWelcomeDismissed;notificationService;onThreadArchived;initialUserInput;getDefaultNewThreadVisibility;openThreadPickerOnStart;neoContext;constructor(A){super();this.analyzeContextForThread=A.analyzeContextForThread,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.initialThreadID=A.initialThreadID,this.showNeoWelcome=A.showNeoWelcome??!1,this.neoWelcomeVariant=A.neoWelcomeVariant??"intro",this.onNeoWelcomeDismissed=A.onNeoWelcomeDismissed,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.initialUserInput=A.initialUserInput,this.getDefaultNewThreadVisibility=A.getDefaultNewThreadVisibility,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new er4}}class er4 extends _0{editorController=new L8;commandPalette=new Xr(this);commandRegistry=new a41;toastController=new z01;exitHintTimer=new rx(this,1000);ideStatus=new h8(this,{});threadNavigationHistory=new p41;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;agentStateSubscription=null;currentTitleText=void 0;currentAgentBusy=!1;currentTerminalTitle=void 0;terminalTitleSpinner=new W6;terminalTitleSpinnerTimer=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;pluginIntegration=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.connectToExistingThread(A,{recordNavigation:!0})};sendFeedbackReport=async(A)=>si4({configService:this.widget.configService,settingsFilePath:this.widget.neoContext.settingsFilePath},A);setThreadVisibility=(A,Q)=>{return ti4({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await md4({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await pd4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};removeThreadLabel=async(A,Q)=>{let B=await dd4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(tB.getInstance().interceptConsole(),this.widget.showNeoWelcome)this.neoWelcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:Q,error:B})=>{if(j.error("Neo failed to connect to thread",{threadID:Q,error:B}),!Q)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configSubscription=this.widget.configService.config.subscribe((Q)=>{this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(k30(Q.settings)))}),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID){let Q={};if(A)Q.initialUserInput=A;this.connectToExistingThread(this.widget.initialThreadID,Q)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.pluginIntegration=new g41({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,neoContext:this.widget.neoContext,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread}),this.pluginIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=C4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this,Q=this.widget.neoContext.pluginService?di4({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,logFilePath:this.widget.neoContext.logFilePath,toastController:this.toastController}):[],$=[{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(J,Y,Z)=>{J.pushWithDismiss((F)=>vA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:F,onThreadSelected:Z}))}},{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(J,Y,Z)=>{A.navigateBack(),Z()}},sr4({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(J,Y,Z)=>{A.navigateForward(),Z()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new ZA1({mcpServers:this.widget.neoContext.mcpServers,onDismiss:Z}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",keywords:["tools","toolbox"],status:{type:"enabled"},run:(J)=>{J.pushWithDismiss((Y)=>new T61({toolboxes:this.widget.neoContext.toolboxes,onDismiss:Y}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async(J,Y,Z)=>{try{await nA(Y,"https://ampcode.com/chronicle")}finally{Z()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{CJ(this.widget.neoContext.settingsFilePath).catch((J)=>{j.error("Failed to open settings file in editor",{error:J})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(J,Y,Z)=>{J.pushWithDismiss((F)=>new JA1({onCancel:F,onSelect:(X)=>{this.handleIdeSelection(X),Z()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new e41({commands:$Z.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(J,Y,Z)=>{Z(),A.showNeoWelcome()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new yA({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new p({text:new C(X01({version:"0.0.1778480457-g5efd50",buildTimestamp:"2026-05-11T06:24:41.556Z",buildType:"'release'"}))})}))}},{noun:"amp",verb:"reconnect",description:"Disconnect and reconnect the active thread",keywords:["connection","disconnect","socket","debug"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: reconnect with no active thread"}},run:(J,Y,Z)=>{A.reconnectActiveThread(),Z()}},{noun:"amp",verb:"disconnect",description:"Disconnect the active thread without reconnecting",keywords:["connection","socket","debug","dev"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: disconnect with no active thread"}},run:(J,Y,Z)=>{A.disconnectActiveThread(),Z()}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:C1.ctrl("c"),status:{type:"enabled"},run:(J,Y)=>{l4.maybeInvoke(Y,new Of)}},...Q,...ki4(this.widget.neoContext.logFilePath)].map((J)=>this.commandRegistry.register(J));return()=>{for(let J of $)J()}}build(A){let Q=this.buildHints(),B=this.ideStatus.getValue(),$=new _61({initialAgentMode:this.widget.neoContext.sessionAgentMode,analyzeContextForThread:this.widget.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,sendFeedbackReport:this.sendFeedbackReport,setThreadVisibility:this.setThreadVisibility,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:B,statusItems:this.pluginIntegration?.getStatusItems()??[]}),J=s1.of(A),Y=J.capabilities.animationSupport!=="disabled",F=[new g0({constraints:w1.tight(J.size.width,J.size.height),child:$})];if(this.commandPalette.isEnabled())F.push(new n4({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new o41({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)F.push(vA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)F.push(new n4({debugLabel:"NeoWelcomeDialogOverlay",child:new f61({onDismiss:this.dismissNeoWelcome,onQuit:()=>C4.instance.stop(),animationsEnabled:Y,variant:this.widget.neoWelcomeVariant})}));if(F.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)F.push(new BA1({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:Ss.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)F.push(new $A1);return new _3({neoContext:this.widget.neoContext,child:new $Z({commandRegistry:this.commandRegistry,child:new uI({completionBuilder:this.widget.completionBuilder,child:new d5({controller:this.toastController,child:new l4({actions:this.buildActions(),child:new $5({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[C1.ctrl("c"),new KG0],[C1.ctrl("o"),new EG0],[C1.alt("i"),new WG0],[C1.alt("p"),new CI],[C1.ctrl("t"),new HG0]]),child:new d4({debugLabel:"AppShellFocus",child:new W01({controller:this.toastController,child:new AA1({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new QA({children:F})})})})})})})})})})}buildActions(){let A=new d1(()=>{if(IJ.hasAnyCopyableSelection())return IJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new d1(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new d1(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new d1(()=>{return this.startNewDraftThread(),"handled"}),J=new d1(()=>{return C4.instance.stop(),"handled"}),Y=new d1((U)=>{if(!U.text)return"ignored";return C4.instance.tuiInstance.clipboard.writeText(U.text).then((K)=>{if(K.ok)this.toastController.show(U.successMessage,"success",2000);else this.toastController.show(`${U.failureMessage}: ${K.userFacingErrorMessage}`,"error",4000)}).catch((K)=>{j.error("Failed to copy Neo text to clipboard",{error:K}),this.toastController.show(U.failureMessage,"error",2000)}),"handled"}),Z=new d1(()=>{return C4.instance.toggleFrameStatsOverlay(),"handled"}),F=new d1(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),X=new d1(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";let K=Dx(U);return C4.instance.tuiInstance.clipboard.writeText(K).then(()=>{this.toastController.show("Copied log path to clipboard","success",2000)}).catch((E)=>{j.error("Failed to copy thread log path",{error:E,threadID:U,logPath:K}),this.toastController.show("Failed to copy log path","error",2000)}),"handled"}),D=new d1(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";let U=this.activeThreadContext?.client.getThreadId();if(!U)return"handled";return this.prepareThreadIssueInvestigation(U),"handled"}),G=new d1(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";return this.toastController.show("Sending report...","success",2000),this.sendFeedbackReport(U).then(async(K)=>{try{await C4.instance.tuiInstance.clipboard.writeText(K),this.toastController.show("Sent report and copied report ID","success",3000)}catch(E){j.warn("Failed to copy report ID to clipboard",{error:E,reportID:K}),this.toastController.show(`Sent report ${K}`,"success",3000)}}).catch((K)=>{j.error("Failed to send report from debug overlay",{error:K,threadID:U}),this.toastController.show("Failed to send report","error",3000)}),"handled"}),V=new d1(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[KG0,A],[Bs,$],[Of,J],[f9,Y],[Ys,B],[EG0,Q],[WG0,F],[Zs,X],[Fs,D],[Xs,G],[CI,Z],[HG0,V]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=null,this.currentAgentBusy=!1,this.syncTerminalTitleSpinner(),this.clearTerminalTitle(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),A.prompt!==void 0)this.editorController.text=A.prompt}prepareThreadIssueInvestigation(A){try{this.startNewDraftThread({prompt:Gg5({ampURL:this.widget.neoContext.ampURL,threadID:A,logPath:Dx(A)}),hideDebugOverlay:!0})}catch(Q){j.error("Failed to prepare thread issue investigation",{error:Q,threadID:A})}}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 hx(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){j.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.neoContext.sessionAgentMode,B=A,$=eB(Q),J=hX0(this.widget.neoContext,Q);if($!==void 0&&J!==void 0)B={...B,[$]:J};return uX0(B,{agentMode:Q,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=tr4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(dZ(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=tr4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(bI);if(this.exitHintTimer.isActive())A.add(Nf);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),C4.instance.stop();else this.exitHintTimer.activate()};dismissNeoWelcome=()=>{if(!this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!1}),this.widget.onNeoWelcomeDismissed?.()};showNeoWelcome=()=>{if(this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!0})};closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,B=null,$)=>{await this.ensureDraftThreadSettingsInitialized();let J=this.activeThreadContext?.client.getThreadId(),Y=A.find((D)=>D.type==="text");if(Y&&Y.type==="text")this.widget.history.add(Y.text,Ss.cwd()),this.widget.history.reset();let Z=B?void 0:await this.widget.getDefaultNewThreadVisibility?.(),F=B??Z??null,X=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,F?wJ(F):void 0);this.sendUserMessage(X,A,Q,$),this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings),this.threadNavigationHistory.recordNavigation(J),this.setActiveClient(X)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.neoContext.sessionAgentMode=A;let B=Q["reasoning.effort"];if(B!==void 0)this.widget.neoContext.lastReasoningEffortByMode={...this.widget.neoContext.lastReasoningEffortByMode??{},[A]:B};let $=eB(A),J=$?Q[$]:void 0;if(J!==void 0)this.widget.neoContext.lastSpeedByMode={...this.widget.neoContext.lastSpeedByMode??{},[A]:J};NJ((Y)=>{let Z={...Y,agentMode:A};if(B!==void 0)Z={...Z,lastReasoningEffortByMode:{...Z.lastReasoningEffortByMode??{},[A]:B}};if(J!==void 0)Z={...Z,lastSpeedByMode:{...Z.lastSpeedByMode??{},[A]:J}};return Z}).catch((Y)=>{j.warn("Failed to persist Neo session defaults for new message",{error:Y instanceof Error?Y.message:String(Y)})})}sendUserMessage(A,Q,B,$){let J=CY0(this.ideStatus.getValue());if($===void 0){A.client.sendUserMessage(Q,B,{userState:J});return}A.client.sendUserMessage(Q,B,{reasoningEffort:$,userState:J})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};appendPluginMessagesToThread=async(A,Q)=>{let B=this.activeThreadContext;if(!B)throw Error("appendToThread is not available - no active thread");let $=B.client.getThreadId();if(Q&&$!==Q)throw Error("thread.append is only available for the active executor thread");for(let J of A)this.sendUserMessage(B,[{type:"text",text:J.content}])};async connectToExistingThread(A,Q={}){let B=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let $=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly});if(this.setActiveClient($),Q.recordNavigation&&B!==A)this.threadNavigationHistory.recordNavigation(B);if(Q.initialUserInput)this.sendUserMessage($,[{type:"text",text:Q.initialUserInput}])}catch($){if(j.error("Failed to load thread",{error:$,threadID:A}),this.toastController.show(`Failed to load ${A}: ${$ instanceof Error?$.message:String($)}`,"error",4000),Q.rethrowError)throw $}finally{this.setState(()=>{this.connectingToThreadID=null})}}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()}}async reconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to reconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Reconnecting ${Q}...`:"Reconnecting thread...","warning",60000);try{await A.client.reconnect(),this.toastController.update(B,Q?`Reconnected ${Q}`:"Reconnected thread","success",2000)}catch($){j.error("Failed to reconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Reconnect failed: ${J}`,"error",4000)}}async disconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to disconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Disconnecting ${Q}...`:"Disconnecting thread...","warning",60000);try{await A.client.disconnectAndWait(),this.toastController.update(B,Q?`Disconnected ${Q}`:"Disconnected thread","success",2000)}catch($){j.error("Failed to disconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Disconnect failed: ${J}`,"error",4000)}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q},this.subscribeTitleUpdates(Q),this.subscribeNotifications(Q)})}subscribeTitleUpdates(A){this.titleSubscription?.unsubscribe(),this.titleSubscription=A.title().subscribe({next:(Q)=>{this.currentTitleText=Q,this.updateTerminalTitle()}}),this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=A.agentState().subscribe({next:(Q)=>{let B=Q!=="idle"&&Q!=="error";if(B===this.currentAgentBusy)return;this.currentAgentBusy=B,this.syncTerminalTitleSpinner(),this.updateTerminalTitle()}})}subscribeNotifications(A){this.widget.notificationService.attach(A.agentState())}clearTerminalTitle(){this.currentTitleText=void 0,this.updateTerminalTitle()}updateTerminalTitle(){let A=Ss.cwd().replace(Ss.env.HOME||"","~"),Q=this.currentAgentBusy?`${this.terminalTitleSpinner.toBraille()} `:"",B=this.currentTitleText?`${Q}amp - ${this.currentTitleText} - ${A}`:this.currentAgentBusy?`${Q}amp - ${A}`:"";if(B===this.currentTerminalTitle)return;this.currentTerminalTitle=B,Ss.stdout.write(KI(B))}syncTerminalTitleSpinner(){if(this.currentAgentBusy){if(this.terminalTitleSpinnerTimer)return;this.terminalTitleSpinnerTimer=setInterval(()=>{this.terminalTitleSpinner.step(),this.updateTerminalTitle()},200);return}if(this.terminalTitleSpinnerTimer)clearInterval(this.terminalTitleSpinnerTimer),this.terminalTitleSpinnerTimer=null}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){j.error("Failed to connect to IDE",{error:Q});let B=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${B}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.titleSubscription?.unsubscribe(),this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=null,this.terminalTitleSpinnerTimer)clearInterval(this.terminalTitleSpinnerTimer),this.terminalTitleSpinnerTimer=null;this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.neoWelcomeVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function tr4(A,Q,B){let $={...A};for(let J of Vg5(Q,B)){if(!dZ(A[J],Q[J]))continue;let Y=B[J];if(Y===void 0)delete $[J];else $[J]=Y}return $}function Vg5(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}i4();function As4(A,Q,B,$){let J=tT(A),Y="\x1B[0m",Z="\x1B[34m",F="\x1B[90m",X="\x1B[2m",D=[];if(A.archived)D.push("\x1B[90m\x1B[2mArchived\x1B[0m");D.push(`${J}`),D.push(`\x1B[34m${Q}\x1B[0m`),D.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let G=14,V=7,U=new rY(G,V),K=new S9(42),E=new WI(G,V,G,V,G,V,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,E0.default(),K);E.layout(w1.tight(G,V)),E.paint(U,0,0);let z=U.getBuffer().getCells(),W=0;for(let P=0;P<V;P++)if(z[P].some((T)=>T.char!==" ")){W=P;break}let H=V-1;for(let P=V-1;P>=0;P--)if(z[P].some((T)=>T.char!==" ")){H=P;break}function q(P,T){if(!P)return"";if(P.type==="rgb"){let{r:k,g:x,b:h}=P.value;if(B.getColorDepth()>=24)return`\x1B[${T?38:48};2;${k};${x};${h}m`;let f=kj(k,x,h);return`\x1B[${T?38:48};5;${f}m`}return""}let N=[];if(H>=W)for(let P=W;P<=H;P++){let T="";for(let k=0;k<G;k++){let x=z[P][k],h=x.char,f=q(x.style.fg,!0);T+=f+h+"\x1B[0m"}N.push(T)}let I=N.length,w=Math.max(I,D.length),O=Math.floor((w-I)/2),L=Math.floor((w-D.length)/2);for(let P=0;P<w;P++){let T=" ".repeat(G);if(P>=O&&P<O+I)T=N[P-O];let k=" ",x="";if(P>=L&&P<L+D.length)x=D[P-L];B.write(T+k+x+`
5805
5805
  `)}if($)B.write(`
5806
5806
  \x1B[90m${$}\x1B[0m
5807
5807
  `)}d0();aX0();var Ug5=2000;function Qs4(A){let Q=!0,B=!0,$=A.configService.config.subscribe((V)=>{Q=V.settings["notifications.enabled"]??!0,B=V.settings["notifications.system.enabled"]!==!1}),J=0,Y=(V)=>{if(!Q)return;let U=Date.now();if(U-J<Ug5)return;if(J=U,uj())return;if(rF0())sF0();else FZ0(V)},Z=(V)=>{if(!Q||!B)return;if(uj()&&!Ar()&&!_x())return;process.stdout.write(bD(`\x1B]777;notify;Amp;${V}\x1B\\`))},F=null,X=null,D=()=>{F?.unsubscribe(),F=null,X=null};return{attach:(V)=>{D(),F=V.subscribe({next:(U)=>{try{let K=X!==null&&BQ(X),E=X==="awaiting_approval";if(U==="awaiting_approval"&&!E)Y("requires-user-input"),Z("Waiting for approval");else if((U==="idle"||U==="error")&&(K||E))Y("idle"),Z("Agent is ready")}catch(K){j.debug("Neo notification handling failed",{error:K})}finally{X=U}},error:(U)=>{j.debug("Neo notification agent state stream errored",{error:U})}})},detach:D,unsubscribe(){D(),$.unsubscribe()}}}function Kg5({initialUserInput:A,showNeoWelcome:Q,hideNeoWelcome:B,neoWelcomeVariant:$,neoWelcomeDismissed:J}){if(B)return{show:!1,markDismissedOnDismiss:!1};if($==="npm-migration")return{show:!0,markDismissedOnDismiss:!1};if(Q)return{show:!0,markDismissedOnDismiss:!0};let Y=!A&&!J;return{show:Y,markDismissedOnDismiss:Y}}async function Eg5(A){await NJ((Q)=>mX0(Q,A,"interactive"))}async function Bs4(A,Q={}){let{initialThreadID:B,initialUserInput:$,getDefaultNewThreadVisibility:J,openThreadPickerOnStart:Y=!1,observerOnly:Z=!1,initialAgentMode:F,initialReasoningEffort:X,showNeoWelcome:D=!1,hideNeoWelcome:G=!1,neoWelcomeVariant:V="intro"}=Q,U=V==="npm-migration",K=async(T)=>{let k=await A.getThreadFromServer(T);if(!k)return null;return xF0(k)},E=async(T)=>{let k=await A.getThreadFromServer(T);if(!k)throw Error(`Thread ${T} not found`);let x=await nY(T,A.configService,A.apiKey,{usesThreadActors:!0}),S=await OU({endpoint:A.rivetEndpoint}).threadActor.getOrCreate([T],{params:{wsToken:x.wsToken},createWithInput:{threadId:x.threadId,threadVersion:x.threadVersion,ownerUserId:x.ownerUserId,...x.agentMode?{agentMode:x.agentMode}:{}}}).fetch("/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({thread:Ex4(k)}),skipReadyWait:!0});if(!S.ok&&S.status!==409)throw Error(`Thread import failed (${S.status}): ${await S.text()}`);try{await px4(T,A.configService,A.apiKey,{executorType:"local-client"})}catch(u){j.warn("failed to mark thread as imported on server",{threadID:T,error:u instanceof Error?u.message:String(u)})}},z=new me0(A.rivetEndpoint,A.apiKey,A.configService,{clientID:QI.parse(`neo-${crypto.randomUUID()}`),toolService:A.toolService,skillService:A.skillService,requestPluginToolCall:(T)=>A.pluginService.event.toolCall(T),requestPluginToolResult:(T)=>A.pluginService.event.toolResult(T),pluginService:A.pluginService,invokeTool:async(T,k)=>{let x=typeof k.args==="object"&&k.args!==null?k.args:{},h=await YI({toolName:k.toolName,configService:A.configService,toolService:A.toolService,mcpService:A.mcpService,skillService:A.skillService,toolUseID:k.toolCallId,threadId:T});return A.toolService.invokeTool(k.toolName,{args:x},h)},persistLastThreadID:Eg5,readFileSystemDirectory:A.readFileSystemDirectory},K,E),W=await II(),H=Kg5({initialUserInput:$,showNeoWelcome:D,hideNeoWelcome:G,neoWelcomeVariant:V,neoWelcomeDismissed:W.neoWelcomeDismissed}),q={ampURL:A.ampURL,configService:A.configService,getThreadMarkdown:async(T)=>{let k=await A.getThreadFromServer(T);return k?SV(k):null},isInternalUser:A.isInternalUser,listThreads:A.listThreads,logFilePath:da,mcpServers:A.mcpService.servers,pluginPlatform:A.pluginPlatform,pluginService:A.pluginService,toolboxes:A.toolboxes,observerOnly:U?!1:Z,sessionAgentMode:F??W.agentMode,explicitReasoningEffort:X,lastReasoningEffortByMode:W.lastReasoningEffortByMode,lastSpeedByMode:W.lastSpeedByMode,settingsFilePath:A.settingsFilePath,splashOrbVisualStyle:Q.splashOrbVisualStyle??"neo",workspaceRoot:A.workspaceRoot},N=(T,k)=>{return Yx({ampURL:A.ampURL,configService:A.configService,threadID:T,signal:k})},I=(T,k)=>{return ph4({ampURL:A.ampURL,configService:A.configService,threadID:T,signal:k})},w=new F01,O=Qs4({configService:A.configService}),L=await A.configService.getLatest();C4.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:L.settings["terminal.animation"]===!1}});let P=new Set;try{await Qr(new h61({clientPool:z,analyzeContextForThread:N,listSkillsForThread:I,completionBuilder:A.completionBuilder,history:new Xo,ideManager:w,configService:A.configService,initialThreadID:U?void 0:B,notificationService:O,initialUserInput:U?void 0:$,getDefaultNewThreadVisibility:J,openThreadPickerOnStart:U?!1:Y,neoContext:q,showNeoWelcome:H.show,neoWelcomeVariant:V,onNeoWelcomeDismissed:H.markDismissedOnDismiss?()=>{NJ(ih4).catch((k)=>{j.warn("Failed to mark Neo welcome as dismissed",{error:k})})}:void 0,onThreadArchived:(k)=>{P.add(k)}}));let T=z.lastActiveObservingClient;if(T){let{client:k,observer:x}=T,h=k.getThreadId();if(h){let f={id:h,title:x.title().getValue(),agentMode:x.agentMode,archived:P.has(h)},S=`${A.ampURL.replace(/\/$/,"")}/threads/${h}`;As4(f,S,process.stdout)}}}finally{process.stdout.write(KI("")),O.unsubscribe(),z.dispose(),await A.dispose?.()}process.exit(0)}mp();eK();async function zg5(A,Q,B){let $=H80(A);if(!$.success)throw Error(`Invalid permission format: ${$.error.message}`);if($.data.length===0)throw Error("No permission entry provided");let J=xH($.data);if(!J.success){let X=J.error.issues.map((D)=>D.message).join(", ");throw Error(`Invalid permission entry: ${X}`)}let Y=await Q.get("permissions",B)??[],F=[$.data[0],...Y];await Q.set("permissions",F,B)}async function $s4(A){try{let Q=A.args.map((B)=>{if(/[\s/\\*?[\]{}()"]/.test(B))return`"${B}"`;return B}).join(" ");await zg5(Q,A.settings,A.scope),A.exit(0)}catch(Q){let B=Q instanceof Error?Q.message:"Unknown error";A.stderr.write(`Error: ${B}
@@ -7483,7 +7483,7 @@ ${J}`,Q);this.line=B,this.column=$,this.codeblock=J}}/*!
7483
7483
  `),Y=[];for(let Z=0;Z<J.length;Z++){let D=J[Z].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let G of D)if(G.startsWith("\x00")&&G.endsWith("\x01"))Y.push(new C(G.slice(1,-1),new v({color:$.app.keybind,bold:!0})));else Y.push(new C(G,new v({color:B.colorScheme.foreground})));if(Z<J.length-1)Y.push(new C(`
7484
7484
  `))}return new g0({decoration:{color:B.colorScheme.background,border:c1.all(new l1($.app.keybind,1,"rounded"))},child:new f0({padding:K0.symmetric(0,1),child:new p({text:new C(void 0,void 0,Y)})})})}}class i51 extends Y8{chartData;highlightIndex;showAxes;colors;constructor({key:A,chartData:Q,highlightIndex:B=null,showAxes:$=!0,colors:J=qU0}){super(A?{key:A}:{});this.chartData=Q,this.highlightIndex=B,this.showAxes=$,this.colors=J}createRenderObject(){return new c51({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(A){let Q=A;Q.chartData=this.chartData,Q.highlightIndex=this.highlightIndex,Q.showAxes=this.showAxes,Q.colors=this.colors,Q.markNeedsLayout()}}function C0A(A,Q,B,$,J,Y,Z){if(Y<=0)return null;switch(A){case"horizontal-bar":{let F=B;return F>=0&&F<Y?F:null}case"bar":case"stacked-bar":{let F=Z?p8:0,X=$-F;if(X<=0)return null;let D=Q-F;if(D<0||D>=X)return null;let G=Math.max(1,Math.floor(X/Y)),V=Math.floor(D/G);return V>=0&&V<Y?V:null}case"line":case"sparkline":case"stacked-area":{let F=Z?p8:0,X=$-F;if(X<=0)return null;let D=Math.max(0,Math.min(X-1,Q-F));if(Y===1)return 0;let G=X/(Y-1),V=Math.round(D/G);return Math.max(0,Math.min(Y-1,V))}default:return null}}function Li5(A,Q,B,$,J,Y,Z,F){if(J<=0||Q<0||Q>=J)return null;let X=2;switch(A){case"horizontal-bar":return{x:Math.floor(B/2),y:Q};case"bar":case"stacked-bar":{let D=Y?p8:0,G=B-D,V=$-(Y?X:0);if(G<=0||V<=0)return null;let U=Math.max(1,Math.floor(G/J)),K=D+Q*U+Math.floor(U/2),E=F>0?Z/F:0,z=Math.round((1-E)*(V-1));return{x:K,y:z}}case"line":case"sparkline":case"stacked-area":{let D=Y?p8:0,G=B-D,V=$-(Y?X:0);if(G<=0||V<=0)return null;let U=J>1?D+Math.round(Q/(J-1)*(G-1)):D+Math.floor(G/2),K=F>0?Z/F:0,E=Math.round((1-K)*(V-1));return{x:U,y:E}}default:return null}}function Oi5(A){let Q=0;for(let B of A)for(let $ of B.points)if($.value>Q)Q=$.value;return Q||1}function ji5(A,Q,B,$,J){if(B.length<=1){let F=$(A.value),X=A.meta?` (${A.meta})`:"";return A.label.length+2+F.length+X.length}let Y=A.label.length,Z=0;for(let F of B){let X=F.points[Q];if(!X)continue;Z+=X.value;let D=2+F.name.length+2+$(X.value).length;Y=Math.max(Y,D)}if(J){let F=9+$(Z).length;Y=Math.max(Y,F)}return Y}function Ri5(A,Q,B,$,J,Y,Z){let F;try{let E=j1.of(A),z=P0.of(A);F={foreground:E.colorScheme.foreground,background:E.colorScheme.background,border:z.app.keybind}}catch{F={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let X=new v({color:F.foreground,bold:!0}),D=new v({color:F.foreground}),G=new v({color:F.foreground,dim:!0}),V=[],U=new v({color:F.foreground,underline:!0}),K=(E,z)=>new C(z,U,void 0,vz(E),()=>{nA(A,E)});if($.length<=1){if(V.push(new C(`${Q.label}: `,X)),Q.link)V.push(K(Q.link,Y(Q.value)));else V.push(new C(Y(Q.value),D));if(Q.meta)V.push(new C(` (${Q.meta})`,G))}else{let E=Z==="stacked-bar"||Z==="stacked-area";V.push(new C(`${Q.label}
7485
7485
  `,X));let z=0;for(let W=0;W<$.length;W++){let H=$[W],q=H.points[B];if(!q)continue;z+=q.value;let N=H.color??J[W%J.length]??F.foreground;if(V.push(new C("● ",new v({color:N}))),V.push(new C(`${H.name}: `,G)),q.link)V.push(K(q.link,Y(q.value)));else V.push(new C(Y(q.value),D));if(W<$.length-1||E)V.push(new C(`
7486
- `))}if(E)V.push(new C(" ",G)),V.push(new C("Total: ",G)),V.push(new C(Y(z),D))}return new g0({decoration:{color:F.background,border:c1.all(new l1(F.border,1,"rounded"))},child:new p({text:new C(void 0,void 0,V)})})}d0();M3();z8();A3();u7();k7();E9();L2();kB();kV();i4();lS();qT();M1();d0();E9();class n51{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(A,Q){this.enabled=A;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let A=Array.from(this.commandCounts.entries()).map(([Q,B])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1778476494-g8a21dc"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await R30(Q,this.configService)}catch(Q){j.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class Fw extends T0{props;constructor(A){super();this.props=A}createState(){return new M0A}}class M0A extends _0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(A){let Q=(B)=>{this.setState(()=>{this._state=B(this._state)})};return this.widget.props.builder(A,Q,this._state)}}class L0A extends _0{controller=new L8;focusNode=new D6({debugLabel:"CommandArgumentPrompt",onKey:(A)=>{if(A.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(A){let Q=P0.of(A),{colors:B,app:$}=Q,J=this.widget.props.isRequiredArg??!0,Y=this.controller.text.trim().length>0,Z=!J||Y,F=c1.all(new l1(B.foreground,1,"solid")),X=new A$({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(K)=>{let E=K.trim();if(J&&E.length===0)return;this.widget.props.onSubmit(E)},autofocus:!0,style:{textColor:B.foreground,border:null},maxLines:1}),D=new r0({children:[new g0({decoration:{color:B.background},child:new p({text:new C(">",new v({color:B.foreground}))})}),new P1({child:X})]}),G=new g0({padding:K0.symmetric(1,0),child:new p({text:this.widget.props.title?new C(this.widget.props.title,new v({color:$.command,bold:!0})):new C("",void 0,[new C("Command: ",new v({color:B.foreground})),new C(this.widget.props.commandName,new v({color:$.command,bold:!0}))])})}),V=[];if(Z)V.push(new C("Enter",new v({color:$.keybind}))),V.push(new C(" to submit, ",new v({color:B.foreground,dim:!0})));V.push(new C("Esc",new v({color:$.keybind}))),V.push(new C(" to cancel",new v({color:B.foreground,dim:!0})));let U=new g0({padding:K0.symmetric(1,0),child:new p({text:new C("",void 0,V)})});return new g0({decoration:{border:F,color:B.background},padding:K0.all(1),child:new x0({children:[G,new U0({height:1}),D,new J5,U]})})}}class os extends T0{props;constructor(A){super();this.props=A}createState(){return new L0A}}kB();class O0A extends _0{controller=new L8;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new D6({debugLabel:"CommandMultilinePrompt",onKey:(A)=>{if(A.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(A)=>{if(this.imageAttachments.length>=s9)return!1;let Q=await sF(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(A){let Q=P0.of(A),{colors:B,app:$}=Q,Y=s1.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),F=new sD({controller:this.controller,triggers:[new PJ],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(K)=>{this.widget.props.onSubmit(K.trim(),this.imageAttachments)},theme:B,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:C4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),X=new d4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:F}),D=new g0({constraints:new w1({maxHeight:Z}),padding:K0.symmetric(1,0),child:X}),G=new g0({padding:K0.symmetric(1,0),child:new p({text:new C("",void 0,[new C("Command: ",new v({color:B.foreground})),new C(this.widget.props.commandName,new v({color:$.command,bold:!0}))])})}),V=new g0({padding:K0.symmetric(1,0),child:new p({text:this.isConfirmingClearInput?new C("",void 0,[new C("Esc",new v({color:$.keybind})),new C(" again to clear input",new v({color:B.foreground,dim:!0}))]):new C("",void 0,[new C("Press ",new v({color:B.foreground,dim:!0})),new C("Enter",new v({color:$.keybind})),new C(" to submit, ",new v({color:B.foreground,dim:!0})),new C("Esc",new v({color:$.keybind})),new C(" to clear",new v({color:B.foreground,dim:!0}))])})}),U=[G,new U0({height:1}),new P1({child:D}),new U0({height:1}),V];return new g0({decoration:{border:c1.all(new l1(B.foreground,1,"solid")),color:B.background},padding:K0.all(1),child:new x0({children:U})})}}class a51 extends T0{props;constructor(A){super();this.props=A}createState(){return new O0A}}function j0A(A){let B=new Date().getTime()-A.getTime(),$=Math.floor(B/60000),J=Math.floor(B/3600000),Y=Math.floor(B/86400000);if($<1)return"just now";if($<60)return`${$}m ago`;if(J<24)return`${J}h ago`;if(Y<7)return`${Y}d ago`;return A.toLocaleDateString()}class o51 extends q1{props;debugLabel="NewsFeedPicker";constructor(A){super();this.props=A}build(A){let Q=[...this.props.entries].sort((J,Y)=>Y.pubDate.getTime()-J.pubDate.getTime()),B=Math.max(0,...Q.map((J)=>j0A(J.pubDate).length));return new u6({items:Q,getLabel:(J)=>J.title,onAccept:(J)=>this.props.onSelect?.(J),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(J,Y,Z,F)=>{let X=P0.of(F),{colors:D}=X,G=X.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(z,W)=>new U0({width:W,child:r0.end([new p({text:new C(z,new v({color:K}))})])});return new g0({decoration:V?{color:V}:void 0,padding:K0.symmetric(2,0),child:new r0({children:[new P1({child:new p({text:new C(J.title,new v({color:U})),overflow:"ellipsis",maxLines:1})}),new U0({width:2}),E(j0A(J.pubDate),B)]})})}})}}class GB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!GB._instance)GB._instance=new GB;return GB._instance}get allExpanded(){return this._allExpanded}setAllExpanded(A){if(this._allExpanded===A)return;this._allExpanded=A,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(A){return this._listeners.add(A),()=>this.removeListener(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A()}}d0();class R0A extends _0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){j.error("Failed to load labels",A.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=A.result,this.isLoading=!1,this.setState()}catch(A){j.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let B=this.widget.props.currentLabels||[],$=this.labels.some((Y)=>Y.name===Q),J=B.includes(Q);return!$&&!J}build(A){let Q=P0.of(A),{app:B,colors:$}=Q,J=this.currentQuery.trim().toLowerCase(),Y=J.length>0?this.getValidationError(J):null,Z=this.getAvailableLabels(),X=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...Z];return new u6({title:"Add Label",items:X,getLabel:(D)=>{if("__isCreateMarker"in D)return this.currentQuery.trim().toLowerCase();return D.name},onAccept:(D)=>{if("__isCreateMarker"in D)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(D.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:Y||"Type to create a new label",renderItem:(D,G,V,U)=>{let K=G?B.selectionBackground:void 0,E=G?B.selectionForeground:$.foreground;if("__isCreateMarker"in D&&D.__isCreateMarker){let W=this.currentQuery.trim().toLowerCase();return new g0({decoration:K?{color:K}:void 0,padding:K0.symmetric(2,0),child:new p({text:new C("",void 0,[new C("Create new label: ",new v({color:E})),new C(W,new v({color:E,bold:!0}))])})})}return new g0({decoration:K?{color:K}:void 0,padding:K0.symmetric(2,0),child:new p({text:new C(D.name,new v({color:E}))})})},filterItem:(D,G)=>{if(this.currentQuery!==G)this.currentQuery=G,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in D&&D.__isCreateMarker)return this.shouldShowCreateMarker(G);let U=G.trim().toLowerCase();return U.length===0||D.name.includes(U)},sortItems:(D,G,V)=>{let U="__isCreateMarker"in D.item&&D.item.__isCreateMarker,K="__isCreateMarker"in G.item&&G.item.__isCreateMarker;if(U&&!K)return-1;if(!U&&K)return 1;return G.score-D.score}})}}class r51 extends T0{props;constructor(A){super();this.props=A}createState(){return new R0A}}class AG extends T0{props;constructor(A){super();this.props=A}createState(){return new P0A}}class P0A extends _0{_spinner=new W6;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(A){let Q=P0.of(A),{colors:B,app:$}=Q,J=c1.all(new l1(B.foreground,1,"solid")),Y=this._spinner.toBraille(),Z=new p({textAlign:"center",text:new C("",void 0,[new C(Y,new v({color:$.processing})),new C(" ",void 0),new C(this.widget.props.message,new v({color:B.foreground}))])}),X=[new P1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)X.push(new U0({height:2,child:new g0({padding:K0.symmetric(2,0),child:new p({text:new C("",new v({dim:!0}),[new C("Press ",new v({color:B.foreground})),new C("Esc",new v({color:B.info})),new C(" to cancel",new v({color:B.foreground}))])})})}));let D=new g0({decoration:new b4(B.background,J),child:new U0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:X})})});if(this.widget.props.onAbort)return new n4({debugLabel:"LoadingDialog",child:new d4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class rU extends T0{props;constructor(A){super();this.props=A}createState(){return new _0A}}class _0A extends _0{scrollController=new hA;scrollAreaKey=new Y2("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(A){return A instanceof y2}resolveFooterStyle(A){if(this.isWidgetMessage(A))return A.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let B=Q.size;if(typeof B.height==="number"&&B.height>0)return this.viewportHeight=B.height,B.height}return this.viewportHeight}build(A){let Q=P0.of(A),B=this.widget.props.message,$=(()=>{if(this.isWidgetMessage(B))return{title:B.title,type:B.type};if(B instanceof Error&&B.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:B.message};if(B instanceof Error&&B.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:B.message};let G=RD0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=c1.all(new l1(Q.colors.border,1,"solid")),Z=new g0({padding:K0.symmetric(1,0),child:new p({text:new C($.title,new v({color:J,bold:!0}))})}),F=this.isWidgetMessage(B)?B.widget:new p({text:new C($.description,new v({color:Q.colors.foreground})),selectable:!0}),X=new P1({child:new $3({child:new g0({padding:K0.symmetric(1,0),child:new r0({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new P1({child:new vA({controller:this.scrollController,autofocus:!0,child:F})}),new D2({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let G=this.scrollController.maxScrollExtent,V=this.scrollController.offset,U=this.getViewportHeight(),K=G+U;return{totalContentHeight:Math.max(K,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(V,0)}}})]})})})}),D=new g0({padding:K0.symmetric(1,0),child:new p({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new v({color:Q.colors.foreground,dim:!0})),new C("R",new v({color:Q.app.keybind})),new C(" to retry, ",new v({color:Q.colors.foreground,dim:!0})),new C("Esc",new v({color:Q.app.keybind})),new C(" to cancel",new v({color:Q.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new C("",new v({color:Q.colors.foreground,dim:!0}));if(G==="help"){let V=new v({color:Q.app.keybind}),U=new v({color:Q.colors.foreground,dim:!0});return new C("",U,[new C("Press ",U),new C("Escape",V),new C(" to close • Use ",U),new C("↑↓",V),new C(" or ",U),new C("j/k",V),new C(" to scroll",U)])}return new C("Press any key to close",new v({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new n4({debugLabel:"MessageDialog",child:new QA({fit:"expand",children:[new k1({onClick:()=>{},child:new U0}),new d4({onKey:(G)=>{if(this.widget.props.onRetry&&G.key==="r")return this.widget.props.onRetry(),"handled";if(G.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new g0({decoration:{border:Y,color:Q.colors.background},padding:K0.all(1),child:new x0({mainAxisAlignment:"center",children:[Z,new U0({height:1}),X,D]})})})]})})}}M3();r1();class T0A extends T0{props;constructor(A){super();this.props=A}createState(){return new k0A}}class k0A extends _0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=o0.file(this.widget.props.cwd),B=Y1.relativePath(Q,PA(A));if(B!==null&&B!==""&&B!==".."&&!B.startsWith("../"))return B;return k5(A)}statusIcon(A){let Q=g8.default(),{colors:B,app:$}=Q;switch(A){case"loading":return{icon:"◌",color:B.warning};case"active":return{icon:"✓",color:$.toolSuccess};case"error":return{icon:"✗",color:$.toolError}}}build(A){let Q=P0.of(A),{app:B}=Q;if(this.plugins.length===0)return new p({text:new C("No plugins found.",new v({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((X)=>X.status==="active").length,Z=this.plugins.reduce((X,D)=>X+D.registeredCommands.length,0),F=this.plugins.reduce((X,D)=>X+D.registeredTools.length,0);if($.push(new C(`${Y}/${J} ${V4(J,"plugin")} active`,new v({bold:!0}))),Z>0||F>0)$.push(new C(` (${Z} ${V4(Z,"command")}, ${F} ${V4(F,"tool")})`,new v({dim:!0})));$.push(new C(`
7486
+ `))}if(E)V.push(new C(" ",G)),V.push(new C("Total: ",G)),V.push(new C(Y(z),D))}return new g0({decoration:{color:F.background,border:c1.all(new l1(F.border,1,"rounded"))},child:new p({text:new C(void 0,void 0,V)})})}d0();M3();z8();A3();u7();k7();E9();L2();kB();kV();i4();lS();qT();M1();d0();E9();class n51{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(A,Q){this.enabled=A;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let A=Array.from(this.commandCounts.entries()).map(([Q,B])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1778480457-g5efd50"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await R30(Q,this.configService)}catch(Q){j.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class Fw extends T0{props;constructor(A){super();this.props=A}createState(){return new M0A}}class M0A extends _0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(A){let Q=(B)=>{this.setState(()=>{this._state=B(this._state)})};return this.widget.props.builder(A,Q,this._state)}}class L0A extends _0{controller=new L8;focusNode=new D6({debugLabel:"CommandArgumentPrompt",onKey:(A)=>{if(A.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(A){let Q=P0.of(A),{colors:B,app:$}=Q,J=this.widget.props.isRequiredArg??!0,Y=this.controller.text.trim().length>0,Z=!J||Y,F=c1.all(new l1(B.foreground,1,"solid")),X=new A$({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(K)=>{let E=K.trim();if(J&&E.length===0)return;this.widget.props.onSubmit(E)},autofocus:!0,style:{textColor:B.foreground,border:null},maxLines:1}),D=new r0({children:[new g0({decoration:{color:B.background},child:new p({text:new C(">",new v({color:B.foreground}))})}),new P1({child:X})]}),G=new g0({padding:K0.symmetric(1,0),child:new p({text:this.widget.props.title?new C(this.widget.props.title,new v({color:$.command,bold:!0})):new C("",void 0,[new C("Command: ",new v({color:B.foreground})),new C(this.widget.props.commandName,new v({color:$.command,bold:!0}))])})}),V=[];if(Z)V.push(new C("Enter",new v({color:$.keybind}))),V.push(new C(" to submit, ",new v({color:B.foreground,dim:!0})));V.push(new C("Esc",new v({color:$.keybind}))),V.push(new C(" to cancel",new v({color:B.foreground,dim:!0})));let U=new g0({padding:K0.symmetric(1,0),child:new p({text:new C("",void 0,V)})});return new g0({decoration:{border:F,color:B.background},padding:K0.all(1),child:new x0({children:[G,new U0({height:1}),D,new J5,U]})})}}class os extends T0{props;constructor(A){super();this.props=A}createState(){return new L0A}}kB();class O0A extends _0{controller=new L8;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new D6({debugLabel:"CommandMultilinePrompt",onKey:(A)=>{if(A.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(A)=>{if(this.imageAttachments.length>=s9)return!1;let Q=await sF(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(A){let Q=P0.of(A),{colors:B,app:$}=Q,Y=s1.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),F=new sD({controller:this.controller,triggers:[new PJ],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(K)=>{this.widget.props.onSubmit(K.trim(),this.imageAttachments)},theme:B,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:C4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),X=new d4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:F}),D=new g0({constraints:new w1({maxHeight:Z}),padding:K0.symmetric(1,0),child:X}),G=new g0({padding:K0.symmetric(1,0),child:new p({text:new C("",void 0,[new C("Command: ",new v({color:B.foreground})),new C(this.widget.props.commandName,new v({color:$.command,bold:!0}))])})}),V=new g0({padding:K0.symmetric(1,0),child:new p({text:this.isConfirmingClearInput?new C("",void 0,[new C("Esc",new v({color:$.keybind})),new C(" again to clear input",new v({color:B.foreground,dim:!0}))]):new C("",void 0,[new C("Press ",new v({color:B.foreground,dim:!0})),new C("Enter",new v({color:$.keybind})),new C(" to submit, ",new v({color:B.foreground,dim:!0})),new C("Esc",new v({color:$.keybind})),new C(" to clear",new v({color:B.foreground,dim:!0}))])})}),U=[G,new U0({height:1}),new P1({child:D}),new U0({height:1}),V];return new g0({decoration:{border:c1.all(new l1(B.foreground,1,"solid")),color:B.background},padding:K0.all(1),child:new x0({children:U})})}}class a51 extends T0{props;constructor(A){super();this.props=A}createState(){return new O0A}}function j0A(A){let B=new Date().getTime()-A.getTime(),$=Math.floor(B/60000),J=Math.floor(B/3600000),Y=Math.floor(B/86400000);if($<1)return"just now";if($<60)return`${$}m ago`;if(J<24)return`${J}h ago`;if(Y<7)return`${Y}d ago`;return A.toLocaleDateString()}class o51 extends q1{props;debugLabel="NewsFeedPicker";constructor(A){super();this.props=A}build(A){let Q=[...this.props.entries].sort((J,Y)=>Y.pubDate.getTime()-J.pubDate.getTime()),B=Math.max(0,...Q.map((J)=>j0A(J.pubDate).length));return new u6({items:Q,getLabel:(J)=>J.title,onAccept:(J)=>this.props.onSelect?.(J),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(J,Y,Z,F)=>{let X=P0.of(F),{colors:D}=X,G=X.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(z,W)=>new U0({width:W,child:r0.end([new p({text:new C(z,new v({color:K}))})])});return new g0({decoration:V?{color:V}:void 0,padding:K0.symmetric(2,0),child:new r0({children:[new P1({child:new p({text:new C(J.title,new v({color:U})),overflow:"ellipsis",maxLines:1})}),new U0({width:2}),E(j0A(J.pubDate),B)]})})}})}}class GB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!GB._instance)GB._instance=new GB;return GB._instance}get allExpanded(){return this._allExpanded}setAllExpanded(A){if(this._allExpanded===A)return;this._allExpanded=A,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(A){return this._listeners.add(A),()=>this.removeListener(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A()}}d0();class R0A extends _0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){j.error("Failed to load labels",A.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=A.result,this.isLoading=!1,this.setState()}catch(A){j.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let B=this.widget.props.currentLabels||[],$=this.labels.some((Y)=>Y.name===Q),J=B.includes(Q);return!$&&!J}build(A){let Q=P0.of(A),{app:B,colors:$}=Q,J=this.currentQuery.trim().toLowerCase(),Y=J.length>0?this.getValidationError(J):null,Z=this.getAvailableLabels(),X=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...Z];return new u6({title:"Add Label",items:X,getLabel:(D)=>{if("__isCreateMarker"in D)return this.currentQuery.trim().toLowerCase();return D.name},onAccept:(D)=>{if("__isCreateMarker"in D)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(D.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:Y||"Type to create a new label",renderItem:(D,G,V,U)=>{let K=G?B.selectionBackground:void 0,E=G?B.selectionForeground:$.foreground;if("__isCreateMarker"in D&&D.__isCreateMarker){let W=this.currentQuery.trim().toLowerCase();return new g0({decoration:K?{color:K}:void 0,padding:K0.symmetric(2,0),child:new p({text:new C("",void 0,[new C("Create new label: ",new v({color:E})),new C(W,new v({color:E,bold:!0}))])})})}return new g0({decoration:K?{color:K}:void 0,padding:K0.symmetric(2,0),child:new p({text:new C(D.name,new v({color:E}))})})},filterItem:(D,G)=>{if(this.currentQuery!==G)this.currentQuery=G,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in D&&D.__isCreateMarker)return this.shouldShowCreateMarker(G);let U=G.trim().toLowerCase();return U.length===0||D.name.includes(U)},sortItems:(D,G,V)=>{let U="__isCreateMarker"in D.item&&D.item.__isCreateMarker,K="__isCreateMarker"in G.item&&G.item.__isCreateMarker;if(U&&!K)return-1;if(!U&&K)return 1;return G.score-D.score}})}}class r51 extends T0{props;constructor(A){super();this.props=A}createState(){return new R0A}}class AG extends T0{props;constructor(A){super();this.props=A}createState(){return new P0A}}class P0A extends _0{_spinner=new W6;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(A){let Q=P0.of(A),{colors:B,app:$}=Q,J=c1.all(new l1(B.foreground,1,"solid")),Y=this._spinner.toBraille(),Z=new p({textAlign:"center",text:new C("",void 0,[new C(Y,new v({color:$.processing})),new C(" ",void 0),new C(this.widget.props.message,new v({color:B.foreground}))])}),X=[new P1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)X.push(new U0({height:2,child:new g0({padding:K0.symmetric(2,0),child:new p({text:new C("",new v({dim:!0}),[new C("Press ",new v({color:B.foreground})),new C("Esc",new v({color:B.info})),new C(" to cancel",new v({color:B.foreground}))])})})}));let D=new g0({decoration:new b4(B.background,J),child:new U0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:X})})});if(this.widget.props.onAbort)return new n4({debugLabel:"LoadingDialog",child:new d4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class rU extends T0{props;constructor(A){super();this.props=A}createState(){return new _0A}}class _0A extends _0{scrollController=new hA;scrollAreaKey=new Y2("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(A){return A instanceof y2}resolveFooterStyle(A){if(this.isWidgetMessage(A))return A.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let B=Q.size;if(typeof B.height==="number"&&B.height>0)return this.viewportHeight=B.height,B.height}return this.viewportHeight}build(A){let Q=P0.of(A),B=this.widget.props.message,$=(()=>{if(this.isWidgetMessage(B))return{title:B.title,type:B.type};if(B instanceof Error&&B.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:B.message};if(B instanceof Error&&B.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:B.message};let G=RD0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=c1.all(new l1(Q.colors.border,1,"solid")),Z=new g0({padding:K0.symmetric(1,0),child:new p({text:new C($.title,new v({color:J,bold:!0}))})}),F=this.isWidgetMessage(B)?B.widget:new p({text:new C($.description,new v({color:Q.colors.foreground})),selectable:!0}),X=new P1({child:new $3({child:new g0({padding:K0.symmetric(1,0),child:new r0({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new P1({child:new vA({controller:this.scrollController,autofocus:!0,child:F})}),new D2({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let G=this.scrollController.maxScrollExtent,V=this.scrollController.offset,U=this.getViewportHeight(),K=G+U;return{totalContentHeight:Math.max(K,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(V,0)}}})]})})})}),D=new g0({padding:K0.symmetric(1,0),child:new p({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new v({color:Q.colors.foreground,dim:!0})),new C("R",new v({color:Q.app.keybind})),new C(" to retry, ",new v({color:Q.colors.foreground,dim:!0})),new C("Esc",new v({color:Q.app.keybind})),new C(" to cancel",new v({color:Q.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new C("",new v({color:Q.colors.foreground,dim:!0}));if(G==="help"){let V=new v({color:Q.app.keybind}),U=new v({color:Q.colors.foreground,dim:!0});return new C("",U,[new C("Press ",U),new C("Escape",V),new C(" to close • Use ",U),new C("↑↓",V),new C(" or ",U),new C("j/k",V),new C(" to scroll",U)])}return new C("Press any key to close",new v({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new n4({debugLabel:"MessageDialog",child:new QA({fit:"expand",children:[new k1({onClick:()=>{},child:new U0}),new d4({onKey:(G)=>{if(this.widget.props.onRetry&&G.key==="r")return this.widget.props.onRetry(),"handled";if(G.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new g0({decoration:{border:Y,color:Q.colors.background},padding:K0.all(1),child:new x0({mainAxisAlignment:"center",children:[Z,new U0({height:1}),X,D]})})})]})})}}M3();r1();class T0A extends T0{props;constructor(A){super();this.props=A}createState(){return new k0A}}class k0A extends _0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=o0.file(this.widget.props.cwd),B=Y1.relativePath(Q,PA(A));if(B!==null&&B!==""&&B!==".."&&!B.startsWith("../"))return B;return k5(A)}statusIcon(A){let Q=g8.default(),{colors:B,app:$}=Q;switch(A){case"loading":return{icon:"◌",color:B.warning};case"active":return{icon:"✓",color:$.toolSuccess};case"error":return{icon:"✗",color:$.toolError}}}build(A){let Q=P0.of(A),{app:B}=Q;if(this.plugins.length===0)return new p({text:new C("No plugins found.",new v({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((X)=>X.status==="active").length,Z=this.plugins.reduce((X,D)=>X+D.registeredCommands.length,0),F=this.plugins.reduce((X,D)=>X+D.registeredTools.length,0);if($.push(new C(`${Y}/${J} ${V4(J,"plugin")} active`,new v({bold:!0}))),Z>0||F>0)$.push(new C(` (${Z} ${V4(Z,"command")}, ${F} ${V4(F,"tool")})`,new v({dim:!0})));$.push(new C(`
7487
7487
 
7488
7488
  `));for(let X of this.plugins){let{icon:D,color:G}=this.statusIcon(X.status),V=this.getRelativePath(X.uri);if($.push(new C(`${D} `,new v({color:G}))),$.push(new C(V,new v({bold:!0}))),$.push(new C(` ${X.status}`,new v({dim:!0}))),$.push(new C(`
7489
7489
  `)),X.status==="active"&&X.registeredEvents.length>0)$.push(new C(" Events: ",new v({dim:!0}))),$.push(new C(X.registeredEvents.join(", "),new v({color:B.link}))),$.push(new C(`
@@ -7661,7 +7661,7 @@ ${r.content||""}`:r.content||"",b0=[],h0=r.baseDir.startsWith("file://")?nU0(r.b
7661
7661
  `)}function UAA(A,Q){A.command("usage").description("Show your current Amp usage and credit balance").action(async(B,$)=>{let J=$.optsWithGlobals(),Y=await Q(J),Z=await Y.settings.get("proxy"),F=B04({settings:{url:Y.ampURL,proxy:Z},secrets:{getToken:(D,G)=>Y.secrets.get(D,G)}}),X=await DA.userDisplayBalanceInfo({},{config:F});if(!X.ok){if(X.error.code==="auth-required")process.stderr.write(n0.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(n0.red("Error: ")+X.error.message+`
7662
7662
  `),process.exit(1)}process.stdout.write(await lo5(X.result.displayText)+`
7663
7663
  `),process.exit(0)})}var K03=vt.join(x$,"logs","headless.log"),e21=vt.join(jx,"device-id.json"),E03=`cli-tui-${h3A(16).toString("hex")}`;async function z03(){for(let A of mM)try{if((await A.listConfigs()).length>0)return A}catch(Q){j.debug("Failed to detect query-based IDE integration",{ideName:A.ideName,error:Q})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => v4(_b(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){fJ.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
7664
- `)}function W03(A){process.emitWarning=(Q,B,$,J)=>{let Y=typeof Q==="string"?Q:Q.message||String(Q),Z=B||"Warning",F=!1;A.warn(Y,{name:Z,code:$})}}function u2(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")FY("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")FY("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)FY("internal.model",N03(Q.model))}function v3A(A){let Q=A.indexOf(":");if(Q===-1)throw new $4(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let B=A.slice(0,Q).trim(),$=A.slice(Q+1).trim();if(!B||!$)throw new $4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function H03(A){if(A===void 0)return;let Q=A.trim();if(de1(Q))return Q;throw new $4(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function q03(A,Q){if(bX(A,Q))return;let B=p$(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new $4(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function N03(A){if(!A.includes("="))return v3A(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new $4(`Invalid mode-specific model entry "${$}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let Y=$.slice(0,J).trim(),Z=$.slice(J+1).trim();if(!Y)throw new $4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new $4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);v3A(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new $4("No valid model overrides found in --model flag value.",1);return Q}function I03(A,Q){if(A.getOptionValueSourceWithGlobals("sp")==="cli"&&Q.sp)return Q.sp;if(A.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Q.systemPrompt)return Q.systemPrompt;return}async function w03(A){try{return await g3A(A,"utf-8")}catch{return A}}async function A91(A,Q,B){let $=I03(A,Q);if(!$)return;let J=mA(B)?B.features:[],Y=mA(B)?B.user.email:void 0;if(!hK0(J,OB.HARNESS_SYSTEM_PROMPT)&&!(Y&&_7(Y)))throw new $4("You are not allowed to do this.",1);FY("systemPrompt",await w03($))}function hK0(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function C03(A){return A!=="pending"}function Mw(A){if(!mA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function M03(A){let Q=Mw(A);if(Q)return Q.id;if(fX(A))throw Error(A.error.message);throw Error("unreachable")}function L03(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 O03(A){let $=L03(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 $4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function yt(A,Q){let B=ir0(Error(A.error.message));if(B.message===D7.networkOffline||B.message===D7.networkTimeout)return O03(Q);if(B.message!==D7.internalBug)return new $4(B.message,1,B.suggestion);return new $4(A.error.message.replace(/^Error: /,""),1)}async function j03(){if(process.versions.bun)return!1;try{return await DI()==="npm"}catch(A){return j.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var y3A=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH; 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??mF,description:`Custom settings file path (overrides the default location ${mF})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${da})`},{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:Z9(),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:hM.SMART.key,description:`Set the agent mode (${g$({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(g$().map((A)=>A.mode))),hiddenChoices:["frontier"]},{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:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neoOrb",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:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0},{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}],x3A=(A)=>("deprecated"in A)&&A.deprecated===!0,R03=(A)=>("hidden"in A)&&A.hidden===!0,P03=(A)=>("default"in A),_03=(A)=>("default"in A)?A.default:void 0;function fK0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=H03(Q.effort);if(B!==void 0)q03(Q.mode,B);return B}function T03(A,Q){let B=Q.args[0],$=Q.commands.map((Y)=>Y.name());if(B&&!B.includes(" ")&&B.length<30&&!/[./\\]/.test(B)){let Y=$.filter((F)=>B.includes(F)||F.includes(B)),Z="Run amp --help for a list of available commands.";if(Y.length>0)Z=`Did you mean: ${Y.join(", ")}? Or run amp --help for all commands.`;throw new $4(D7.unknownCommand(B),1,Z)}}async function gK0(A){return{...A,getThreadEnvironment:Iz,getEnvironmentData:(Q,B)=>$D({filesystem:A.fileSystem},Q,B),osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new ML(A.fileSystem),generateThreadTitle:QF4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>jQ(A.configService),pluginService:A.pluginService}}function m3A(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:Iz,getEnvironmentData:(Q,B)=>$D({filesystem:A.fileSystem},Q,B),filesystem:A.fileSystem,threadService:A.threadService}}var bK0=o0.file(U03.homedir()),Q91=process.env.XDG_CONFIG_HOME?o0.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(bK0,".config");function k03(A){return _R4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(rF0())sF0();else FZ0(Q);let B=uj(),$=Ar();if((!B||$||_x())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(bD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(bD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(uj()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function d8(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;ye1("0.0.1778476494-g8a21dc");let Y=v30({storage:A.settings,secretStorage:A.secrets,workspaceRoot:m0.of(o0.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:bK0,userConfigDir:Q91});Ps4(Y);let Z=await Y.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let F=!1;{let g=await A.secrets.get("apiKey",A.ampURL);if(F=Boolean(g),j.info("API key lookup before login",{found:Boolean(g),ampURL:A.ampURL,deferAuth:$}),!g)if($)j.info("No API key found, continuing startup with deferred auth");else{X5.write(`No API key found. Starting login flow...
7664
+ `)}function W03(A){process.emitWarning=(Q,B,$,J)=>{let Y=typeof Q==="string"?Q:Q.message||String(Q),Z=B||"Warning",F=!1;A.warn(Y,{name:Z,code:$})}}function u2(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")FY("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")FY("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)FY("internal.model",N03(Q.model))}function v3A(A){let Q=A.indexOf(":");if(Q===-1)throw new $4(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let B=A.slice(0,Q).trim(),$=A.slice(Q+1).trim();if(!B||!$)throw new $4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function H03(A){if(A===void 0)return;let Q=A.trim();if(de1(Q))return Q;throw new $4(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function q03(A,Q){if(bX(A,Q))return;let B=p$(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new $4(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function N03(A){if(!A.includes("="))return v3A(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new $4(`Invalid mode-specific model entry "${$}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let Y=$.slice(0,J).trim(),Z=$.slice(J+1).trim();if(!Y)throw new $4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new $4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);v3A(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new $4("No valid model overrides found in --model flag value.",1);return Q}function I03(A,Q){if(A.getOptionValueSourceWithGlobals("sp")==="cli"&&Q.sp)return Q.sp;if(A.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Q.systemPrompt)return Q.systemPrompt;return}async function w03(A){try{return await g3A(A,"utf-8")}catch{return A}}async function A91(A,Q,B){let $=I03(A,Q);if(!$)return;let J=mA(B)?B.features:[],Y=mA(B)?B.user.email:void 0;if(!hK0(J,OB.HARNESS_SYSTEM_PROMPT)&&!(Y&&_7(Y)))throw new $4("You are not allowed to do this.",1);FY("systemPrompt",await w03($))}function hK0(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function C03(A){return A!=="pending"}function Mw(A){if(!mA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function M03(A){let Q=Mw(A);if(Q)return Q.id;if(fX(A))throw Error(A.error.message);throw Error("unreachable")}function L03(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 O03(A){let $=L03(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 $4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function yt(A,Q){let B=ir0(Error(A.error.message));if(B.message===D7.networkOffline||B.message===D7.networkTimeout)return O03(Q);if(B.message!==D7.internalBug)return new $4(B.message,1,B.suggestion);return new $4(A.error.message.replace(/^Error: /,""),1)}async function j03(){if(process.versions.bun)return!1;try{return await DI()==="npm"}catch(A){return j.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var y3A=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH; 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??mF,description:`Custom settings file path (overrides the default location ${mF})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${da})`},{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:Z9(),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:hM.SMART.key,description:`Set the agent mode (${g$({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(g$().map((A)=>A.mode))),hiddenChoices:["frontier"]},{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:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neoOrb",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:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0},{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}],x3A=(A)=>("deprecated"in A)&&A.deprecated===!0,R03=(A)=>("hidden"in A)&&A.hidden===!0,P03=(A)=>("default"in A),_03=(A)=>("default"in A)?A.default:void 0;function fK0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=H03(Q.effort);if(B!==void 0)q03(Q.mode,B);return B}function T03(A,Q){let B=Q.args[0],$=Q.commands.map((Y)=>Y.name());if(B&&!B.includes(" ")&&B.length<30&&!/[./\\]/.test(B)){let Y=$.filter((F)=>B.includes(F)||F.includes(B)),Z="Run amp --help for a list of available commands.";if(Y.length>0)Z=`Did you mean: ${Y.join(", ")}? Or run amp --help for all commands.`;throw new $4(D7.unknownCommand(B),1,Z)}}async function gK0(A){return{...A,getThreadEnvironment:Iz,getEnvironmentData:(Q,B)=>$D({filesystem:A.fileSystem},Q,B),osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new ML(A.fileSystem),generateThreadTitle:QF4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>jQ(A.configService),pluginService:A.pluginService}}function m3A(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:Iz,getEnvironmentData:(Q,B)=>$D({filesystem:A.fileSystem},Q,B),filesystem:A.fileSystem,threadService:A.threadService}}var bK0=o0.file(U03.homedir()),Q91=process.env.XDG_CONFIG_HOME?o0.file(process.env.XDG_CONFIG_HOME):Y1.joinPath(bK0,".config");function k03(A){return _R4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(rF0())sF0();else FZ0(Q);let B=uj(),$=Ar();if((!B||$||_x())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(bD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(bD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(uj()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function d8(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;ye1("0.0.1778480457-g5efd50");let Y=v30({storage:A.settings,secretStorage:A.secrets,workspaceRoot:m0.of(o0.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:bK0,userConfigDir:Q91});Ps4(Y);let Z=await Y.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let F=!1;{let g=await A.secrets.get("apiKey",A.ampURL);if(F=Boolean(g),j.info("API key lookup before login",{found:Boolean(g),ampURL:A.ampURL,deferAuth:$}),!g)if($)j.info("No API key found, continuing startup with deferred auth");else{X5.write(`No API key found. Starting login flow...
7665
7665
  `);let l=await S03(A),s=await A.secrets.get("apiKey",A.ampURL);if(j.info("Login flow completed",{success:l,storedKeyPresent:Boolean(s),ampURL:A.ampURL}),!l)await jz(),process.exit(1);F=!0}}{let g=await Y.getLatest(),l=g.settings.url,s=g.secrets.isSet?.[l];j.info("Config secrets state after login",{configURL:l,apiKeySet:s?.apiKey??!1})}let X=T1(jQ(Y).pipe(t6(C03))),D=$?"pending":await X;if(!$)j.info("Server status resolved",{status:"ready",isAuthenticated:mA(D),isError:fX(D),errorMessage:fX(D)?D.error.message:void 0});let G=X.then((g)=>M03(g));G.catch(()=>{return});let U=!Q.takeMeBack&&mA(D)&&hK0(D.features,OB.THREAD_ACTORS_TUI)?"all":process.env.PLUGINS??"permissions",{toolService:K,dispose:E}=LR4({configService:Y}),z=new Map,W=()=>z.clear(),H=new kf0(Y,A.settings.getWorkspaceRootPath()),q=kJ4({configService:Y,filesystem:j3}),N=w74({configService:Y,trustStore:H,skillMCPServers:q.skillMCPServers,createOAuthProvider:async(g,l,s)=>{let A0=`${g}:${l}`,H0=z.get(A0);if(H0)return j.debug("Reusing existing OAuth provider for server",{serverName:g,serverUrl:l}),H0;j.debug("Creating OAuth provider for server",{serverName:g,serverUrl:l});let V0=(async()=>{let w0=new nM(A.secrets),Z0=await w0.getClientInfo(g,l),R0=s?.scopes??Z0?.scopes,B0=Rf4();j.info("OAuth headless mode check",{useHeadless:B0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:X5.isTTY});let N0;if(B0)N0=A.executeMode?jf4():Of4(g);let n=new pS0({storage:w0,serverName:g,serverUrl:l,clientId:s?.clientId??Z0?.clientId,clientSecret:s?.clientSecret??Z0?.clientSecret,authUrl:s?.authUrl??Z0?.authUrl,tokenUrl:s?.tokenUrl??Z0?.tokenUrl,scopes:R0,headlessAuthHandler:N0});return j.debug("OAuth provider created",{serverName:g,serverUrl:l,hasManualClientId:!!(s?.clientId??Z0?.clientId),willUseDCR:!(s?.clientId??Z0?.clientId),scopes:R0,headlessMode:B0,executeMode:A.executeMode}),n})();return z.set(A0,V0),V0}}),I=Sn0({configService:Y,filesystem:j3,spawn:RY0}),w=Q.headless?Ds4():void 0,O=w??new ZV0({configService:Y}),L=O instanceof ZV0?O:void 0;if(L)L.pluginExecutorKind="local";let P=of0({configService:Y,fileSystem:j3,platform:O,loadGlobalPlugins:Mt0(Y),pluginFilter:U}),T=IQ4(P),k=[N,I,T],x;if(J)x=new Map;else if(A.executeMode){let g=await AO4({toolService:K,providers:k,initialTimeout:15000});x=g.registrations;for(let[l,s]of g.initErrors)j.warn(`${l} provider initialization slow or failed:`,s)}else x=vn0({toolService:K,providers:k});if(Q.jetbrains)xM("JetBrains");else if(Q.ide&&Vb4())xM("VS Code");else if(Q.ide&&Ub4())xM("Neovim");else if(Q.ide){let g=await z03();if(g){let l=d30(g.ideName);if(l)xM(l)}}if(A.executeMode)xe1(!0);let h,f=u3.status.pipe(I1((g)=>Boolean(g.connected&&g.authenticated&&g.ideName&&S04(g.ideName))),_4()).subscribe((g)=>{if(g){if(!h)h=K.registerTool(eL4)}else h?.dispose(),h=void 0}),S;if(!A.executeMode){let g=await A.settings.get("fuzzy.alwaysIncludePaths")??[];S=new nF0(process.cwd(),{alwaysIncludePaths:g},!0)}else S=new class extends nF0{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let u=new ah0(Ll(Y,{usesThreadActors:!1}),{maxThreads:200});j.info("Starting Amp background services");let d=new i61,c={configService:Y,toolService:K,mcpService:N,skillService:q,toolboxService:I,trustStore:H,threadService:u,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:S,fileSystem:j3,terminal:d,pluginService:P,pluginPlatform:L,headlessPluginPlatform:w,serverStatus:D,serverStatusPromise:X,viewerUserIDPromise:G,hasAPIKeyAtStartup:F};return{...c,async asyncDispose(){if(c.mcpService.hasAuthenticatingClients())j.info("Waiting for OAuth authentication to complete before exit..."),await c.mcpService.waitForAuthentication();for(let g of x.values())g.dispose();await c.mcpService.dispose(),W(),await c.threadService.asyncDispose(),c.configService.unsubscribe(),E(),c.fuzzyServer.dispose(),c.settingsStorage[Symbol.dispose](),f.unsubscribe(),h?.dispose(),await c.pluginService.dispose()}}}async function S03(A){if(!A.executeMode){if(!await fX0("Would you like to log in to Amp? [(y)es, (n)o]: "))return X5.write(`Login cancelled. Run the command again to retry.
7666
7666
  `),!1}return await p3A(A)}async function p3A(A){let Q=h3A(32).toString("hex"),B=await ux(A.ampURL,Q),$=new AbortController;try{await vX(B,$.signal)}catch(Y){j.error("Error opening browser",{error:Y})}let J=await ux(A.ampURL,Q,!1);X5.write(`If your browser does not open automatically, visit:
7667
7667
 
@@ -7669,7 +7669,7 @@ ${n0.blue.bold(J)}
7669
7669
 
7670
7670
  `);try{return await _h4(A.ampURL,Q,A.secrets,$),X5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(Y){return j.error("Login failed",{error:Y}),fJ.write(`
7671
7671
  Login failed: ${Y instanceof Error?Y.message:String(Y)}
7672
- `),!1}}async function v03(A,Q,B){let $=await Q.get("apiKey",A);if(!$)throw new $4("No Amp API key found. Run `amp login` first.",1);let J=D03("curl",["-H",`Authorization: Bearer ${$}`,...B],{stdio:"inherit"});process.exitCode=await new Promise((Y,Z)=>{J.on("error",Z),J.on("close",(F)=>Y(F??1))})}function y03(A){let Q=new pN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((W)=>{if(W.code==="commander.help"||W.code==="commander.version"||W.exitCode===0)Wj(),process.exit(0);let H=W.originalError??W;Dv4(H)}),bg4(Q,{version:"0.0.1778476494-g8a21dc",buildTimestamp:"2026-05-11T05:19:01.767Z",buildType:"'release'"}),Q.addHelpText("after",Xb4()),Q.configureHelp({formatHelp:Db4}),Q.command("logout").description("Log out by removing stored API key").action(async(W,H)=>{let q=H.optsWithGlobals(),N=await c5(q);await d03(N)}),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(W,H)=>{let q=H.optsWithGlobals(),N=await c5(q);await p03(N,await xt0(q,N.settings))}),Zv4(Q,c5);let $=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(...W)=>{let H=W.find((w)=>typeof w==="object"&&w!==null&&typeof w.optsWithGlobals==="function")??$,q=W.filter((w)=>w!==H).flatMap((w)=>Array.isArray(w)?w:typeof w==="string"?[w]:[]),N=H.optsWithGlobals(),I=await c5(N);await v03(I.ampURL,I.secrets,q),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(W,H,q)=>{let N=q.optsWithGlobals(),I=await c5(N);await Hf4(W??"get",I.ampURL,I.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(W,H)=>{let q=H.optsWithGlobals(),N=await c5(q);await qf4(N.ampURL,N.secrets),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(W)=>{await Pu4({raw:W.raw===!0}),process.exit(process.exitCode??0)}),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(`
7672
+ `),!1}}async function v03(A,Q,B){let $=await Q.get("apiKey",A);if(!$)throw new $4("No Amp API key found. Run `amp login` first.",1);let J=D03("curl",["-H",`Authorization: Bearer ${$}`,...B],{stdio:"inherit"});process.exitCode=await new Promise((Y,Z)=>{J.on("error",Z),J.on("close",(F)=>Y(F??1))})}function y03(A){let Q=new pN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((W)=>{if(W.code==="commander.help"||W.code==="commander.version"||W.exitCode===0)Wj(),process.exit(0);let H=W.originalError??W;Dv4(H)}),bg4(Q,{version:"0.0.1778480457-g5efd50",buildTimestamp:"2026-05-11T06:24:41.556Z",buildType:"'release'"}),Q.addHelpText("after",Xb4()),Q.configureHelp({formatHelp:Db4}),Q.command("logout").description("Log out by removing stored API key").action(async(W,H)=>{let q=H.optsWithGlobals(),N=await c5(q);await d03(N)}),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(W,H)=>{let q=H.optsWithGlobals(),N=await c5(q);await p03(N,await xt0(q,N.settings))}),Zv4(Q,c5);let $=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(...W)=>{let H=W.find((w)=>typeof w==="object"&&w!==null&&typeof w.optsWithGlobals==="function")??$,q=W.filter((w)=>w!==H).flatMap((w)=>Array.isArray(w)?w:typeof w==="string"?[w]:[]),N=H.optsWithGlobals(),I=await c5(N);await v03(I.ampURL,I.secrets,q),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(W,H,q)=>{let N=q.optsWithGlobals(),I=await c5(N);await Hf4(W??"get",I.ampURL,I.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(W,H)=>{let q=H.optsWithGlobals(),N=await c5(q);await qf4(N.ampURL,N.secrets),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(W)=>{await Pu4({raw:W.raw===!0}),process.exit(process.exitCode??0)}),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(`
7673
7673
  `)).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(W,H,q)=>{if(W&&H.apply)throw new $4("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let N=H.apply??W;if(!N||N.trim().length===0)X5.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.
7674
7674
 
7675
7675
  `),q.outputHelp(),process.exit(0);let I=C2(N)??zJ(N),w=q.optsWithGlobals(),O=await c5(w);u2(q,w);let L=await d8(O,w),P=!1;try{if(H.checkout&&H.skipCheckout)throw new $4("Choose either --checkout or --skip-checkout, not both.",1);if(fX(L.serverStatus))throw yt(L.serverStatus,O.ampURL);let T=mA(L.serverStatus)?L.serverStatus.features:void 0;if(!hK0(T,OB.V2))throw new $4("live-sync is not enabled for your user",1);await qh4({ampURL:O.ampURL,threadId:I,configService:L.configService,threadService:L.threadService,apiKey:process.env.AMP_API_KEY,applyOnce:typeof H.apply==="string",checkoutMode:H.checkout?"always":H.skipCheckout?"never":"prompt",promptForYesNo:fX0}),P=!0}finally{if(await L.asyncDispose(),P)process.exit(0)}});let J=async(W,H,q)=>{v30({storage:H.settings,secretStorage:H.secrets,workspaceRoot:m0.of(o0.file(process.cwd())),defaultAmpURL:H.ampURL,homeDir:bK0,userConfigDir:Q91});let N={...H,executeMode:!1};await uK0(N,{...W,openThreadSwitcher:!0},q,A)},Y=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").action(async(W,H)=>{let q=H.optsWithGlobals(),N=await c5(q);await u3A(q,N,H)});Y.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(W,H)=>{let q=H.optsWithGlobals(),N=await c5(q);await A13(q,N,H)}),Y.command("continue [threadIDOrURL]").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.").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(W,H,q)=>{let N=q.optsWithGlobals(),I=await c5(N);if(H.pick)fJ.write(`${n0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
@@ -7702,8 +7702,8 @@ ${O}
7702
7702
  `))}),H.args.length>0)T03(N,H);await uK0(N,q,H,A)}),cb4(Q),Q}async function Tb(A,Q){await NJ((B)=>mX0(B,A,Q))}async function f3A(A,Q,B){let $=Date.now(),[J,Y]=await Promise.all([DA.getThreadLinkInfo({thread:A},{config:Q}),B]);if(j.getChild("fetchAndStartThread").info(`Ownership check in ${Date.now()-$}ms`),J.ok){let Z=J.result.creatorUserID;if(Z&&Z!==Y&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new $4(`Cannot resume thread created by another user.
7703
7703
 
7704
7704
  This thread belongs to a different user and cannot be continued for security reasons. Set AMP_RESUME_OTHER_USER_THREADS_INSECURE=1 to bypass this check.`)}}async function d3A(A){if(A.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof A.execute==="string"){let Q=(await XV0()).trimEnd();return{userInput:A.execute,stdinInput:Q||null}}return{userInput:(await XV0()).trimEnd(),stdinInput:null}}function c3A(A,Q,B){if(A.streamJson&&!Q)throw new $4("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new $4("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new $4("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new $4("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 $4("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archive&&!Q)throw new $4("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(A.streamJsonInput&&typeof A.execute==="string"&&A.execute.trim()!=="")throw new $4("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&&B===""&&!A.streamJsonInput&&!A.headless)throw new $4("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"
7705
- Or pipe via stdin: echo "your message" | amp --execute`)}function x03(A,Q){if(YA4([c50.parse({tool:"*",action:"allow"})]),o44({bypass:!0}),Us4(A.settings))j.debug("Enabling permissions plugin"),Q.registerInternalPlugin({name:"permissions",entryPoint:m61})}async function uK0(A,Q,B,$){if(Q.headless)return f03(A,Q,B);let J=await d8(A,Q),Y=await J.serverStatusPromise,Z=await J.configService.getLatest(),F=mA(Y)&&hK0(Y.features,OB.THREAD_ACTORS_TUI),X=F&&!Q.takeMeBack;if(Q.showWelcome&&Q.hideWelcome)throw await J.asyncDispose(),new $4("Cannot use --show-welcome and --hide-welcome together",1);if(Q.showWelcome&&!F)throw await J.asyncDispose(),new $4("--show-welcome is only available with the new Amp CLI feature flag",1);if(X){let D=!A.executeMode&&await j03();return x03(Z,J.pluginService),b03(A,Q,B,J,{showNpmMigrationWelcome:D})}else{if(Q.threadId&&MQ(Q.threadId)){let D=await DA.getThreadLinkInfo({thread:Q.threadId},{config:J.configService}).catch(()=>null);if(D?.ok&&D.result.usesThreadActors)throw await J.asyncDispose(),new $4(`Thread ${Q.threadId} was created with the Neo TUI and cannot be continued in the legacy CLI.`,1,"Re-run without --take-me-back to continue this thread.")}return u03(A,Q,B,$,{dependencies:J})}}async function f03(A,Q,B){let $=(H,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=br0();j.info("Startup phase",{phase:H,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};u2(B,Q);let J=process.hrtime.bigint(),Y=await d8(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(fX(Z))throw yt(Z,A.ampURL);let F=mA(Z)?Z:null,X=F?.user.email;await A91(B,Q,Z);let D=Mw(Z),G=ax(Q,D);if(G instanceof Error)M5(G.message);if(F&&!$k(Q.mode,X))throw new $4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!X||!_7(X)))throw new $4("Headless executor mode is only available for Amp employees",1);GF0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new $4("API key required for headless mode. Please run `amp login` first.",1);let K=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(K&&!MQ(K))throw new $4(`Invalid thread ID: ${K}`,1);let E=K?void 0:await t03({dependencies:Y,apiKey:U,visibility:G??void 0}),z=K??E?.threadId;if(!z)throw new $4("Failed to resolve headless thread ID",1);let W=await kf4(z);if(W.status==="already-running")await Y.asyncDispose(),await jz(),process.exit(0);try{await Cf4({ampURL:A.ampURL,apiKey:U,workspaceRoot:process.cwd(),threadId:z,ownerUserId:E?.ownerUserId,threadVersion:E?.threadVersion,agentMode:E?.agentMode,initialToolDiscovery:Promise.all([Y.mcpService.initialized,Y.toolboxService.initialized,Y.pluginService.initialized]).then(()=>{return}),configService:Y.configService,mcpService:Y.mcpService,toolService:Y.toolService,skillService:Y.skillService,fileSystem:Y.fileSystem,pluginService:Y.pluginService,pluginPlatform:Y.headlessPluginPlatform})}finally{await W.release(),await Y.asyncDispose()}await jz(),process.exit(0)}async function b03(A,Q,B,$,J){let{userInput:Y,stdinInput:Z}=await d3A(Q),F=!!Q.streamJson||!!Q.streamJsonThinking;c3A({...Q,streamJson:F},A.executeMode,Y),u2(B,Q),eS4(),GF0();let X=Q.threadId&&MQ(Q.threadId)?Q.threadId:void 0,D=Q.observe?C2(Q.observe)??zJ(Q.observe):void 0,G=await $.serverStatusPromise;if(fX(G))throw yt(G,A.ampURL);let V=Mw(G),U=ax(Q,V);if(U instanceof Error)M5(U.message);let K=null,E=()=>{return K??=(async()=>{let H=await ca(A.settings,process.cwd(),V,U);if(H instanceof Error)M5(H.message);return H})(),K},z=await $.secretStorage.get("apiKey",A.ampURL);if(!z)throw new $4("API key required. Please run `amp login` first.",1);let W=mA(G)&&_7(G.user.email);if(A.executeMode){be0($.mcpService,A.settings);try{let H=fK0(B,Q),q=await II(),N=X?H:bX0({agentMode:Q.mode,explicitEffort:H,sessionState:q}),I=X?void 0:uX0(await hx($.configService),{agentMode:Q.mode,explicitEffort:H,sessionState:q}),w=X?void 0:await E(),O=await ox4({apiKey:z,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:$,userInput:Y,stdinInput:Z,stats:!!Q.stats,streamJson:F,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:N,labels:Q.label,initialThreadID:X,initialThreadMeta:w?wJ(w):void 0,initialSettings:I});if(await Tb(O,"execute"),Q.archive)await $.threadService.archive(O,!0)}finally{await $.asyncDispose()}await jz(),process.exit(0)}else{let H=fK0(B,Q),q=J.showNpmMigrationWelcome?"npm-migration":"intro",N=Ll($.configService),I=new rs($.fuzzyServer),w=process.cwd();await Bs4({ampURL:A.ampURL,apiKey:z,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??uF(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:O})=>qx({fileSystem:$.fileSystem,workspaceRoot:w},O),completionBuilder:I,workspaceRoot:w,listThreads:()=>N.listThreads(),getThreadFromServer:(O)=>N.getThread(O),toolboxes:$.toolboxService.toolboxes,isInternalUser:W,settingsFilePath:$.settingsStorage.getSettingsFilePath()},{initialThreadID:D??X,initialUserInput:Y||void 0,getDefaultNewThreadVisibility:E,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!D,splashOrbVisualStyle:"neo",hideNeoWelcome:!!Q.hideWelcome,showNeoWelcome:Q.showWelcome,neoWelcomeVariant:q,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:H}),process.exit(0)}}async function u03(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(Z0,R0)=>{let B0=Number(process.hrtime.bigint()-R0)/1e6,N0=br0();j.info("Startup phase",{phase:Z0,phaseMs:Math.round(B0),sinceMainMs:N0===null?void 0:Math.round(N0)})},{userInput:F,stdinInput:X}=await d3A(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;c3A({...Q,streamJson:D},A.executeMode,F),u2(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await d8(A,Q),U=V.hasAPIKeyAtStartup,K=V.serverStatus==="pending";if(j.info("Interactive auth startup mode",{deferInteractiveAuth:K,hasAPIKeyAtStartup:U,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!J)Z("runMainThread:createThreadDependencies",G);let{serverStatus:E}=V;if(!K&&fX(E))throw yt(E,A.ampURL);let z=mA(E)?E:null,W=z?.user.email,H=!!(W&&_7(W));if(H)GF0();if(!K)await A91(B,Q,E);let q=Mw(E),N=q?.features??[],I=q?.team??null,w=ax(Q,q);if(w instanceof Error)M5(w.message);if(z&&!$k(Q.mode,W))throw new $4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let O=Q.threadId&&MQ(Q.threadId)?Q.threadId:void 0;G=process.hrtime.bigint();let L=await gK0(V);Z("runMainThread:createWorkerDeps",G);let P=A.executeMode?void 0:async(Z0)=>Tb(Z0,"interactive"),T={threadService:V.threadService,workerDeps:L,createThread:async(Z0)=>{let R0=K?await V.serverStatusPromise:E,B0=await ca(A.settings,process.cwd(),Mw(R0),w);if(B0 instanceof Error)M5(B0.message);return j81(L,{threadMeta:B0?wJ(B0):void 0,agentMode:Z0??Q.mode,onFirstAssistantMessage:P})},validateThreadOwnership:async(Z0,R0)=>{if(R0?.nonBlockingOwnershipCheck){f3A(Z0,V.configService,V.viewerUserIDPromise).catch((B0)=>{if(B0 instanceof $4){if(R0.onOwnershipError){R0.onOwnershipError(B0,Z0);return}Rz(B0,Z0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:B0})});return}try{await f3A(Z0,V.configService,V.viewerUserIDPromise)}catch(B0){if(B0 instanceof $4)throw B0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:B0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:P,handleError:Rz},k=async()=>{try{return XAA(T,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(Z0){if(Z0 instanceof $4)throw Z0;throw await Rz(Z0,Q.threadId),Error("handleError should have called process.exit()")}},x=(async()=>{if(K){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let Z0=await V.configService.getLatest(),R0=ym(Z0),B0=await DA.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(R0)});if(B0.ok)return j.info("User free tier status:",B0),B0.result;return}catch(Z0){j.error("Failed to fetch free tier status:",Z0);return}})(),f=!A.executeMode?new s61:null,S,u=null;if(f)S=f,u=(async()=>{let Z0=K?await V.serverStatusPromise:V.serverStatus;if(fX(Z0))throw yt(Z0,A.ampURL);await A91(B,Q,Z0);let R0=process.hrtime.bigint(),B0=await k();if(Z("runMainThread:createThreadPool",R0),f.attach(B0),F){let N0=await T1(B0.threadHandles$);if(!N0)throw new $4("No active thread is available yet.",1);await N0.sendMessage({content:[{type:"text",text:F}]})}})(),u.catch(async(Z0)=>{let R0=Z0 instanceof Error?Z0:Error(String(Z0));f.setInitError(R0),await Rz(Z0,Q.threadId)});else G=process.hrtime.bigint(),S=await k(),Z("runMainThread:createThreadPool",G);let d=Q.notifications!==void 0?Q.notifications:!A.executeMode;G=process.hrtime.bigint();let c=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),k03({configService:V.configService,threadService:V.threadService,config:c,useNotificationsForService:d,threadViewStates$:()=>S.threadHandles$.pipe(h4((Z0)=>{if(!Z0)return m0.of({});return R6(Z0.thread$,Z0.threadViewState$).pipe(I1(([R0,B0])=>({[R0.id]:B0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){be0(V.mcpService,A.settings);let Z0=fK0(B,Q),R0=await II(),B0=O?Z0:bX0({agentMode:Q.mode,explicitEffort:Z0,sessionState:R0}),N0={userInput:F,stdinInput:X,dependencies:V,streamJson:D,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:H,agentMode:Q.mode,reasoningEffort:B0,labels:Q.label},n=await Tv4({threadPool:S,...N0});if(await Tb(n,"execute"),Q.archive)await V.threadService.archive(n,!0);await V.asyncDispose(),process.exit(0)}let g=!1,l=!1;if(Q.jetbrains||Q.ide){await c30();let Z0=await hX({jetbrainsOnly:Q.jetbrains});if(Z0.length===0){if(Q.jetbrains)g=!await V.configService.get("jetbrains.skipInstall")}else if(Z0.length===1){let R0=Z0[0];if(R0)u3.selectConfig(R0)}else l=!0}G=process.hrtime.bigint();let s=$e0("0.0.1778476494-g8a21dc",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let A0=new ue0(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),F&&A.executeMode){let Z0=await T1(S.threadHandles$);if(!Z0)throw new $4("No active thread is available yet.",1);await Z0.sendMessage({content:[{type:"text",text:F}]})}G=process.hrtime.bigint();let H0=await II();Z("runMainThread:loadSessionState",G),j.info("Loaded session state:",H0);let V0=fK0(B,Q),w0={...H0,launchCount:H0.launchCount+1,lastReasoningEffortByMode:V0?{...H0.lastReasoningEffortByMode,[Q.mode]:V0}:H0.lastReasoningEffortByMode};NJ((Z0)=>({...Z0,launchCount:Z0.launchCount+1}));try{if(G=process.hrtime.bigint(),await Ct4({history:new Xo,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:DA,threadPool:S,createSystemPromptDeps:async()=>m3A(V),ideClient:u3,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:A0,updateService:s,pluginPlatform:V.pluginPlatform,pluginService:V.pluginService},{initialServerStatus:V.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:V.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:O,showJetBrainsInstaller:g,showIdePickerHint:l,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:E03,logFile:{path:$},sessionState:w0,freeTierStatusPromise:x,workspace:I??null,features:N,isInternalUser:H,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-11T05:19:01.767Z"},(Z0)=>new J51({...Z0,threadPool:Z0.threadPool},(R0)=>new L81({...R0,threadState:R0.threadState}))),Z("runMainThread:mountApp-returned",G),u)await u}finally{await S.dispose().catch((Z0)=>{j.error("Failed to dispose thread pool during shutdown",Z0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function c5(A){if(j.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)fJ.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7706
- `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await j74({get:async(F)=>{if(F!==bd)return;try{let X=await g3A(e21,"utf-8");return JSON.parse(X).installationID}catch{return}},set:async(F,X)=>{if(F!==bd)return;await G03(vt.dirname(e21),{recursive:!0}),await V03(e21,JSON.stringify({installationID:X},null,2),{mode:384})}},{clientType:"cli",platform:E90()});fe1($);let J=await cf4({...A,workspaceTrust:{current:!0,changes:hT0},getHook:process.env.AMP_URL?(F,X)=>{if(F==="url")return Promise.resolve(process.env.AMP_URL);return X()}:void 0});if(A.mcpConfig){let F=await hh4(A.mcpConfig);J=gh4(J,F)}let Y=vt.dirname(J.getSettingsFilePath());PR4(jx,Y),J=Es1(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=T7;if(j.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!yH(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:Ls4(await xt0(A,J))}}function h03(A){let Q={};for(let B=0;B<A.length;B++){let $=A[B];if($?.startsWith("--")){let Y=$.slice(2).replace(/-([a-z])/g,(F,X)=>X.toUpperCase()),Z=A[B+1];if(Z&&!Z.startsWith("--"))Q[Y]=Z,B++}}return Q}function g03(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=vt.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?K03:da));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function m03(){nS4();let A=h03(process.argv),Q=g03(process.argv,A),B=Av4(Q);yZ0("silent");let $=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)n0.level=0;if(W03(j),j.info("Starting Amp CLI.",{version:"0.0.1778476494-g8a21dc",buildTimestamp:"2026-05-11T05:19:01.767Z"}),process.platform==="win32"&&jj())kb4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new $4(D7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await y03(B).parseAsync(process.argv)}jR4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await m03().catch(Rz)});async function p03(A,Q){let B=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!B)await A.settings.set("url",process.env.AMP_URL,"global"),X5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7705
+ Or pipe via stdin: echo "your message" | amp --execute`)}function x03(A,Q){if(YA4([c50.parse({tool:"*",action:"allow"})]),o44({bypass:!0}),Us4(A.settings))j.debug("Enabling permissions plugin"),Q.registerInternalPlugin({name:"permissions",entryPoint:m61})}async function uK0(A,Q,B,$){if(Q.headless)return f03(A,Q,B);let J=await d8(A,Q),Y=await J.serverStatusPromise,Z=await J.configService.getLatest(),F=mA(Y)&&hK0(Y.features,OB.THREAD_ACTORS_TUI),X=F&&!Q.takeMeBack;if(Q.showWelcome&&Q.hideWelcome)throw await J.asyncDispose(),new $4("Cannot use --show-welcome and --hide-welcome together",1);if(Q.showWelcome&&!F)throw await J.asyncDispose(),new $4("--show-welcome is only available with the new Amp CLI feature flag",1);if(X){let D=!A.executeMode&&await j03();return x03(Z,J.pluginService),b03(A,Q,B,J,{showNpmMigrationWelcome:D})}else{if(Q.threadId&&MQ(Q.threadId)){let D=await DA.getThreadLinkInfo({thread:Q.threadId},{config:J.configService}).catch(()=>null);if(D?.ok&&D.result.usesThreadActors)throw await J.asyncDispose(),new $4(`Thread ${Q.threadId} was created with the Neo TUI and cannot be continued in the legacy CLI.`,1,"Re-run without --take-me-back to continue this thread.")}return u03(A,Q,B,$,{dependencies:J})}}async function f03(A,Q,B){let $=(H,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=br0();j.info("Startup phase",{phase:H,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};u2(B,Q);let J=process.hrtime.bigint(),Y=await d8(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(fX(Z))throw yt(Z,A.ampURL);let F=mA(Z)?Z:null,X=F?.user.email;await A91(B,Q,Z);let D=Mw(Z),G=ax(Q,D);if(G instanceof Error)M5(G.message);if(F&&!$k(Q.mode,X))throw new $4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!X||!_7(X)))throw new $4("Headless executor mode is only available for Amp employees",1);GF0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new $4("API key required for headless mode. Please run `amp login` first.",1);let K=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(K&&!MQ(K))throw new $4(`Invalid thread ID: ${K}`,1);let E=K?void 0:await t03({dependencies:Y,apiKey:U,visibility:G??void 0}),z=K??E?.threadId;if(!z)throw new $4("Failed to resolve headless thread ID",1);let W=await kf4(z);if(W.status==="already-running")await Y.asyncDispose(),await jz(),process.exit(0);try{await Cf4({ampURL:A.ampURL,apiKey:U,workspaceRoot:process.cwd(),threadId:z,ownerUserId:E?.ownerUserId,threadVersion:E?.threadVersion,agentMode:E?.agentMode,initialToolDiscovery:Promise.all([Y.mcpService.initialized,Y.toolboxService.initialized,Y.pluginService.initialized]).then(()=>{return}),configService:Y.configService,mcpService:Y.mcpService,toolService:Y.toolService,skillService:Y.skillService,fileSystem:Y.fileSystem,pluginService:Y.pluginService,pluginPlatform:Y.headlessPluginPlatform})}finally{await W.release(),await Y.asyncDispose()}await jz(),process.exit(0)}async function b03(A,Q,B,$,J){let{userInput:Y,stdinInput:Z}=await d3A(Q),F=!!Q.streamJson||!!Q.streamJsonThinking;c3A({...Q,streamJson:F},A.executeMode,Y),u2(B,Q),eS4(),GF0();let X=Q.threadId&&MQ(Q.threadId)?Q.threadId:void 0,D=Q.observe?C2(Q.observe)??zJ(Q.observe):void 0,G=await $.serverStatusPromise;if(fX(G))throw yt(G,A.ampURL);let V=Mw(G),U=ax(Q,V);if(U instanceof Error)M5(U.message);let K=null,E=()=>{return K??=(async()=>{let H=await ca(A.settings,process.cwd(),V,U);if(H instanceof Error)M5(H.message);return H})(),K},z=await $.secretStorage.get("apiKey",A.ampURL);if(!z)throw new $4("API key required. Please run `amp login` first.",1);let W=mA(G)&&_7(G.user.email);if(A.executeMode){be0($.mcpService,A.settings);try{let H=fK0(B,Q),q=await II(),N=X?H:bX0({agentMode:Q.mode,explicitEffort:H,sessionState:q}),I=X?void 0:uX0(await hx($.configService),{agentMode:Q.mode,explicitEffort:H,sessionState:q}),w=X?void 0:await E(),O=await ox4({apiKey:z,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:$,userInput:Y,stdinInput:Z,stats:!!Q.stats,streamJson:F,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:N,labels:Q.label,initialThreadID:X,initialThreadMeta:w?wJ(w):void 0,initialSettings:I});if(await Tb(O,"execute"),Q.archive)await $.threadService.archive(O,!0)}finally{await $.asyncDispose()}await jz(),process.exit(0)}else{let H=fK0(B,Q),q=J.showNpmMigrationWelcome?"npm-migration":"intro",N=Ll($.configService),I=new rs($.fuzzyServer),w=process.cwd();await Bs4({ampURL:A.ampURL,apiKey:z,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??uF(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:O})=>qx({fileSystem:$.fileSystem,workspaceRoot:w},O),completionBuilder:I,workspaceRoot:w,listThreads:()=>N.listThreads(),getThreadFromServer:(O)=>N.getThread(O),toolboxes:$.toolboxService.toolboxes,isInternalUser:W,settingsFilePath:$.settingsStorage.getSettingsFilePath()},{initialThreadID:D??X,initialUserInput:Y||void 0,getDefaultNewThreadVisibility:E,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!D,splashOrbVisualStyle:"neo",hideNeoWelcome:!!Q.hideWelcome,showNeoWelcome:Q.showWelcome,neoWelcomeVariant:q,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:H}),process.exit(0)}}async function u03(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(Z0,R0)=>{let B0=Number(process.hrtime.bigint()-R0)/1e6,N0=br0();j.info("Startup phase",{phase:Z0,phaseMs:Math.round(B0),sinceMainMs:N0===null?void 0:Math.round(N0)})},{userInput:F,stdinInput:X}=await d3A(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;c3A({...Q,streamJson:D},A.executeMode,F),u2(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await d8(A,Q),U=V.hasAPIKeyAtStartup,K=V.serverStatus==="pending";if(j.info("Interactive auth startup mode",{deferInteractiveAuth:K,hasAPIKeyAtStartup:U,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!J)Z("runMainThread:createThreadDependencies",G);let{serverStatus:E}=V;if(!K&&fX(E))throw yt(E,A.ampURL);let z=mA(E)?E:null,W=z?.user.email,H=!!(W&&_7(W));if(H)GF0();if(!K)await A91(B,Q,E);let q=Mw(E),N=q?.features??[],I=q?.team??null,w=ax(Q,q);if(w instanceof Error)M5(w.message);if(z&&!$k(Q.mode,W))throw new $4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let O=Q.threadId&&MQ(Q.threadId)?Q.threadId:void 0;G=process.hrtime.bigint();let L=await gK0(V);Z("runMainThread:createWorkerDeps",G);let P=A.executeMode?void 0:async(Z0)=>Tb(Z0,"interactive"),T={threadService:V.threadService,workerDeps:L,createThread:async(Z0)=>{let R0=K?await V.serverStatusPromise:E,B0=await ca(A.settings,process.cwd(),Mw(R0),w);if(B0 instanceof Error)M5(B0.message);return j81(L,{threadMeta:B0?wJ(B0):void 0,agentMode:Z0??Q.mode,onFirstAssistantMessage:P})},validateThreadOwnership:async(Z0,R0)=>{if(R0?.nonBlockingOwnershipCheck){f3A(Z0,V.configService,V.viewerUserIDPromise).catch((B0)=>{if(B0 instanceof $4){if(R0.onOwnershipError){R0.onOwnershipError(B0,Z0);return}Rz(B0,Z0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:B0})});return}try{await f3A(Z0,V.configService,V.viewerUserIDPromise)}catch(B0){if(B0 instanceof $4)throw B0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:B0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:P,handleError:Rz},k=async()=>{try{return XAA(T,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(Z0){if(Z0 instanceof $4)throw Z0;throw await Rz(Z0,Q.threadId),Error("handleError should have called process.exit()")}},x=(async()=>{if(K){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let Z0=await V.configService.getLatest(),R0=ym(Z0),B0=await DA.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(R0)});if(B0.ok)return j.info("User free tier status:",B0),B0.result;return}catch(Z0){j.error("Failed to fetch free tier status:",Z0);return}})(),f=!A.executeMode?new s61:null,S,u=null;if(f)S=f,u=(async()=>{let Z0=K?await V.serverStatusPromise:V.serverStatus;if(fX(Z0))throw yt(Z0,A.ampURL);await A91(B,Q,Z0);let R0=process.hrtime.bigint(),B0=await k();if(Z("runMainThread:createThreadPool",R0),f.attach(B0),F){let N0=await T1(B0.threadHandles$);if(!N0)throw new $4("No active thread is available yet.",1);await N0.sendMessage({content:[{type:"text",text:F}]})}})(),u.catch(async(Z0)=>{let R0=Z0 instanceof Error?Z0:Error(String(Z0));f.setInitError(R0),await Rz(Z0,Q.threadId)});else G=process.hrtime.bigint(),S=await k(),Z("runMainThread:createThreadPool",G);let d=Q.notifications!==void 0?Q.notifications:!A.executeMode;G=process.hrtime.bigint();let c=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),k03({configService:V.configService,threadService:V.threadService,config:c,useNotificationsForService:d,threadViewStates$:()=>S.threadHandles$.pipe(h4((Z0)=>{if(!Z0)return m0.of({});return R6(Z0.thread$,Z0.threadViewState$).pipe(I1(([R0,B0])=>({[R0.id]:B0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){be0(V.mcpService,A.settings);let Z0=fK0(B,Q),R0=await II(),B0=O?Z0:bX0({agentMode:Q.mode,explicitEffort:Z0,sessionState:R0}),N0={userInput:F,stdinInput:X,dependencies:V,streamJson:D,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:H,agentMode:Q.mode,reasoningEffort:B0,labels:Q.label},n=await Tv4({threadPool:S,...N0});if(await Tb(n,"execute"),Q.archive)await V.threadService.archive(n,!0);await V.asyncDispose(),process.exit(0)}let g=!1,l=!1;if(Q.jetbrains||Q.ide){await c30();let Z0=await hX({jetbrainsOnly:Q.jetbrains});if(Z0.length===0){if(Q.jetbrains)g=!await V.configService.get("jetbrains.skipInstall")}else if(Z0.length===1){let R0=Z0[0];if(R0)u3.selectConfig(R0)}else l=!0}G=process.hrtime.bigint();let s=$e0("0.0.1778480457-g5efd50",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let A0=new ue0(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),F&&A.executeMode){let Z0=await T1(S.threadHandles$);if(!Z0)throw new $4("No active thread is available yet.",1);await Z0.sendMessage({content:[{type:"text",text:F}]})}G=process.hrtime.bigint();let H0=await II();Z("runMainThread:loadSessionState",G),j.info("Loaded session state:",H0);let V0=fK0(B,Q),w0={...H0,launchCount:H0.launchCount+1,lastReasoningEffortByMode:V0?{...H0.lastReasoningEffortByMode,[Q.mode]:V0}:H0.lastReasoningEffortByMode};NJ((Z0)=>({...Z0,launchCount:Z0.launchCount+1}));try{if(G=process.hrtime.bigint(),await Ct4({history:new Xo,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:DA,threadPool:S,createSystemPromptDeps:async()=>m3A(V),ideClient:u3,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:A0,updateService:s,pluginPlatform:V.pluginPlatform,pluginService:V.pluginService},{initialServerStatus:V.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:V.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:O,showJetBrainsInstaller:g,showIdePickerHint:l,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:E03,logFile:{path:$},sessionState:w0,freeTierStatusPromise:x,workspace:I??null,features:N,isInternalUser:H,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-11T06:24:41.556Z"},(Z0)=>new J51({...Z0,threadPool:Z0.threadPool},(R0)=>new L81({...R0,threadState:R0.threadState}))),Z("runMainThread:mountApp-returned",G),u)await u}finally{await S.dispose().catch((Z0)=>{j.error("Failed to dispose thread pool during shutdown",Z0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function c5(A){if(j.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)fJ.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7706
+ `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await j74({get:async(F)=>{if(F!==bd)return;try{let X=await g3A(e21,"utf-8");return JSON.parse(X).installationID}catch{return}},set:async(F,X)=>{if(F!==bd)return;await G03(vt.dirname(e21),{recursive:!0}),await V03(e21,JSON.stringify({installationID:X},null,2),{mode:384})}},{clientType:"cli",platform:E90()});fe1($);let J=await cf4({...A,workspaceTrust:{current:!0,changes:hT0},getHook:process.env.AMP_URL?(F,X)=>{if(F==="url")return Promise.resolve(process.env.AMP_URL);return X()}:void 0});if(A.mcpConfig){let F=await hh4(A.mcpConfig);J=gh4(J,F)}let Y=vt.dirname(J.getSettingsFilePath());PR4(jx,Y),J=Es1(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=T7;if(j.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!yH(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:Ls4(await xt0(A,J))}}function h03(A){let Q={};for(let B=0;B<A.length;B++){let $=A[B];if($?.startsWith("--")){let Y=$.slice(2).replace(/-([a-z])/g,(F,X)=>X.toUpperCase()),Z=A[B+1];if(Z&&!Z.startsWith("--"))Q[Y]=Z,B++}}return Q}function g03(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=vt.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?K03:da));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function m03(){nS4();let A=h03(process.argv),Q=g03(process.argv,A),B=Av4(Q);yZ0("silent");let $=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)n0.level=0;if(W03(j),j.info("Starting Amp CLI.",{version:"0.0.1778480457-g5efd50",buildTimestamp:"2026-05-11T06:24:41.556Z"}),process.platform==="win32"&&jj())kb4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new $4(D7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await y03(B).parseAsync(process.argv)}jR4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await m03().catch(Rz)});async function p03(A,Q){let B=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!B)await A.settings.set("url",process.env.AMP_URL,"global"),X5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7707
7707
  `);else if(!yH(A.ampURL))X5.write(`Logging in to ${new URL(A.ampURL).hostname}
7708
7708
  `);let $=process.env.AMP_API_KEY;if($)X5.write(`API key found in environment variable, storing...
7709
7709
  `),await Q.set("apiKey",$,A.ampURL),X5.write(`API key successfully stored.