@maincode-ai/matilda-code 0.21.10-nightly.20261007.eb073eef7 → 0.21.10-preview.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/chunks/{agent-2XTQ5FI7.js → agent-U43GELHB.js} +1 -1
- package/chunks/{agent-headless-CSQ7XGZ5.js → agent-headless-7STBERN4.js} +1 -1
- package/chunks/{chunk-Z2SJIXK3.js → chunk-2NBII5ND.js} +1 -1
- package/chunks/{chunk-QGM4UPJ2.js → chunk-6ZMDAPGZ.js} +2 -2
- package/chunks/{chunk-X2P4CXXM.js → chunk-GWGQRU36.js} +1 -1
- package/chunks/{chunk-SX2USXNK.js → chunk-H6WMNUW2.js} +1 -1
- package/chunks/{chunk-J672B7OE.js → chunk-TFWOXSAP.js} +2 -2
- package/chunks/{chunk-2KNZCBPK.js → chunk-X6BEBYGX.js} +1 -1
- package/chunks/{chunk-DJHQSPCU.js → chunk-XJYPRCV7.js} +1 -1
- package/chunks/{computer-use-W6KUKBKK.js → computer-use-QN46FSNK.js} +1 -1
- package/chunks/{contextCommand-OMGIDA33.js → contextCommand-7G5FHBBE.js} +1 -1
- package/chunks/{edit-L3W2WH4Z.js → edit-7AZARQPL.js} +1 -1
- package/chunks/{enter-worktree-Z4UYFS3F.js → enter-worktree-GKYG5CD2.js} +1 -1
- package/chunks/{enterPlanMode-YHPPNYON.js → enterPlanMode-ICTG6ULZ.js} +1 -1
- package/chunks/{exit-worktree-SHU5SHPJ.js → exit-worktree-ZWYXIEIC.js} +1 -1
- package/chunks/{exitPlanMode-DZTE3NXN.js → exitPlanMode-5BQ4MY5I.js} +1 -1
- package/chunks/{geminiContentGenerator-OAKIFFGZ.js → geminiContentGenerator-APSI54U5.js} +1 -1
- package/chunks/{glob-JIQCZHO5.js → glob-NPEYXTA6.js} +1 -1
- package/chunks/{grep-OXBAYAAO.js → grep-4NQTKAN6.js} +1 -1
- package/chunks/{matildaAgentContentGenerator-S3IOYE4X.js → matildaAgentContentGenerator-HVIGLQJZ.js} +1 -1
- package/chunks/{matildaContentGenerator-TZJM5ABQ.js → matildaContentGenerator-5VOBYNAJ.js} +1 -1
- package/chunks/{monitor-E5XFRHMT.js → monitor-RMKMKOUY.js} +1 -1
- package/chunks/{notebook-edit-K7O3DLKU.js → notebook-edit-H3ZFKBLR.js} +1 -1
- package/chunks/{openaiContentGenerator-OMPAGAT4.js → openaiContentGenerator-X6TFPZGL.js} +1 -1
- package/chunks/{ripGrep-Q7ZYWTWK.js → ripGrep-WDYTLRCE.js} +1 -1
- package/chunks/{scheduler-L7I3SLSI.js → scheduler-TKK5QECI.js} +1 -1
- package/chunks/{serve-LYF52JPB.js → serve-24HVCLFM.js} +1 -1
- package/chunks/{shell-NK4PD32X.js → shell-YPEMRDRO.js} +1 -1
- package/chunks/{skill-XWVQ7IBN.js → skill-HWDNN7P7.js} +1 -1
- package/chunks/{src-7RD4LDGG.js → src-W5VAKS5Y.js} +1 -1
- package/chunks/{team-create-LUNLX56X.js → team-create-D4N2QVBX.js} +1 -1
- package/chunks/{workflow-CLD3PADK.js → workflow-BSK53DUN.js} +2 -2
- package/chunks/{write-file-ALAYY7RE.js → write-file-GDKSQBMU.js} +1 -1
- package/cli.js +6 -6
- package/package.json +2 -2
package/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// Force strict mode and setup for ESM
|
|
3
3
|
"use strict";
|
|
4
|
-
import{$ as YN,A as WN,C as $Z,D as VZ,E as n8,F as Ch,G as jN,H as OA,I as KZ,J as cy,K as zZ,L as XZ,M as uy,N as ZZ,Na as Fr,O as eee,P as o8,Q as r8,R as $o,S as s8,Sa as ql,T as ZT,Ta as Na,U as tee,Ua as $N,V as nee,W as oee,X as ree,Y as on,Z as see,_ as iee,a as JT,aa as aee,ab as hee,b as ay,ba as bOe,c as OZ,ca as iu,cb as yh,d as ui,da as qN,e as na,ea as TOe,eb as Cee,f as oa,fa as QOe,fb as Jl,g as gr,ga as JN,gb as tS,h as X3,ha as eQ,hb as zg,i as Z3,ia as Eh,ib as Nn,j as PZ,jb as Eee,k as UZ,kb as yee,l as Kg,lb as VN,m as HZ,n as Ps,o as Bf,oa as pee,p as WZ,q as VT,r as KT,s as zT,t as qZ,u as e8,v as ly,w as JZ,x as XT,y as GN,z as t8}from"./chunks/chunk-J672B7OE.js";import{a as Ce,b as KN,c as Dee,d as Bee,e as See}from"./chunks/chunk-SX2USXNK.js";import{a as rt,b as We,c as PN,d as $T,e as UN,f as GZ,j as HN,k as eS,l as f,m as jZ,n as YZ}from"./chunks/chunk-X2P4CXXM.js";import{a as Iee}from"./chunks/chunk-7ZATDBWL.js";import{a as Aee,c as l8,d as gee,e as mee,g as fee}from"./chunks/chunk-GC2F575A.js";import{a as lee,c as tQ,d as i8,e as a8}from"./chunks/chunk-3HUM74NZ.js";import{a as cee,b as uee,c as dee,e as ke}from"./chunks/chunk-JSFA3NEP.js";import{$a as Pz,$h as q3,A as UB,Ab as qg,Ae as vX,Af as FX,Ah as VX,Aj as lZ,Ak as hZ,Al as QZ,Be as Ar,Bk as CZ,Bl as vZ,Ca as Lz,Cj as cZ,Ck as zB,Cl as XB,De as RX,Dg as WX,Dh as Rd,Ee as MX,Ef as jl,Eh as Y3,Ej as uZ,El as RZ,Fe as SOe,Fh as KX,Fj as wN,Fk as EZ,Gj as bN,Hd as lX,Hi as oZ,Hl as MZ,Id as cX,If as NX,Ik as MN,Il as kZ,J as hz,Jc as Xz,Jd as uX,Jf as _X,Jk as yZ,Jl as FZ,Kc as Zz,Kd as dX,Kl as NZ,Lc as eX,Ld as AX,Le as yN,Ll as _Z,Mc as G3,Md as gX,Me as qB,Ml as LZ,Na as HT,Nc as pN,Ng as ry,Nk as IZ,Nl as NN,Ob as jz,Oc as tX,Od as mX,Ok as DZ,Ol as _N,Pa as Li,Pb as Yz,Pc as DOe,Pe as Vg,Pi as rZ,Pk as V3,Pl as ZB,Q as vz,Qb as qz,Qc as W3,Qj as dZ,Qk as K3,Ql as LN,R as If,Rb as Jg,Rh as zX,Rk as iy,Rl as ON,S as Rz,Sb as Jz,Sc as nX,Sd as jB,Si as LA,Td as fX,U as aN,Ua as cN,Uc as oX,Ud as pX,Uf as LX,Uh as XX,Va as Oz,Vb as $z,Vj as TN,Vk as BZ,We as WT,Wf as OX,Wg as DN,Wj as AZ,X as Mz,Xa as uN,Xd as hX,Xj as gZ,Y as kz,Ya as oy,Yd as CX,Yf as PX,Yj as VB,Z as Fz,Za as dN,Zd as EX,Zf as UX,Zh as SN,_ as Nz,_a as Yg,_i as sZ,_j as ta,ab as GB,ak as qT,bb as Wl,be as yX,ca as H3,cb as Wu,ce as IX,ci as ZX,cj as xOe,db as Uz,di as eZ,dj as iZ,ee as DX,eg as fh,eh as jX,ei as tZ,f as FB,fb as Hz,fd as rX,fe as BX,fh as YX,fi as YT,fk as ph,g as ZE,gd as j3,ge as SX,gg as IN,gk as sy,h as T7,hc as mN,hh as jT,ic as fN,id as sX,ie as xX,ig as HX,ih as qX,j as mz,jc as Vz,je as CN,jg as GX,jk as QN,kk as KB,ld as iX,lj as wOe,ll as SZ,mc as Kz,me as wX,mf as kX,mh as JX,mi as nZ,ml as xZ,nl as z3,oe as bX,oh as _A,oj as aZ,ol as kN,pa as lN,pe as EN,pi as J3,pj as $B,pl as wZ,qa as _z,qb as GT,qe as YB,qk as vN,ql as bZ,re as TX,rf as Df,rg as JB,rj as xN,rk as $3,rl as TZ,sb as Gz,sh as BN,sk as mZ,t as fz,tb as WB,td as aX,tk as fZ,tl as FN,ub as Wz,uj as Yl,wb as mh,x as pz,xd as hN,ye as QX,yk as RN,z as oN,ze as BOe,zh as $X,zk as pZ,zl as hh}from"./chunks/chunk-QGM4UPJ2.js";import{a as Kn}from"./chunks/chunk-TZIDSCTF.js";import"./chunks/chunk-TXMXCR7D.js";import"./chunks/chunk-YULUB745.js";import"./chunks/chunk-VYTYYCBR.js";import"./chunks/chunk-ROETRE5J.js";import"./chunks/chunk-INAZKGGR.js";import{a as IOe}from"./chunks/chunk-DCQKJTAX.js";import"./chunks/chunk-TISQNFB5.js";import{a as ny}from"./chunks/chunk-6Q6PMGBD.js";import"./chunks/chunk-MTMU7JYZ.js";import"./chunks/chunk-RNKDFE2S.js";import{A as iN,b as P3,c as Cz,d as Fa,e as Ez,f as yz,i as Iz,j as HB,l as rN,m as Dz,o as Bz,p as Sz,r as bz,s as Tz,x as Qz,z as yf}from"./chunks/chunk-BN2CPSZ5.js";import"./chunks/chunk-47XR7IMP.js";import"./chunks/chunk-FWIVFCKF.js";import{a as $g,b as zz}from"./chunks/chunk-HMZOLFRP.js";import"./chunks/chunk-QKYGQLWC.js";import{a as AN,d as gN}from"./chunks/chunk-SE3XDSIJ.js";import{b as sN,d as xz,h as wz,i as U3}from"./chunks/chunk-VWWEEU4V.js";import"./chunks/chunk-HYVP4472.js";import"./chunks/chunk-Q2I3ARPJ.js";import"./chunks/chunk-2KNZCBPK.js";import{b as cz,d as uz,e as O3,i as dz,k as Az}from"./chunks/chunk-QHA3ZBRO.js";import{B as Z7,Y as L3,Z as sz,c as vd,ga as tN,i as z7,ja as UT,ka as iz,la as az,n as X7,na as lz,oa as nN,pa as ea}from"./chunks/chunk-DJHQSPCU.js";import{c as nz,d as oz}from"./chunks/chunk-4F4DA5UI.js";import{e as NA}from"./chunks/chunk-DC7LAFZZ.js";import{m as rz,v as _3}from"./chunks/chunk-S7G6QPEP.js";import{b as Zi}from"./chunks/chunk-4J6DC24J.js";import"./chunks/chunk-LJR4RZZ2.js";import"./chunks/chunk-U347OO7S.js";import{h as Ah,i as eN,j as PB,k as ez,m as tz}from"./chunks/chunk-SDTWBD62.js";import{Bb as F7,Cc as jg,Eb as N7,Gc as XF,Hb as _B,Hc as Y7,Ib as _7,Jb as k3,Lc as q7,Qb as L7,Tc as N3,Vb as F3,Wb as zF,Xb as OT,Xc as ZF,Yc as PT,Zb as O7,Zc as J7,cc as P7,db as R3,e as KF,gb as v7,h as kr,hb as R7,hd as $7,ib as M7,jb as k7,jc as ey,jd as ty,kb as M3,lc as U7,nd as V7,pc as LB,qc as H7,r as v3,s as Q7,sd as OB,t as Gu,td as K7}from"./chunks/chunk-KSNBNXBC.js";import"./chunks/chunk-WVY2P6WH.js";import"./chunks/chunk-UIRBHC5X.js";import{h as dh,j as G7,s as W7,w as j7}from"./chunks/chunk-32PTAACU.js";import"./chunks/chunk-2PPJ3MJT.js";import{e as b7,l as Hu,p as nn,q as NB}from"./chunks/chunk-PIFQEMZZ.js";import{a as gh,o as Ef,t as gz}from"./chunks/chunk-RJX7DK4Y.js";import"./chunks/chunk-XCJYORZX.js";import"./chunks/chunk-ESSYHTAZ.js";import"./chunks/chunk-3YLXGE6T.js";import{b as x7,e as w7}from"./chunks/chunk-EQEQPZLQ.js";import{B as JF,D as $F,F as _T,G as LT,J as uh,P as Mt,Q as S7,Y as VF,aa as He,b as FA,c as C7,d as ts,e as Q3,g as E7,i as YF,j as Xi,k as Gl,l as XE,n as y7,o as I7,q as D7,s as qF,u as B7}from"./chunks/chunk-VLYRNOD3.js";import"./chunks/chunk-G7R2XEEF.js";import"./chunks/chunk-OA56BXPD.js";import"./chunks/chunk-FWDMPRKU.js";import{a as __matilda_dirname,b as p}from"./chunks/chunk-GZPNIYVZ.js";import{a as Xe,d as Fe,e as EOe,f as k,g as yOe}from"./chunks/chunk-OWGSC52X.js";var Kee=Fe((Vwt,o1)=>{p();o1.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&o1.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&o1.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var tte=Fe((zwt,dS)=>{p();var Es=globalThis.process,gy=function(e){return e&&typeof e=="object"&&typeof e.removeListener=="function"&&typeof e.emit=="function"&&typeof e.reallyExit=="function"&&typeof e.listeners=="function"&&typeof e.kill=="function"&&typeof e.pid=="number"&&typeof e.on=="function"};gy(Es)?(zee=Xe("assert"),cS=Kee(),Xee=/^win/i.test(Es.platform),sQ=Xe("events"),typeof sQ!="function"&&(sQ=sQ.EventEmitter),Es.__signal_exit_emitter__?Oa=Es.__signal_exit_emitter__:(Oa=Es.__signal_exit_emitter__=new sQ,Oa.count=0,Oa.emitted={}),Oa.infinite||(Oa.setMaxListeners(1/0),Oa.infinite=!0),dS.exports=function(e,t){if(!gy(globalThis.process))return function(){};zee.equal(typeof e,"function","a callback must be provided for exit handler"),uS===!1&&E8();var n="exit";t&&t.alwaysLast&&(n="afterexit");var o=function(){Oa.removeListener(n,e),Oa.listeners("exit").length===0&&Oa.listeners("afterexit").length===0&&r1()};return Oa.on(n,e),o},r1=function(){!uS||!gy(globalThis.process)||(uS=!1,cS.forEach(function(t){try{Es.removeListener(t,s1[t])}catch{}}),Es.emit=i1,Es.reallyExit=y8,Oa.count-=1)},dS.exports.unload=r1,my=function(t,n,o){Oa.emitted[t]||(Oa.emitted[t]=!0,Oa.emit(t,n,o))},s1={},cS.forEach(function(e){s1[e]=function(){if(gy(globalThis.process)){var n=Es.listeners(e);n.length===Oa.count&&(r1(),my("exit",null,e),my("afterexit",null,e),Xee&&e==="SIGHUP"&&(e="SIGINT"),Es.kill(Es.pid,e))}}}),dS.exports.signals=function(){return cS},uS=!1,E8=function(){uS||!gy(globalThis.process)||(uS=!0,Oa.count+=1,cS=cS.filter(function(t){try{return Es.on(t,s1[t]),!0}catch{return!1}}),Es.emit=ete,Es.reallyExit=Zee)},dS.exports.load=E8,y8=Es.reallyExit,Zee=function(t){gy(globalThis.process)&&(Es.exitCode=t||0,my("exit",Es.exitCode,null),my("afterexit",Es.exitCode,null),y8.call(Es,Es.exitCode))},i1=Es.emit,ete=function(t,n){if(t==="exit"&&gy(globalThis.process)){n!==void 0&&(Es.exitCode=n);var o=i1.apply(this,arguments);return my("exit",Es.exitCode,null),my("afterexit",Es.exitCode,null),o}else return i1.apply(this,arguments)}):dS.exports=function(){return function(){}};var zee,cS,Xee,sQ,Oa,r1,my,s1,uS,E8,y8,Zee,i1,ete});var ste=Fe(Sh=>{"use strict";p();Sh.ConcurrentRoot=1;Sh.ContinuousEventPriority=8;Sh.DefaultEventPriority=32;Sh.DiscreteEventPriority=2;Sh.IdleEventPriority=268435456;Sh.LegacyRoot=0;Sh.NoEventPriority=0});var a1=Fe((rbt,ite)=>{"use strict";p();ite.exports=ste()});var ene=Fe(Is=>{"use strict";p();function P8(e,t){var n=e.length;e.push(t);e:for(;0<n;){var o=n-1>>>1,r=e[o];if(0<h1(r,t))e[o]=t,e[n]=r,n=o;else break e}}function Xg(e){return e.length===0?null:e[0]}function E1(e){if(e.length===0)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;e:for(var o=0,r=e.length,s=r>>>1;o<s;){var i=2*(o+1)-1,a=e[i],l=i+1,c=e[l];if(0>h1(a,n))l<r&&0>h1(c,a)?(e[o]=c,e[l]=n,o=l):(e[o]=a,e[i]=n,o=i);else if(l<r&&0>h1(c,n))e[o]=c,e[l]=n,o=l;else break e}}return t}function h1(e,t){var n=e.sortIndex-t.sortIndex;return n!==0?n:e.id-t.id}Is.unstable_now=void 0;typeof performance=="object"&&typeof performance.now=="function"?(Yte=performance,Is.unstable_now=function(){return Yte.now()}):(_8=Date,qte=_8.now(),Is.unstable_now=function(){return _8.now()-qte});var Yte,_8,qte,bf=[],xh=[],QUe=1,Nd=null,Kl=3,U8=!1,cQ=!1,uQ=!1,H8=!1,Vte=typeof setTimeout=="function"?setTimeout:null,Kte=typeof clearTimeout=="function"?clearTimeout:null,Jte=typeof setImmediate<"u"?setImmediate:null;function C1(e){for(var t=Xg(xh);t!==null;){if(t.callback===null)E1(xh);else if(t.startTime<=e)E1(xh),t.sortIndex=t.expirationTime,P8(bf,t);else break;t=Xg(xh)}}function G8(e){if(uQ=!1,C1(e),!cQ)if(Xg(bf)!==null)cQ=!0,hS||(hS=!0,pS());else{var t=Xg(xh);t!==null&&W8(G8,t.startTime-e)}}var hS=!1,dQ=-1,zte=5,Xte=-1;function Zte(){return H8?!0:!(Is.unstable_now()-Xte<zte)}function L8(){if(H8=!1,hS){var e=Is.unstable_now();Xte=e;var t=!0;try{e:{cQ=!1,uQ&&(uQ=!1,Kte(dQ),dQ=-1),U8=!0;var n=Kl;try{t:{for(C1(e),Nd=Xg(bf);Nd!==null&&!(Nd.expirationTime>e&&Zte());){var o=Nd.callback;if(typeof o=="function"){Nd.callback=null,Kl=Nd.priorityLevel;var r=o(Nd.expirationTime<=e);if(e=Is.unstable_now(),typeof r=="function"){Nd.callback=r,C1(e),t=!0;break t}Nd===Xg(bf)&&E1(bf),C1(e)}else E1(bf);Nd=Xg(bf)}if(Nd!==null)t=!0;else{var s=Xg(xh);s!==null&&W8(G8,s.startTime-e),t=!1}}break e}finally{Nd=null,Kl=n,U8=!1}t=void 0}}finally{t?pS():hS=!1}}}var pS;typeof Jte=="function"?pS=function(){Jte(L8)}:typeof MessageChannel<"u"?(O8=new MessageChannel,$te=O8.port2,O8.port1.onmessage=L8,pS=function(){$te.postMessage(null)}):pS=function(){Vte(L8,0)};var O8,$te;function W8(e,t){dQ=Vte(function(){e(Is.unstable_now())},t)}Is.unstable_IdlePriority=5;Is.unstable_ImmediatePriority=1;Is.unstable_LowPriority=4;Is.unstable_NormalPriority=3;Is.unstable_Profiling=null;Is.unstable_UserBlockingPriority=2;Is.unstable_cancelCallback=function(e){e.callback=null};Is.unstable_forceFrameRate=function(e){0>e||125<e?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):zte=0<e?Math.floor(1e3/e):5};Is.unstable_getCurrentPriorityLevel=function(){return Kl};Is.unstable_next=function(e){switch(Kl){case 1:case 2:case 3:var t=3;break;default:t=Kl}var n=Kl;Kl=t;try{return e()}finally{Kl=n}};Is.unstable_requestPaint=function(){H8=!0};Is.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=Kl;Kl=e;try{return t()}finally{Kl=n}};Is.unstable_scheduleCallback=function(e,t,n){var o=Is.unstable_now();switch(typeof n=="object"&&n!==null?(n=n.delay,n=typeof n=="number"&&0<n?o+n:o):n=o,e){case 1:var r=-1;break;case 2:r=250;break;case 5:r=1073741823;break;case 4:r=1e4;break;default:r=5e3}return r=n+r,e={id:QUe++,callback:t,priorityLevel:e,startTime:n,expirationTime:r,sortIndex:-1},n>o?(e.sortIndex=n,P8(xh,e),Xg(bf)===null&&e===Xg(xh)&&(uQ?(Kte(dQ),dQ=-1):uQ=!0,W8(G8,n-o))):(e.sortIndex=r,P8(bf,e),cQ||U8||(cQ=!0,hS||(hS=!0,pS()))),e};Is.unstable_shouldYield=Zte;Is.unstable_wrapCallback=function(e){var t=Kl;return function(){var n=Kl;Kl=t;try{return e.apply(this,arguments)}finally{Kl=n}}}});var j8=Fe((i0t,tne)=>{"use strict";p();tne.exports=ene()});var nne=Fe((l0t,AQ)=>{"use strict";p();AQ.exports=function(e){function t(d,g,B,b){return new CF(d,g,B,b)}function n(){}function o(d){var g="https://react.dev/errors/"+d;if(1<arguments.length){g+="?args[]="+encodeURIComponent(arguments[1]);for(var B=2;B<arguments.length;B++)g+="&args[]="+encodeURIComponent(arguments[B])}return"Minified React error #"+d+"; visit "+g+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function r(d){var g=d,B=d;if(d.alternate)for(;g.return;)g=g.return;else{d=g;do g=d,(g.flags&4098)!==0&&(B=g.return),d=g.return;while(d)}return g.tag===3?B:null}function s(d){if(r(d)!==d)throw Error(o(188))}function i(d){var g=d.alternate;if(!g){if(g=r(d),g===null)throw Error(o(188));return g!==d?null:d}for(var B=d,b=g;;){var R=B.return;if(R===null)break;var _=R.alternate;if(_===null){if(b=R.return,b!==null){B=b;continue}break}if(R.child===_.child){for(_=R.child;_;){if(_===B)return s(R),d;if(_===b)return s(R),g;_=_.sibling}throw Error(o(188))}if(B.return!==b.return)B=R,b=_;else{for(var oe=!1,Se=R.child;Se;){if(Se===B){oe=!0,B=R,b=_;break}if(Se===b){oe=!0,b=R,B=_;break}Se=Se.sibling}if(!oe){for(Se=_.child;Se;){if(Se===B){oe=!0,B=_,b=R;break}if(Se===b){oe=!0,b=_,B=R;break}Se=Se.sibling}if(!oe)throw Error(o(189))}}if(B.alternate!==b)throw Error(o(190))}if(B.tag!==3)throw Error(o(188));return B.stateNode.current===B?d:g}function a(d){var g=d.tag;if(g===5||g===26||g===27||g===6)return d;for(d=d.child;d!==null;){if(g=a(d),g!==null)return g;d=d.sibling}return null}function l(d){var g=d.tag;if(g===5||g===26||g===27||g===6)return d;for(d=d.child;d!==null;){if(d.tag!==4&&(g=l(d),g!==null))return g;d=d.sibling}return null}function c(d){return d===null||typeof d!="object"?null:(d=Pt&&d[Pt]||d["@@iterator"],typeof d=="function"?d:null)}function u(d){if(d==null)return null;if(typeof d=="function")return d.$$typeof===mo?null:d.displayName||d.name||null;if(typeof d=="string")return d;switch(d){case Pg:return"Fragment";case mT:return"Profiler";case DF:return"StrictMode";case hT:return"Suspense";case CT:return"SuspenseList";case gt:return"Activity"}if(typeof d=="object")switch(d.$$typeof){case Xp:return"Portal";case Ug:return d.displayName||"Context";case fT:return(d._context.displayName||"Context")+".Consumer";case pT:var g=d.render;return d=d.displayName,d||(d=g.displayName||g.name||"",d=d!==""?"ForwardRef("+d+")":"ForwardRef"),d;case ET:return g=d.displayName||null,g!==null?g:u(d.type)||"Memo";case Ue:g=d._payload,d=d._init;try{return u(d(g))}catch{}}return null}function A(d){return{current:d}}function h(d){0>hB||(d.current=i3[hB],i3[hB]=null,hB--)}function m(d,g){hB++,i3[hB]=d.current,d.current=g}function y(d){return d>>>=0,d===0?32:31-(oOe(d)/rOe|0)|0}function D(d){var g=d&42;if(g!==0)return g;switch(d&-d){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return d&261888;case 262144:case 524288:case 1048576:case 2097152:return d&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return d&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return d}}function S(d,g,B){var b=d.pendingLanes;if(b===0)return 0;var R=0,_=d.suspendedLanes,oe=d.pingedLanes;d=d.warmLanes;var Se=b&134217727;return Se!==0?(b=Se&~_,b!==0?R=D(b):(oe&=Se,oe!==0?R=D(oe):B||(B=Se&~d,B!==0&&(R=D(B))))):(Se=b&~_,Se!==0?R=D(Se):oe!==0?R=D(oe):B||(B=b&~d,B!==0&&(R=D(B)))),R===0?0:g!==0&&g!==R&&(g&_)===0&&(_=R&-R,B=g&-g,_>=B||_===32&&(B&4194048)!==0)?g:R}function w(d,g){return(d.pendingLanes&~(d.suspendedLanes&~d.pingedLanes)&g)===0}function x(d,g){switch(d){case 1:case 2:case 4:case 8:case 64:return g+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return g+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function T(){var d=wF;return wF<<=1,(wF&62914560)===0&&(wF=4194304),d}function Q(d){for(var g=[],B=0;31>B;B++)g.push(d);return g}function v(d,g){d.pendingLanes|=g,g!==268435456&&(d.suspendedLanes=0,d.pingedLanes=0,d.warmLanes=0)}function F(d,g,B,b,R,_){var oe=d.pendingLanes;d.pendingLanes=B,d.suspendedLanes=0,d.pingedLanes=0,d.warmLanes=0,d.expiredLanes&=B,d.entangledLanes&=B,d.errorRecoveryDisabledLanes&=B,d.shellSuspendCounter=0;var Se=d.entanglements,et=d.expirationTimes,lt=d.hiddenUpdates;for(B=oe&~B;0<B;){var bt=31-Nu(B),ht=1<<bt;Se[bt]=0,et[bt]=-1;var Ft=lt[bt];if(Ft!==null)for(lt[bt]=null,bt=0;bt<Ft.length;bt++){var Vn=Ft[bt];Vn!==null&&(Vn.lane&=-536870913)}B&=~ht}b!==0&&H(d,b,0),_!==0&&R===0&&d.tag!==0&&(d.suspendedLanes|=_&~(oe&~g))}function H(d,g,B){d.pendingLanes|=g,d.suspendedLanes&=~g;var b=31-Nu(g);d.entangledLanes|=g,d.entanglements[b]=d.entanglements[b]|1073741824|B&261930}function Y(d,g){var B=d.entangledLanes|=g;for(d=d.entanglements;B;){var b=31-Nu(B),R=1<<b;R&g|d[b]&g&&(d[b]|=g),B&=~R}}function j(d,g){var B=g&-g;return B=(B&42)!==0?1:N(B),(B&(d.suspendedLanes|g))!==0?0:B}function N(d){switch(d){case 2:d=1;break;case 8:d=4;break;case 32:d=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:d=128;break;case 268435456:d=134217728;break;default:d=0}return d}function W(d){return d&=-d,2<d?8<d?(d&134217727)!==0?32:268435456:8:2}function L(d){if(typeof cOe=="function"&&uOe(d),_u&&typeof _u.setStrictMode=="function")try{_u.setStrictMode(ST,d)}catch{}}function O(d,g){return d===g&&(d!==0||1/d===1/g)||d!==d&&g!==g}function P(d){if(c3===void 0)try{throw Error()}catch(B){var g=B.stack.trim().match(/\n( *(at )?)/);c3=g&&g[1]||"",c7=-1<B.stack.indexOf(`
|
|
4
|
+
import{$ as YN,A as WN,C as $Z,D as VZ,E as n8,F as Ch,G as jN,H as OA,I as KZ,J as cy,K as zZ,L as XZ,M as uy,N as ZZ,Na as Fr,O as eee,P as o8,Q as r8,R as $o,S as s8,Sa as ql,T as ZT,Ta as Na,U as tee,Ua as $N,V as nee,W as oee,X as ree,Y as on,Z as see,_ as iee,a as JT,aa as aee,ab as hee,b as ay,ba as bOe,c as OZ,ca as iu,cb as yh,d as ui,da as qN,e as na,ea as TOe,eb as Cee,f as oa,fa as QOe,fb as Jl,g as gr,ga as JN,gb as tS,h as X3,ha as eQ,hb as zg,i as Z3,ia as Eh,ib as Nn,j as PZ,jb as Eee,k as UZ,kb as yee,l as Kg,lb as VN,m as HZ,n as Ps,o as Bf,oa as pee,p as WZ,q as VT,r as KT,s as zT,t as qZ,u as e8,v as ly,w as JZ,x as XT,y as GN,z as t8}from"./chunks/chunk-TFWOXSAP.js";import{a as Ce,b as KN,c as Dee,d as Bee,e as See}from"./chunks/chunk-H6WMNUW2.js";import{a as rt,b as We,c as PN,d as $T,e as UN,f as GZ,j as HN,k as eS,l as f,m as jZ,n as YZ}from"./chunks/chunk-GWGQRU36.js";import{a as Iee}from"./chunks/chunk-7ZATDBWL.js";import{a as Aee,c as l8,d as gee,e as mee,g as fee}from"./chunks/chunk-GC2F575A.js";import{a as lee,c as tQ,d as i8,e as a8}from"./chunks/chunk-3HUM74NZ.js";import{a as cee,b as uee,c as dee,e as ke}from"./chunks/chunk-JSFA3NEP.js";import{$a as Pz,$h as q3,A as UB,Ab as qg,Ae as vX,Af as FX,Ah as VX,Aj as lZ,Ak as hZ,Al as QZ,Be as Ar,Bk as CZ,Bl as vZ,Ca as Lz,Cj as cZ,Ck as zB,Cl as XB,De as RX,Dg as WX,Dh as Rd,Ee as MX,Ef as jl,Eh as Y3,Ej as uZ,El as RZ,Fe as SOe,Fh as KX,Fj as wN,Fk as EZ,Gj as bN,Hd as lX,Hi as oZ,Hl as MZ,Id as cX,If as NX,Ik as MN,Il as kZ,J as hz,Jc as Xz,Jd as uX,Jf as _X,Jk as yZ,Jl as FZ,Kc as Zz,Kd as dX,Kl as NZ,Lc as eX,Ld as AX,Le as yN,Ll as _Z,Mc as G3,Md as gX,Me as qB,Ml as LZ,Na as HT,Nc as pN,Ng as ry,Nk as IZ,Nl as NN,Ob as jz,Oc as tX,Od as mX,Ok as DZ,Ol as _N,Pa as Li,Pb as Yz,Pc as DOe,Pe as Vg,Pi as rZ,Pk as V3,Pl as ZB,Q as vz,Qb as qz,Qc as W3,Qj as dZ,Qk as K3,Ql as LN,R as If,Rb as Jg,Rh as zX,Rk as iy,Rl as ON,S as Rz,Sb as Jz,Sc as nX,Sd as jB,Si as LA,Td as fX,U as aN,Ua as cN,Uc as oX,Ud as pX,Uf as LX,Uh as XX,Va as Oz,Vb as $z,Vj as TN,Vk as BZ,We as WT,Wf as OX,Wg as DN,Wj as AZ,X as Mz,Xa as uN,Xd as hX,Xj as gZ,Y as kz,Ya as oy,Yd as CX,Yf as PX,Yj as VB,Z as Fz,Za as dN,Zd as EX,Zf as UX,Zh as SN,_ as Nz,_a as Yg,_i as sZ,_j as ta,ab as GB,ak as qT,bb as Wl,be as yX,ca as H3,cb as Wu,ce as IX,ci as ZX,cj as xOe,db as Uz,di as eZ,dj as iZ,ee as DX,eg as fh,eh as jX,ei as tZ,f as FB,fb as Hz,fd as rX,fe as BX,fh as YX,fi as YT,fk as ph,g as ZE,gd as j3,ge as SX,gg as IN,gk as sy,h as T7,hc as mN,hh as jT,ic as fN,id as sX,ie as xX,ig as HX,ih as qX,j as mz,jc as Vz,je as CN,jg as GX,jk as QN,kk as KB,ld as iX,lj as wOe,ll as SZ,mc as Kz,me as wX,mf as kX,mh as JX,mi as nZ,ml as xZ,nl as z3,oe as bX,oh as _A,oj as aZ,ol as kN,pa as lN,pe as EN,pi as J3,pj as $B,pl as wZ,qa as _z,qb as GT,qe as YB,qk as vN,ql as bZ,re as TX,rf as Df,rg as JB,rj as xN,rk as $3,rl as TZ,sb as Gz,sh as BN,sk as mZ,t as fz,tb as WB,td as aX,tk as fZ,tl as FN,ub as Wz,uj as Yl,wb as mh,x as pz,xd as hN,ye as QX,yk as RN,z as oN,ze as BOe,zh as $X,zk as pZ,zl as hh}from"./chunks/chunk-6ZMDAPGZ.js";import{a as Kn}from"./chunks/chunk-TZIDSCTF.js";import"./chunks/chunk-TXMXCR7D.js";import"./chunks/chunk-YULUB745.js";import"./chunks/chunk-VYTYYCBR.js";import"./chunks/chunk-ROETRE5J.js";import"./chunks/chunk-INAZKGGR.js";import{a as IOe}from"./chunks/chunk-DCQKJTAX.js";import"./chunks/chunk-TISQNFB5.js";import{a as ny}from"./chunks/chunk-6Q6PMGBD.js";import"./chunks/chunk-MTMU7JYZ.js";import"./chunks/chunk-RNKDFE2S.js";import{A as iN,b as P3,c as Cz,d as Fa,e as Ez,f as yz,i as Iz,j as HB,l as rN,m as Dz,o as Bz,p as Sz,r as bz,s as Tz,x as Qz,z as yf}from"./chunks/chunk-BN2CPSZ5.js";import"./chunks/chunk-47XR7IMP.js";import"./chunks/chunk-FWIVFCKF.js";import{a as $g,b as zz}from"./chunks/chunk-HMZOLFRP.js";import"./chunks/chunk-QKYGQLWC.js";import{a as AN,d as gN}from"./chunks/chunk-SE3XDSIJ.js";import{b as sN,d as xz,h as wz,i as U3}from"./chunks/chunk-VWWEEU4V.js";import"./chunks/chunk-HYVP4472.js";import"./chunks/chunk-Q2I3ARPJ.js";import"./chunks/chunk-X6BEBYGX.js";import{b as cz,d as uz,e as O3,i as dz,k as Az}from"./chunks/chunk-QHA3ZBRO.js";import{B as Z7,Y as L3,Z as sz,c as vd,ga as tN,i as z7,ja as UT,ka as iz,la as az,n as X7,na as lz,oa as nN,pa as ea}from"./chunks/chunk-XJYPRCV7.js";import{c as nz,d as oz}from"./chunks/chunk-4F4DA5UI.js";import{e as NA}from"./chunks/chunk-DC7LAFZZ.js";import{m as rz,v as _3}from"./chunks/chunk-S7G6QPEP.js";import{b as Zi}from"./chunks/chunk-4J6DC24J.js";import"./chunks/chunk-LJR4RZZ2.js";import"./chunks/chunk-U347OO7S.js";import{h as Ah,i as eN,j as PB,k as ez,m as tz}from"./chunks/chunk-SDTWBD62.js";import{Bb as F7,Cc as jg,Eb as N7,Gc as XF,Hb as _B,Hc as Y7,Ib as _7,Jb as k3,Lc as q7,Qb as L7,Tc as N3,Vb as F3,Wb as zF,Xb as OT,Xc as ZF,Yc as PT,Zb as O7,Zc as J7,cc as P7,db as R3,e as KF,gb as v7,h as kr,hb as R7,hd as $7,ib as M7,jb as k7,jc as ey,jd as ty,kb as M3,lc as U7,nd as V7,pc as LB,qc as H7,r as v3,s as Q7,sd as OB,t as Gu,td as K7}from"./chunks/chunk-KSNBNXBC.js";import"./chunks/chunk-WVY2P6WH.js";import"./chunks/chunk-UIRBHC5X.js";import{h as dh,j as G7,s as W7,w as j7}from"./chunks/chunk-32PTAACU.js";import"./chunks/chunk-2PPJ3MJT.js";import{e as b7,l as Hu,p as nn,q as NB}from"./chunks/chunk-PIFQEMZZ.js";import{a as gh,o as Ef,t as gz}from"./chunks/chunk-RJX7DK4Y.js";import"./chunks/chunk-XCJYORZX.js";import"./chunks/chunk-ESSYHTAZ.js";import"./chunks/chunk-3YLXGE6T.js";import{b as x7,e as w7}from"./chunks/chunk-EQEQPZLQ.js";import{B as JF,D as $F,F as _T,G as LT,J as uh,P as Mt,Q as S7,Y as VF,aa as He,b as FA,c as C7,d as ts,e as Q3,g as E7,i as YF,j as Xi,k as Gl,l as XE,n as y7,o as I7,q as D7,s as qF,u as B7}from"./chunks/chunk-VLYRNOD3.js";import"./chunks/chunk-G7R2XEEF.js";import"./chunks/chunk-OA56BXPD.js";import"./chunks/chunk-FWDMPRKU.js";import{a as __matilda_dirname,b as p}from"./chunks/chunk-GZPNIYVZ.js";import{a as Xe,d as Fe,e as EOe,f as k,g as yOe}from"./chunks/chunk-OWGSC52X.js";var Kee=Fe((Vwt,o1)=>{p();o1.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&o1.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&o1.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var tte=Fe((zwt,dS)=>{p();var Es=globalThis.process,gy=function(e){return e&&typeof e=="object"&&typeof e.removeListener=="function"&&typeof e.emit=="function"&&typeof e.reallyExit=="function"&&typeof e.listeners=="function"&&typeof e.kill=="function"&&typeof e.pid=="number"&&typeof e.on=="function"};gy(Es)?(zee=Xe("assert"),cS=Kee(),Xee=/^win/i.test(Es.platform),sQ=Xe("events"),typeof sQ!="function"&&(sQ=sQ.EventEmitter),Es.__signal_exit_emitter__?Oa=Es.__signal_exit_emitter__:(Oa=Es.__signal_exit_emitter__=new sQ,Oa.count=0,Oa.emitted={}),Oa.infinite||(Oa.setMaxListeners(1/0),Oa.infinite=!0),dS.exports=function(e,t){if(!gy(globalThis.process))return function(){};zee.equal(typeof e,"function","a callback must be provided for exit handler"),uS===!1&&E8();var n="exit";t&&t.alwaysLast&&(n="afterexit");var o=function(){Oa.removeListener(n,e),Oa.listeners("exit").length===0&&Oa.listeners("afterexit").length===0&&r1()};return Oa.on(n,e),o},r1=function(){!uS||!gy(globalThis.process)||(uS=!1,cS.forEach(function(t){try{Es.removeListener(t,s1[t])}catch{}}),Es.emit=i1,Es.reallyExit=y8,Oa.count-=1)},dS.exports.unload=r1,my=function(t,n,o){Oa.emitted[t]||(Oa.emitted[t]=!0,Oa.emit(t,n,o))},s1={},cS.forEach(function(e){s1[e]=function(){if(gy(globalThis.process)){var n=Es.listeners(e);n.length===Oa.count&&(r1(),my("exit",null,e),my("afterexit",null,e),Xee&&e==="SIGHUP"&&(e="SIGINT"),Es.kill(Es.pid,e))}}}),dS.exports.signals=function(){return cS},uS=!1,E8=function(){uS||!gy(globalThis.process)||(uS=!0,Oa.count+=1,cS=cS.filter(function(t){try{return Es.on(t,s1[t]),!0}catch{return!1}}),Es.emit=ete,Es.reallyExit=Zee)},dS.exports.load=E8,y8=Es.reallyExit,Zee=function(t){gy(globalThis.process)&&(Es.exitCode=t||0,my("exit",Es.exitCode,null),my("afterexit",Es.exitCode,null),y8.call(Es,Es.exitCode))},i1=Es.emit,ete=function(t,n){if(t==="exit"&&gy(globalThis.process)){n!==void 0&&(Es.exitCode=n);var o=i1.apply(this,arguments);return my("exit",Es.exitCode,null),my("afterexit",Es.exitCode,null),o}else return i1.apply(this,arguments)}):dS.exports=function(){return function(){}};var zee,cS,Xee,sQ,Oa,r1,my,s1,uS,E8,y8,Zee,i1,ete});var ste=Fe(Sh=>{"use strict";p();Sh.ConcurrentRoot=1;Sh.ContinuousEventPriority=8;Sh.DefaultEventPriority=32;Sh.DiscreteEventPriority=2;Sh.IdleEventPriority=268435456;Sh.LegacyRoot=0;Sh.NoEventPriority=0});var a1=Fe((rbt,ite)=>{"use strict";p();ite.exports=ste()});var ene=Fe(Is=>{"use strict";p();function P8(e,t){var n=e.length;e.push(t);e:for(;0<n;){var o=n-1>>>1,r=e[o];if(0<h1(r,t))e[o]=t,e[n]=r,n=o;else break e}}function Xg(e){return e.length===0?null:e[0]}function E1(e){if(e.length===0)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;e:for(var o=0,r=e.length,s=r>>>1;o<s;){var i=2*(o+1)-1,a=e[i],l=i+1,c=e[l];if(0>h1(a,n))l<r&&0>h1(c,a)?(e[o]=c,e[l]=n,o=l):(e[o]=a,e[i]=n,o=i);else if(l<r&&0>h1(c,n))e[o]=c,e[l]=n,o=l;else break e}}return t}function h1(e,t){var n=e.sortIndex-t.sortIndex;return n!==0?n:e.id-t.id}Is.unstable_now=void 0;typeof performance=="object"&&typeof performance.now=="function"?(Yte=performance,Is.unstable_now=function(){return Yte.now()}):(_8=Date,qte=_8.now(),Is.unstable_now=function(){return _8.now()-qte});var Yte,_8,qte,bf=[],xh=[],QUe=1,Nd=null,Kl=3,U8=!1,cQ=!1,uQ=!1,H8=!1,Vte=typeof setTimeout=="function"?setTimeout:null,Kte=typeof clearTimeout=="function"?clearTimeout:null,Jte=typeof setImmediate<"u"?setImmediate:null;function C1(e){for(var t=Xg(xh);t!==null;){if(t.callback===null)E1(xh);else if(t.startTime<=e)E1(xh),t.sortIndex=t.expirationTime,P8(bf,t);else break;t=Xg(xh)}}function G8(e){if(uQ=!1,C1(e),!cQ)if(Xg(bf)!==null)cQ=!0,hS||(hS=!0,pS());else{var t=Xg(xh);t!==null&&W8(G8,t.startTime-e)}}var hS=!1,dQ=-1,zte=5,Xte=-1;function Zte(){return H8?!0:!(Is.unstable_now()-Xte<zte)}function L8(){if(H8=!1,hS){var e=Is.unstable_now();Xte=e;var t=!0;try{e:{cQ=!1,uQ&&(uQ=!1,Kte(dQ),dQ=-1),U8=!0;var n=Kl;try{t:{for(C1(e),Nd=Xg(bf);Nd!==null&&!(Nd.expirationTime>e&&Zte());){var o=Nd.callback;if(typeof o=="function"){Nd.callback=null,Kl=Nd.priorityLevel;var r=o(Nd.expirationTime<=e);if(e=Is.unstable_now(),typeof r=="function"){Nd.callback=r,C1(e),t=!0;break t}Nd===Xg(bf)&&E1(bf),C1(e)}else E1(bf);Nd=Xg(bf)}if(Nd!==null)t=!0;else{var s=Xg(xh);s!==null&&W8(G8,s.startTime-e),t=!1}}break e}finally{Nd=null,Kl=n,U8=!1}t=void 0}}finally{t?pS():hS=!1}}}var pS;typeof Jte=="function"?pS=function(){Jte(L8)}:typeof MessageChannel<"u"?(O8=new MessageChannel,$te=O8.port2,O8.port1.onmessage=L8,pS=function(){$te.postMessage(null)}):pS=function(){Vte(L8,0)};var O8,$te;function W8(e,t){dQ=Vte(function(){e(Is.unstable_now())},t)}Is.unstable_IdlePriority=5;Is.unstable_ImmediatePriority=1;Is.unstable_LowPriority=4;Is.unstable_NormalPriority=3;Is.unstable_Profiling=null;Is.unstable_UserBlockingPriority=2;Is.unstable_cancelCallback=function(e){e.callback=null};Is.unstable_forceFrameRate=function(e){0>e||125<e?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):zte=0<e?Math.floor(1e3/e):5};Is.unstable_getCurrentPriorityLevel=function(){return Kl};Is.unstable_next=function(e){switch(Kl){case 1:case 2:case 3:var t=3;break;default:t=Kl}var n=Kl;Kl=t;try{return e()}finally{Kl=n}};Is.unstable_requestPaint=function(){H8=!0};Is.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=Kl;Kl=e;try{return t()}finally{Kl=n}};Is.unstable_scheduleCallback=function(e,t,n){var o=Is.unstable_now();switch(typeof n=="object"&&n!==null?(n=n.delay,n=typeof n=="number"&&0<n?o+n:o):n=o,e){case 1:var r=-1;break;case 2:r=250;break;case 5:r=1073741823;break;case 4:r=1e4;break;default:r=5e3}return r=n+r,e={id:QUe++,callback:t,priorityLevel:e,startTime:n,expirationTime:r,sortIndex:-1},n>o?(e.sortIndex=n,P8(xh,e),Xg(bf)===null&&e===Xg(xh)&&(uQ?(Kte(dQ),dQ=-1):uQ=!0,W8(G8,n-o))):(e.sortIndex=r,P8(bf,e),cQ||U8||(cQ=!0,hS||(hS=!0,pS()))),e};Is.unstable_shouldYield=Zte;Is.unstable_wrapCallback=function(e){var t=Kl;return function(){var n=Kl;Kl=t;try{return e.apply(this,arguments)}finally{Kl=n}}}});var j8=Fe((i0t,tne)=>{"use strict";p();tne.exports=ene()});var nne=Fe((l0t,AQ)=>{"use strict";p();AQ.exports=function(e){function t(d,g,B,b){return new CF(d,g,B,b)}function n(){}function o(d){var g="https://react.dev/errors/"+d;if(1<arguments.length){g+="?args[]="+encodeURIComponent(arguments[1]);for(var B=2;B<arguments.length;B++)g+="&args[]="+encodeURIComponent(arguments[B])}return"Minified React error #"+d+"; visit "+g+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function r(d){var g=d,B=d;if(d.alternate)for(;g.return;)g=g.return;else{d=g;do g=d,(g.flags&4098)!==0&&(B=g.return),d=g.return;while(d)}return g.tag===3?B:null}function s(d){if(r(d)!==d)throw Error(o(188))}function i(d){var g=d.alternate;if(!g){if(g=r(d),g===null)throw Error(o(188));return g!==d?null:d}for(var B=d,b=g;;){var R=B.return;if(R===null)break;var _=R.alternate;if(_===null){if(b=R.return,b!==null){B=b;continue}break}if(R.child===_.child){for(_=R.child;_;){if(_===B)return s(R),d;if(_===b)return s(R),g;_=_.sibling}throw Error(o(188))}if(B.return!==b.return)B=R,b=_;else{for(var oe=!1,Se=R.child;Se;){if(Se===B){oe=!0,B=R,b=_;break}if(Se===b){oe=!0,b=R,B=_;break}Se=Se.sibling}if(!oe){for(Se=_.child;Se;){if(Se===B){oe=!0,B=_,b=R;break}if(Se===b){oe=!0,b=_,B=R;break}Se=Se.sibling}if(!oe)throw Error(o(189))}}if(B.alternate!==b)throw Error(o(190))}if(B.tag!==3)throw Error(o(188));return B.stateNode.current===B?d:g}function a(d){var g=d.tag;if(g===5||g===26||g===27||g===6)return d;for(d=d.child;d!==null;){if(g=a(d),g!==null)return g;d=d.sibling}return null}function l(d){var g=d.tag;if(g===5||g===26||g===27||g===6)return d;for(d=d.child;d!==null;){if(d.tag!==4&&(g=l(d),g!==null))return g;d=d.sibling}return null}function c(d){return d===null||typeof d!="object"?null:(d=Pt&&d[Pt]||d["@@iterator"],typeof d=="function"?d:null)}function u(d){if(d==null)return null;if(typeof d=="function")return d.$$typeof===mo?null:d.displayName||d.name||null;if(typeof d=="string")return d;switch(d){case Pg:return"Fragment";case mT:return"Profiler";case DF:return"StrictMode";case hT:return"Suspense";case CT:return"SuspenseList";case gt:return"Activity"}if(typeof d=="object")switch(d.$$typeof){case Xp:return"Portal";case Ug:return d.displayName||"Context";case fT:return(d._context.displayName||"Context")+".Consumer";case pT:var g=d.render;return d=d.displayName,d||(d=g.displayName||g.name||"",d=d!==""?"ForwardRef("+d+")":"ForwardRef"),d;case ET:return g=d.displayName||null,g!==null?g:u(d.type)||"Memo";case Ue:g=d._payload,d=d._init;try{return u(d(g))}catch{}}return null}function A(d){return{current:d}}function h(d){0>hB||(d.current=i3[hB],i3[hB]=null,hB--)}function m(d,g){hB++,i3[hB]=d.current,d.current=g}function y(d){return d>>>=0,d===0?32:31-(oOe(d)/rOe|0)|0}function D(d){var g=d&42;if(g!==0)return g;switch(d&-d){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return d&261888;case 262144:case 524288:case 1048576:case 2097152:return d&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return d&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return d}}function S(d,g,B){var b=d.pendingLanes;if(b===0)return 0;var R=0,_=d.suspendedLanes,oe=d.pingedLanes;d=d.warmLanes;var Se=b&134217727;return Se!==0?(b=Se&~_,b!==0?R=D(b):(oe&=Se,oe!==0?R=D(oe):B||(B=Se&~d,B!==0&&(R=D(B))))):(Se=b&~_,Se!==0?R=D(Se):oe!==0?R=D(oe):B||(B=b&~d,B!==0&&(R=D(B)))),R===0?0:g!==0&&g!==R&&(g&_)===0&&(_=R&-R,B=g&-g,_>=B||_===32&&(B&4194048)!==0)?g:R}function w(d,g){return(d.pendingLanes&~(d.suspendedLanes&~d.pingedLanes)&g)===0}function x(d,g){switch(d){case 1:case 2:case 4:case 8:case 64:return g+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return g+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function T(){var d=wF;return wF<<=1,(wF&62914560)===0&&(wF=4194304),d}function Q(d){for(var g=[],B=0;31>B;B++)g.push(d);return g}function v(d,g){d.pendingLanes|=g,g!==268435456&&(d.suspendedLanes=0,d.pingedLanes=0,d.warmLanes=0)}function F(d,g,B,b,R,_){var oe=d.pendingLanes;d.pendingLanes=B,d.suspendedLanes=0,d.pingedLanes=0,d.warmLanes=0,d.expiredLanes&=B,d.entangledLanes&=B,d.errorRecoveryDisabledLanes&=B,d.shellSuspendCounter=0;var Se=d.entanglements,et=d.expirationTimes,lt=d.hiddenUpdates;for(B=oe&~B;0<B;){var bt=31-Nu(B),ht=1<<bt;Se[bt]=0,et[bt]=-1;var Ft=lt[bt];if(Ft!==null)for(lt[bt]=null,bt=0;bt<Ft.length;bt++){var Vn=Ft[bt];Vn!==null&&(Vn.lane&=-536870913)}B&=~ht}b!==0&&H(d,b,0),_!==0&&R===0&&d.tag!==0&&(d.suspendedLanes|=_&~(oe&~g))}function H(d,g,B){d.pendingLanes|=g,d.suspendedLanes&=~g;var b=31-Nu(g);d.entangledLanes|=g,d.entanglements[b]=d.entanglements[b]|1073741824|B&261930}function Y(d,g){var B=d.entangledLanes|=g;for(d=d.entanglements;B;){var b=31-Nu(B),R=1<<b;R&g|d[b]&g&&(d[b]|=g),B&=~R}}function j(d,g){var B=g&-g;return B=(B&42)!==0?1:N(B),(B&(d.suspendedLanes|g))!==0?0:B}function N(d){switch(d){case 2:d=1;break;case 8:d=4;break;case 32:d=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:d=128;break;case 268435456:d=134217728;break;default:d=0}return d}function W(d){return d&=-d,2<d?8<d?(d&134217727)!==0?32:268435456:8:2}function L(d){if(typeof cOe=="function"&&uOe(d),_u&&typeof _u.setStrictMode=="function")try{_u.setStrictMode(ST,d)}catch{}}function O(d,g){return d===g&&(d!==0||1/d===1/g)||d!==d&&g!==g}function P(d){if(c3===void 0)try{throw Error()}catch(B){var g=B.stack.trim().match(/\n( *(at )?)/);c3=g&&g[1]||"",c7=-1<B.stack.indexOf(`
|
|
5
5
|
at`)?" (<anonymous>)":-1<B.stack.indexOf("@")?"@unknown:0:0":""}return`
|
|
6
6
|
`+c3+d+c7}function U(d,g){if(!d||u3)return"";u3=!0;var B=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var b={DetermineComponentFrameRoot:function(){try{if(g){var ht=function(){throw Error()};if(Object.defineProperty(ht.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(ht,[])}catch(Vn){var Ft=Vn}Reflect.construct(d,[],ht)}else{try{ht.call()}catch(Vn){Ft=Vn}d.call(ht.prototype)}}else{try{throw Error()}catch(Vn){Ft=Vn}(ht=d())&&typeof ht.catch=="function"&&ht.catch(function(){})}}catch(Vn){if(Vn&&Ft&&typeof Vn.stack=="string")return[Vn.stack,Ft.stack]}return[null,null]}};b.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var R=Object.getOwnPropertyDescriptor(b.DetermineComponentFrameRoot,"name");R&&R.configurable&&Object.defineProperty(b.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var _=b.DetermineComponentFrameRoot(),oe=_[0],Se=_[1];if(oe&&Se){var et=oe.split(`
|
|
7
7
|
`),lt=Se.split(`
|
|
@@ -285,7 +285,7 @@ ${t.stderr}`,e.worktree,e.changedFilesSet);return{exitCode:t.exitCode,findings:n
|
|
|
285
285
|
`)){if(!r.startsWith("{"))continue;let s;try{s=JSON.parse(r)}catch{continue}if(s.reason!=="compiler-message"||!s.message)continue;let i=s.message;if(i.level!=="error"&&i.level!=="warning")continue;let a=(i.spans||[]).find(c=>c.is_primary);if(!a)continue;let l=AI(a.file_name,t);$x(l,n)&&o.push({source:"typecheck",tool:"cargo-clippy",file:l,line:a.line_start,column:a.column_start,severity:i.level==="error"?"Critical":"Nice to have",message:i.message,ruleId:i.code?.code})}return o}var LZe={name:"go-vet",source:"typecheck",detect:({worktree:e})=>qf(aC(e,"go.mod"))?Jx("go")?{ok:!0}:{ok:!1,reason:"go not in PATH"}:{ok:!1,reason:"go.mod not found"},run:e=>{let t=qx(e.worktree,"go",["vet","./..."],Iq),n=OZe(`${t.stdout}
|
|
286
286
|
${t.stderr}`,e.worktree,e.changedFilesSet);return{exitCode:t.exitCode,findings:n,timedOut:t.timedOut}}};function OZe(e,t,n){let o=[],r=/^(.+?\.go):(\d+)(?::(\d+))?:\s+(.+)$/gm,s;for(;(s=r.exec(e))!==null;){let i=AI(s[1],t);$x(i,n)&&o.push({source:"typecheck",tool:"go-vet",file:i,line:parseInt(s[2],10),column:s[3]?parseInt(s[3],10):void 0,severity:"Critical",message:s[4].trim()})}return o}var PZe={name:"golangci-lint",source:"linter",detect:({worktree:e})=>qf(aC(e,"go.mod"))?Jx("golangci-lint")?{ok:!0}:{ok:!1,reason:"golangci-lint not in PATH"}:{ok:!1,reason:"go.mod not found"},run:e=>{let t=qx(e.worktree,"golangci-lint",["run","--out-format=json","./..."],Dq),n=UZe(t.stdout,e.worktree,e.changedFilesSet);return{exitCode:t.exitCode,findings:n,timedOut:t.timedOut}}};function UZe(e,t,n){let o;try{o=JSON.parse(e)}catch{return[]}let r=[];for(let s of o.Issues??[]){let i=AI(s.Pos.Filename,t);$x(i,n)&&r.push({source:"linter",tool:"golangci-lint",file:i,line:s.Pos.Line,column:s.Pos.Column,severity:s.Severity?.toLowerCase()==="warning"?"Nice to have":"Critical",message:s.Text,ruleId:s.FromLinter})}return r}var HZe=[bZe,vZe,kZe,NZe,LZe,PZe];async function GZe(e){let t=xZe(e.worktree);if(!qf(t))throw new Error(`Worktree not found: ${t}`);let n=[];try{let A=Npe(e["changed-files"],"utf8");n=JSON.parse(A)}catch(A){throw new Error(`Failed to read changed-files JSON at ${e["changed-files"]}: ${A.message}`)}if(!Array.isArray(n))throw new Error("changed-files JSON must be an array of paths");let o=n.map(A=>AI(A,t)),r=new Set(o),s={worktree:t,changedFiles:o,changedFilesSet:r},i=[],a=[],l=[];for(let A of HZe){let h=A.detect(s);if(!h.ok){l.push({tool:A.name,reason:h.reason});continue}let m=Date.now(),y=A.run(s),D=Date.now()-m;i.push(...y.findings),a.push({tool:A.name,source:A.source,exitCode:y.exitCode,durationMs:D,findingsCount:y.findings.length,timedOut:y.timedOut})}let c={worktree:t,changedFiles:o,findings:i,toolsRun:a,toolsSkipped:l};BZe(SZe(e.out),{recursive:!0}),DZe(e.out,JSON.stringify(c,null,2)+`
|
|
287
287
|
`,"utf8");let u=a.map(A=>`${A.tool}=${A.findingsCount}${A.timedOut?" (timeout)":""}`).join(", ");rt(`Wrote deterministic report to ${e.out}: ${i.length} findings (${u||"no tools applicable"}; skipped ${l.length})`)}var _pe={command:"deterministic <worktree>",describe:"Run deterministic typecheck / lint on changed files (TypeScript/JavaScript: tsc + eslint)",builder:e=>e.positional("worktree",{type:"string",demandOption:!0,describe:"Worktree directory to run tools in"}).option("changed-files",{type:"string",demandOption:!0,describe:"Path to a JSON file containing an array of changed file paths (relative to worktree)"}).option("out",{type:"string",demandOption:!0,describe:"Output JSON path (will be overwritten)"}),handler:async e=>{await GZe(e)}};p();import{writeFileSync as WZe,readFileSync as jZe}from"node:fs";var YZe=new Set(["failure","cancelled","timed_out","action_required"]),qZe=new Set(["failure","error"]),Lpe=new Set(["queued","in_progress","pending"]);function JZe(e,t){let n=[],o=!1;for(let s of e)s.status==="completed"?s.conclusion&&YZe.has(s.conclusion)&&n.push(s.name):Lpe.has(s.status)&&(o=!0);for(let s of t)qZe.has(s.state)?n.push(s.context):Lpe.has(s.state)&&(o=!0);let r;return n.length>0?r="any_failure":e.length===0&&t.length===0?r="no_checks":o?r="all_pending":r="all_pass",{class:r,failedCheckNames:n,totalChecks:e.length+t.length}}function $Ze(e,t,n,o){let r={stale:[],resolved:[],overlap:[],noConflict:[]};for(let s of e){let i={id:s.id,path:s.path??"",line:s.line??0,commit_id:s.commit_id??"",body:(s.body||"").slice(0,80)};s.commit_id!==o?r.stale.push(i):t.has(s.id)?r.resolved.push(i):n.has(`${s.path}:${s.line}`)?r.overlap.push(i):r.noConflict.push(i)}return r}async function VZe(e){let{pr_number:t,commit_sha:n,owner_repo:o,out_path:r}=e,s=e["new-findings"],i=o.indexOf("/");if(i<0)throw new Error('owner_repo must look like "owner/repo"');let a=o.slice(0,i),l=o.slice(i+1);Yx();let c=Yf("api",`repos/${a}/${l}/pulls/${t}`,"--jq",".user.login"),u=xpe(),A=c.toLowerCase()===u.toLowerCase(),m=Eq(`repos/${a}/${l}/commits/${n}/check-runs`)?.check_runs??[],D=Eq(`repos/${a}/${l}/commits/${n}/status`)?.statuses??[],S=JZe(m,D),w=jx(`repos/${a}/${l}/pulls/${t}/comments`),x=w.filter(j=>/via Matilda \/review/.test(j.body??"")),T=new Set;for(let j of w)j.in_reply_to_id&&T.add(j.in_reply_to_id);let Q=[];s&&(Q=JSON.parse(jZe(s,"utf8")));let v=new Set(Q.map(j=>`${j.path}:${j.line}`)),F=$Ze(x,T,v,n),H=[];A&&H.push("self-PR"),S.class==="any_failure"&&H.push(`CI failing: ${S.failedCheckNames.join(", ")}`),S.class==="all_pending"&&H.push("CI still running");let Y={prNumber:t,commitSha:n,ownerRepo:o,isSelfPr:A,ciStatus:S,existingComments:{total:x.length,byBucket:{stale:F.stale.length,resolved:F.resolved.length,overlap:F.overlap.length,noConflict:F.noConflict.length},overlap:F.overlap,stale:F.stale,resolved:F.resolved,noConflict:F.noConflict},downgradeApprove:A||S.class==="any_failure"||S.class==="all_pending",downgradeRequestChanges:A,downgradeReasons:H,blockOnExistingComments:F.overlap.length>0};WZe(r,JSON.stringify(Y,null,2)+`
|
|
288
|
-
`,"utf8"),rt(`Wrote presubmit report to ${r}`)}var Ope={command:"presubmit <pr_number> <commit_sha> <owner_repo> <out_path>",describe:"Pre-submission checks for /review Step 9 (self-PR detection, CI status, existing-comments classification)",builder:e=>e.positional("pr_number",{type:"string",demandOption:!0,describe:"PR number"}).positional("commit_sha",{type:"string",demandOption:!0,describe:"PR HEAD commit SHA"}).positional("owner_repo",{type:"string",demandOption:!0,describe:'GitHub "owner/repo"'}).positional("out_path",{type:"string",demandOption:!0,describe:"Output JSON path (will be overwritten)"}).option("new-findings",{type:"string",describe:"Path to a JSON file shaped as [{path, line}, ...] \u2014 when provided, existing comments are checked for same-(path, line) overlap with the new findings."}),handler:async e=>{await VZe(e)}};p();import{execFileSync as Ppe}from"node:child_process";import{existsSync as Upe,readdirSync as KZe,unlinkSync as zZe}from"node:fs";import{join as XZe}from"node:path";function ZZe(e){let t=!1,n=/^pr-(\d+)$/.exec(e);if(n){let s=n[1],i=aR(s);if(Upe(i))try{Ppe("git",["worktree","remove",i,"--force"],{stdio:"pipe"}),rt(`Removed worktree: ${i}`),t=!0}catch(l){We(`Failed to remove worktree ${i}: ${l.message}`)}let a=lR(s);if(q2(a))try{Ppe("git",["branch","-D",a],{stdio:"pipe"}),rt(`Deleted ref: ${a}`),t=!0}catch(l){We(`Failed to delete branch ${a}: ${l.message}`)}}let o=bpe(e),r=[];try{r=Upe(iC)?KZe(iC):[]}catch(s){We(`Failed to read ${iC}: ${s.message}`)}for(let s of r){if(!s.startsWith(o))continue;let i=XZe(iC,s);try{zZe(i),rt(`Removed temp file: ${i}`),t=!0}catch(a){We(`Failed to remove ${i}: ${a.message}`)}}t||rt(`Nothing to clean for target "${e}".`)}var Hpe={command:"cleanup <target>",describe:"Post-review cleanup: remove worktree, branch ref, and per-target temp files",builder:e=>e.positional("target",{type:"string",demandOption:!0,describe:'Review target \u2014 "pr-<n>" for a PR review, "local" for an uncommitted review, or a filename for a file review'}),handler:e=>{ZZe(e.target)}};var Gpe={command:"review",describe:"Internal helpers used by the /review skill (PR worktree setup, context fetch, rules loading, deterministic analysis, presubmit checks, cleanup)",builder:e=>e.command(Qpe).command(Rpe).command(kpe).command(_pe).command(Ope).command(Hpe).demandCommand(1,"Specify a subcommand: fetch-pr, pr-context, load-rules, deterministic, presubmit, or cleanup.").version(!1),handler:()=>{}};p();p();var Bq="Warning: running headless with --bogan / approval-mode=bogan and no sandbox. All tool calls (shell, write, edit) auto-execute at this process's privilege level. Enable a sandbox via --sandbox / MATILDA_SANDBOX, or set MATILDA_CODE_SUPPRESS_BOGAN_WARNING=1 to silence this notice.";function Wpe(e,t=process.env){return e.getApprovalMode()!=="bogan"||e.getSandbox()||t.SANDBOX||eet(t.MATILDA_CODE_SUPPRESS_BOGAN_WARNING)?null:Bq}function eet(e){return e==="1"||e==="true"}function net(){return new Promise(()=>{})}var jpe={command:"serve",describe:"Run Matilda as a local HTTP daemon (Stage 1 experimental: --http-bridge)",builder:e=>e.option("port",{type:"number",default:4170,description:"TCP port to bind (use 0 for an OS-assigned ephemeral port)"}).option("hostname",{type:"string",default:"127.0.0.1",description:"Interface to bind. Loopback (127.0.0.1, localhost, ::1, [::1]) is auth-free; anything else requires a token."}).option("token",{type:"string",description:"Bearer token required on every request. Falls back to the MATILDA_SERVER_TOKEN env var."}).option("max-sessions",{type:"number",default:20,description:"Cap on concurrent live sessions. New spawn requests beyond this return 503; attach to existing sessions still works. Set to 0 to disable."}).option("max-pending-prompts-per-session",{type:"number",default:5,description:"Per-session cap on accepted prompts waiting or running. New prompts beyond this return 503. Set to 0 to disable."}).option("workspace",{type:"string",description:"Absolute workspace path this daemon binds to. POST /session requests with a mismatched cwd return 400 workspace_mismatch. Defaults to process.cwd() when omitted. For multi-workspace deployments, run one `matilda serve` per workspace on separate ports (or behind an external orchestrator)."}).option("max-connections",{type:"number",default:256,description:"Listener-level TCP connection cap (server.maxConnections). Bounds raw sockets \u2014 slow/phantom SSE clients get rejected at accept time once full. Set to 0 to disable."}).option("require-auth",{type:"boolean",default:!1,description:"Refuse to start without a bearer token, even on loopback. Hardens the loopback developer default for shared dev hosts / CI runners / multi-tenant workstations where any local user can hit 127.0.0.1. Requires --token or MATILDA_SERVER_TOKEN. /health also requires Authorization when enabled (no loopback exemption \u2014 k8s/Compose probes must pass the bearer too)."}).option("enable-session-shell",{type:"boolean",default:!1,description:"Enable direct POST /session/:id/shell execution. Requires a bearer token and a session-bound client id on each call."}).option("event-ring-size",{type:"number",default:8e3,description:"Per-session SSE replay ring depth. Sets the replay backlog available to `GET /session/:id/events` reconnects that send a `Last-Event-ID: N` header. Larger = more reconnect headroom at the cost of a few hundred KB extra RAM per session. Must be a positive finite integer."}).option("http-bridge",{type:"boolean",default:!0,description:"Stage 1 mode: one `matilda --acp` child per daemon (the daemon binds to one workspace at boot, multiplexing N sessions onto that child via the agent's native `newSession()`). Stage 2 native in-process mode is not yet implemented; this flag will become opt-in then."}).option("mcp-client-budget",{type:"number",description:"Cap on live MCP clients spawned inside the ACP child for the bound workspace. Positive integer. Combine with --mcp-budget-mode to control behavior at the cap. When unset, mode defaults to off (no accounting-driven enforcement, but GET /workspace/mcp still reports `clientCount`). Distinct from claude-code MCP_SERVER_CONNECTION_BATCH_SIZE which gates startup concurrency, not the total client count."}).option("mcp-budget-mode",{choices:["enforce","warn","off"],description:'How --mcp-client-budget is enforced. `warn` (default when budget set): no refusal, snapshot surfaces warning at >=75% of budget. `enforce`: connects past the cap are refused (`disabledReason: "budget"`, deterministic by mcpServers declaration order). `off`: pure observability. Boot rejects `enforce` without a budget.'}).option("allow-origin",{type:"string",array:!0,description:"Cross-origin allowlist for browser webui clients."}).option("allow-private-auth-base-url",{type:"boolean",default:!1,description:"Allow /workspace/auth/provider to install localhost/private-network baseUrl values. Use only for local development with trusted clients."}).option("prompt-deadline-ms",{type:"number",description:"Server-side wallclock cap on POST /session/:id/prompt (ms). Falls back to MATILDA_SERVE_PROMPT_DEADLINE_MS. Positive integer."}).option("writer-idle-timeout-ms",{type:"number",description:"Per-SSE-connection idle deadline (ms). Falls back to MATILDA_SERVE_WRITER_IDLE_TIMEOUT_MS. Positive integer."}).option("channel-idle-timeout-ms",{type:"number",description:"Milliseconds to keep ACP child alive after last session closes. 0 or unset = immediate kill (default)."}).option("session-reap-interval-ms",{type:"number",description:"Session reaper scan interval (ms). 0 = disabled. Default: 60000."}).option("session-idle-timeout-ms",{type:"number",description:"Idle timeout before a disconnected session is reaped (ms). 0 = disabled. Default: 1800000 (30 min)."}).option("rate-limit",{type:"boolean",description:"Enable per-tier HTTP rate limiting. Tiers: prompt (10/min), mutation (30/min), read (120/min). Health, heartbeat, SSE, and /acp are exempt."}).option("rate-limit-prompt",{type:"number",description:"Max prompt requests per window per client (default 10). Requires --rate-limit."}).option("rate-limit-mutation",{type:"number",description:"Max mutation requests per window per client (default 30). Requires --rate-limit."}).option("rate-limit-read",{type:"number",description:"Max read requests per window per client (default 120). Requires --rate-limit."}).option("rate-limit-window-ms",{type:"number",description:"Rate limit window duration in ms (default 60000). Requires --rate-limit."}),handler:async e=>{e["http-bridge"]||We("matilda serve: --no-http-bridge (native mode) is not yet implemented; falling back to http-bridge."),e.token&&We("matilda serve: --token is visible in the process command line; prefer the MATILDA_SERVER_TOKEN env var for any non-trivial deployment.");let t=e["mcp-client-budget"],n=e["mcp-budget-mode"];t!==void 0&&(!Number.isFinite(t)||!Number.isInteger(t)||t<=0)&&(We("matilda serve: --mcp-client-budget must be a positive integer."),process.exit(1)),n==="enforce"&&t===void 0&&(We("matilda serve: --mcp-budget-mode=enforce requires --mcp-client-budget=N."),process.exit(1));let o=n??(t!==void 0?"warn":"off"),r=e["max-pending-prompts-per-session"];r!==Number.POSITIVE_INFINITY&&(!Number.isFinite(r)||!Number.isInteger(r)||r<0)&&(We("matilda serve: --max-pending-prompts-per-session must be a non-negative integer (0 / Infinity = unlimited)."),process.exit(1)),t!==void 0&&We(`matilda serve: --mcp-client-budget=${t} mode=${o}`+(o==="enforce"?" (servers past the cap will be refused at discovery)":o==="warn"?` (warnings at >=${Math.ceil(t*YT)}, no refusal)`:""));try{let h=on(e.workspace??process.cwd()).merged,m=h.tools?.approvalMode,y=h.tools?.sandbox,D=process.env.SANDBOX,S=process.env.MATILDA_CODE_SUPPRESS_BOGAN_WARNING,w=S==="1"||S==="true";m==="bogan"&&!y&&!D&&!w&&We(Bq)}catch{}let s=e["rate-limit"]??(process.env.MATILDA_SERVE_RATE_LIMIT==="1"||process.env.MATILDA_SERVE_RATE_LIMIT==="true"),i,a,l,c;if(s){let A=h=>{let m=process.env[h];return m?Number(m):void 0};i=e["rate-limit-prompt"]??A("MATILDA_SERVE_RATE_LIMIT_PROMPT"),a=e["rate-limit-mutation"]??A("MATILDA_SERVE_RATE_LIMIT_MUTATION"),l=e["rate-limit-read"]??A("MATILDA_SERVE_RATE_LIMIT_READ"),c=e["rate-limit-window-ms"]??A("MATILDA_SERVE_RATE_LIMIT_WINDOW_MS");for(let[h,m]of[["--rate-limit-prompt",i],["--rate-limit-mutation",a],["--rate-limit-read",l]])m!==void 0&&(!Number.isFinite(m)||!Number.isInteger(m)||m<=0)&&(We(`matilda serve: ${h} must be a positive integer.`),process.exit(1));c!==void 0&&(!Number.isFinite(c)||!Number.isInteger(c)||c<1e3)&&(We("matilda serve: --rate-limit-window-ms must be an integer >= 1000."),process.exit(1))}let{runMatildaServe:u}=await import("./chunks/serve-LYF52JPB.js");try{await u({port:e.port,hostname:e.hostname,token:e.token,mode:"http-bridge",maxSessions:e["max-sessions"],maxPendingPromptsPerSession:r,maxConnections:e["max-connections"],eventRingSize:e["event-ring-size"],workspace:e.workspace,requireAuth:e["require-auth"],enableSessionShell:e["enable-session-shell"],allowPrivateAuthBaseUrl:e["allow-private-auth-base-url"],mcpClientBudget:t,mcpBudgetMode:o,...e["allow-origin"]&&e["allow-origin"].length>0?{allowOrigins:e["allow-origin"]}:{},...e["prompt-deadline-ms"]!==void 0?{promptDeadlineMs:e["prompt-deadline-ms"]}:{},...e["writer-idle-timeout-ms"]!==void 0?{writerIdleTimeoutMs:e["writer-idle-timeout-ms"]}:{},...e["channel-idle-timeout-ms"]!==void 0?{channelIdleTimeoutMs:e["channel-idle-timeout-ms"]}:{},...e["session-reap-interval-ms"]!==void 0?{sessionReapIntervalMs:e["session-reap-interval-ms"]}:{},...e["session-idle-timeout-ms"]!==void 0?{sessionIdleTimeoutMs:e["session-idle-timeout-ms"]}:{},...s?{rateLimit:!0}:{},...i!==void 0?{rateLimitPrompt:i}:{},...a!==void 0?{rateLimitMutation:a}:{},...l!==void 0?{rateLimitRead:l}:{},...c!==void 0?{rateLimitWindowMs:c}:{}})}catch(A){We(`matilda serve: ${A instanceof Error?A.message:String(A)}`),process.exit(1)}await net()}};p();p();p();var Jpe=k(qpe(),1),oet=new Intl.Segmenter,ret=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function un(e,t={}){if(typeof e!="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:o=!1}=t;if(o||(e=Ar(e)),e.length===0)return 0;let r=0,s={ambiguousAsWide:!n};for(let{segment:i}of oet.segment(e)){let a=i.codePointAt(0);if(!(a<=31||a>=127&&a<=159)&&!(a>=8203&&a<=8207||a===65279)&&!(a>=768&&a<=879||a>=6832&&a<=6911||a>=7616&&a<=7679||a>=8400&&a<=8447||a>=65056&&a<=65071)&&!(a>=55296&&a<=57343)&&!(a>=65024&&a<=65039)&&!ret.test(i)){if((0,Jpe.default)().test(i)){r+=2;continue}r+=Vl(a,s)}}return r}p();vX();import{stripVTControlCharacters as set}from"node:util";var wq=e=>{if(!e)return 0;let t=e.split(`
|
|
288
|
+
`,"utf8"),rt(`Wrote presubmit report to ${r}`)}var Ope={command:"presubmit <pr_number> <commit_sha> <owner_repo> <out_path>",describe:"Pre-submission checks for /review Step 9 (self-PR detection, CI status, existing-comments classification)",builder:e=>e.positional("pr_number",{type:"string",demandOption:!0,describe:"PR number"}).positional("commit_sha",{type:"string",demandOption:!0,describe:"PR HEAD commit SHA"}).positional("owner_repo",{type:"string",demandOption:!0,describe:'GitHub "owner/repo"'}).positional("out_path",{type:"string",demandOption:!0,describe:"Output JSON path (will be overwritten)"}).option("new-findings",{type:"string",describe:"Path to a JSON file shaped as [{path, line}, ...] \u2014 when provided, existing comments are checked for same-(path, line) overlap with the new findings."}),handler:async e=>{await VZe(e)}};p();import{execFileSync as Ppe}from"node:child_process";import{existsSync as Upe,readdirSync as KZe,unlinkSync as zZe}from"node:fs";import{join as XZe}from"node:path";function ZZe(e){let t=!1,n=/^pr-(\d+)$/.exec(e);if(n){let s=n[1],i=aR(s);if(Upe(i))try{Ppe("git",["worktree","remove",i,"--force"],{stdio:"pipe"}),rt(`Removed worktree: ${i}`),t=!0}catch(l){We(`Failed to remove worktree ${i}: ${l.message}`)}let a=lR(s);if(q2(a))try{Ppe("git",["branch","-D",a],{stdio:"pipe"}),rt(`Deleted ref: ${a}`),t=!0}catch(l){We(`Failed to delete branch ${a}: ${l.message}`)}}let o=bpe(e),r=[];try{r=Upe(iC)?KZe(iC):[]}catch(s){We(`Failed to read ${iC}: ${s.message}`)}for(let s of r){if(!s.startsWith(o))continue;let i=XZe(iC,s);try{zZe(i),rt(`Removed temp file: ${i}`),t=!0}catch(a){We(`Failed to remove ${i}: ${a.message}`)}}t||rt(`Nothing to clean for target "${e}".`)}var Hpe={command:"cleanup <target>",describe:"Post-review cleanup: remove worktree, branch ref, and per-target temp files",builder:e=>e.positional("target",{type:"string",demandOption:!0,describe:'Review target \u2014 "pr-<n>" for a PR review, "local" for an uncommitted review, or a filename for a file review'}),handler:e=>{ZZe(e.target)}};var Gpe={command:"review",describe:"Internal helpers used by the /review skill (PR worktree setup, context fetch, rules loading, deterministic analysis, presubmit checks, cleanup)",builder:e=>e.command(Qpe).command(Rpe).command(kpe).command(_pe).command(Ope).command(Hpe).demandCommand(1,"Specify a subcommand: fetch-pr, pr-context, load-rules, deterministic, presubmit, or cleanup.").version(!1),handler:()=>{}};p();p();var Bq="Warning: running headless with --bogan / approval-mode=bogan and no sandbox. All tool calls (shell, write, edit) auto-execute at this process's privilege level. Enable a sandbox via --sandbox / MATILDA_SANDBOX, or set MATILDA_CODE_SUPPRESS_BOGAN_WARNING=1 to silence this notice.";function Wpe(e,t=process.env){return e.getApprovalMode()!=="bogan"||e.getSandbox()||t.SANDBOX||eet(t.MATILDA_CODE_SUPPRESS_BOGAN_WARNING)?null:Bq}function eet(e){return e==="1"||e==="true"}function net(){return new Promise(()=>{})}var jpe={command:"serve",describe:"Run Matilda as a local HTTP daemon (Stage 1 experimental: --http-bridge)",builder:e=>e.option("port",{type:"number",default:4170,description:"TCP port to bind (use 0 for an OS-assigned ephemeral port)"}).option("hostname",{type:"string",default:"127.0.0.1",description:"Interface to bind. Loopback (127.0.0.1, localhost, ::1, [::1]) is auth-free; anything else requires a token."}).option("token",{type:"string",description:"Bearer token required on every request. Falls back to the MATILDA_SERVER_TOKEN env var."}).option("max-sessions",{type:"number",default:20,description:"Cap on concurrent live sessions. New spawn requests beyond this return 503; attach to existing sessions still works. Set to 0 to disable."}).option("max-pending-prompts-per-session",{type:"number",default:5,description:"Per-session cap on accepted prompts waiting or running. New prompts beyond this return 503. Set to 0 to disable."}).option("workspace",{type:"string",description:"Absolute workspace path this daemon binds to. POST /session requests with a mismatched cwd return 400 workspace_mismatch. Defaults to process.cwd() when omitted. For multi-workspace deployments, run one `matilda serve` per workspace on separate ports (or behind an external orchestrator)."}).option("max-connections",{type:"number",default:256,description:"Listener-level TCP connection cap (server.maxConnections). Bounds raw sockets \u2014 slow/phantom SSE clients get rejected at accept time once full. Set to 0 to disable."}).option("require-auth",{type:"boolean",default:!1,description:"Refuse to start without a bearer token, even on loopback. Hardens the loopback developer default for shared dev hosts / CI runners / multi-tenant workstations where any local user can hit 127.0.0.1. Requires --token or MATILDA_SERVER_TOKEN. /health also requires Authorization when enabled (no loopback exemption \u2014 k8s/Compose probes must pass the bearer too)."}).option("enable-session-shell",{type:"boolean",default:!1,description:"Enable direct POST /session/:id/shell execution. Requires a bearer token and a session-bound client id on each call."}).option("event-ring-size",{type:"number",default:8e3,description:"Per-session SSE replay ring depth. Sets the replay backlog available to `GET /session/:id/events` reconnects that send a `Last-Event-ID: N` header. Larger = more reconnect headroom at the cost of a few hundred KB extra RAM per session. Must be a positive finite integer."}).option("http-bridge",{type:"boolean",default:!0,description:"Stage 1 mode: one `matilda --acp` child per daemon (the daemon binds to one workspace at boot, multiplexing N sessions onto that child via the agent's native `newSession()`). Stage 2 native in-process mode is not yet implemented; this flag will become opt-in then."}).option("mcp-client-budget",{type:"number",description:"Cap on live MCP clients spawned inside the ACP child for the bound workspace. Positive integer. Combine with --mcp-budget-mode to control behavior at the cap. When unset, mode defaults to off (no accounting-driven enforcement, but GET /workspace/mcp still reports `clientCount`). Distinct from claude-code MCP_SERVER_CONNECTION_BATCH_SIZE which gates startup concurrency, not the total client count."}).option("mcp-budget-mode",{choices:["enforce","warn","off"],description:'How --mcp-client-budget is enforced. `warn` (default when budget set): no refusal, snapshot surfaces warning at >=75% of budget. `enforce`: connects past the cap are refused (`disabledReason: "budget"`, deterministic by mcpServers declaration order). `off`: pure observability. Boot rejects `enforce` without a budget.'}).option("allow-origin",{type:"string",array:!0,description:"Cross-origin allowlist for browser webui clients."}).option("allow-private-auth-base-url",{type:"boolean",default:!1,description:"Allow /workspace/auth/provider to install localhost/private-network baseUrl values. Use only for local development with trusted clients."}).option("prompt-deadline-ms",{type:"number",description:"Server-side wallclock cap on POST /session/:id/prompt (ms). Falls back to MATILDA_SERVE_PROMPT_DEADLINE_MS. Positive integer."}).option("writer-idle-timeout-ms",{type:"number",description:"Per-SSE-connection idle deadline (ms). Falls back to MATILDA_SERVE_WRITER_IDLE_TIMEOUT_MS. Positive integer."}).option("channel-idle-timeout-ms",{type:"number",description:"Milliseconds to keep ACP child alive after last session closes. 0 or unset = immediate kill (default)."}).option("session-reap-interval-ms",{type:"number",description:"Session reaper scan interval (ms). 0 = disabled. Default: 60000."}).option("session-idle-timeout-ms",{type:"number",description:"Idle timeout before a disconnected session is reaped (ms). 0 = disabled. Default: 1800000 (30 min)."}).option("rate-limit",{type:"boolean",description:"Enable per-tier HTTP rate limiting. Tiers: prompt (10/min), mutation (30/min), read (120/min). Health, heartbeat, SSE, and /acp are exempt."}).option("rate-limit-prompt",{type:"number",description:"Max prompt requests per window per client (default 10). Requires --rate-limit."}).option("rate-limit-mutation",{type:"number",description:"Max mutation requests per window per client (default 30). Requires --rate-limit."}).option("rate-limit-read",{type:"number",description:"Max read requests per window per client (default 120). Requires --rate-limit."}).option("rate-limit-window-ms",{type:"number",description:"Rate limit window duration in ms (default 60000). Requires --rate-limit."}),handler:async e=>{e["http-bridge"]||We("matilda serve: --no-http-bridge (native mode) is not yet implemented; falling back to http-bridge."),e.token&&We("matilda serve: --token is visible in the process command line; prefer the MATILDA_SERVER_TOKEN env var for any non-trivial deployment.");let t=e["mcp-client-budget"],n=e["mcp-budget-mode"];t!==void 0&&(!Number.isFinite(t)||!Number.isInteger(t)||t<=0)&&(We("matilda serve: --mcp-client-budget must be a positive integer."),process.exit(1)),n==="enforce"&&t===void 0&&(We("matilda serve: --mcp-budget-mode=enforce requires --mcp-client-budget=N."),process.exit(1));let o=n??(t!==void 0?"warn":"off"),r=e["max-pending-prompts-per-session"];r!==Number.POSITIVE_INFINITY&&(!Number.isFinite(r)||!Number.isInteger(r)||r<0)&&(We("matilda serve: --max-pending-prompts-per-session must be a non-negative integer (0 / Infinity = unlimited)."),process.exit(1)),t!==void 0&&We(`matilda serve: --mcp-client-budget=${t} mode=${o}`+(o==="enforce"?" (servers past the cap will be refused at discovery)":o==="warn"?` (warnings at >=${Math.ceil(t*YT)}, no refusal)`:""));try{let h=on(e.workspace??process.cwd()).merged,m=h.tools?.approvalMode,y=h.tools?.sandbox,D=process.env.SANDBOX,S=process.env.MATILDA_CODE_SUPPRESS_BOGAN_WARNING,w=S==="1"||S==="true";m==="bogan"&&!y&&!D&&!w&&We(Bq)}catch{}let s=e["rate-limit"]??(process.env.MATILDA_SERVE_RATE_LIMIT==="1"||process.env.MATILDA_SERVE_RATE_LIMIT==="true"),i,a,l,c;if(s){let A=h=>{let m=process.env[h];return m?Number(m):void 0};i=e["rate-limit-prompt"]??A("MATILDA_SERVE_RATE_LIMIT_PROMPT"),a=e["rate-limit-mutation"]??A("MATILDA_SERVE_RATE_LIMIT_MUTATION"),l=e["rate-limit-read"]??A("MATILDA_SERVE_RATE_LIMIT_READ"),c=e["rate-limit-window-ms"]??A("MATILDA_SERVE_RATE_LIMIT_WINDOW_MS");for(let[h,m]of[["--rate-limit-prompt",i],["--rate-limit-mutation",a],["--rate-limit-read",l]])m!==void 0&&(!Number.isFinite(m)||!Number.isInteger(m)||m<=0)&&(We(`matilda serve: ${h} must be a positive integer.`),process.exit(1));c!==void 0&&(!Number.isFinite(c)||!Number.isInteger(c)||c<1e3)&&(We("matilda serve: --rate-limit-window-ms must be an integer >= 1000."),process.exit(1))}let{runMatildaServe:u}=await import("./chunks/serve-24HVCLFM.js");try{await u({port:e.port,hostname:e.hostname,token:e.token,mode:"http-bridge",maxSessions:e["max-sessions"],maxPendingPromptsPerSession:r,maxConnections:e["max-connections"],eventRingSize:e["event-ring-size"],workspace:e.workspace,requireAuth:e["require-auth"],enableSessionShell:e["enable-session-shell"],allowPrivateAuthBaseUrl:e["allow-private-auth-base-url"],mcpClientBudget:t,mcpBudgetMode:o,...e["allow-origin"]&&e["allow-origin"].length>0?{allowOrigins:e["allow-origin"]}:{},...e["prompt-deadline-ms"]!==void 0?{promptDeadlineMs:e["prompt-deadline-ms"]}:{},...e["writer-idle-timeout-ms"]!==void 0?{writerIdleTimeoutMs:e["writer-idle-timeout-ms"]}:{},...e["channel-idle-timeout-ms"]!==void 0?{channelIdleTimeoutMs:e["channel-idle-timeout-ms"]}:{},...e["session-reap-interval-ms"]!==void 0?{sessionReapIntervalMs:e["session-reap-interval-ms"]}:{},...e["session-idle-timeout-ms"]!==void 0?{sessionIdleTimeoutMs:e["session-idle-timeout-ms"]}:{},...s?{rateLimit:!0}:{},...i!==void 0?{rateLimitPrompt:i}:{},...a!==void 0?{rateLimitMutation:a}:{},...l!==void 0?{rateLimitRead:l}:{},...c!==void 0?{rateLimitWindowMs:c}:{}})}catch(A){We(`matilda serve: ${A instanceof Error?A.message:String(A)}`),process.exit(1)}await net()}};p();p();p();var Jpe=k(qpe(),1),oet=new Intl.Segmenter,ret=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function un(e,t={}){if(typeof e!="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:o=!1}=t;if(o||(e=Ar(e)),e.length===0)return 0;let r=0,s={ambiguousAsWide:!n};for(let{segment:i}of oet.segment(e)){let a=i.codePointAt(0);if(!(a<=31||a>=127&&a<=159)&&!(a>=8203&&a<=8207||a===65279)&&!(a>=768&&a<=879||a>=6832&&a<=6911||a>=7616&&a<=7679||a>=8400&&a<=8447||a>=65056&&a<=65071)&&!(a>=55296&&a<=57343)&&!(a>=65024&&a<=65039)&&!ret.test(i)){if((0,Jpe.default)().test(i)){r+=2;continue}r+=Vl(a,s)}}return r}p();vX();import{stripVTControlCharacters as set}from"node:util";var wq=e=>{if(!e)return 0;let t=e.split(`
|
|
289
289
|
`);return Math.max(...t.map(n=>ia(n)))},$pe=new Map,Vpe=1e3;function Uo(e){let t=!0;for(let o=0;o<e.length;o++)if(e.charCodeAt(o)>127){t=!1;break}if(t)return e.split("");if(e.length<=Vpe){let o=$pe.get(e);if(o)return o}let n=Array.from(e);return e.length<=Vpe&&$pe.set(e,n),n}function Et(e){return Uo(e).length}function Zt(e,t,n){return Uo(e).slice(t,n).join("")}function Vx(e){let t=Ar(e),n=set(t);return Uo(n).filter(o=>{let r=o.codePointAt(0);return r===void 0?!1:r===9||r===10||r===13?!0:!(r>=0&&r<=31||r>=128&&r<=159)}).join("")}var Sq=new Map,ia=e=>{if(/^[\x20-\x7E]*$/.test(e))return e.length;if(Sq.has(e))return Sq.get(e);let t=un(e);return Sq.set(e,t),t};var xq=QX();function Yr(e){if(typeof e=="string")return e.search(xq)===-1?e:(xq.lastIndex=0,e.replace(xq,o=>JSON.stringify(o).slice(1,-1)));if(e===null||typeof e!="object")return e;if(Array.isArray(e)){let o=null;for(let r=0;r<e.length;r++){let s=e[r],i=Yr(s);i!==s&&(o===null&&(o=[...e]),o[r]=i)}return o!==null?o:e}let t=null,n=Object.keys(e);for(let o of n){let r=e[o],s=Yr(r);s!==r&&(t===null&&(t={...e}),t[o]=s)}return t!==null?t:e}var iet=[{pattern:/(sk-[a-zA-Z0-9]{20,})/g,replacement:"sk-***REDACTED***"},{pattern:/(api[_-]?key[_-]?[=:]\s*)[a-zA-Z0-9_-]{20,}/gi,replacement:"$1***REDACTED***"},{pattern:/(Bearer\s+)[a-zA-Z0-9._-]+/gi,replacement:"$1***REDACTED***"},{pattern:/(token[_-]?[=:]\s*)[a-zA-Z0-9._-]{10,}/gi,replacement:"$1***REDACTED***"},{pattern:/(password[_-]?[=:]\s*)[^\s]+/gi,replacement:"$1***REDACTED***"},{pattern:/(pwd[_-]?[=:]\s*)[^\s]+/gi,replacement:"$1***REDACTED***"},{pattern:/(AKIA[A-Z0-9]{16})/g,replacement:"***REDACTED***"},{pattern:/(secret[_-]?[=:]\s*)[a-zA-Z0-9._-]{10,}/gi,replacement:"$1***REDACTED***"}];function Kpe(e,t=200){let n=e;for(let{pattern:o,replacement:r}of iet)n=n.replace(o,r);return n.length>t?t<=3?n.slice(0,t):n.slice(0,t-3)+"...":n}var aet=/[\x00-\x1f\x7f-\x9f]/g;function cet(e){switch(e){case"\b":return"\\b";case" ":return"\\t";case`
|
|
290
290
|
`:return"\\n";case"\f":return"\\f";case"\r":return"\\r";default:return`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`}}function Kx(e){return Yr(e).replace(aet,cet)}p();function zpe(){let e=on();return Mt.setRuntimeBaseDir(e.merged.advanced?.runtimeOutputDir,process.cwd()),new Li(process.cwd())}var K2=38,z2=16,X2=24,Z2=12;function uet(e){let t=new Date(e);if(isNaN(t.getTime()))return e;let n=o=>String(o).padStart(2,"0");return`${t.getUTCFullYear()}-${n(t.getUTCMonth()+1)}-${n(t.getUTCDate())} ${n(t.getUTCHours())}:${n(t.getUTCMinutes())}`}function dR(e){let t=e.replace(/[\r\n\t]/g,"");return Yr(t).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"")}function lC(e,t){let n=un(e);return n>=t?e:e+" ".repeat(t-n)}function AR(e,t){if(un(e)<=t)return e;let o=t>3?"...":"",r=t-un(o),s="",i=0;for(let a of e){if(i+=un(a),i>r)break;s+=a}return s+o}function det(e){if(e.length===0){rt("No sessions found.");return}let t=process.stdout.columns??80,n=Math.max(20,t-K2-z2-X2-Z2-4),o=lC("SESSION ID",K2)+" "+lC("STARTED",z2)+" "+lC("TITLE",X2)+" "+lC("BRANCH",Z2)+" PROMPT";rt(o);for(let r of e){let s=AR(dR(String(r.sessionId??"")),K2),i=AR(dR(uet(r.startTime)),z2),a=dR(r.prompt??""),l=AR(r.customTitle!=null?dR(r.customTitle):a,X2),c=AR(r.gitBranch!=null?dR(r.gitBranch):"-",Z2),u=AR(a,n);rt(`${lC(s,K2)} ${lC(i,z2)} ${lC(l,X2)} ${lC(c,Z2)} ${u}`)}}function Aet(e){return{sessionId:e.sessionId,startTime:e.startTime,mtime:e.mtime,prompt:e.prompt,gitBranch:e.gitBranch??null,customTitle:e.customTitle??null,titleSource:e.titleSource??null,filePath:e.filePath,cwd:e.cwd}}function Xpe(e){return e instanceof Error?e.message:String(e)}async function get(e){let t;try{t=zpe()}catch(o){We(`Error: failed to initialize session service: ${Xpe(o)}`),process.exit(1);return}let n;try{n=await t.listSessions({size:e.limit??20})}catch(o){We(`Error: failed to list sessions: ${Xpe(o)}`),process.exit(1);return}if(e.json){for(let o of n.items)rt(JSON.stringify(Aet(o)));n.items.length>0&&n.hasMore&&We(`Note: ${n.items.length} sessions shown, more available. Use --limit to show more.`)}else det(n.items),n.items.length>0&&n.hasMore&&rt(`Showing ${n.items.length} sessions. Use --limit to show more.`)}var Zpe={command:"list",describe:"List sessions",builder:e=>e.option("json",{type:"boolean",describe:"Output as JSON Lines",default:!1}).option("limit",{type:"number",describe:"Maximum number of sessions to show",default:20,coerce:t=>Number.isInteger(t)&&t>0?t:20}),handler:async e=>{await get(e)}};var ehe={command:"sessions",describe:"Manage Matilda sessions",builder:e=>e.command(Zpe).demandCommand(1,"You need at least one command before continuing.").version(!1),handler:()=>{}};p();import{spawnSync as Lst}from"node:child_process";p();import*as gR from"node:fs";import*as cC from"node:path";import{execFileSync as met,spawnSync as fet}from"node:child_process";import pet from"node:readline/promises";import{stdin as het,stdout as Cet}from"node:process";function Xx(e,t,n=5e3){return met("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:n}).trim()}function the(e){let t=gR.statSync(e).isDirectory()?e:cC.dirname(e);for(;;){if(gR.existsSync(cC.join(t,".git"))&&gR.existsSync(cC.join(t,"package.json")))return t;let n=cC.dirname(t);if(n===t)return null;t=n}}function eO(){let e=process.argv[1];if(e)try{let t=the(cC.resolve(e));if(t)return t}catch{}try{return the(process.cwd())}catch{return null}}function bq(e=eO()){if(!e||process.env.DEV==="true")return null;let t=Xx(e,["rev-parse","--abbrev-ref","HEAD"]);if(!t||t==="HEAD")return null;Xx(e,["fetch","--quiet","origin",t],3e3);let n=Xx(e,["rev-parse","HEAD"]),o=Xx(e,["rev-parse",`origin/${t}`]);return!n||!o||n===o?null:{root:e,branch:t,local:n,remote:o}}function zx(e,t,n){if(fet(t,n,{cwd:e,stdio:"inherit",shell:process.platform==="win32"}).status!==0)throw new Error(`${t} ${n.join(" ")} failed.`)}function Eet(e){return/(^|\/)NOTICES\.txt$/.test(e)||/(^|\/)settings\.schema\.json$/.test(e)}function yet(e){return e.split(`
|
|
291
291
|
`).map(t=>t.slice(2).trim()).filter(Boolean).filter(t=>!Eet(t))}function Tq(e=eO()){if(!e)throw new Error("Could not find a Matilda Code source checkout to update.");let t=Xx(e,["rev-parse","--abbrev-ref","HEAD"]);if(!t||t==="HEAD")throw new Error("Matilda Code is not on a branch; cannot self-update safely.");let n=Xx(e,["status","--porcelain"]),o=yet(n);if(o.length>0)throw new Error(`Matilda Code checkout has local changes; refusing to self-update:
|
|
@@ -426,7 +426,7 @@ ${a.join(`
|
|
|
426
426
|
`)}${l}`:i}function lct(e){if(e.length===0)return[];let{addWidth:t,remWidth:n,statColumnWidth:o}=TJ(e),r=[];for(let s of e){let i=Kx(s.filename);if(s.isBinary){let u=s.isUntracked?` ${f("(binary, new)")}`:s.isDeleted?` ${f("(binary, deleted)")}`:` ${f("(binary)")}`;r.push(` ${cct("~",o)} ${i}${u}`);continue}let a=`+${String(s.added??0).padStart(t)}`,l=`-${String(s.removed??0).padStart(n)}`,c="";s.isUntracked?c=s.truncated?` ${f("(new, partial)")}`:` ${f("(new)")}`:s.isDeleted&&(c=` ${f("(deleted)")}`),r.push(` ${a} ${l} ${i}${c}`)}return r}function cct(e,t){return e.length>=t?e:`${e}${" ".repeat(t-e.length)}`}var YSe={name:"diff",get description(){return f("Show working-tree change stats versus HEAD")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:rct};p();var qSe={name:"editor",get description(){return f("set external editor preference")},kind:"built-in",supportedModes:["interactive"],action:()=>({type:"dialog",dialog:"editor"})};p();import*as rg from"node:fs/promises";import XR from"node:path";p();p();import{randomUUID as Act}from"node:crypto";p();p();p();var Mc=class{constructor(t){this.ctx=t}static toEpochMs(t){if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(typeof t=="string"){let n=new Date(t).getTime();return Number.isFinite(n)?n:void 0}}async sendUpdate(t){return this.ctx.messageRewriter?this.ctx.messageRewriter.interceptUpdate(t):this.ctx.sendUpdate(t)}get config(){return this.ctx.config}get sessionId(){return this.ctx.sessionId}};var IC=class extends Mc{async emitStopHookLoop(t,n,o){let r=Fa(this.sessionId);await this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:""},_meta:{stopHookLoop:{iterationCount:t,reasons:n,stopHookCount:o,...r?{goal:{condition:r.condition,iterations:r.iterations,setAt:r.setAt,lastReason:r.lastReason}}:{}}}})}async emitGoalTerminal(t){await this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:""},_meta:{goalTerminal:t}})}async emitGoalStatus(t){await this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:""},_meta:{goalStatus:t}})}async emitUserMessage(t,n){let o=Mc.toEpochMs(n);await this.sendUpdate({sessionUpdate:"user_message_chunk",content:{type:"text",text:t},...o!=null&&{_meta:{timestamp:o}}})}async emitAgentThought(t,n,o){let r=this.buildChunkMeta(Mc.toEpochMs(n),o);await this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:t},...r?{_meta:r}:{}})}async emitAgentMessage(t,n,o,r){let s=this.buildChunkMeta(Mc.toEpochMs(n),o);await this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:t},...s||r?{_meta:{...r,...s}}:{}})}async emitUsageMetadata(t,n="",o,r){let s={inputTokens:t.promptTokenCount??0,outputTokens:t.candidatesTokenCount??0,totalTokens:t.totalTokenCount??0,thoughtTokens:t.thoughtsTokenCount,cachedReadTokens:t.cachedContentTokenCount},i=this.ctx.cumulativeUsage;if(i){let l=(c,u)=>typeof u=="number"&&Number.isFinite(u)?c+u:c;i.promptTokens=l(i.promptTokens,s.inputTokens),i.candidateTokens=l(i.candidateTokens,s.outputTokens),i.cachedTokens=l(i.cachedTokens,s.cachedReadTokens),i.apiTimeMs=l(i.apiTimeMs,o)}let a=typeof o=="number"?{usage:s,durationMs:o,...r}:{usage:s,...r};await this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:n},_meta:a})}async emitMessage(t,n,o=!1,r,s){return n==="user"?this.emitUserMessage(t,r):o?this.emitAgentThought(t,r,s):this.emitAgentMessage(t,r,s)}buildChunkMeta(t,n){let o={...n?.parentToolCallId?{parentToolCallId:n.parentToolCallId}:{},...n?.subagentType?{subagentType:n.subagentType}:{},...t!=null?{timestamp:t}:{}};return Object.keys(o).length>0?o:void 0}};p();p();var ww=class extends Mc{async emitPlan(t){let n=t.map(r=>({content:r.content,priority:"medium",status:r.status})),o=this.ctx.cumulativeUsage;await this.sendUpdate({sessionUpdate:"plan",entries:n,...o?{_meta:{stats:{...o}}}:{}})}extractTodos(t,n){let o=this.extractFromResultDisplay(t);return o||(n&&Array.isArray(n.todos)?n.todos:null)}extractFromResultDisplay(t){if(!t)return null;if(typeof t=="object"){let n=t;if(n.type==="todo_list"&&Array.isArray(n.todos))return n.todos}if(typeof t=="string")try{let n=JSON.parse(t);if(n?.type==="todo_list"&&Array.isArray(n.todos))return n.todos}catch{}return null}};p();function EP(e){let t=typeof e.fileName=="string"?e.fileName:"the edited file",n=typeof e.fileDiffLength=="number"?` Original fileDiff length: ${e.fileDiffLength} chars.`:"";return e.fileDiffTruncated===!0?`Full diff omitted from saved session history for ${t}.${n}`:`Saved session preview only for ${t}; full original and new file contents are unavailable.`}var dct={read:"read",edit:"edit",delete:"delete",move:"move",search:"search",execute:"execute",think:"think",fetch:"fetch",agent:"other",other:"other"},DC=class e extends Mc{planEmitter;constructor(t){super(t),this.planEmitter=new ww(t)}async emitStart(t){if(this.isTodoWriteTool(t.toolName))return!1;let{title:n,locations:o,kind:r}=this.resolveToolMetadata(t.toolName,t.args),s=e.resolveToolProvenance(t.toolName,t.subagentMeta);return await this.sendUpdate({sessionUpdate:"tool_call",toolCallId:t.callId,status:t.status||"pending",title:n,content:[],locations:o,kind:r,rawInput:t.args??{},_meta:{toolName:t.toolName,...t.subagentMeta,provenance:s.provenance,...s.serverId?{serverId:s.serverId}:{},...Mc.toEpochMs(t.timestamp)!=null&&{timestamp:Mc.toEpochMs(t.timestamp)}}}),!0}async emitResult(t){if(this.isTodoWriteTool(t.toolName)){let i=this.planEmitter.extractTodos(t.resultDisplay,t.args);i&&i.length>0?await this.planEmitter.emitPlan(i):t.args&&Array.isArray(t.args.todos)&&await this.planEmitter.emitPlan([]);return}let n=[],o=this.extractDiffContent(t.resultDisplay);o?n=[o]:t.error?n=[{type:"content",content:{type:"text",text:t.error.message}}]:n=this.transformPartsToToolCallContent(t.message);let r=e.resolveToolProvenance(t.toolName,t.subagentMeta),s={sessionUpdate:"tool_call_update",toolCallId:t.callId,status:t.success?"completed":"failed",content:n,_meta:{toolName:t.toolName,...t.errorType?{errorType:t.errorType}:{},...t.subagentMeta,provenance:r.provenance,...r.serverId?{serverId:r.serverId}:{},...Mc.toEpochMs(t.timestamp)!=null&&{timestamp:Mc.toEpochMs(t.timestamp)}}};t.resultDisplay!==void 0&&!this.isTruncatedSessionDiffDisplay(t.resultDisplay)&&(s.rawOutput=t.resultDisplay),await this.sendUpdate(s)}async emitError(t,n,o,r){let s=e.resolveToolProvenance(n,r);await this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:t,status:"failed",content:[{type:"content",content:{type:"text",text:o.message}}],_meta:{toolName:n,...r,provenance:s.provenance,...s.serverId?{serverId:s.serverId}:{}}})}static resolveToolProvenance(t,n){if(n!==void 0)return{provenance:"subagent"};if(t.startsWith("mcp__")){let o=t.split("__");if(o.length>=3&&o[1]&&o[1].length>0)return{provenance:"mcp",serverId:o[1]}}return{provenance:"builtin"}}isTodoWriteTool(t){return t===nn.TODO_WRITE}isExitPlanModeTool(t){return t===nn.EXIT_PLAN_MODE}isEnterPlanModeTool(t){return t===nn.ENTER_PLAN_MODE}resolveToolMetadata(t,n){let r=this.config.getToolRegistry().getTool(t),s=r?.displayName??t,i=[],a="other";if(r&&n)try{let l=r.build(n);s=`${s}: ${l.getDescription()}`,i=l.toolLocations().map(c=>({path:c.path,line:c.line??null})),a=this.mapToolKind(r.kind,t)}catch{typeof n.description=="string"&&(s=`${s}: ${n.description}`),r.kind&&(a=this.mapToolKind(r.kind,t))}return{title:s,locations:i,kind:a}}mapToolKind(t,n){return n&&(this.isExitPlanModeTool(n)||this.isEnterPlanModeTool(n))?"switch_mode":dct[t]??"other"}extractDiffContent(t){if(!t||typeof t!="object")return null;let n=t;return"fileName"in n&&"newContent"in n?this.isTruncatedSessionDiffDisplay(t)?{type:"content",content:{type:"text",text:EP(n)}}:{type:"diff",path:n.fileName,oldText:n.originalContent??"",newText:n.newContent}:null}isTruncatedSessionDiffDisplay(t){if(!t||typeof t!="object")return!1;let n=t;return n.truncatedForSession===!0&&"fileName"in n&&"newContent"in n}transformPartsToToolCallContent(t){let n=[];for(let o of t)if("text"in o&&o.text&&n.push({type:"content",content:{type:"text",text:o.text}}),"functionResponse"in o&&o.functionResponse)try{let r=o.functionResponse.response,s=r.output,i=r.error,a=typeof s=="string"?s:typeof i=="string"?i:JSON.stringify(r);n.push({type:"content",content:{type:"text",text:a}})}catch{}return n}};var BC=class{constructor(t,n=!1,o){this.taskOutcomes=n;this.activeTaskStartUuid=o;this.ctx=t,this.messageEmitter=new IC(t),this.toolCallEmitter=new DC(t)}ctx;messageEmitter;toolCallEmitter;async replay(t){let n=new Map,o=new Map,r=new Set;if(this.taskOutcomes){let s,i,a,l=()=>{s&&s!==this.activeTaskStartUuid&&a&&r.add(a.uuid)};for(let c of t)if(c.startsTask||c.subtype==="task_start"?(l(),s=c.uuid,i=void 0):c.type==="user"&&c.subtype!=="hook_prompt"&&c.subtype!=="mid_turn_user_message"&&!(c.subtype==="notification"&&c.systemPayload?.completion==="joined")&&(l(),s=void 0,i=void 0),!!s){if(a=c,c.type==="assistant")n.set(c.uuid,"commentary"),i=c;else if(c.type==="user"||c.type==="tool_result")i=void 0;else if(c.subtype==="task_outcome"){let u=c.systemPayload;if(u?.taskStartUuid!==s)continue;o.set(c.uuid,!1),u.outcome==="completed"&&i?.message?.parts?.some(A=>A.text?.trim()&&!A.thought)&&!i.message.parts.some(A=>A.functionCall)&&(n.set(i.uuid,"final_answer"),o.set(c.uuid,!0)),s=void 0,i=void 0}}l()}for(let s of t)if(await this.replayRecord(s,n.get(s.uuid)),o.has(s.uuid)){let i=s.systemPayload;await this.messageEmitter.emitAgentMessage("",s.timestamp,void 0,{matildaTask:{version:1,outcome:i.outcome,...i.outcome==="completed"?{hasFinalAnswer:o.get(s.uuid)}:{}}})}else r.has(s.uuid)&&await this.messageEmitter.emitAgentMessage("",s.timestamp,void 0,{matildaTask:{version:1,state:"unfinished"}})}async replayRecord(t,n){switch(this.setActiveRecordId(t.uuid,t.timestamp),t.type){case"user":if(t.subtype==="hook_prompt")break;if(t.subtype==="notification"||t.subtype==="cron"){let o=t.systemPayload,r=o?.displayText;r&&(t.subtype==="notification"&&o?.completion==="joined"?await this.messageEmitter.emitAgentMessage(r,t.timestamp,void 0,{source:"background_notification_joined",matildaDiscreteMessage:!0}):await this.messageEmitter.emitUserMessage(r,t.timestamp));break}if(t.subtype==="mid_turn_user_message"){let o=t.systemPayload?.displayText;o?await this.messageEmitter.emitUserMessage(o,t.timestamp):t.message&&await this.replayContent(t.message,"user",t.timestamp);break}t.message&&await this.replayContent(t.message,"user",t.timestamp);break;case"assistant":t.message&&await this.replayContent(t.message,"assistant",t.timestamp,n),t.usageMetadata&&await this.replayUsageMetadata(t.usageMetadata);break;case"tool_result":await this.replayToolResult(t);break;case"system":t.subtype==="slash_command"&&await this.replaySlashCommandResult(t);break;default:break}this.setActiveRecordId(null)}async replayContent(t,n,o,r){for(let s of t.parts??[]){if("text"in s&&s.text){let i=s.thought??!1;n==="assistant"&&!i&&r?await this.messageEmitter.emitAgentMessage(s.text,o,void 0,{matildaTask:{version:1,phase:r}}):await this.messageEmitter.emitMessage(s.text,n,i,o)}if("functionCall"in s&&s.functionCall){let i=s.functionCall.name??"",a=s.functionCall.id??`${i}-${Date.now()}`;await this.toolCallEmitter.emitStart({toolName:i,callId:a,args:s.functionCall.args,status:"in_progress",timestamp:o})}}}async replayUsageMetadata(t){await this.messageEmitter.emitUsageMetadata(t)}async replayToolResult(t){if(!t.message?.parts)return;let n=t.toolCallResult,o=n?.callId??t.uuid,r=this.extractToolNameFromRecord(t);await this.toolCallEmitter.emitResult({toolName:r,callId:o,success:!n?.error,message:t.message.parts,resultDisplay:n?.resultDisplay,args:void 0,timestamp:t.timestamp});let{resultDisplay:s}=n??{};s&&typeof s=="object"&&"type"in s&&s.type==="task_execution"&&await this.emitTaskUsageFromResultDisplay(s)}async emitTaskUsageFromResultDisplay(t){let n=t.executionSummary;if(!n)return;let o={};Number.isFinite(n.inputTokens)&&(o.promptTokenCount=n.inputTokens),Number.isFinite(n.outputTokens)&&(o.candidatesTokenCount=n.outputTokens),Number.isFinite(n.thoughtTokens)&&(o.thoughtsTokenCount=n.thoughtTokens),Number.isFinite(n.cachedTokens)&&(o.cachedContentTokenCount=n.cachedTokens),Number.isFinite(n.totalTokens)&&(o.totalTokenCount=n.totalTokens),Object.keys(o).length>0&&await this.messageEmitter.emitUsageMetadata(o)}async replaySlashCommandResult(t){let n=t.systemPayload;if(!(n?.phase!=="result"||!n.outputHistoryItems?.length))for(let o of n.outputHistoryItems){let r=typeof o.text=="string"?o.text:"";r&&await this.messageEmitter.emitAgentMessage(r.replace(/\n/g,`
|
|
427
427
|
`),t.timestamp)}}extractToolNameFromRecord(t){if(t.message?.parts){for(let n of t.message.parts)if("functionResponse"in n&&n.functionResponse?.name)return n.functionResponse.name}return""}setActiveRecordId(t,n){let o=this.ctx;typeof o.setActiveRecordId=="function"&&o.setActiveRecordId(t,n)}};function gct(e){if(e.message?.parts){for(let t of e.message.parts)if("functionResponse"in t&&t.functionResponse?.name)return t.functionResponse.name}}function mct(e){if(e.message?.parts){for(let t of e.message.parts)if("functionResponse"in t&&t.functionResponse?.id)return t.functionResponse.id}}function fct(e){if(e&&typeof e=="object")return e;if(typeof e=="string")try{let t=JSON.parse(e);if(t&&typeof t=="object")return t}catch{}}function pct(e){let t=new Map,n=new Map;for(let o of e)if(!(o.type!=="assistant"||!o.message?.parts))for(let r of o.message.parts){if(!("functionCall"in r)||!r.functionCall?.name)continue;let s=fct(r.functionCall.args);if(!s)continue;let i=r.functionCall.name,a=typeof r.functionCall.id=="string"?r.functionCall.id:null;a&&t.set(a,s);let l=n.get(i)??[];l.push(s),n.set(i,l)}return{byId:t,byName:n}}function hct(e){let t=pct(e),n=new Map,o={filesWritten:0,linesAdded:0,linesRemoved:0,writtenFilePaths:new Set};for(let r of e){if(r.type!=="tool_result"||!r.toolCallResult)continue;let s=gct(r),i=r.toolCallResult.callId??mct(r),l=i&&t.byId.has(i)?t.byId.get(i):void 0;if(!l&&s){let u=t.byName.get(s);if(u&&u.length>0){let A=n.get(s)??0;l=u[A],n.set(s,A+1)}}let{resultDisplay:c}=r.toolCallResult;if(c&&typeof c=="object"&&"fileName"in c){let u=c,A="originalContent"in u,h="newContent"in u,m;if(typeof u.fileName=="string"?m=l?.file_path||u.fileName:m="unknown",A||h){if(o.filesWritten++,o.writtenFilePaths.add(m),u.diffStat)o.linesAdded+=u.diffStat.model_added_lines??0,o.linesRemoved+=u.diffStat.model_removed_lines??0;else if(!u.truncatedForSession){let y=String(u.originalContent??""),D=String(u.newContent??""),S=y.split(`
|
|
428
428
|
`).filter(x=>x.length>0).length,w=D.split(`
|
|
429
|
-
`).filter(x=>x.length>0).length;o.linesAdded+=w,o.linesRemoved+=S}}}}return o}function Cct(e){if(e.type!=="tool_result"||!e.toolCallResult?.resultDisplay)return 0;let{resultDisplay:t}=e.toolCallResult;if(typeof t=="object"&&"type"in t&&t.type==="task_execution"&&"executionSummary"in t){let n=t.executionSummary;return typeof n.totalTokens=="number"?n.totalTokens:(n.inputTokens??0)+(n.outputTokens??0)+(n.thoughtTokens??0)+(n.cachedTokens??0)}return 0}function Ect(e){let t=0,n=null;for(let r of e){r.type==="assistant"&&(r.usageMetadata&&(t+=r.usageMetadata.totalTokenCount??0),r.usageMetadata?.totalTokenCount!==void 0&&r.contextWindowSize!==void 0&&(n={totalTokenCount:r.usageMetadata.totalTokenCount,contextWindowSize:r.contextWindowSize}));let s=Cct(r);s>0&&(t+=s)}if(n){let r=n.totalTokenCount/n.contextWindowSize*100;return{totalTokens:t,contextUsagePercent:Math.round(r*10)/10,contextWindowSize:n.contextWindowSize}}let o=[...e].reverse().find(r=>r.type==="assistant"&&r.contextWindowSize!==void 0);return{totalTokens:t,contextWindowSize:o?.contextWindowSize}}async function yct(e,t){let{sessionId:n,startTime:o,messages:r}=e,s=r[0],i=s?.cwd??"",a=s?.gitBranch,l;if(i){let{getGitRepoName:y}=await import("./chunks/src-
|
|
429
|
+
`).filter(x=>x.length>0).length;o.linesAdded+=w,o.linesRemoved+=S}}}}return o}function Cct(e){if(e.type!=="tool_result"||!e.toolCallResult?.resultDisplay)return 0;let{resultDisplay:t}=e.toolCallResult;if(typeof t=="object"&&"type"in t&&t.type==="task_execution"&&"executionSummary"in t){let n=t.executionSummary;return typeof n.totalTokens=="number"?n.totalTokens:(n.inputTokens??0)+(n.outputTokens??0)+(n.thoughtTokens??0)+(n.cachedTokens??0)}return 0}function Ect(e){let t=0,n=null;for(let r of e){r.type==="assistant"&&(r.usageMetadata&&(t+=r.usageMetadata.totalTokenCount??0),r.usageMetadata?.totalTokenCount!==void 0&&r.contextWindowSize!==void 0&&(n={totalTokenCount:r.usageMetadata.totalTokenCount,contextWindowSize:r.contextWindowSize}));let s=Cct(r);s>0&&(t+=s)}if(n){let r=n.totalTokenCount/n.contextWindowSize*100;return{totalTokens:t,contextUsagePercent:Math.round(r*10)/10,contextWindowSize:n.contextWindowSize}}let o=[...e].reverse().find(r=>r.type==="assistant"&&r.contextWindowSize!==void 0);return{totalTokens:t,contextWindowSize:o?.contextWindowSize}}async function yct(e,t){let{sessionId:n,startTime:o,messages:r}=e,s=r[0],i=s?.cwd??"",a=s?.gitBranch,l;if(i){let{getGitRepoName:y}=await import("./chunks/src-W5VAKS5Y.js");l=y(i)}let c;for(let y of r)if(y.type==="assistant"&&y.model){c=y.model;break}let u=t.getChannel?.(),A=r.filter(qg).length,h=hct(r),m=Ect(r);return{sessionId:n,startTime:o,exportTime:new Date().toISOString(),cwd:i,gitRepo:l,gitBranch:a,model:c,channel:u,promptCount:A,contextUsagePercent:m.contextUsagePercent,contextWindowSize:m.contextWindowSize,totalTokens:m.totalTokens,filesWritten:h.writtenFilePaths.size,linesAdded:h.linesAdded,linesRemoved:h.linesRemoved,uniqueFiles:Array.from(h.writtenFilePaths)}}var QJ=class{sessionId;config;messages=[];currentMessage=null;activeRecordId=null;activeRecordTimestamp=null;toolCallMap=new Map;constructor(t,n){this.sessionId=t,this.config=n}async sendUpdate(t){switch(t.sessionUpdate){case"user_message_chunk":this.handleMessageChunk("user",t.content);break;case"agent_message_chunk":{let n=t._meta,o=n?.usage?{promptTokenCount:n.usage.inputTokens,candidatesTokenCount:n.usage.outputTokens,totalTokenCount:n.usage.totalTokens,thoughtsTokenCount:n.usage.thoughtTokens,cachedContentTokenCount:n.usage.cachedReadTokens}:void 0;this.handleMessageChunk("assistant",t.content,"assistant",o);break}case"agent_thought_chunk":this.handleMessageChunk("assistant",t.content,"thinking");break;case"tool_call":this.flushCurrentMessage(),this.handleToolCallStart(t);break;case"tool_call_update":this.handleToolCallUpdate(t);break;case"plan":this.flushCurrentMessage(),this.handlePlanUpdate(t);break;default:break}}setActiveRecordId(t,n){this.activeRecordId=t,this.activeRecordTimestamp=n??null}getMessageTimestamp(){return this.activeRecordTimestamp??new Date().toISOString()}getMessageUuid(){return this.activeRecordId??Act()}handleMessageChunk(t,n,o=t,r){n.type!=="text"||!n.text||(this.currentMessage&&(this.currentMessage.type!==t||this.currentMessage.role!==o)&&this.flushCurrentMessage(),this.currentMessage&&this.currentMessage.type===t&&this.currentMessage.role===o?(this.currentMessage.parts.push({text:n.text}),r&&t==="assistant"&&(this.currentMessage.usageMetadata=r)):this.currentMessage={type:t,role:o,parts:[{text:n.text}],timestamp:Date.now(),...r&&t==="assistant"?{usageMetadata:r}:{}})}handleToolCallStart(t){let n={toolCallId:t.toolCallId,kind:t.kind||"other",title:typeof t.title=="string"?t.title:t.title||"",status:t.status||"pending",rawInput:t.rawInput,locations:t.locations,timestamp:Date.now()};this.toolCallMap.set(t.toolCallId,n);let o=this.getMessageUuid();this.messages.push({uuid:o,sessionId:this.sessionId,timestamp:this.getMessageTimestamp(),type:"tool_call",toolCall:n})}handleToolCallUpdate(t){let n=this.toolCallMap.get(t.toolCallId);n&&(t.status&&(n.status=t.status),t.content&&(n.content=t.content),t.title&&(n.title=typeof t.title=="string"?t.title:""))}handlePlanUpdate(t){let n=this.getMessageUuid(),o=this.getMessageTimestamp(),s=[{type:"content",content:{type:"text",text:t.entries.map(i=>`- ${i.status==="completed"?"[x]":i.status==="in_progress"?"[-]":"[ ]"} ${i.content}`).join(`
|
|
430
430
|
`)}}];this.messages.push({uuid:n,sessionId:this.sessionId,timestamp:o,type:"tool_call",toolCall:{toolCallId:n,kind:"todowrite",title:"TodoWrite",status:"completed",content:s,timestamp:Date.parse(o)}})}flushCurrentMessage(){if(!this.currentMessage)return;let n={uuid:this.getMessageUuid(),sessionId:this.sessionId,timestamp:this.getMessageTimestamp(),type:this.currentMessage.type,message:{role:this.currentMessage.role,parts:this.currentMessage.parts}};this.currentMessage.type==="assistant"&&this.currentMessage.usageMetadata&&(n.usageMetadata=this.currentMessage.usageMetadata),this.messages.push(n),this.currentMessage=null}flushMessages(){this.flushCurrentMessage()}getMessages(){return this.messages}};async function vJ(e,t){let n=new QJ(e.sessionId,t);await new BC(n).replay(e.messages),n.flushMessages();let r=n.getMessages(),s=await yct(e,t);return{sessionId:e.sessionId,startTime:e.startTime,messages:r,metadata:s}}p();function RJ(e,t,n){let o=[...e.messages],r=new Map;o.forEach((i,a)=>{i.type==="tool_call"&&i.toolCall?.toolCallId&&r.set(i.toolCall.toolCallId,a)});let s=new Map;o.forEach((i,a)=>{i.type==="assistant"&&s.set(i.uuid,a)});for(let i of t){if(i.type!=="tool_result")continue;let a=Dct(i,n);if(!a?.toolCall)continue;let l=r.get(a.toolCall.toolCallId);if(l===void 0){r.set(a.toolCall.toolCallId,o.length),o.push(a);continue}let c=o[l];c.type!=="tool_call"||!c.toolCall||Ict(c.toolCall,a.toolCall)}for(let i of t){if(i.type!=="assistant"||!i.usageMetadata)continue;let a=s.get(i.uuid);a!==void 0&&(o[a].usageMetadata||(o[a].usageMetadata=i.usageMetadata))}return{...e,messages:o}}function Ict(e,t){(!e.content||e.content.length===0)&&(e.content=t.content),(e.status==="pending"||e.status==="in_progress")&&(e.status=t.status),!e.rawInput&&t.rawInput&&(e.rawInput=t.rawInput),(!e.kind||e.kind==="other")&&(e.kind=t.kind),(!e.title||e.title==="")&&t.title&&(e.title=t.title),(!e.locations||e.locations.length===0)&&t.locations&&t.locations.length>0&&(e.locations=t.locations)}function Dct(e,t){let n=e.toolCallResult,o=Bct(e);if(o===nn.TODO_WRITE)return null;let r=n?.callId??e.uuid,s=Sct(e),{kind:i,title:a,locations:l}=xct(t,o,s??n?.args),c=Tct(s??n?.args),u=bct(n?.resultDisplay)??Qct(e.message?.parts??[]);return{uuid:e.uuid,parentUuid:e.parentUuid,sessionId:e.sessionId,timestamp:e.timestamp,type:"tool_call",toolCall:{toolCallId:r,kind:i,title:a,status:n?.error?"failed":"completed",rawInput:c,content:u,locations:l,timestamp:Date.parse(e.timestamp)}}}function Bct(e){if(!e.message?.parts)return"";for(let t of e.message.parts)if("functionResponse"in t&&t.functionResponse?.name)return t.functionResponse.name;return""}function Sct(e){if(e.message?.parts){for(let t of e.message.parts)if("functionCall"in t&&t.functionCall?.args)return t.functionCall.args}}function xct(e,t,n){let o=e.getToolRegistry?.(),r=t?o?.getTool?.(t):void 0,s=r?.displayName??t??"tool_call",i,a=wct(r?.kind,t);if(r&&n)try{let l=r.build(n);s=`${s}: ${l.getDescription()}`,i=l.toolLocations().map(c=>({path:c.path,line:c.line??null}))}catch{}return{kind:a,title:s,locations:i}}function wct(e,t){return t&&(t===nn.EXIT_PLAN_MODE||t===nn.ENTER_PLAN_MODE)?"switch_mode":t&&t===nn.TODO_WRITE?"todowrite":e&&new Set(["read","edit","delete","move","search","execute","think","fetch","other"]).has(e)?e:"other"}function bct(e){if(!e||typeof e!="object")return null;let t=e;return"fileName"in t&&"newContent"in t?t.truncatedForSession===!0?[{type:"content",content:{type:"text",text:EP(t)}}]:[{type:"diff",path:t.fileName,oldText:t.originalContent??"",newText:t.newContent}]:null}function Tct(e){if(typeof e=="string"||typeof e=="object"&&e!==null)return e}function Qct(e){let t=[];for(let n of e){if("text"in n&&n.text){t.push({type:"content",content:{type:"text",text:n.text}});continue}if("functionResponse"in n&&n.functionResponse){let o=n.functionResponse.response,r=o?.output,s=o?.error,i=typeof r=="string"?r:typeof s=="string"?s:JSON.stringify(o);t.push({type:"content",content:{type:"text",text:i}})}}return t}p();function kJ(e){let t=[],n=e.metadata;if(t.push(`# Chat Session Export
|
|
431
431
|
`),t.push(`- **Session ID**: \`${id(e.sessionId)}\``),t.push(`- **Start Time**: ${id(e.startTime)}`),t.push(`- **Exported**: ${id(n?.exportTime??new Date().toISOString())}`),t.push(""),n?.cwd&&t.push(`- **Working Directory**: \`${id(n.cwd)}\``),n?.gitRepo&&t.push(`- **Git Repository**: ${id(n.gitRepo)}`),n?.gitBranch&&t.push(`- **Git Branch**: \`${id(n.gitBranch)}\``),t.push(""),n?.model&&t.push(`- **Model**: ${id(n.model)}`),n?.channel&&t.push(`- **Channel**: ${id(n.channel)}`),n?.promptCount!==void 0&&t.push(`- **Prompt Count**: ${n.promptCount}`),t.push(""),n?.totalTokens!==void 0&&t.push(`- **Total Tokens**: ${n.totalTokens}`),n?.contextWindowSize!==void 0&&t.push(`- **Context Window Size**: ${n.contextWindowSize}`),n?.contextUsagePercent!==void 0&&t.push(`- **Context Usage**: ${n.contextUsagePercent}%`),t.push(""),n?.filesWritten!==void 0&&t.push(`- **Files Written**: ${n.filesWritten}`),n?.linesAdded!==void 0&&t.push(`- **Lines Added**: ${n.linesAdded}`),n?.linesRemoved!==void 0&&t.push(`- **Lines Removed**: ${n.linesRemoved}`),n?.uniqueFiles&&n.uniqueFiles.length>0){t.push(""),t.push("<details>"),t.push(`<summary><strong>Unique Files Referenced (${n.uniqueFiles.length})</strong></summary>`),t.push("");for(let o of n.uniqueFiles)t.push(`- \`${id(o)}\``);t.push("</details>")}t.push(`
|
|
432
432
|
---
|
|
@@ -746,7 +746,7 @@ ${Ae}
|
|
|
746
746
|
`)};Ye&&V[0]?V[0].parts=[...V[0].parts||[],je]:V=[{role:"user",parts:[je]}],de=!0}Ye=!1,V=Q(V),m++,e.getMaxSessionTurns()>=0&&m>e.getMaxSessionTurns()&&await YW(e);let Ae;he?Ae=r.sendMessageType??"userQuery":de?Ae="teammate":Ae="toolResult",de&&PB(a.begin("unknown"));let ne=[],pe=Date.now(),Te=w.sendMessageStream(V[0]?.parts||[],x.signal,o,{type:Ae,modelOverride:De,...he&&r.notificationDisplayText&&{notificationDisplayText:r.notificationDisplayText},...he&&r.onNotificationAccepted&&{onNotificationAccepted:r.onNotificationAccepted}});he=!1,l.startAssistantMessage();for await(let Pe of Te){if(x.signal.aborted&&(l.finalizeAssistantMessage(),await v()),S(Pe,pe),l.processEvent(Pe),Pe.type==="tool_call_request"?ne.push(Pe.value):Pe.type==="retry"&&(ne.length=0),Pe.type==="content"&&ee.length<re){let je=re-ee.length;ee+=String(Pe.value).slice(0,je)}Pe.type==="loop_detected"&&Pwe(e,Pe.value?.loopType)}if(l.finalizeAssistantMessage(),y+=Date.now()-pe,ne.length>0){let Pe=await ye(ne,je=>{De=je});if(ge!==void 0)return Qe();V=[{role:"user",parts:Pe}],Ye=!0}else{let Pe=e.getTeamManager();if(Pe?.hasActiveTeammates()){if(Pe.allRemainingStalled()){Pe.abortStalledTeammates();let It=Pe.buildTeamStatusSummary();q.push(It);continue}for(;Pe.hasActiveTeammates()&&!x.signal.aborted&&!(q.length>0);){if(Pe.allRemainingStalled()){Pe.abortStalledTeammates();let Ht=Pe.buildTeamStatusSummary();q.push(Ht);break}await Pe.waitForTeammateActivity(void 0,x.signal)==="timeout"&&sp.warn("[runNonInteractive] waitForTeammateActivity timed out (120s); will continue waiting until stall threshold or messages arrive.")}if(q.length>0)continue}if(x.signal.aborted&&await jW(e),Pe&&await Pe.drainLeaderInbox(),q.length>0)continue;let je=async()=>{if(F.length===0)return;let It=F[0].sendMessageType,Ht=Le=>Le.task!==void 0&&s.owns(Le.task),Jn=Ht(F[0]),so=It==="cron"?1:0;if(so===0)for(;so<F.length&&F[so].sendMessageType===It&&Ht(F[so])===Jn;)so++;let $t=F.slice(0,so);if($t.length===0)return;let en={displayText:$t.map(Le=>Le.displayText).join("; "),modelText:$t.map(Le=>Le.modelText).join(`
|
|
747
747
|
|
|
748
748
|
`),sendMessageType:It};m++,e.getMaxSessionTurns()>=0&&m>e.getMaxSessionTurns()&&await YW(e);let hr=[{role:"user",parts:[{text:en.modelText}]}],Cr=!0,Fo;for(PB(a.begin(jT(en.sendMessageType)));;){let Le=[],tn=Date.now(),Do=w.sendMessageStream(hr[0]?.parts||[],x.signal,o,{type:Cr?en.sendMessageType:"toolResult",modelOverride:Fo,...Cr&&{notificationDisplayText:en.displayText,onNotificationAccepted:()=>{F.splice(0,$t.length);for(let Lt of $t)Lt.task&&s.owns(Lt.task)&&s.consume(Lt.task),Y(Lt,!0);return!x.signal.aborted}}});Cr=!1,l.startAssistantMessage();for await(let Lt of Do)x.signal.aborted&&(l.finalizeAssistantMessage(),j(F),L(),await v()),S(Lt,tn),l.processEvent(Lt),Lt.type==="tool_call_request"?Le.push(Lt.value):Lt.type==="retry"&&(Le.length=0),Lt.type==="loop_detected"&&Pwe(e,Lt.value?.loopType);if(l.finalizeAssistantMessage(),y+=Date.now()-tn,Le.length>0){let Lt=await ye(Le,oo=>{Fo=oo});if(ge!==void 0)return;hr=[{role:"user",parts:Lt}]}else break}},Be=null,ce=()=>{if(Be)return Be;let It=(async()=>{for(;F.length>0;){if(ge!==void 0)return;let Jn=F[0]?.task;await(Jn&&s.owns(Jn)?s.run(je):$g.detached(je))}})();Be=It;let Ht=()=>{Be===It&&(Be=null)};return It.then(Ht,Ht),It},Re=e.isCronEnabled()?e.getCronScheduler():null;for(Re&&(await Re.enableDurable(e.getSessionId()).catch(It=>{sp.warn(`Durable cron init failed \u2014 persistent tasks will not fire in this run: ${It}`)}),await new Promise((It,Ht)=>{let Jn=()=>{Re.stop(),It()};if(x.signal.aborted){Jn();return}x.signal.addEventListener("abort",Jn,{once:!0});let so=()=>{if(ge!==void 0){x.signal.removeEventListener("abort",Jn),Re.stop(),It();return}Re.sessionSize===0&&!Be&&(x.signal.removeEventListener("abort",Jn),Re.stop(),It())},$t=en=>{x.signal.removeEventListener("abort",Jn),Re.stop(),Ht(en)};Re.start(en=>{let hr=en.prompt.slice(0,40);F.push({displayText:`Cron: ${hr}`,modelText:en.prompt,sendMessageType:"cron"}),ce().then(so,$t)}),so()}));x.signal.aborted&&(s.close(),j(F),L(),await v()),N=!1,await ce(),!(ge!==void 0||!s.pending&&F.length===0);){if(s.paused)throw new Error("A task was interrupted and requires an explicit resume.");await new Promise(It=>setTimeout(It,100))}let Ve=e.getGeminiClient().consumePendingMemoryTaskPromises();Ve.length>0&&await Promise.allSettled(Ve),L();let ve=kr.getMetrics(),st=fM(ve),Qt=c==="json"?kr.getMetrics():void 0;if(ge!==void 0)return Qe();if(e.getJsonSchema()){let It=ee.trim(),Ht=It?` Output preview (${ee.length}${ee.length>=re?"+":""} chars): ${JSON.stringify(It)}.`:"",Jn=`Model produced plain text instead of calling the structured_output tool as required by --json-schema after ${m} turn(s).`+Ht;return l.emitResult({isError:!0,durationMs:Date.now()-D,apiDurationMs:y,numTurns:m,errorMessage:Jn,usage:st,stats:Qt}),1}return l.emitResult({isError:!1,durationMs:Date.now()-D,apiDurationMs:y,numTurns:m,usage:st,stats:Qt}),0}}}catch(se){try{l.finalizeAssistantMessage()}catch{}j(F),L();let Ee=T.getExceeded(),xe=Ee?Ee.message:se instanceof Error?se.message:String(se),ie=kr.getMetrics(),we=fM(ie),J=c==="json"?kr.getMetrics():void 0,V=se instanceof vh;if(!(c==="text"&&V))try{l.emitResult({isError:!0,durationMs:Date.now()-D,apiDurationMs:y,numTurns:m,errorMessage:xe,...se instanceof XE&&{subtype:"error_max_turns"},usage:we,stats:J})}catch(ae){sp.error(`Failed to emit terminal result envelope: ${ae instanceof Error?ae.message:String(ae)}`)}if(Ee&&await qW(e,Ee),V||se instanceof XE)return se.exitCode;await Zre(se,e)}finally{e.onTeamManagerChange(null,Z),M&&($(M),M=null),T.stop();let se=e.getBackgroundTaskRegistry();se.setNotificationCallback(void 0),se.setRegisterCallback(void 0),e.getBackgroundShellRegistry().setNotificationCallback(void 0);let Ee=e.getMonitorRegistry();if(r.captureMonitorNotifications!==!1&&(W||Ee.abortAll({notify:!1}),Ee.setNotificationCallback(void 0)),r.captureMonitorRegistrations!==!1&&Ee.setRegisterCallback(void 0),process.stdout.removeListener("error",P),process.removeListener("SIGINT",U),process.removeListener("SIGTERM",U),u)try{await u.shutdown()}catch{}F7()&&await N7()}return 1})}p();import*as eU from"node:path";var Wwe=He("WORKTREE_STARTUP"),A9="HEAD";async function jwe(e,t){if(e===void 0)return null;let n=e.trim(),o=process.cwd(),r=new fh(o),s=await r.checkGitAvailable();if(!s.available)return{ok:!1,error:`--worktree: ${s.error??"git is not available on PATH."}`};if(/[\\/]\.matilda[\\/]worktrees[\\/]/.test(o))return{ok:!1,error:`--worktree: cannot start a new worktree from inside another worktree (cwd: ${o}). Run from the main checkout.`};let i=await r.getRepoTopLevel();if(i===null)return{ok:!1,error:`--worktree: ${o} is not a git repository. Run \`git init\` first or relaunch from inside one.`};let a=eU.resolve(i),l=a===o?r:new fh(a),c=fh.parsePRReference(n),u=c!==null,A;if(c!==null)A=`pr-${c}`;else if(n.length===0)A=fh.generateAutoSlug();else{let F=fh.validateUserWorktreeSlug(n);if(F)return{ok:!1,error:`--worktree: ${F}`};A=n}let[h,m]=await Promise.all([l.getCurrentBranch().catch(()=>{}),l.getCurrentCommitHash().catch(()=>"")]),y=h&&h!==A9?h:void 0,D=l.getUserWorktreePath(A),S=OX(A),w=null;try{w=await l.getRegisteredWorktreeBranch(D)}catch{w=null}if(w!==null){if(w.branch!==S)return{ok:!1,error:`--worktree: ${D} is already a git worktree, but its branch is ${w.branch} (expected ${S}). Refusing to re-attach. Resolve the conflict manually (e.g. \`git worktree remove ${D}\`).`};let F=eU.resolve(D);try{process.chdir(F)}catch(H){return{ok:!1,error:`--worktree: failed to chdir into ${F} (${H instanceof Error?H.message:String(H)}).`}}return Wwe.debug(`setupStartupWorktree: re-attached to existing worktree at ${F} (branch=${w.branch})`),{ok:!0,context:{worktreePath:F,slug:A,branch:w.branch,repoRoot:a,originalBranch:y??A9,originalHeadCommit:w.headCommit,isPullRequest:u,wasReattached:!0}}}let x=null;if(c!==null){let F=await l.fetchPullRequestRef(c);if(!F.success)return{ok:!1,error:`--worktree: ${F.error}`};if(x=await l.resolveRef("FETCH_HEAD"),x===null)return{ok:!1,error:`--worktree: fetched PR #${c} but FETCH_HEAD did not resolve to a commit SHA. Refusing to proceed (the worktree would otherwise branch off an unknown commit).`}}let T=u?x:y,Q=await l.createUserWorktree(A,T,{symlinkDirectories:t?.symlinkDirectories});if(!Q.success||!Q.worktree)return{ok:!1,error:`--worktree: ${Q.error??"failed to create worktree."}`};let v=eU.resolve(Q.worktree.path);try{process.chdir(v)}catch(F){return{ok:!1,error:`--worktree: created worktree at ${v} but failed to chdir into it (${F instanceof Error?F.message:String(F)}). Run \`cd ${v}\` manually.`}}return{ok:!0,context:{worktreePath:v,slug:A,branch:Q.worktree.branch,repoRoot:a,originalBranch:y??A9,originalHeadCommit:u?x:m,isPullRequest:u,wasReattached:!1}}}async function Ywe(e,t){let n=e.getSessionId(),o=e.getSessionService().getWorktreeSessionPath(n),r=!1,s,i=null;try{i=await TN(o)}catch(a){Wwe.warn(`persistStartupWorktreeSidecar: failed to read existing sidecar at ${o} \u2014 treating as "no previous worktree" and proceeding: ${a}`),i=null}return i&&i.slug!==t.slug&&(r=!0,s=i.slug),t.wasReattached||await PX(t.worktreePath,n).catch(()=>{}),await AZ(o,{slug:t.slug,worktreePath:t.worktreePath,worktreeBranch:t.branch,originalCwd:t.repoRoot,originalBranch:t.originalBranch,originalHeadCommit:t.originalHeadCommit}),{overrodeResumedWorktree:r,overriddenSlug:s,sidecarPath:o}}function g9(e,t){let o=`[Startup] ${e.wasReattached?"Re-attached to worktree":"Active worktree"}: "${e.slug}" at ${e.worktreePath} (branch: ${e.branch}). Continue using this path for all file operations.`;return t?.overrodeResumedWorktree&&t.overriddenSlug?`${o}
|
|
749
|
-
Note: --worktree overrode the resumed session's previous worktree "${t.overriddenSlug}". That worktree directory was left intact; re-attach with \`matilda --worktree ${t.overriddenSlug}\` if needed.`:o}p();p();import{createInterface as Ldt}from"node:readline/promises";import Odt from"node:process";var Gw=class extends Error{},tU=class{input;constructor(t=Odt.stdin){this.input=t}async*read(){let t=Ldt({input:this.input,crlfDelay:Number.POSITIVE_INFINITY,terminal:!1});try{for await(let n of t){let o=n.trim();o&&(yield this.parse(o))}}finally{t.close()}}parse(t){try{let n=JSON.parse(t);if(!n||typeof n!="object")throw new Gw("Parsed value is not an object");if(!("type"in n)||typeof n.type!="string")throw new Gw('Missing required "type" field');return n}catch(n){if(n instanceof Gw)throw n;let o=n instanceof Error?n.message:String(n);throw new Gw(`Failed to parse stream-json line: ${o}`)}}};p();var nU=class{config;streamJson;sessionId;abortSignal;debugMode;settings;permissionMode;sdkCanUseToolTimeoutMs;sdkMcpServers;mcpClients;inputClosed;onInterrupt;constructor(t){this.config=t.config,this.streamJson=t.streamJson,this.sessionId=t.sessionId,this.abortSignal=t.abortSignal,this.debugMode=t.config.getDebugMode(),this.settings=t.settings,this.permissionMode=t.permissionMode||"default",this.sdkMcpServers=new Set,this.mcpClients=new Map,this.inputClosed=!1,this.onInterrupt=t.onInterrupt}};p();p();p();import{randomUUID as Pdt}from"node:crypto";var qwe=3e4,TC=class{context;registry;controllerName;debugLogger;constructor(t,n,o){this.context=t,this.registry=n,this.controllerName=o,this.debugLogger=He()}async handleRequest(t,n){let o=new AbortController,r=setTimeout(()=>{o.abort(),this.registry.deregisterIncomingRequest(n),this.debugLogger.warn(`[${this.controllerName}] Request timeout: ${n}`)},qwe);this.registry.registerIncomingRequest(n,this.controllerName,o,r);try{let s=await this.handleRequestPayload(t,o.signal);return this.registry.deregisterIncomingRequest(n),s}catch(s){throw this.registry.deregisterIncomingRequest(n),s}}async sendControlRequest(t,n=qwe,o){if(this.context.inputClosed)throw new Error("Input closed");if(o?.aborted)throw new Error("Request aborted");let r=Pdt();return new Promise((s,i)=>{let a=()=>{this.registry.deregisterOutgoingRequest(r),i(new Error("Request aborted")),this.debugLogger.warn(`[${this.controllerName}] Outgoing request aborted: ${r}`)};o&&o.addEventListener("abort",a,{once:!0});let l=setTimeout(()=>{o&&o.removeEventListener("abort",a),this.registry.deregisterOutgoingRequest(r),i(new Error("Control request timeout")),this.debugLogger.warn(`[${this.controllerName}] Outgoing request timeout: ${r}`)},n),c=h=>{o&&o.removeEventListener("abort",a),s(h)},u=h=>{o&&o.removeEventListener("abort",a),i(h)};this.registry.registerOutgoingRequest(r,this.controllerName,c,u,l);let A={type:"control_request",request_id:r,request:t};try{this.context.streamJson.send(A)}catch(h){o&&o.removeEventListener("abort",a),this.registry.deregisterOutgoingRequest(r),i(h)}})}cleanup(){}};var Fc=He("SYSTEM_CONTROLLER"),Udt=6e5,oU=class extends TC{async handleRequestPayload(t,n){if(n.aborted)throw new Error("Request aborted");switch(t.subtype){case"initialize":return this.handleInitialize(t,n);case"interrupt":return this.handleInterrupt();case"set_model":return this.handleSetModel(t,n);case"supported_commands":return this.handleSupportedCommands(n);case"get_context_usage":return this.handleGetContextUsage(t,n);default:throw new Error("Unsupported request subtype in SystemController")}}async handleGetContextUsage(t,n){if(n.aborted)throw new Error("Request aborted");try{let o=await import("./chunks/contextCommand-OMGIDA33.js");if(n.aborted)throw new Error("Request aborted");if(typeof o.collectContextData!="function")throw new Error("collectContextData is not available");let r=t.show_details??!1,s=await o.collectContextData(this.context.config,r);if(n.aborted)throw new Error("Request aborted");let{type:i,...a}=s;return{subtype:"get_context_usage",...a}}catch(o){let r=o instanceof Error?o.message:"Failed to get context usage";throw Fc.error("[SystemController] Failed to get context usage:",o),new Error(r)}}async handleInitialize(t,n){if(n.aborted)throw new Error("Request aborted");this.context.config.setSdkMode(!0);let o=t.timeout?.canUseTool;if(typeof o=="number"&&Number.isFinite(o)&&o>0&&o<=Udt&&(this.context.sdkCanUseToolTimeoutMs=o),t.sdkMcpServers&&typeof t.sdkMcpServers=="object"&&t.sdkMcpServers!==null){let s={};for(let[a,l]of Object.entries(t.sdkMcpServers)){let c=typeof l?.name=="string"&&l.name.trim().length?l.name:a;this.context.sdkMcpServers.add(c),s[c]=new sy(void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,!0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,"sdk")}let i=Object.keys(s).length;if(i>0)try{this.context.config.addMcpServers(s),Fc.debug(`[SystemController] Added ${i} SDK MCP servers to config`)}catch(a){Fc.error("[SystemController] Failed to add SDK MCP servers:",a)}}if(t.mcpServers&&typeof t.mcpServers=="object"&&t.mcpServers!==null){let s={};for(let[a,l]of Object.entries(t.mcpServers)){let c=this.normalizeMcpServerConfig(a,l);c&&(s[a]=c)}let i=Object.keys(s).length;if(i>0)try{this.context.config.addMcpServers(s),Fc.debug(`[SystemController] Added ${i} external MCP servers to config`)}catch(a){Fc.error("[SystemController] Failed to add external MCP servers:",a)}}if(t.agents&&Array.isArray(t.agents))try{this.context.config.setSessionSubagents(t.agents),Fc.debug(`[SystemController] Added ${t.agents.length} session subagents to config`)}catch(s){Fc.error("[SystemController] Failed to add session subagents:",s)}let r=this.buildControlCapabilities();return Fc.debug(`[SystemController] Initialized with ${this.context.sdkMcpServers.size} SDK MCP servers`),{subtype:"initialize",session_id:this.context.config.getSessionId(),capabilities:r}}buildControlCapabilities(){return{can_handle_can_use_tool:!0,can_handle_hook_callback:!1,can_set_permission_mode:typeof this.context.config.setApprovalMode=="function",can_set_model:typeof this.context.config.setModel=="function",can_get_context_usage:!0,can_handle_mcp_message:!0}}normalizeMcpServerConfig(t,n){if(!n||typeof n!="object")return Fc.warn(`[SystemController] Ignoring invalid MCP server config for '${t}'`),null;let o=this.normalizeAuthProviderType(n.authProviderType),r=this.normalizeOAuthConfig(n.oauth);return new sy(n.command,n.args,n.env,n.cwd,n.url,n.httpUrl,n.headers,n.tcp,n.timeout,n.trust,n.description,n.includeTools,n.excludeTools,n.extensionName,r,o,n.targetAudience,n.targetServiceAccount)}normalizeAuthProviderType(t){if(t)switch(t){case"dynamic_discovery":case"google_credentials":case"service_account_impersonation":return t;default:Fc.warn(`[SystemController] Unsupported authProviderType '${t}', skipping`);return}}normalizeOAuthConfig(t){if(t)return{enabled:t.enabled,clientId:t.clientId,clientSecret:t.clientSecret,authorizationUrl:t.authorizationUrl,tokenUrl:t.tokenUrl,scopes:t.scopes,audiences:t.audiences,redirectUri:t.redirectUri,tokenParamName:t.tokenParamName,registrationUrl:t.registrationUrl}}async handleInterrupt(){return this.context.onInterrupt&&this.context.onInterrupt(),this.context.abortSignal&&!this.context.abortSignal.aborted&&Fc.debug("[SystemController] Interrupt signal triggered"),Fc.debug("[SystemController] Interrupt handled"),{subtype:"interrupt"}}async handleSetModel(t,n){if(n.aborted)throw new Error("Request aborted");let o=t.model;if(typeof o!="string"||o.trim()==="")throw new Error("Invalid model specified for set_model request");try{return await this.context.config.setModel(o),Fc.info(`[SystemController] Model switched to: ${o}`),{subtype:"set_model",model:o}}catch(r){let s=r instanceof Error?r.message:"Failed to set model";throw Fc.error(`[SystemController] Failed to set model ${o}:`,r),new Error(s)}}async handleSupportedCommands(t){if(t.aborted)throw new Error("Request aborted");return{subtype:"supported_commands",commands:await this.loadSlashCommandNames(t)}}async loadSlashCommandNames(t){if(t.aborted)return[];try{let n=await Lw(this.context.config,t,"non_interactive");return t.aborted?[]:n.map(o=>o.name).sort()}catch(n){return t.aborted?[]:(Fc.error("[SystemController] Failed to load slash commands:",n),[])}}};p();var Hdt=6e4,rU=class extends TC{pendingOutgoingRequests=new Set;async handleRequestPayload(t,n){if(n.aborted)throw new Error("Request aborted");switch(t.subtype){case"can_use_tool":return this.handleCanUseTool(t,n);case"set_permission_mode":return this.handleSetPermissionMode(t,n);default:throw new Error("Unsupported request subtype in PermissionController")}}async handleCanUseTool(t,n){if(n.aborted)throw new Error("Request aborted");let o=t.tool_name;if(!o||typeof o!="string"||o.trim().length===0)return{subtype:"can_use_tool",behavior:"deny",message:"Missing or invalid tool_name in can_use_tool request"};let r="allow",s;try{let a=this.checkPermissionMode();if(a.allowed||(r="deny",s=a.message),r==="allow"){let l=this.checkToolRegistry(o);l.allowed||(r="deny",s=l.message)}}catch(a){r="deny",s=a instanceof Error?`Failed to evaluate tool permission: ${a.message}`:"Failed to evaluate tool permission"}let i={subtype:"can_use_tool",behavior:r};return s&&(i.message=s),i}checkPermissionMode(){switch(this.context.permissionMode){case"bogan":case"auto-edit":case"auto":case"plan":return{allowed:!0};case"default":default:return{allowed:!1,message:"Tool execution requires manual approval. Update permission mode or approve via host."}}}checkToolRegistry(t){try{let o=this.context.config;if(typeof o.getToolRegistry=="function"){let r=o.getToolRegistry();if(r&&typeof r.getTool=="function"&&!r.getTool(t))return{allowed:!1,message:`Tool "${t}" is not registered.`}}return{allowed:!0}}catch(n){return{allowed:!1,message:`Failed to check tool registry: ${n instanceof Error?n.message:"Unknown error"}`}}}async handleSetPermissionMode(t,n){if(n.aborted)throw new Error("Request aborted");let o=t.mode,r=["default","plan","auto-edit","auto","bogan"];if(!r.includes(o))throw new Error(`Invalid permission mode: ${o}. Valid values are: ${r.join(", ")}`);return this.context.permissionMode=o,this.context.config.setApprovalMode(o),this.debugLogger.info(`[PermissionController] Permission mode updated to: ${o}`),{status:"updated",mode:o}}buildPermissionSuggestions(t){if(!t||typeof t!="object"||!("type"in t))return null;let n=t,o=String(n.type??""),r=typeof n.title=="string"?n.title:void 0;switch(o){case"exec":return[{type:"allow",label:"Allow Command",description:`Execute: ${n.command}`},{type:"deny",label:"Deny",description:"Block this command execution"}];case"edit":return[{type:"allow",label:"Allow Edit",description:`Edit file: ${n.fileName}`},{type:"deny",label:"Deny",description:"Block this file edit"},...n.hideModify===!0?[]:[{type:"modify",label:"Review Changes",description:"Review the proposed changes before applying"}]];case"plan":return[{type:"allow",label:"Approve Plan",description:r||"Execute the proposed plan"},{type:"deny",label:"Reject Plan",description:"Do not execute this plan"}];case"mcp":return[{type:"allow",label:"Allow MCP Call",description:`${n.serverName}: ${n.toolName}`},{type:"deny",label:"Deny",description:"Block this MCP server call"}];case"info":return[{type:"allow",label:"Allow Info Request",description:r||"Allow information request"},{type:"deny",label:"Deny",description:"Block this information request"}];default:return[{type:"allow",label:"Allow",description:r||`Allow ${o} operation`},{type:"deny",label:"Deny",description:`Block ${o} operation`}]}}getToolCallUpdateCallback(){return t=>{for(let n of t)if(n&&typeof n=="object"&&n.status==="awaiting_approval"){let o=n;typeof o.confirmationDetails?.onConfirm=="function"&&!this.pendingOutgoingRequests.has(o.request.callId)&&(this.pendingOutgoingRequests.add(o.request.callId),this.handleOutgoingPermissionRequest(o))}}}async handleTeammateApproval(t){try{if(this.context.abortSignal?.aborted){await t.respond("cancel");return}if(this.context.config.getInputFormat?.()!=="stream-json"){await t.respond("cancel");return}let o=`teammate-${t.teammateName}-${t.timestamp}`,r=await this.sendControlRequest({subtype:"can_use_tool",tool_name:t.toolName,tool_use_id:o,input:t.toolInput,permission_suggestions:[],blocked_path:null},void 0,this.context.abortSignal);if(r.subtype!=="success"){await t.respond("cancel");return}let s=r.response||{};if(String(s.behavior||"").toLowerCase()==="allow"){let a=s.updatedInput,l=a&&typeof a=="object"&&!Array.isArray(a)?{updatedInput:a}:void 0;await t.respond("proceed_once",l)}else{let a=typeof s.message=="string"?s.message:void 0;await t.respond("cancel",a?{cancelMessage:a}:void 0)}}catch(n){this.debugLogger.error("[PermissionController] Teammate approval failed:",n);try{await t.respond("cancel")}catch(o){this.debugLogger.error("[PermissionController] Teammate approval cancel failed:",o)}}}async handleOutgoingPermissionRequest(t){try{if(this.context.abortSignal?.aborted){await t.confirmationDetails.onConfirm("cancel");return}if(!(this.context.config.getInputFormat?.()==="stream-json")){let c=this.checkPermissionMode().allowed?"proceed_once":"cancel";await t.confirmationDetails.onConfirm(c);return}let r=this.buildPermissionSuggestions(t.confirmationDetails),s=await this.sendControlRequest({subtype:"can_use_tool",tool_name:t.request.name,tool_use_id:t.request.callId,input:t.request.args,permission_suggestions:r,blocked_path:null},this.context.sdkCanUseToolTimeoutMs??Hdt,this.context.abortSignal);if(s.subtype!=="success"){await t.confirmationDetails.onConfirm("cancel");return}let i=s.response||{};if(String(i.behavior||"").toLowerCase()==="allow"){let l=i.updatedInput;l&&typeof l=="object"&&(t.request.args=l),await t.confirmationDetails.onConfirm("proceed_once")}else{let l=typeof i.message=="string"?i.message:void 0;await t.confirmationDetails.onConfirm("cancel",l?{cancelMessage:l}:void 0)}}catch(n){this.debugLogger.error("[PermissionController] Outgoing permission failed:",n);let o=n instanceof Error?n.message:String(n),r=t.confirmationDetails.type;["edit","exec","mcp"].includes(r)?await t.confirmationDetails.onConfirm("cancel",{cancelMessage:`Error: ${o}`}):await t.confirmationDetails.onConfirm("cancel",{cancelMessage:`Error: ${o}`})}finally{this.pendingOutgoingRequests.delete(t.request.callId)}}};p();var Gdt=3e4,sU=class extends TC{async handleRequestPayload(t,n){if(n.aborted)throw new Error("Request aborted");switch(t.subtype){case"mcp_server_status":return this.handleMcpStatus();default:throw new Error("Unsupported request subtype in SdkMcpController")}}async handleMcpStatus(){let t={};for(let n of this.context.sdkMcpServers)t[n]="connected";return{subtype:"mcp_server_status",status:t}}async sendMcpMessageToSdk(t,n){this.debugLogger.debug(`[SdkMcpController] Sending MCP message to SDK server '${t}':`,JSON.stringify(n));let s=(await this.sendControlRequest({subtype:"mcp_message",server_name:t,message:n},Gdt,this.context.abortSignal)).response?.mcp_response;if(!s)throw new Error(`Invalid MCP response from SDK for server '${t}'`);return this.debugLogger.debug(`[SdkMcpController] Received MCP response from SDK server '${t}':`,JSON.stringify(s)),s}createSendSdkMcpMessage(){return(t,n)=>this.sendMcpMessageToSdk(t,n)}};var jI=He("CONTROL_DISPATCHER"),iU=class{context;systemController;permissionController;sdkMcpController;pendingIncomingRequests=new Map;pendingOutgoingRequests=new Map;abortHandler=null;constructor(t){this.context=t,this.systemController=new oU(t,this,"SystemController"),this.permissionController=new rU(t,this,"PermissionController"),this.sdkMcpController=new sU(t,this,"SdkMcpController"),this.abortHandler=()=>{this.shutdown()},this.context.abortSignal.addEventListener("abort",this.abortHandler)}async dispatch(t){let{request_id:n,request:o}=t;try{let s=await this.getControllerForRequest(o.subtype).handleRequest(o,n);this.sendSuccessResponse(n,s)}catch(r){let s=r instanceof Error?r.message:String(r);this.sendErrorResponse(n,s)}}handleControlResponse(t){let n=t.response,o=n.request_id,r=this.pendingOutgoingRequests.get(o);if(!r){jI.debug(`[ControlDispatcher] No pending outgoing request for: ${o}`);return}if(this.deregisterOutgoingRequest(o),n.subtype==="success")r.resolve(n);else{let s=typeof n.error=="string"?n.error:n.error?.message??"Unknown error";r.reject(new Error(s))}}async sendControlRequest(t,n){return this.systemController.sendControlRequest(t,n)}handleCancel(t){if(t){let n=this.pendingIncomingRequests.get(t);n&&(n.abortController.abort(),this.deregisterIncomingRequest(t),this.sendErrorResponse(t,"Request cancelled"),jI.debug(`[ControlDispatcher] Cancelled incoming request: ${t}`))}else{let n=Array.from(this.pendingIncomingRequests.keys());for(let o of n){let r=this.pendingIncomingRequests.get(o);r&&(r.abortController.abort(),this.deregisterIncomingRequest(o),this.sendErrorResponse(o,"All requests cancelled"))}jI.debug(`[ControlDispatcher] Cancelled all ${n.length} pending incoming requests`)}}markInputClosed(){if(this.context.inputClosed)return;this.context.inputClosed=!0;let t=Array.from(this.pendingOutgoingRequests.keys());this.context.debugMode&&jI.debug(`[ControlDispatcher] Input closed, rejecting ${t.length} pending outgoing requests`);for(let n of t){let o=this.pendingOutgoingRequests.get(n);o&&(this.deregisterOutgoingRequest(n),o.reject(new Error("Input closed")))}}shutdown(){jI.debug("[ControlDispatcher] Shutting down"),this.abortHandler&&(this.context.abortSignal.removeEventListener("abort",this.abortHandler),this.abortHandler=null);for(let[t,n]of this.pendingIncomingRequests.entries())n.abortController.abort(),clearTimeout(n.timeoutId);this.pendingIncomingRequests.clear();for(let[t,n]of this.pendingOutgoingRequests.entries())clearTimeout(n.timeoutId),n.reject(new Error("Dispatcher shutdown"));this.pendingOutgoingRequests.clear(),this.systemController.cleanup(),this.permissionController.cleanup(),this.sdkMcpController.cleanup()}registerIncomingRequest(t,n,o,r){this.pendingIncomingRequests.set(t,{controller:n,abortController:o,timeoutId:r})}deregisterIncomingRequest(t){let n=this.pendingIncomingRequests.get(t);n&&(clearTimeout(n.timeoutId),this.pendingIncomingRequests.delete(t))}registerOutgoingRequest(t,n,o,r,s){this.pendingOutgoingRequests.set(t,{controller:n,resolve:o,reject:r,timeoutId:s})}deregisterOutgoingRequest(t){let n=this.pendingOutgoingRequests.get(t);n&&(clearTimeout(n.timeoutId),this.pendingOutgoingRequests.delete(t))}getPendingIncomingRequestCount(){return this.pendingIncomingRequests.size}async waitForPendingIncomingRequests(t=50,n=3e4){let o=Date.now();for(;this.pendingIncomingRequests.size>0;){if(Date.now()-o>n){jI.warn(`[ControlDispatcher] Timeout waiting for ${this.pendingIncomingRequests.size} pending incoming requests`);break}await new Promise(r=>setTimeout(r,t))}this.pendingIncomingRequests.size===0&&jI.debug("[ControlDispatcher] All incoming requests completed")}getControllerForRequest(t){switch(t){case"initialize":case"interrupt":case"set_model":case"supported_commands":case"get_context_usage":return this.systemController;case"can_use_tool":case"set_permission_mode":return this.permissionController;case"mcp_server_status":return this.sdkMcpController;default:throw new Error(`Unknown control request subtype: ${t}`)}}sendSuccessResponse(t,n){let o={type:"control_response",response:{subtype:"success",request_id:t,response:n}};this.context.streamJson.send(o)}sendErrorResponse(t,n){let o={type:"control_response",response:{subtype:"error",request_id:t,error:n}};this.context.streamJson.send(o)}};p();var aU=class{dispatcher;constructor(t,n){this.dispatcher=n}get permission(){let t=this.dispatcher.permissionController;return{buildPermissionSuggestions:t.buildPermissionSuggestions.bind(t),getToolCallUpdateCallback:t.getToolCallUpdateCallback.bind(t),handleTeammateApproval:t.handleTeammateApproval.bind(t)}}get system(){let t=this.dispatcher.systemController;return{getControlCapabilities:()=>t.buildControlCapabilities()}}cleanup(){this.dispatcher.shutdown()}};p();function m9(e){return e&&typeof e=="object"&&e.type==="user"&&"message"in e}function Jwe(e){return e&&typeof e=="object"&&e.type==="assistant"&&"uuid"in e&&"message"in e&&"session_id"in e&&"parent_tool_use_id"in e}function $we(e){return e&&typeof e=="object"&&e.type==="system"&&"subtype"in e&&"uuid"in e&&"session_id"in e}function Vwe(e){return e&&typeof e=="object"&&e.type==="result"&&"subtype"in e&&"duration_ms"in e&&"is_error"in e&&"uuid"in e&&"session_id"in e}function Kwe(e){return e&&typeof e=="object"&&e.type==="stream_event"&&"uuid"in e&&"session_id"in e&&"event"in e&&"parent_tool_use_id"in e}function f9(e){return e&&typeof e=="object"&&e.type==="control_request"&&"request_id"in e&&"request"in e}function zwe(e){return e&&typeof e=="object"&&e.type==="control_response"&&"response"in e}function Xwe(e){return e&&typeof e=="object"&&e.type==="control_cancel_request"&&"request_id"in e}p();import*as p9 from"node:path";function yM(e){if(!e)return"";let t=[];for(let n of e)"text"in n&&n.text&&("thought"in n&&n.thought||t.push(n.text));return t.join(`
|
|
749
|
+
Note: --worktree overrode the resumed session's previous worktree "${t.overriddenSlug}". That worktree directory was left intact; re-attach with \`matilda --worktree ${t.overriddenSlug}\` if needed.`:o}p();p();import{createInterface as Ldt}from"node:readline/promises";import Odt from"node:process";var Gw=class extends Error{},tU=class{input;constructor(t=Odt.stdin){this.input=t}async*read(){let t=Ldt({input:this.input,crlfDelay:Number.POSITIVE_INFINITY,terminal:!1});try{for await(let n of t){let o=n.trim();o&&(yield this.parse(o))}}finally{t.close()}}parse(t){try{let n=JSON.parse(t);if(!n||typeof n!="object")throw new Gw("Parsed value is not an object");if(!("type"in n)||typeof n.type!="string")throw new Gw('Missing required "type" field');return n}catch(n){if(n instanceof Gw)throw n;let o=n instanceof Error?n.message:String(n);throw new Gw(`Failed to parse stream-json line: ${o}`)}}};p();var nU=class{config;streamJson;sessionId;abortSignal;debugMode;settings;permissionMode;sdkCanUseToolTimeoutMs;sdkMcpServers;mcpClients;inputClosed;onInterrupt;constructor(t){this.config=t.config,this.streamJson=t.streamJson,this.sessionId=t.sessionId,this.abortSignal=t.abortSignal,this.debugMode=t.config.getDebugMode(),this.settings=t.settings,this.permissionMode=t.permissionMode||"default",this.sdkMcpServers=new Set,this.mcpClients=new Map,this.inputClosed=!1,this.onInterrupt=t.onInterrupt}};p();p();p();import{randomUUID as Pdt}from"node:crypto";var qwe=3e4,TC=class{context;registry;controllerName;debugLogger;constructor(t,n,o){this.context=t,this.registry=n,this.controllerName=o,this.debugLogger=He()}async handleRequest(t,n){let o=new AbortController,r=setTimeout(()=>{o.abort(),this.registry.deregisterIncomingRequest(n),this.debugLogger.warn(`[${this.controllerName}] Request timeout: ${n}`)},qwe);this.registry.registerIncomingRequest(n,this.controllerName,o,r);try{let s=await this.handleRequestPayload(t,o.signal);return this.registry.deregisterIncomingRequest(n),s}catch(s){throw this.registry.deregisterIncomingRequest(n),s}}async sendControlRequest(t,n=qwe,o){if(this.context.inputClosed)throw new Error("Input closed");if(o?.aborted)throw new Error("Request aborted");let r=Pdt();return new Promise((s,i)=>{let a=()=>{this.registry.deregisterOutgoingRequest(r),i(new Error("Request aborted")),this.debugLogger.warn(`[${this.controllerName}] Outgoing request aborted: ${r}`)};o&&o.addEventListener("abort",a,{once:!0});let l=setTimeout(()=>{o&&o.removeEventListener("abort",a),this.registry.deregisterOutgoingRequest(r),i(new Error("Control request timeout")),this.debugLogger.warn(`[${this.controllerName}] Outgoing request timeout: ${r}`)},n),c=h=>{o&&o.removeEventListener("abort",a),s(h)},u=h=>{o&&o.removeEventListener("abort",a),i(h)};this.registry.registerOutgoingRequest(r,this.controllerName,c,u,l);let A={type:"control_request",request_id:r,request:t};try{this.context.streamJson.send(A)}catch(h){o&&o.removeEventListener("abort",a),this.registry.deregisterOutgoingRequest(r),i(h)}})}cleanup(){}};var Fc=He("SYSTEM_CONTROLLER"),Udt=6e5,oU=class extends TC{async handleRequestPayload(t,n){if(n.aborted)throw new Error("Request aborted");switch(t.subtype){case"initialize":return this.handleInitialize(t,n);case"interrupt":return this.handleInterrupt();case"set_model":return this.handleSetModel(t,n);case"supported_commands":return this.handleSupportedCommands(n);case"get_context_usage":return this.handleGetContextUsage(t,n);default:throw new Error("Unsupported request subtype in SystemController")}}async handleGetContextUsage(t,n){if(n.aborted)throw new Error("Request aborted");try{let o=await import("./chunks/contextCommand-7G5FHBBE.js");if(n.aborted)throw new Error("Request aborted");if(typeof o.collectContextData!="function")throw new Error("collectContextData is not available");let r=t.show_details??!1,s=await o.collectContextData(this.context.config,r);if(n.aborted)throw new Error("Request aborted");let{type:i,...a}=s;return{subtype:"get_context_usage",...a}}catch(o){let r=o instanceof Error?o.message:"Failed to get context usage";throw Fc.error("[SystemController] Failed to get context usage:",o),new Error(r)}}async handleInitialize(t,n){if(n.aborted)throw new Error("Request aborted");this.context.config.setSdkMode(!0);let o=t.timeout?.canUseTool;if(typeof o=="number"&&Number.isFinite(o)&&o>0&&o<=Udt&&(this.context.sdkCanUseToolTimeoutMs=o),t.sdkMcpServers&&typeof t.sdkMcpServers=="object"&&t.sdkMcpServers!==null){let s={};for(let[a,l]of Object.entries(t.sdkMcpServers)){let c=typeof l?.name=="string"&&l.name.trim().length?l.name:a;this.context.sdkMcpServers.add(c),s[c]=new sy(void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,!0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,"sdk")}let i=Object.keys(s).length;if(i>0)try{this.context.config.addMcpServers(s),Fc.debug(`[SystemController] Added ${i} SDK MCP servers to config`)}catch(a){Fc.error("[SystemController] Failed to add SDK MCP servers:",a)}}if(t.mcpServers&&typeof t.mcpServers=="object"&&t.mcpServers!==null){let s={};for(let[a,l]of Object.entries(t.mcpServers)){let c=this.normalizeMcpServerConfig(a,l);c&&(s[a]=c)}let i=Object.keys(s).length;if(i>0)try{this.context.config.addMcpServers(s),Fc.debug(`[SystemController] Added ${i} external MCP servers to config`)}catch(a){Fc.error("[SystemController] Failed to add external MCP servers:",a)}}if(t.agents&&Array.isArray(t.agents))try{this.context.config.setSessionSubagents(t.agents),Fc.debug(`[SystemController] Added ${t.agents.length} session subagents to config`)}catch(s){Fc.error("[SystemController] Failed to add session subagents:",s)}let r=this.buildControlCapabilities();return Fc.debug(`[SystemController] Initialized with ${this.context.sdkMcpServers.size} SDK MCP servers`),{subtype:"initialize",session_id:this.context.config.getSessionId(),capabilities:r}}buildControlCapabilities(){return{can_handle_can_use_tool:!0,can_handle_hook_callback:!1,can_set_permission_mode:typeof this.context.config.setApprovalMode=="function",can_set_model:typeof this.context.config.setModel=="function",can_get_context_usage:!0,can_handle_mcp_message:!0}}normalizeMcpServerConfig(t,n){if(!n||typeof n!="object")return Fc.warn(`[SystemController] Ignoring invalid MCP server config for '${t}'`),null;let o=this.normalizeAuthProviderType(n.authProviderType),r=this.normalizeOAuthConfig(n.oauth);return new sy(n.command,n.args,n.env,n.cwd,n.url,n.httpUrl,n.headers,n.tcp,n.timeout,n.trust,n.description,n.includeTools,n.excludeTools,n.extensionName,r,o,n.targetAudience,n.targetServiceAccount)}normalizeAuthProviderType(t){if(t)switch(t){case"dynamic_discovery":case"google_credentials":case"service_account_impersonation":return t;default:Fc.warn(`[SystemController] Unsupported authProviderType '${t}', skipping`);return}}normalizeOAuthConfig(t){if(t)return{enabled:t.enabled,clientId:t.clientId,clientSecret:t.clientSecret,authorizationUrl:t.authorizationUrl,tokenUrl:t.tokenUrl,scopes:t.scopes,audiences:t.audiences,redirectUri:t.redirectUri,tokenParamName:t.tokenParamName,registrationUrl:t.registrationUrl}}async handleInterrupt(){return this.context.onInterrupt&&this.context.onInterrupt(),this.context.abortSignal&&!this.context.abortSignal.aborted&&Fc.debug("[SystemController] Interrupt signal triggered"),Fc.debug("[SystemController] Interrupt handled"),{subtype:"interrupt"}}async handleSetModel(t,n){if(n.aborted)throw new Error("Request aborted");let o=t.model;if(typeof o!="string"||o.trim()==="")throw new Error("Invalid model specified for set_model request");try{return await this.context.config.setModel(o),Fc.info(`[SystemController] Model switched to: ${o}`),{subtype:"set_model",model:o}}catch(r){let s=r instanceof Error?r.message:"Failed to set model";throw Fc.error(`[SystemController] Failed to set model ${o}:`,r),new Error(s)}}async handleSupportedCommands(t){if(t.aborted)throw new Error("Request aborted");return{subtype:"supported_commands",commands:await this.loadSlashCommandNames(t)}}async loadSlashCommandNames(t){if(t.aborted)return[];try{let n=await Lw(this.context.config,t,"non_interactive");return t.aborted?[]:n.map(o=>o.name).sort()}catch(n){return t.aborted?[]:(Fc.error("[SystemController] Failed to load slash commands:",n),[])}}};p();var Hdt=6e4,rU=class extends TC{pendingOutgoingRequests=new Set;async handleRequestPayload(t,n){if(n.aborted)throw new Error("Request aborted");switch(t.subtype){case"can_use_tool":return this.handleCanUseTool(t,n);case"set_permission_mode":return this.handleSetPermissionMode(t,n);default:throw new Error("Unsupported request subtype in PermissionController")}}async handleCanUseTool(t,n){if(n.aborted)throw new Error("Request aborted");let o=t.tool_name;if(!o||typeof o!="string"||o.trim().length===0)return{subtype:"can_use_tool",behavior:"deny",message:"Missing or invalid tool_name in can_use_tool request"};let r="allow",s;try{let a=this.checkPermissionMode();if(a.allowed||(r="deny",s=a.message),r==="allow"){let l=this.checkToolRegistry(o);l.allowed||(r="deny",s=l.message)}}catch(a){r="deny",s=a instanceof Error?`Failed to evaluate tool permission: ${a.message}`:"Failed to evaluate tool permission"}let i={subtype:"can_use_tool",behavior:r};return s&&(i.message=s),i}checkPermissionMode(){switch(this.context.permissionMode){case"bogan":case"auto-edit":case"auto":case"plan":return{allowed:!0};case"default":default:return{allowed:!1,message:"Tool execution requires manual approval. Update permission mode or approve via host."}}}checkToolRegistry(t){try{let o=this.context.config;if(typeof o.getToolRegistry=="function"){let r=o.getToolRegistry();if(r&&typeof r.getTool=="function"&&!r.getTool(t))return{allowed:!1,message:`Tool "${t}" is not registered.`}}return{allowed:!0}}catch(n){return{allowed:!1,message:`Failed to check tool registry: ${n instanceof Error?n.message:"Unknown error"}`}}}async handleSetPermissionMode(t,n){if(n.aborted)throw new Error("Request aborted");let o=t.mode,r=["default","plan","auto-edit","auto","bogan"];if(!r.includes(o))throw new Error(`Invalid permission mode: ${o}. Valid values are: ${r.join(", ")}`);return this.context.permissionMode=o,this.context.config.setApprovalMode(o),this.debugLogger.info(`[PermissionController] Permission mode updated to: ${o}`),{status:"updated",mode:o}}buildPermissionSuggestions(t){if(!t||typeof t!="object"||!("type"in t))return null;let n=t,o=String(n.type??""),r=typeof n.title=="string"?n.title:void 0;switch(o){case"exec":return[{type:"allow",label:"Allow Command",description:`Execute: ${n.command}`},{type:"deny",label:"Deny",description:"Block this command execution"}];case"edit":return[{type:"allow",label:"Allow Edit",description:`Edit file: ${n.fileName}`},{type:"deny",label:"Deny",description:"Block this file edit"},...n.hideModify===!0?[]:[{type:"modify",label:"Review Changes",description:"Review the proposed changes before applying"}]];case"plan":return[{type:"allow",label:"Approve Plan",description:r||"Execute the proposed plan"},{type:"deny",label:"Reject Plan",description:"Do not execute this plan"}];case"mcp":return[{type:"allow",label:"Allow MCP Call",description:`${n.serverName}: ${n.toolName}`},{type:"deny",label:"Deny",description:"Block this MCP server call"}];case"info":return[{type:"allow",label:"Allow Info Request",description:r||"Allow information request"},{type:"deny",label:"Deny",description:"Block this information request"}];default:return[{type:"allow",label:"Allow",description:r||`Allow ${o} operation`},{type:"deny",label:"Deny",description:`Block ${o} operation`}]}}getToolCallUpdateCallback(){return t=>{for(let n of t)if(n&&typeof n=="object"&&n.status==="awaiting_approval"){let o=n;typeof o.confirmationDetails?.onConfirm=="function"&&!this.pendingOutgoingRequests.has(o.request.callId)&&(this.pendingOutgoingRequests.add(o.request.callId),this.handleOutgoingPermissionRequest(o))}}}async handleTeammateApproval(t){try{if(this.context.abortSignal?.aborted){await t.respond("cancel");return}if(this.context.config.getInputFormat?.()!=="stream-json"){await t.respond("cancel");return}let o=`teammate-${t.teammateName}-${t.timestamp}`,r=await this.sendControlRequest({subtype:"can_use_tool",tool_name:t.toolName,tool_use_id:o,input:t.toolInput,permission_suggestions:[],blocked_path:null},void 0,this.context.abortSignal);if(r.subtype!=="success"){await t.respond("cancel");return}let s=r.response||{};if(String(s.behavior||"").toLowerCase()==="allow"){let a=s.updatedInput,l=a&&typeof a=="object"&&!Array.isArray(a)?{updatedInput:a}:void 0;await t.respond("proceed_once",l)}else{let a=typeof s.message=="string"?s.message:void 0;await t.respond("cancel",a?{cancelMessage:a}:void 0)}}catch(n){this.debugLogger.error("[PermissionController] Teammate approval failed:",n);try{await t.respond("cancel")}catch(o){this.debugLogger.error("[PermissionController] Teammate approval cancel failed:",o)}}}async handleOutgoingPermissionRequest(t){try{if(this.context.abortSignal?.aborted){await t.confirmationDetails.onConfirm("cancel");return}if(!(this.context.config.getInputFormat?.()==="stream-json")){let c=this.checkPermissionMode().allowed?"proceed_once":"cancel";await t.confirmationDetails.onConfirm(c);return}let r=this.buildPermissionSuggestions(t.confirmationDetails),s=await this.sendControlRequest({subtype:"can_use_tool",tool_name:t.request.name,tool_use_id:t.request.callId,input:t.request.args,permission_suggestions:r,blocked_path:null},this.context.sdkCanUseToolTimeoutMs??Hdt,this.context.abortSignal);if(s.subtype!=="success"){await t.confirmationDetails.onConfirm("cancel");return}let i=s.response||{};if(String(i.behavior||"").toLowerCase()==="allow"){let l=i.updatedInput;l&&typeof l=="object"&&(t.request.args=l),await t.confirmationDetails.onConfirm("proceed_once")}else{let l=typeof i.message=="string"?i.message:void 0;await t.confirmationDetails.onConfirm("cancel",l?{cancelMessage:l}:void 0)}}catch(n){this.debugLogger.error("[PermissionController] Outgoing permission failed:",n);let o=n instanceof Error?n.message:String(n),r=t.confirmationDetails.type;["edit","exec","mcp"].includes(r)?await t.confirmationDetails.onConfirm("cancel",{cancelMessage:`Error: ${o}`}):await t.confirmationDetails.onConfirm("cancel",{cancelMessage:`Error: ${o}`})}finally{this.pendingOutgoingRequests.delete(t.request.callId)}}};p();var Gdt=3e4,sU=class extends TC{async handleRequestPayload(t,n){if(n.aborted)throw new Error("Request aborted");switch(t.subtype){case"mcp_server_status":return this.handleMcpStatus();default:throw new Error("Unsupported request subtype in SdkMcpController")}}async handleMcpStatus(){let t={};for(let n of this.context.sdkMcpServers)t[n]="connected";return{subtype:"mcp_server_status",status:t}}async sendMcpMessageToSdk(t,n){this.debugLogger.debug(`[SdkMcpController] Sending MCP message to SDK server '${t}':`,JSON.stringify(n));let s=(await this.sendControlRequest({subtype:"mcp_message",server_name:t,message:n},Gdt,this.context.abortSignal)).response?.mcp_response;if(!s)throw new Error(`Invalid MCP response from SDK for server '${t}'`);return this.debugLogger.debug(`[SdkMcpController] Received MCP response from SDK server '${t}':`,JSON.stringify(s)),s}createSendSdkMcpMessage(){return(t,n)=>this.sendMcpMessageToSdk(t,n)}};var jI=He("CONTROL_DISPATCHER"),iU=class{context;systemController;permissionController;sdkMcpController;pendingIncomingRequests=new Map;pendingOutgoingRequests=new Map;abortHandler=null;constructor(t){this.context=t,this.systemController=new oU(t,this,"SystemController"),this.permissionController=new rU(t,this,"PermissionController"),this.sdkMcpController=new sU(t,this,"SdkMcpController"),this.abortHandler=()=>{this.shutdown()},this.context.abortSignal.addEventListener("abort",this.abortHandler)}async dispatch(t){let{request_id:n,request:o}=t;try{let s=await this.getControllerForRequest(o.subtype).handleRequest(o,n);this.sendSuccessResponse(n,s)}catch(r){let s=r instanceof Error?r.message:String(r);this.sendErrorResponse(n,s)}}handleControlResponse(t){let n=t.response,o=n.request_id,r=this.pendingOutgoingRequests.get(o);if(!r){jI.debug(`[ControlDispatcher] No pending outgoing request for: ${o}`);return}if(this.deregisterOutgoingRequest(o),n.subtype==="success")r.resolve(n);else{let s=typeof n.error=="string"?n.error:n.error?.message??"Unknown error";r.reject(new Error(s))}}async sendControlRequest(t,n){return this.systemController.sendControlRequest(t,n)}handleCancel(t){if(t){let n=this.pendingIncomingRequests.get(t);n&&(n.abortController.abort(),this.deregisterIncomingRequest(t),this.sendErrorResponse(t,"Request cancelled"),jI.debug(`[ControlDispatcher] Cancelled incoming request: ${t}`))}else{let n=Array.from(this.pendingIncomingRequests.keys());for(let o of n){let r=this.pendingIncomingRequests.get(o);r&&(r.abortController.abort(),this.deregisterIncomingRequest(o),this.sendErrorResponse(o,"All requests cancelled"))}jI.debug(`[ControlDispatcher] Cancelled all ${n.length} pending incoming requests`)}}markInputClosed(){if(this.context.inputClosed)return;this.context.inputClosed=!0;let t=Array.from(this.pendingOutgoingRequests.keys());this.context.debugMode&&jI.debug(`[ControlDispatcher] Input closed, rejecting ${t.length} pending outgoing requests`);for(let n of t){let o=this.pendingOutgoingRequests.get(n);o&&(this.deregisterOutgoingRequest(n),o.reject(new Error("Input closed")))}}shutdown(){jI.debug("[ControlDispatcher] Shutting down"),this.abortHandler&&(this.context.abortSignal.removeEventListener("abort",this.abortHandler),this.abortHandler=null);for(let[t,n]of this.pendingIncomingRequests.entries())n.abortController.abort(),clearTimeout(n.timeoutId);this.pendingIncomingRequests.clear();for(let[t,n]of this.pendingOutgoingRequests.entries())clearTimeout(n.timeoutId),n.reject(new Error("Dispatcher shutdown"));this.pendingOutgoingRequests.clear(),this.systemController.cleanup(),this.permissionController.cleanup(),this.sdkMcpController.cleanup()}registerIncomingRequest(t,n,o,r){this.pendingIncomingRequests.set(t,{controller:n,abortController:o,timeoutId:r})}deregisterIncomingRequest(t){let n=this.pendingIncomingRequests.get(t);n&&(clearTimeout(n.timeoutId),this.pendingIncomingRequests.delete(t))}registerOutgoingRequest(t,n,o,r,s){this.pendingOutgoingRequests.set(t,{controller:n,resolve:o,reject:r,timeoutId:s})}deregisterOutgoingRequest(t){let n=this.pendingOutgoingRequests.get(t);n&&(clearTimeout(n.timeoutId),this.pendingOutgoingRequests.delete(t))}getPendingIncomingRequestCount(){return this.pendingIncomingRequests.size}async waitForPendingIncomingRequests(t=50,n=3e4){let o=Date.now();for(;this.pendingIncomingRequests.size>0;){if(Date.now()-o>n){jI.warn(`[ControlDispatcher] Timeout waiting for ${this.pendingIncomingRequests.size} pending incoming requests`);break}await new Promise(r=>setTimeout(r,t))}this.pendingIncomingRequests.size===0&&jI.debug("[ControlDispatcher] All incoming requests completed")}getControllerForRequest(t){switch(t){case"initialize":case"interrupt":case"set_model":case"supported_commands":case"get_context_usage":return this.systemController;case"can_use_tool":case"set_permission_mode":return this.permissionController;case"mcp_server_status":return this.sdkMcpController;default:throw new Error(`Unknown control request subtype: ${t}`)}}sendSuccessResponse(t,n){let o={type:"control_response",response:{subtype:"success",request_id:t,response:n}};this.context.streamJson.send(o)}sendErrorResponse(t,n){let o={type:"control_response",response:{subtype:"error",request_id:t,error:n}};this.context.streamJson.send(o)}};p();var aU=class{dispatcher;constructor(t,n){this.dispatcher=n}get permission(){let t=this.dispatcher.permissionController;return{buildPermissionSuggestions:t.buildPermissionSuggestions.bind(t),getToolCallUpdateCallback:t.getToolCallUpdateCallback.bind(t),handleTeammateApproval:t.handleTeammateApproval.bind(t)}}get system(){let t=this.dispatcher.systemController;return{getControlCapabilities:()=>t.buildControlCapabilities()}}cleanup(){this.dispatcher.shutdown()}};p();function m9(e){return e&&typeof e=="object"&&e.type==="user"&&"message"in e}function Jwe(e){return e&&typeof e=="object"&&e.type==="assistant"&&"uuid"in e&&"message"in e&&"session_id"in e&&"parent_tool_use_id"in e}function $we(e){return e&&typeof e=="object"&&e.type==="system"&&"subtype"in e&&"uuid"in e&&"session_id"in e}function Vwe(e){return e&&typeof e=="object"&&e.type==="result"&&"subtype"in e&&"duration_ms"in e&&"is_error"in e&&"uuid"in e&&"session_id"in e}function Kwe(e){return e&&typeof e=="object"&&e.type==="stream_event"&&"uuid"in e&&"session_id"in e&&"event"in e&&"parent_tool_use_id"in e}function f9(e){return e&&typeof e=="object"&&e.type==="control_request"&&"request_id"in e&&"request"in e}function zwe(e){return e&&typeof e=="object"&&e.type==="control_response"&&"response"in e}function Xwe(e){return e&&typeof e=="object"&&e.type==="control_cancel_request"&&"request_id"in e}p();import*as p9 from"node:path";function yM(e){if(!e)return"";let t=[];for(let n of e)"text"in n&&n.text&&("thought"in n&&n.thought||t.push(n.text));return t.join(`
|
|
750
750
|
`)}function Wdt(e){if(!e)return"";let t=[];for(let n of e)"text"in n&&n.text&&"thought"in n&&n.thought&&t.push(n.text);return t.join(`
|
|
751
751
|
`)}function jdt(e){if(!e)return[];let t=[];for(let n of e)if("functionCall"in n&&n.functionCall){let o=n.functionCall;t.push({id:o.id||`call-${t.length}`,name:o.name||"unknown",args:o.args||{}})}return t}function Ydt(e,t){return e?e.getToolRegistry().getTool(t):void 0}function qdt(e,t){try{return e.build(t).getDescription()}catch{return typeof t.description=="string"?t.description:""}}function Jdt(e){if(!e||typeof e!="object")return;let t={...e};if("timestamp"in t){let n=t.timestamp;(typeof n=="string"||typeof n=="number")&&(t.timestamp=new Date(n))}if(typeof t.type=="string")return t}function $dt(e,t){let n=[],o=[],r=0,s=new Map,i=[],a=l=>{if(l.status==="error"){r+=1;let c=l.filesRead?.length?l.filesRead.join(", "):"files";return[{callId:`at-command-${r}`,name:"Read File(s)",description:"Error attempting to read files",status:"Error",resultDisplay:l.message||`Error reading files (${c})`,confirmationDetails:void 0}]}return l.filesRead?.length?l.filesRead.map(c=>{r+=1;let u=c.endsWith("/");return{callId:`at-command-${r}`,name:u?"Read Directory":"Read File",description:u?`Read directory ${p9.basename(c)}`:`Read file ${p9.basename(c)}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}}):(r+=1,[{callId:`at-command-${r}`,name:"Read File",description:"Read File(s)",status:"Success",resultDisplay:void 0,confirmationDetails:void 0}])};for(let l of e.messages){if(l.type==="system"){if(l.subtype==="slash_command"){i.length>0&&(n.push({type:"tool_group",tools:[...i]}),i=[]);let c=l.systemPayload;if(!c)continue;if(c.phase==="invocation"&&c.rawCommand){let u=typeof c.sentToModel=="boolean"?c.sentToModel:void 0;n.push({type:"user",text:c.rawCommand,...u===void 0?{}:{sentToModel:u}})}if(c.phase==="result"){let u=c.outputHistoryItems??[];for(let A of u){let h=Jdt(A);h&&n.push(h)}}}if(l.subtype==="at_command"){let c=l.systemPayload;if(!c)continue;o.push(c)}l.subtype==="rewind"&&n.push({type:"info",text:"Conversation rewound."});continue}switch(l.type){case"user":{if(l.subtype==="hook_prompt")break;if(l.subtype==="notification"||l.subtype==="cron"){let u=l.systemPayload,A=l.subtype==="cron"?"Cron job fired":"Background agent completed",h=u?.displayText||yM(l.message?.parts)||A;n.push({type:"notification",text:h});break}if(l.subtype==="mid_turn_user_message"){let A=l.systemPayload?.displayText||yM(l.message?.parts);A&&n.push({type:"notification",text:A});break}if(o.length>0){i.length>0&&(n.push({type:"tool_group",tools:[...i]}),i=[]);let u=o.shift(),A=u.userText||yM(l.message?.parts);A&&n.push({type:"user",text:A});let h=a(u);h.length>0&&n.push({type:"tool_group",tools:h});break}i.length>0&&(n.push({type:"tool_group",tools:[...i]}),i=[]);let c=yM(l.message?.parts);c&&n.push({type:"user",text:c});break}case"assistant":{let c=l.message?.parts,u=t?"":Wdt(c),A=yM(c),h=jdt(c);u&&(i.length>0&&(n.push({type:"tool_group",tools:[...i]}),i=[]),n.push({type:"gemini_thought",text:u})),A&&(i.length>0&&(n.push({type:"tool_group",tools:[...i]}),i=[]),n.push({type:"gemini",text:A}));for(let m of h){let y=Ydt(t,m.name);s.set(m.id,{name:m.name,args:m.args}),i.push({callId:m.id,name:y?.displayName||m.name,description:y?qdt(y,m.args):"",resultDisplay:void 0,status:"Success",confirmationDetails:void 0})}break}case"tool_result":{if(l.toolCallResult){let c=l.toolCallResult.callId,u=i.find(A=>A.callId===c);if(u){let A=l.toolCallResult.resultDisplay;u.resultDisplay=A;let h=l.toolCallResult.status;u.status=h==="error"?"Error":"Success"}s.delete(c||"")}break}default:break}}if(o.length>0)for(let l of o){i.length>0&&(n.push({type:"tool_group",tools:[...i]}),i=[]);let c=l.userText;c&&n.push({type:"user",text:c});let u=a(l);u.length>0&&n.push({type:"tool_group",tools:u})}return i.length>0&&n.push({type:"tool_group",tools:i}),n}function Eu(e,t,n=Date.now()){let o=[],r=1,s=()=>n+r++,i=$dt(e.conversation,t);for(let a of i)o.push({...a,id:s()});return o}var ms=He("NON_INTERACTIVE_SESSION"),h9=class{userMessageQueue=[];monitorStartedQueue=[];monitorQueue=[];pendingMonitorBatch=null;monitorAdmissionPaused=!1;abortController;config;sessionId;promptIdCounter=0;inputReader;outputAdapter;controlContext=null;dispatcher=null;controlService=null;controlSystemEnabled=null;shutdownHandler=null;initialPrompt=null;processingPromise=null;isShuttingDown=!1;configInitialized=!1;monitorNotificationsRegistered=!1;monitorRegistrationsRegistered=!1;settings;initializationPromise=null;initializationResolve=null;initializationReject=null;constructor(t,n,o=ZT()){this.config=t,this.settings=o,this.sessionId=t.getSessionId(),this.abortController=new AbortController,this.initialPrompt=n??null,this.inputReader=new tU,this.outputAdapter=new ag(t,t.getIncludePartialMessages()),this.setupSignalHandlers()}ensureInitializationPromise(){this.initializationPromise||(this.initializationPromise=new Promise((t,n)=>{this.initializationResolve=()=>{t(),this.initializationResolve=null,this.initializationReject=null},this.initializationReject=o=>{n(o),this.initializationResolve=null,this.initializationReject=null}}))}getNextPromptId(){return this.promptIdCounter++,`${this.sessionId}########${this.promptIdCounter}`}async ensureConfigInitialized(t){if(!this.configInitialized){ms.debug("[Session] Initializing config");try{_a("config_initialize_start"),await this.config.initialize(t);let n=this.config.getResumedSessionData?.();n&&rA(Eu(n,this.config),this.config,()=>{}),_a("config_initialize_end"),await this.config.waitForMcpReady();let o=typeof this.config.getFailedMcpServerNames=="function"?this.config.getFailedMcpServerNames():[];o.length>0&&process.stderr.write(`Warning: MCP server(s) failed to start: ${o.join(", ")}. Continuing with built-in tools and any servers that did connect.
|
|
752
752
|
`),oS(this.config.getSessionId()),this.configInitialized=!0,this.registerMonitorRegistrations(),this.registerMonitorNotifications()}catch(n){throw ms.error("[Session] Failed to initialize config:",n),n}}}registerMonitorNotifications(){if(this.monitorNotificationsRegistered)return;let t=this.config.getMonitorRegistry();t.setNotificationCallback((n,o,r)=>{if(!(this.isShuttingDown||this.abortController.signal.aborted)){if(r.status==="running"&&typeof t.get=="function"){let s=t.get(r.monitorId);if(!s||s.status!=="running")return}this.enqueueMonitorNotification({displayText:n,modelText:o,sdkNotification:{task_id:r.monitorId,tool_use_id:r.toolUseId,status:r.status}})}}),this.monitorNotificationsRegistered=!0}registerMonitorRegistrations(){if(this.monitorRegistrationsRegistered)return;this.config.getMonitorRegistry().setRegisterCallback(n=>{this.isShuttingDown||this.abortController.signal.aborted||this.enqueueMonitorStarted({task_id:n.monitorId,tool_use_id:n.toolUseId,description:n.description})}),this.monitorRegistrationsRegistered=!0}completeInitialization(){this.initializationResolve&&(ms.debug("[Session] Initialization complete"),this.initializationResolve(),this.initializationResolve=null,this.initializationReject=null)}failInitialization(t){this.initializationReject&&(ms.error("[Session] Initialization failed:",t),this.initializationReject(t),this.initializationResolve=null,this.initializationReject=null)}async waitForInitialization(){this.initializationPromise&&await this.initializationPromise}ensureControlSystem(){this.controlContext&&this.dispatcher&&this.controlService||(this.controlContext=new nU({config:this.config,streamJson:this.outputAdapter,sessionId:this.sessionId,abortSignal:this.abortController.signal,settings:this.settings,permissionMode:this.config.getApprovalMode(),onInterrupt:()=>this.handleInterrupt()}),this.dispatcher=new iU(this.controlContext),this.controlService=new aU(this.controlContext,this.dispatcher))}getDispatcher(){return this.controlSystemEnabled!==!0?null:(this.dispatcher||this.ensureControlSystem(),this.dispatcher)}handleFirstMessage(t){if(f9(t)){let n=t;if(this.controlSystemEnabled=!0,this.ensureControlSystem(),n.request.subtype==="initialize"){this.initializeSdkMode(n);return}ms.debug("[Session] Ignoring non-initialize control request during initialization");return}if(m9(t)){this.controlSystemEnabled=!1,this.initializeDirectMode(t);return}this.controlSystemEnabled=!1}async initializeSdkMode(t){this.ensureInitializationPromise();try{await this.dispatcher?.dispatch(t);let n=this.dispatcher?.sdkMcpController.createSendSdkMcpMessage();await this.ensureConfigInitialized({sendSdkMcpMessage:n}),this.completeInitialization()}catch(n){ms.error("[Session] SDK mode initialization failed:",n),this.failInitialization(n instanceof Error?n:new Error(String(n)))}}async initializeDirectMode(t){this.ensureInitializationPromise();try{await this.ensureConfigInitialized(),this.completeInitialization(),this.enqueueUserMessage(t)}catch(n){ms.error("[Session] Direct mode initialization failed:",n),this.failInitialization(n instanceof Error?n:new Error(String(n)))}}handleControlRequestAsync(t){let n=this.getDispatcher();if(!n){ms.warn("[Session] Control system not enabled");return}n.dispatch(t).catch(o=>{ms.error("[Session] Control request dispatch error:",o)})}handleControlResponse(t){let n=this.getDispatcher();n&&n.handleControlResponse(t)}handleControlCancel(t){let n=this.getDispatcher();n&&n.handleCancel(t.request_id)}async processUserMessage(t){let n=Vdt(t);if(!n){ms.debug("[Session] No text content in user message");return}await this.waitForInitialization();let o=this.getNextPromptId();try{await EM(this.config,this.settings,n,o,{abortController:this.abortController,adapter:this.outputAdapter,controlService:this.controlService??void 0,captureMonitorNotifications:!1,captureMonitorRegistrations:!1})}catch(r){ms.error("[Session] Query execution error:",r)}}async processMonitorNotificationBatch(t){await this.waitForInitialization();let n=t.map(s=>s.modelText).join(`
|
|
@@ -967,7 +967,7 @@ ${r.join(`
|
|
|
967
967
|
`)}
|
|
968
968
|
---
|
|
969
969
|
${o}`}var BLe=new Set(["github.com","raw.githubusercontent.com","codeload.github.com","api.github.com"]);function SLe(e){let t;try{t=new URL(e)}catch{throw ke.invalidParams(void 0,"Skill sourceUrl must be a valid URL")}if(t.protocol!=="https:")throw ke.invalidParams(void 0,"Skill sourceUrl must be an HTTPS URL");if(!BLe.has(t.hostname))throw ke.invalidParams(void 0,"Skill sourceUrl host is not allowed (only github.com sources are supported)")}function xLe(e){let t=new URL(e);if(t.protocol!=="https:")throw ke.invalidParams(void 0,"Skill sourceUrl must be an HTTPS URL");if(t.hostname!=="github.com")return null;let n=t.pathname.split("/").filter(Boolean);if(n.length<5||n[2]!=="blob")return null;let o=n[0],r=n[1],s=n[3],i=n.slice(4);return!o||!r||!s||i.length===0?null:{owner:o,repo:r,ref:s,filePath:i.join("/")}}function qSt(e){return`https://raw.githubusercontent.com/${e.owner}/${e.repo}/${e.ref}/${e.filePath}`}function JSt(e){return!e||e==="."?"":e.split("/").map(encodeURIComponent).join("/")}function _K(e,t,n){let o=e.subarray(t,t+n),r=o.indexOf(0),s=r>=0?r:o.length;return Buffer.from(o.subarray(0,s)).toString("utf8").trim()}function $St(e,t){let n=_K(e,t+124,12);return n?Number.parseInt(n,8):0}function VSt(e,t){for(let n=0;n<512;n+=1)if(e[t+n]!==0)return!1;return!0}function KSt(e,t){let n=_K(e,t,100),o=_K(e,t+345,155);return o?`${o}/${n}`:n}function zSt(e){let t=e.split("/").filter(Boolean);return t.length>1?t.slice(1).join("/"):""}var Zk=100*1024*1024,wLe=500*1024*1024,XSt=16,ZSt=2e3,XG=class extends Error{};async function ext(e,t,n={}){let o=n.maxCompressedBytes??Zk,r=n.maxDecompressedBytes??wLe;if(e.length>o)throw ke.invalidParams(void 0,"Skill archive exceeds the maximum allowed size");let s;try{let c=[],u=0;await TSt(hLe.from([Buffer.from(e)]),QSt(),new CLe({write(A,h,m){if(u+=A.length,u>r){m(new XG);return}c.push(A),m()}})),s=Buffer.concat(c)}catch(c){throw c instanceof XG?ke.invalidParams(void 0,"Decompressed skill archive exceeds the maximum allowed size"):ke.invalidParams(void 0,`Failed to decompress skill archive: ${c instanceof Error?c.message:String(c)}`)}let i=t.replace(/^\/+|\/+$/g,""),a=i&&i!=="."?`${i}/`:"",l=[];for(let c=0;c+512<=s.length&&!VSt(s,c);){let u=KSt(s,c),A=String.fromCharCode(s[c+156]||0),h=$St(s,c),m=c+512,y=m+Math.ceil(h/512)*512;if(A==="0"||A==="\0"){let D=zSt(u);if(D.startsWith(a)){let S=D.slice(a.length);S&&l.push({relativePath:S,content:s.subarray(m,m+h)})}}c=y}return l}var txt=[".githubusercontent.com",".github.com"];function nxt(e){return BLe.has(e)?!0:txt.some(t=>e.endsWith(t))}async function PK(e,t={},n=5){let o=e;for(let r=0;r<=n;r+=1){let s=await fetch(o,{...t,redirect:"manual"});if(s.status<300||s.status>=400)return s;let i=s.headers?.get("location");if(!i)return s;let a;try{a=new URL(i,o)}catch{throw ke.invalidParams(void 0,"Skill download redirected to an invalid URL")}if(a.protocol!=="https:"||!nxt(a.hostname))throw ke.invalidParams(void 0,"Skill download redirected to a disallowed host");o=a.toString()}throw ke.invalidParams(void 0,"Skill download exceeded the maximum number of redirects")}async function bLe(e,t){let n=e.body;if(!n){let l=new Uint8Array(await e.arrayBuffer());if(l.byteLength>t)throw ke.invalidParams(void 0,"Skill download exceeds the maximum allowed size");return l}let o=n.getReader(),r=[],s=0;for(;;){let{done:l,value:c}=await o.read();if(l)break;if(c){if(s+=c.byteLength,s>t)throw await o.cancel(),ke.invalidParams(void 0,"Skill download exceeds the maximum allowed size");r.push(c)}}let i=new Uint8Array(s),a=0;for(let l of r)i.set(l,a),a+=l.byteLength;return i}async function TLe(e){let t=await PK(e);if(!t.ok)throw ke.invalidParams(void 0,`Failed to download skill (${t.status})`);let n=t.headers?.get("content-length");if(n){let o=Number.parseInt(n,10);if(Number.isFinite(o)&&o>Zk)throw ke.invalidParams(void 0,"Skill download exceeds the maximum allowed size")}return bLe(t,Zk)}async function oxt(e){let t=xLe(e),n=t?qSt(t):e,o=await TLe(n);return{skillContent:Buffer.from(o).toString("utf8"),files:[{relativePath:"SKILL.md",content:o}]}}async function rxt(e,t){let n=`https://codeload.github.com/${e.owner}/${e.repo}/tar.gz/${encodeURIComponent(e.ref)}`,o=await PK(n,{headers:{"User-Agent":"matilda-code"}});if(!o.ok)throw ke.invalidParams(void 0,`Failed to download GitHub skill archive (${o.status})`);let r=o.headers?.get("content-length");if(r){let s=Number.parseInt(r,10);if(Number.isFinite(s)&&s>Zk)throw ke.invalidParams(void 0,"Skill archive exceeds the maximum allowed size")}return ext(await bLe(o,Zk),t)}async function sxt(e,t){let n=JSt(t),o=`https://api.github.com/repos/${e.owner}/${e.repo}/contents/${n}?ref=${encodeURIComponent(e.ref)}`,r=await PK(o,{headers:{Accept:"application/vnd.github+json","User-Agent":"matilda-code"}});if(!r.ok)throw ke.invalidParams(void 0,`Failed to list GitHub skill files (${r.status})`);let s=await r.json();if(!Array.isArray(s))throw ke.invalidParams(void 0,"GitHub skill URL must point to a directory-backed SKILL.md file");return s}async function QLe(e,t,n="",o=0,r={files:0,bytes:0}){if(o>XSt)throw ke.invalidParams(void 0,"Skill directory nesting exceeds the maximum allowed depth");let s=await sxt(e,t),i=[];for(let a of s){let l=Hr(a),c=Mp(l.name,"github.name"),u=Mp(l.path,"github.path"),A=Mp(l.type,"github.type"),h=n?Yo.posix.join(n,c):c;if(A==="dir"){i.push(...await QLe(e,u,h,o+1,r));continue}if(A!=="file")continue;if(r.files+=1,r.files>ZSt)throw ke.invalidParams(void 0,"Skill directory contains too many files");let m=Mp(l.download_url,"github.download_url");SLe(m);let y=await TLe(m);if(r.bytes+=y.length,r.bytes>wLe)throw ke.invalidParams(void 0,"Skill directory exceeds the maximum allowed size");i.push({relativePath:h,content:y})}return i}async function ixt(e,t){let n=await QLe(e,t).catch(o=>(Xn.warn("GitHub API directory listing failed, falling back to archive download:",o),null));return n||rxt(e,t)}async function axt(e){SLe(e);let t=xLe(e);if(!t||Yo.posix.basename(t.filePath)!=="SKILL.md")return oxt(e);let n=Yo.posix.dirname(t.filePath),o=await ixt(t,n),r=o.find(s=>s.relativePath==="SKILL.md");if(!r)throw ke.invalidParams(void 0,"GitHub skill directory does not contain SKILL.md");return{skillContent:Buffer.from(r.content).toString("utf8"),files:o}}function lxt(e,t){let n=Yo.resolve(e),o=Yo.resolve(e,t);if(o!==n&&!o.startsWith(n+Yo.sep))throw ke.invalidParams(void 0,`Invalid skill file path: ${t}`);return o}function dLe(e,t){let n=Yo.resolve(e),o=Yo.resolve(e,t);if(!o.startsWith(n+Yo.sep))throw ke.invalidParams(void 0,"Invalid skill.slug");return o}function cxt(e,t){if(e==null)return[];if(!Array.isArray(e))throw ke.invalidParams(void 0,`Invalid ${t}: expected string[]`);return Array.from(new Set(e.map(n=>{if(typeof n!="string")throw ke.invalidParams(void 0,`Invalid ${t}: expected string[]`);return n.trim()}).filter(Boolean)))}function ALe(e,t){if(!(e==null||e==="")){if(typeof e!="number"||!Number.isFinite(e)||e<=0)throw ke.invalidParams(void 0,`Invalid ${t}: expected positive number`);return e}}function uxt(e){if(e==null)return;let t=Hr(e);if(t.enableThinking!==void 0&&typeof t.enableThinking!="boolean")throw ke.invalidParams(void 0,"Invalid advancedConfig.enableThinking: expected boolean");let n=Hr(t.multimodal),o={};for(let a of["image","video","audio","pdf"]){let l=n[a];if(l!==void 0){if(typeof l!="boolean")throw ke.invalidParams(void 0,`Invalid advancedConfig.multimodal.${a}: expected boolean`);o[a]=l}}let r=ALe(t.contextWindowSize,"advancedConfig.contextWindowSize"),s=ALe(t.maxTokens,"advancedConfig.maxTokens"),i={...typeof t.enableThinking=="boolean"?{enableThinking:t.enableThinking}:{},...Object.keys(o).length>0?{multimodal:o}:{},...r?{contextWindowSize:r}:{},...s?{maxTokens:s}:{}};return Object.keys(i).length>0?i:void 0}function dxt(e,t){if(typeof e.documentationUrl=="string")return e.documentationUrl;if(typeof e.documentationUrl=="function")try{return e.documentationUrl(t)}catch{return}}function Axt(e){return typeof Hr(e).id=="string"}function vLe(e,t){if(!t)return;let o=Hr(e.env)[t];return typeof o=="string"&&o.length>0?o:void 0}function gxt(e,t){let o=Hr(e.modelProviders)[t];return Array.isArray(o)?o.filter(Axt):[]}function RLe(e,t){let n=uN(e);if(!n)return;let o=e.protocolOptions?.length?e.protocolOptions:[e.protocol];for(let r of o){let s=gxt(t,r).filter(n);if(s.length>0)return{protocol:r,models:s}}}function MLe(e,t,n){try{return typeof e.envKey=="function"?e.envKey(t,n):e.envKey}catch{return}}function mxt(e){let t=Hr(e?.generationConfig),n=Hr(t.extra_body),o={};return typeof n.enable_thinking=="boolean"&&(o.enableThinking=n.enable_thinking),typeof t.contextWindowSize=="number"&&(o.contextWindowSize=t.contextWindowSize),Object.keys(o).length>0?o:void 0}function fxt(e,t){let n=RLe(e,t),o=n?.models[0],r=n?.protocol??e.protocol,s=typeof o?.baseUrl=="string"?o.baseUrl:Wl(e),i=typeof o?.envKey=="string"?o.envKey:MLe(e,r,s),a=vLe(t,i);if(!(!!a||!!n))return;let c=mxt(o);return{protocol:r,baseUrl:zG(s),...a?{hasApiKey:!0}:{},...n?{modelIds:n.models.map(u=>u.id)}:{},...c?{advancedConfig:c}:{}}}function pxt(e,t){let n=RLe(e,t),o=n?.models[0],r=n?.protocol??e.protocol,s=typeof o?.baseUrl=="string"?o.baseUrl:Wl(e),i=typeof o?.envKey=="string"?o.envKey:MLe(e,r,s);return vLe(t,i)}function hxt(e,t){let n=e.protocolOptions?.[0]??e.protocol,o=e.baseUrl===void 0?GB(n):Wl(e),r=fxt(e,t);return{id:e.id,label:e.label,description:e.description,protocol:e.protocol,protocolOptions:e.protocolOptions??[],baseUrl:e.baseUrl,baseUrlPlaceholder:e.baseUrl===void 0?o:void 0,defaultModelIds:Wu(e),models:e.models??[],modelsEditable:e.modelsEditable===!0||!e.models,showAdvancedConfig:e.showAdvancedConfig===!0,apiKeyPlaceholder:e.apiKeyPlaceholder,documentationUrl:dxt(e,o),uiGroup:e.uiGroup??"third-party",uiLabels:e.uiLabels,...r?{existingConfig:r}:{}}}function Cxt(e,t,n){let o=Km(t.protocol,"protocol");if(o&&o!==e.protocol&&!e.protocolOptions?.includes(o))throw ke.invalidParams(void 0,`Invalid protocol for provider "${e.id}"`);let r=Wl(e,Km(t.baseUrl,"baseUrl")).trim();if(!r&&e.baseUrl===void 0&&(r=GB(o??e.protocol)),!r)throw ke.invalidParams(void 0,`Invalid or missing baseUrl for provider "${e.id}"`);let s=Km(t.apiKey,"apiKey")??n;if(!s)throw ke.invalidParams(void 0,"Invalid or missing apiKey");let i=e.validateApiKey?.(s,r);if(i)throw ke.invalidParams(void 0,i);let a=Wu(e),l=cxt(t.modelIds,"modelIds"),c=l.length>0?l:a;if(c.length===0)throw ke.invalidParams(void 0,`Invalid or missing modelIds for provider "${e.id}"`);let u=uxt(t.advancedConfig);return{...o?{protocol:o}:{},baseUrl:r,apiKey:s,modelIds:c,...u?{advancedConfig:u}:{}}}function Ext(e){if(e!==void 0){if(e==="user")return"User";if(e==="workspace")return"Workspace";throw ke.invalidParams(void 0,"Invalid scope for provider connect")}}function yxt(e,t){let n=e;for(let o of t.split(".")){if(!n||typeof n!="object"||Array.isArray(n))return;n=n[o]}if(typeof n=="string"||typeof n=="number"||typeof n=="boolean"||Array.isArray(n))return n}function NK(e){let t={};for(let n of ILe){let o=yxt(e,n);o!==void 0&&(t[n]=o)}return t}function Ixt(e,t){let n=yLe[e];switch(n.type){case"boolean":if(typeof t!="boolean")throw ke.invalidParams(void 0,`${e} must be a boolean`);return t;case"number":if(typeof t!="number"||!Number.isFinite(t))throw ke.invalidParams(void 0,`${e} must be a number`);if(n.min!==void 0&&t<n.min)throw ke.invalidParams(void 0,`${e} must be at least ${n.min}`);return t;case"enum":{let o=n.values;if(typeof t!="string"||!o?.includes(t))throw ke.invalidParams(void 0,`${e} must be one of ${o?.join(", ")}`);return t}case"string":{if(t===void 0)return;if(typeof t!="string")throw ke.invalidParams(void 0,`${e} must be a string`);let o=/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g;return t.replace(o," ").trim()||void 0}default:throw ke.invalidParams(void 0,`${e} has an unsupported setting type`)}}function Rg(e){if(e!==void 0){if(!Array.isArray(e))throw ke.invalidParams(void 0,"Expected an array of strings");return e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean)}}function WD(e){if(e===void 0)return;let t=Hr(e),n={};for(let[o,r]of Object.entries(t))typeof r=="string"&&o.trim()&&(n[o.trim()]=r);return n}function Xk(e){if(e==null||e==="")return;let t=typeof e=="number"?e:Number.parseInt(String(e),10);if(!Number.isFinite(t)||t<=0)throw ke.invalidParams(void 0,"Expected a positive number");return t}function Dxt(e){let t=Hr(e),n=t.transport;if(n!=="stdio"&&n!=="http"&&n!=="sse")throw ke.invalidParams(void 0,"MCP transport must be stdio, http, or sse");let o={transport:n},r=t.description;typeof r=="string"&&r.trim()&&(o.description=r.trim());let s=t.cwd;typeof s=="string"&&s.trim()&&(o.cwd=s.trim());let i=Xk(t.timeout);if(i!==void 0&&(o.timeout=i),typeof t.trust=="boolean"&&(o.trust=t.trust),o.includeTools=Rg(t.includeTools),o.excludeTools=Rg(t.excludeTools),n==="stdio"){let c=t.command;if(typeof c!="string"||!c.trim())throw ke.invalidParams(void 0,"Stdio MCP servers require a command");return o.command=c.trim(),o.args=Rg(t.args),o.env=WD(t.env),o}let l=t[n==="http"?"httpUrl":"url"];if(typeof l!="string"||!l.trim())throw ke.invalidParams(void 0,`${n.toUpperCase()} MCP servers require a URL`);return n==="http"?o.httpUrl=l.trim():o.url=l.trim(),o.headers=WD(t.headers),o}function Bxt(e){let t={};for(let n of["timeout","trust","description","includeTools","excludeTools"])e[n]!==void 0&&(t[n]=e[n]);return e.transport==="stdio"?(t.command=e.command,e.args!==void 0&&(t.args=e.args),e.cwd!==void 0&&(t.cwd=e.cwd),e.env!==void 0&&(t.env=e.env)):e.transport==="http"?(t.httpUrl=e.httpUrl,e.headers!==void 0&&(t.headers=e.headers)):(t.url=e.url,e.headers!==void 0&&(t.headers=e.headers)),t}function Sxt(e){let t=Hr(e);if(typeof t.httpUrl=="string")return{transport:"http",httpUrl:t.httpUrl,headers:WD(t.headers),timeout:Xk(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:Rg(t.includeTools),excludeTools:Rg(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0};if(typeof t.url=="string")return{transport:"sse",url:t.url,headers:WD(t.headers),timeout:Xk(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:Rg(t.includeTools),excludeTools:Rg(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0};if(typeof t.command=="string")return{transport:"stdio",command:t.command,args:Rg(t.args),cwd:typeof t.cwd=="string"?t.cwd:void 0,env:WD(t.env),timeout:Xk(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:Rg(t.includeTools),excludeTools:Rg(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0}}var ZG="__redacted__";function xxt(e){let t=n=>n&&Object.fromEntries(Object.keys(n).map(o=>[o,ZG]));return{...e,env:t(e.env),headers:t(e.headers)}}function wxt(e,t){let n=(o,r)=>{if(!o)return o;let s=Hr(r),i={};for(let[a,l]of Object.entries(o)){if(l!==ZG){i[a]=l;continue}let c=s[a];typeof c=="string"&&(i[a]=c)}return i};return{...e,env:n(e.env,t.env),headers:n(e.headers,t.headers)}}function gLe(e){return e&&Object.fromEntries(Object.keys(e).map(t=>[t,ZG]))}function mLe(e,t){if(!e)return e;let n=Hr(t),o={};for(let[r,s]of Object.entries(e)){if(s!==ZG){o[r]=s;continue}let i=n[r];typeof i=="string"&&(o[r]=i)}return o}function bxt(e){return{...e,hooks:e.hooks.map(t=>({...t,...t.env?{env:gLe(t.env)}:{},...t.headers?{headers:gLe(t.headers)}:{}}))}}function Txt(e,t){let n=Array.isArray(t.hooks)?t.hooks:[];return{...e,hooks:e.hooks.map((o,r)=>{let s=Hr(n[r]);return{...o,...o.env?{env:mLe(o.env,s.env)}:{},...o.headers?{headers:mLe(o.headers,s.headers)}:{}}})}}function Kk(e,t){let n=Hr(e.mcpServers);return Object.entries(n).map(([o,r])=>{try{let s=Sxt(r);return s?{name:o,scope:t,server:xxt(s)}:void 0}catch(s){Xn.warn(`Skipping malformed MCP server config [${t}:${o}]:`,s);return}}).filter(o=>!!o)}function fLe(e){return typeof e=="string"&&DLe.includes(e)}function Qxt(e){let t=Hr(e),n=t.type;if(n!=="command"&&n!=="http")throw ke.invalidParams(void 0,"Hook type must be command or http");let o={type:n};if(n==="command"){let s=t.command;if(typeof s!="string"||!s.trim())throw ke.invalidParams(void 0,"Command hooks require a command");o.command=s.trim(),o.env=WD(t.env),typeof t.async=="boolean"&&(o.async=t.async);let i=t.shell;(i==="bash"||i==="powershell")&&(o.shell=i)}else{let s=t.url;if(typeof s!="string"||!s.trim())throw ke.invalidParams(void 0,"HTTP hooks require a URL");o.url=s.trim(),o.headers=WD(t.headers),o.allowedEnvVars=Rg(t.allowedEnvVars),typeof t.once=="boolean"&&(o.once=t.once)}let r=Xk(t.timeout);r!==void 0&&(o.timeout=r);for(let s of["name","description","statusMessage"]){let i=t[s];typeof i=="string"&&i.trim()&&(o[s]=i.trim())}return o}function kLe(e){let t=Hr(e),n=t.hooks;if(!Array.isArray(n)||n.length===0)throw ke.invalidParams(void 0,"Hook definition requires at least one hook");let o={hooks:n.map(Qxt)};return typeof t.matcher=="string"&&(o.matcher=t.matcher),typeof t.sequential=="boolean"&&(o.sequential=t.sequential),o}function zk(e,t,n){let o=Hr(e.hooks),r=[];for(let s of DLe){let i=o[s];Array.isArray(i)&&i.forEach((a,l)=>{try{r.push({event:s,scope:t,index:l,hook:bxt(kLe(a)),extensionName:n})}catch(c){Xn.warn(`Skipping malformed hook entry [${t}:${s}:${l}]:`,c)}})}return r}function GD(e){if(e==="workspace")return"Workspace";if(e==="user")return"User";throw ke.invalidParams(void 0,"scope must be user or workspace")}function KG(e,t){return e.forScope(GD(t)).settings}async function pLe(e,t){for(let n of Gu()){let o=Yo.join(e,n);try{return await sl.access(o),o}catch{}}return Yo.join(e,t)}async function vxt(e){let t=Gu()[0]??"MATILDA.md",n=await pLe(Mt.getGlobalMatildaDir(),t),o=await pLe(e.cwd,t),r=dh(e.projectRoot);return{userMemoryFile:n,projectMemoryFile:o,autoMemoryDir:r}}async function FLe(e,t,n){await e.initialize({skipGeminiInitialization:!0,skipMcpDiscovery:!0});let o=CLe.toWeb(process.stdout),r=hLe.toWeb(process.stdin);console.log=console.error,console.info=console.error,console.debug=console.error;let s=uee(o,r),i,a=new dee(y=>(i=new LK(e,t,n,y),i),s),l=async y=>{if(i)try{await i.shutdownMcpPool(8e3)}catch(D){Xn.error(`[ACP] MCP pool drain (${y}) error:`,D)}},c=!1,u=!1,A=async y=>{if(u)return;u=!0;let D=new Set([e]),S=i?.getActiveSessions();if(S)for(let w of S){let x=w.getConfig?.();x&&D.add(x)}for(let w of D){let x=w.getHookSystem?.();if(!(w.getDisableAllHooks?.()||!x||!w.hasHooksForEvent?.("SessionEnd")))try{await x.fireSessionEndEvent(y)}catch(Q){Xn.warn(`SessionEnd hook failed: ${Q instanceof Error?Q.message:String(Q)}`)}}},h=async()=>{if(c)return;c=!0,Xn.debug("[ACP] Shutdown signal received, closing streams"),await A("other");let y=i?.disposeSessions();try{process.stdin.destroy()}catch{}try{process.stdout.destroy()}catch{}await l("signal"),await y,La().catch(D=>{Xn.error("[ACP] Cleanup error:",D)}).finally(()=>{process.exit(0)})};process.on("SIGTERM",h),process.on("SIGINT",h),await a.closed,await A("prompt_input_exit");let m=i?.disposeSessions();await l("ide_close"),await m,process.off("SIGTERM",h),process.off("SIGINT",h)}function Rxt(e){if("command"in e&&"args"in e&&"env"in e)return e}function Mxt(e){if("type"in e&&e.type==="sse")return e}function kxt(e){if("type"in e&&e.type==="http")return e}function Fxt(e){if(!e||!e.trim())return q3;let t=new Set(["stdio","websocket","http","sse"]),n=new Set;for(let o of e.split(",")){let r=o.trim().toLowerCase();t.has(r)&&n.add(r)}return n.size>0?n:q3}function Nxt(e){if(!e)return 3e4;let t=e.trim();if(!/^\d+$/.test(t))return process.stderr.write(`matilda serve: MATILDA_SERVE_MCP_POOL_DRAIN_MS=${JSON.stringify(e)} is not a valid integer; using default 30000ms.
|
|
970
|
-
`),3e4;let n=Number.parseInt(t,10);return Number.isFinite(n)?Math.min(6e5,Math.max(1e3,n)):3e4}function _xt(e){let t=process.env.MATILDA_SERVE_MCP_CLIENT_BUDGET,n=process.env.MATILDA_SERVE_MCP_BUDGET_MODE,o=t!==void 0&&t!==""?Number(t):void 0,r=n==="enforce"||n==="warn"||n==="off"?n:o!==void 0&&Number.isFinite(o)&&Number.isInteger(o)&&o>0?"warn":"off";if(!(r==="off"||o===void 0||!Number.isFinite(o)||!Number.isInteger(o)||o<=0))return new CZ({clientBudget:o,mode:r,onEvent:e})}var LK=class{constructor(t,n,o,r){this.config=t;this.settings=n;this.argv=o;this.connection=r;process.env.MATILDA_SERVE_NO_MCP_POOL==="1"?(this.mcpPool=void 0,this.workspaceMcpBudget=void 0):(this.workspaceMcpBudget=_xt(s=>{this.broadcastBudgetEvent(s)}),this.mcpPool=new hZ(this.config,{workspaceContext:this.config.getWorkspaceContext(),debugMode:this.config.getDebugMode(),pooledTransports:Fxt(process.env.MATILDA_SERVE_MCP_POOL_TRANSPORTS),drainDelayMs:Nxt(process.env.MATILDA_SERVE_MCP_POOL_DRAIN_MS),budget:this.workspaceMcpBudget}))}sessions=new Map;sessionRestoreCompletions=new Map;clientCapabilities;transcriptReadNegotiated=!1;transcriptChangedNegotiated=!1;backgroundExecutionNegotiated=!1;sessionStateNegotiated=!1;mcpPool;workspaceMcpBudget;getActiveSessions(){return[...this.sessions.values()]}async shutdownMcpPool(t=1e4){if(this.mcpPool)try{let n=await this.mcpPool.drainAll({force:!0,timeoutMs:t});(n.forced>0||n.errors.length>0)&&Xn.warn(`MCP pool drain: ${n.drained} clean, ${n.forced} timed out, ${n.errors.length} errors`)}catch(n){Xn.error(`MCP pool drainAll failed: ${n instanceof Error?n.message:String(n)}`)}}async closeStoredSession(t){let n=this.sessions.get(t);if(!n){this.mcpPool?.releaseSession(t);return}await n.shutdown();try{await n.getConfig().getToolRegistry()?.stop()}catch(o){Xn.debug(`Session ${t} tool registry stop during close failed: ${o instanceof Error?o.message:String(o)}`)}yf(n.getConfig(),t,{persist:!1}),this.mcpPool?.releaseSession(t),kr.removeSession(t),this.sessions.delete(t)}async disposeSessions(){let t=await Promise.allSettled([...this.sessions.keys()].map(n=>this.closeStoredSession(n)));for(let n of t)n.status==="rejected"&&Xn.debug(`Session shutdown failed: ${n.reason instanceof Error?n.reason.message:String(n.reason)}`)}effectiveSettings(t=this.settings){return PR(t.merged,this.argv.channel)}getWorkspaceMcpBudget(){return this.workspaceMcpBudget}broadcastBudgetEvent(t){let n=Array.from(this.sessions.keys());for(let o of n)this.connection.extNotification("matilda/notify/session/mcp-budget-event",{v:1,sessionId:o,scope:"workspace",...t}).catch(r=>{Xn.debug(`MCP workspace budget event delivery to session ${o} failed (kind=${t.kind}): ${r instanceof Error?r.message:String(r)}`)})}async initialize(t){this.clientCapabilities=t.clientCapabilities;let n=t.clientCapabilities?._meta?.[ELe];this.transcriptReadNegotiated=!!n&&typeof n=="object"&&!Array.isArray(n)&&n.transcriptRead===kK,this.transcriptChangedNegotiated=this.transcriptReadNegotiated&&n.transcriptChanged===jG,this.backgroundExecutionNegotiated=!!n&&typeof n=="object"&&!Array.isArray(n)&&n.backgroundExecution===1,this.sessionStateNegotiated=this.transcriptReadNegotiated&&n.sessionState===1;let o=xK({channel:this.config.getChannel(),openAIRequestProfile:FK(this.config)});return{protocolVersion:cee,agentInfo:{name:"matilda-code",title:"Matilda",version:"0.21.10-nightly.20261007.eb073eef7"},authMethods:o,agentCapabilities:{...this.transcriptReadNegotiated||this.backgroundExecutionNegotiated?{_meta:{matilda:{...this.transcriptReadNegotiated?{transcriptRead:kK}:{},...this.transcriptChangedNegotiated?{transcriptChanged:jG}:{},...this.backgroundExecutionNegotiated?{backgroundExecution:1}:{},...this.sessionStateNegotiated?{sessionState:1}:{}}}}:{},loadSession:!0,promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},sessionCapabilities:{list:{},resume:{}},mcpCapabilities:{sse:!0,http:!0}}}}async authenticate({methodId:t}){let n=Kn.nativeEnum(ea).parse(t),o,r=s=>{o=s.verification_uri_complete,this.connection.extNotification("authenticate/update",{_meta:{authUri:o}})};n==="matilda-oauth"&&Ef.once("auth-uri",r),await gz();try{await this.config.refreshAuth(n),this.settings.setValue("User","security.auth.selectedType",n)}finally{n==="matilda-oauth"&&Ef.off("auth-uri",r)}}async newSession({cwd:t,mcpServers:n}){let o=await this.newSessionConfig(t,n);await this.ensureAuthenticated(o),this.setupFileSystem(o);let r=await this.createAndStoreSession(o),s=this.buildAvailableModels(o),i=this.buildModesData(o),a=this.buildConfigOptions(o);return{sessionId:r.getId(),models:s,modes:i,configOptions:a}}async loadSession(t){return this.restoreSession(t,!0)}async unstable_resumeSession(t){return this.restoreSession(t,!1)}async restoreSession(t,n){let o=this.sessionRestoreCompletions.get(t.sessionId),r,s=new Promise(i=>{r=i});this.sessionRestoreCompletions.set(t.sessionId,s);try{await o;let i=kSt(t),a=FSt(i);if(!await new Li(i,a).sessionExists(t.sessionId))throw ke.resourceNotFound(`session:${t.sessionId}`);let c=this.sessions.get(t.sessionId);c&&(await c.shutdown(),this.sessions.delete(t.sessionId));let u=await this.newSessionConfig(t.cwd,t.mcpServers??[],t.sessionId,!0,i,a),A;try{await this.ensureAuthenticated(u),this.setupFileSystem(u),A=await this.createAndStoreSession(u,n?u.getResumedSessionData()?.conversation:void 0)}catch(h){throw await u.getChatRecordingService()?.releaseTranscriptOwnership().catch(()=>{}),h}return await this.#e(u,A),{modes:this.buildModesData(u),models:this.buildAvailableModels(u),configOptions:this.buildConfigOptions(u)}}finally{r(),this.sessionRestoreCompletions.get(t.sessionId)===s&&this.sessionRestoreCompletions.delete(t.sessionId)}}async#e(t,n){try{let o=t.getSessionService().getWorktreeSessionPath(t.getSessionId()),r=await VB(o);r.contextMessage&&(n.pendingWorktreeNotice=r.contextMessage)}catch(o){Xn.warn(`ACP worktree restore failed: ${o}`)}}async unstable_listSessions(t){let n=t.cwd||process.cwd(),o=t._meta?.size,r=typeof o=="number"&&o>0?Math.floor(o):void 0,s=await HD(this.settings,n,()=>new Li(n).listSessions({cursor:t.cursor??void 0,size:r}));return{sessions:s.items.map(a=>({_meta:{createdAt:a.startTime,startTime:a.startTime,preview:a.prompt,...a.gitBranch?{gitBranch:a.gitBranch}:{},...a.titleSource?{titleSource:a.titleSource}:{}},cwd:a.cwd,sessionId:a.sessionId,title:a.customTitle||a.prompt||"(session)",updatedAt:a.lastMessageAt!==void 0?new Date(a.lastMessageAt).toISOString():a.startTime})),nextCursor:s.nextCursor!=null?String(s.nextCursor):void 0}}async setSessionMode(t){let n=this.sessions.get(t.sessionId);if(!n)throw ke.invalidParams(void 0,`Session not found for id: ${t.sessionId}`);return n.setMode(t)}async unstable_setSessionModel(t){let n=this.sessions.get(t.sessionId);if(!n)throw ke.invalidParams(void 0,`Session not found for id: ${t.sessionId}`);return await n.setModel(t)}async setSessionConfigOption(t){let{sessionId:n,configId:o,value:r}=t,s=this.sessions.get(n);if(!s)throw ke.invalidParams(void 0,`Session not found for id: ${n}`);switch(o){case"mode":{await this.setSessionMode({sessionId:n,modeId:r});break}case"model":{await s.setModel({sessionId:n,modelId:r},{persistDefault:!1});break}default:throw ke.invalidParams(void 0,`Unsupported configId: ${o}`)}return{configOptions:this.buildConfigOptions(s.getConfig())}}async prompt(t){let n=this.sessions.get(t.sessionId);if(!n)throw new Error(`Session not found: ${t.sessionId}`);try{return await n.prompt(t)}catch(o){throw o instanceof qF?new ke(o.status,o.message,{code:o.code}):o}}async cancel(t){let n=this.sessions.get(t.sessionId);if(!n)throw new Error(`Session not found: ${t.sessionId}`);await n.cancelPendingPrompt()}loadPermissionSettings(t){return this.settings=on(t),this.settings}buildPermissionSettings(t){return{user:{path:t.user.path,rules:Vk(t.user.settings)},workspace:{path:t.workspace.path,rules:Vk(t.workspace.settings)},merged:Vk(t.merged),isTrusted:t.isTrusted}}async buildCoreSettings(t,n){let o=t.user.settings,r=t.workspace.settings,s=this.effectiveSettings(t),i=[];try{let m=new Yl({workspaceDir:n,isWorkspaceTrusted:t.isTrusted});await m.refreshCache(),i=m.getLoadedExtensions()}catch(m){Xn.warn("Extension loading failed, continuing without extensions:",m)}let a=await Promise.all(i.map(async m=>{let y=await $B(m.config,m.id,"user"),D=await $B(m.config,m.id,"workspace"),S=m.settings??[];return{id:m.id,name:m.name,version:m.version,isActive:m.isActive,path:m.path,commands:m.commands??[],skills:(m.skills??[]).map(w=>w.name),mcpServers:Object.keys(m.config.mcpServers??{}),settings:S.map(w=>{let x=y[w.envVar],T=D[w.envVar],Q=T!==void 0,v=x!==void 0,F=Q?T:x,H=Q?"workspace":v?"user":void 0;return{name:w.name,description:w.description,envVar:w.envVar,sensitive:!!w.sensitive,userValue:w.sensitive?void 0:x,workspaceValue:w.sensitive?void 0:T,effectiveValue:w.sensitive?void 0:F,effectiveScope:H,hasUserValue:v,hasWorkspaceValue:Q}})}})),l=i.filter(m=>m.isActive),c=l.flatMap(m=>Kk({mcpServers:m.config.mcpServers??{}},"extension").map(y=>({...y,server:{...y.server,extensionName:m.name}}))),u=l.flatMap(m=>zk({hooks:m.hooks??{}},"extension",m.name)),A=new Map;for(let m of Kk(o,"user"))A.set(m.name,m);if(t.isTrusted)for(let m of Kk(r,"workspace"))A.set(m.name,m);let h=[...zk(o,"user"),...t.isTrusted?zk(r,"workspace"):[]];return{user:{path:t.user.path,values:NK(o),mcpServers:Kk(o,"user"),hooks:zk(o,"user")},workspace:{path:t.workspace.path,values:NK(r),mcpServers:Kk(r,"workspace"),hooks:zk(r,"workspace")},merged:{values:NK(s),mcpServers:[...A.values(),...c],hooks:[...h,...u]},extensions:a,isTrusted:t.isTrusted}}syncLivePermissionManagers(t,n){for(let o of _St){let r=new Set(t[o]),s=new Set(n[o]),i=t[o].filter(l=>!s.has(l)),a=n[o].filter(l=>!r.has(l));if(!(i.length===0&&a.length===0))for(let l of this.sessions.values()){let c=l.getConfig().getPermissionManager?.();if(c)try{for(let u of i)c.removePersistentRule(u,o);for(let u of a)c.addPersistentRule(u,o)}catch(u){Xn.warn(`Failed to sync permission rules to a live session: ${u instanceof Error?u.message:String(u)}`)}}}}workspaceCwd(t){return t.getTargetDir()}safeWorkspaceCwd(t){try{return this.workspaceCwd(t)}catch{return""}}mcpTransport(t){if(!t||typeof t!="object")return"unknown";let n=t;return n.type==="sdk"?"sdk":typeof n.httpUrl=="string"?"http":typeof n.url=="string"?"sse":typeof n.tcp=="string"?"websocket":typeof n.command=="string"?"stdio":"unknown"}mcpStatus(t){switch(t){case"connected":return"connected";case"connecting":return"connecting";case"disconnected":default:return"disconnected"}}mcpCellStatus(t,n){if(n)return"disabled";switch(t){case"connected":return"ok";case"connecting":return"warning";case"disconnected":default:return"error"}}discoveryState(){switch(KX()){case"in_progress":return"in_progress";case"completed":return"completed";case"not_started":default:return"not_started"}}async buildWorkspaceMcpStatus(t){try{let n=this.workspaceCwd(t),r=on(t.getTargetDir()).forScope("Workspace").settings,s=t.getMcpServers()??{},i={};try{let y=this.mcpPool?.getSnapshot();y&&(i=y.byName)}catch(y){process.stderr.write(`matilda serve: pool snapshot for workspace MCP status failed: ${y instanceof Error?y.message:String(y)}
|
|
970
|
+
`),3e4;let n=Number.parseInt(t,10);return Number.isFinite(n)?Math.min(6e5,Math.max(1e3,n)):3e4}function _xt(e){let t=process.env.MATILDA_SERVE_MCP_CLIENT_BUDGET,n=process.env.MATILDA_SERVE_MCP_BUDGET_MODE,o=t!==void 0&&t!==""?Number(t):void 0,r=n==="enforce"||n==="warn"||n==="off"?n:o!==void 0&&Number.isFinite(o)&&Number.isInteger(o)&&o>0?"warn":"off";if(!(r==="off"||o===void 0||!Number.isFinite(o)||!Number.isInteger(o)||o<=0))return new CZ({clientBudget:o,mode:r,onEvent:e})}var LK=class{constructor(t,n,o,r){this.config=t;this.settings=n;this.argv=o;this.connection=r;process.env.MATILDA_SERVE_NO_MCP_POOL==="1"?(this.mcpPool=void 0,this.workspaceMcpBudget=void 0):(this.workspaceMcpBudget=_xt(s=>{this.broadcastBudgetEvent(s)}),this.mcpPool=new hZ(this.config,{workspaceContext:this.config.getWorkspaceContext(),debugMode:this.config.getDebugMode(),pooledTransports:Fxt(process.env.MATILDA_SERVE_MCP_POOL_TRANSPORTS),drainDelayMs:Nxt(process.env.MATILDA_SERVE_MCP_POOL_DRAIN_MS),budget:this.workspaceMcpBudget}))}sessions=new Map;sessionRestoreCompletions=new Map;clientCapabilities;transcriptReadNegotiated=!1;transcriptChangedNegotiated=!1;backgroundExecutionNegotiated=!1;sessionStateNegotiated=!1;mcpPool;workspaceMcpBudget;getActiveSessions(){return[...this.sessions.values()]}async shutdownMcpPool(t=1e4){if(this.mcpPool)try{let n=await this.mcpPool.drainAll({force:!0,timeoutMs:t});(n.forced>0||n.errors.length>0)&&Xn.warn(`MCP pool drain: ${n.drained} clean, ${n.forced} timed out, ${n.errors.length} errors`)}catch(n){Xn.error(`MCP pool drainAll failed: ${n instanceof Error?n.message:String(n)}`)}}async closeStoredSession(t){let n=this.sessions.get(t);if(!n){this.mcpPool?.releaseSession(t);return}await n.shutdown();try{await n.getConfig().getToolRegistry()?.stop()}catch(o){Xn.debug(`Session ${t} tool registry stop during close failed: ${o instanceof Error?o.message:String(o)}`)}yf(n.getConfig(),t,{persist:!1}),this.mcpPool?.releaseSession(t),kr.removeSession(t),this.sessions.delete(t)}async disposeSessions(){let t=await Promise.allSettled([...this.sessions.keys()].map(n=>this.closeStoredSession(n)));for(let n of t)n.status==="rejected"&&Xn.debug(`Session shutdown failed: ${n.reason instanceof Error?n.reason.message:String(n.reason)}`)}effectiveSettings(t=this.settings){return PR(t.merged,this.argv.channel)}getWorkspaceMcpBudget(){return this.workspaceMcpBudget}broadcastBudgetEvent(t){let n=Array.from(this.sessions.keys());for(let o of n)this.connection.extNotification("matilda/notify/session/mcp-budget-event",{v:1,sessionId:o,scope:"workspace",...t}).catch(r=>{Xn.debug(`MCP workspace budget event delivery to session ${o} failed (kind=${t.kind}): ${r instanceof Error?r.message:String(r)}`)})}async initialize(t){this.clientCapabilities=t.clientCapabilities;let n=t.clientCapabilities?._meta?.[ELe];this.transcriptReadNegotiated=!!n&&typeof n=="object"&&!Array.isArray(n)&&n.transcriptRead===kK,this.transcriptChangedNegotiated=this.transcriptReadNegotiated&&n.transcriptChanged===jG,this.backgroundExecutionNegotiated=!!n&&typeof n=="object"&&!Array.isArray(n)&&n.backgroundExecution===1,this.sessionStateNegotiated=this.transcriptReadNegotiated&&n.sessionState===1;let o=xK({channel:this.config.getChannel(),openAIRequestProfile:FK(this.config)});return{protocolVersion:cee,agentInfo:{name:"matilda-code",title:"Matilda",version:"0.21.10-preview.0"},authMethods:o,agentCapabilities:{...this.transcriptReadNegotiated||this.backgroundExecutionNegotiated?{_meta:{matilda:{...this.transcriptReadNegotiated?{transcriptRead:kK}:{},...this.transcriptChangedNegotiated?{transcriptChanged:jG}:{},...this.backgroundExecutionNegotiated?{backgroundExecution:1}:{},...this.sessionStateNegotiated?{sessionState:1}:{}}}}:{},loadSession:!0,promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},sessionCapabilities:{list:{},resume:{}},mcpCapabilities:{sse:!0,http:!0}}}}async authenticate({methodId:t}){let n=Kn.nativeEnum(ea).parse(t),o,r=s=>{o=s.verification_uri_complete,this.connection.extNotification("authenticate/update",{_meta:{authUri:o}})};n==="matilda-oauth"&&Ef.once("auth-uri",r),await gz();try{await this.config.refreshAuth(n),this.settings.setValue("User","security.auth.selectedType",n)}finally{n==="matilda-oauth"&&Ef.off("auth-uri",r)}}async newSession({cwd:t,mcpServers:n}){let o=await this.newSessionConfig(t,n);await this.ensureAuthenticated(o),this.setupFileSystem(o);let r=await this.createAndStoreSession(o),s=this.buildAvailableModels(o),i=this.buildModesData(o),a=this.buildConfigOptions(o);return{sessionId:r.getId(),models:s,modes:i,configOptions:a}}async loadSession(t){return this.restoreSession(t,!0)}async unstable_resumeSession(t){return this.restoreSession(t,!1)}async restoreSession(t,n){let o=this.sessionRestoreCompletions.get(t.sessionId),r,s=new Promise(i=>{r=i});this.sessionRestoreCompletions.set(t.sessionId,s);try{await o;let i=kSt(t),a=FSt(i);if(!await new Li(i,a).sessionExists(t.sessionId))throw ke.resourceNotFound(`session:${t.sessionId}`);let c=this.sessions.get(t.sessionId);c&&(await c.shutdown(),this.sessions.delete(t.sessionId));let u=await this.newSessionConfig(t.cwd,t.mcpServers??[],t.sessionId,!0,i,a),A;try{await this.ensureAuthenticated(u),this.setupFileSystem(u),A=await this.createAndStoreSession(u,n?u.getResumedSessionData()?.conversation:void 0)}catch(h){throw await u.getChatRecordingService()?.releaseTranscriptOwnership().catch(()=>{}),h}return await this.#e(u,A),{modes:this.buildModesData(u),models:this.buildAvailableModels(u),configOptions:this.buildConfigOptions(u)}}finally{r(),this.sessionRestoreCompletions.get(t.sessionId)===s&&this.sessionRestoreCompletions.delete(t.sessionId)}}async#e(t,n){try{let o=t.getSessionService().getWorktreeSessionPath(t.getSessionId()),r=await VB(o);r.contextMessage&&(n.pendingWorktreeNotice=r.contextMessage)}catch(o){Xn.warn(`ACP worktree restore failed: ${o}`)}}async unstable_listSessions(t){let n=t.cwd||process.cwd(),o=t._meta?.size,r=typeof o=="number"&&o>0?Math.floor(o):void 0,s=await HD(this.settings,n,()=>new Li(n).listSessions({cursor:t.cursor??void 0,size:r}));return{sessions:s.items.map(a=>({_meta:{createdAt:a.startTime,startTime:a.startTime,preview:a.prompt,...a.gitBranch?{gitBranch:a.gitBranch}:{},...a.titleSource?{titleSource:a.titleSource}:{}},cwd:a.cwd,sessionId:a.sessionId,title:a.customTitle||a.prompt||"(session)",updatedAt:a.lastMessageAt!==void 0?new Date(a.lastMessageAt).toISOString():a.startTime})),nextCursor:s.nextCursor!=null?String(s.nextCursor):void 0}}async setSessionMode(t){let n=this.sessions.get(t.sessionId);if(!n)throw ke.invalidParams(void 0,`Session not found for id: ${t.sessionId}`);return n.setMode(t)}async unstable_setSessionModel(t){let n=this.sessions.get(t.sessionId);if(!n)throw ke.invalidParams(void 0,`Session not found for id: ${t.sessionId}`);return await n.setModel(t)}async setSessionConfigOption(t){let{sessionId:n,configId:o,value:r}=t,s=this.sessions.get(n);if(!s)throw ke.invalidParams(void 0,`Session not found for id: ${n}`);switch(o){case"mode":{await this.setSessionMode({sessionId:n,modeId:r});break}case"model":{await s.setModel({sessionId:n,modelId:r},{persistDefault:!1});break}default:throw ke.invalidParams(void 0,`Unsupported configId: ${o}`)}return{configOptions:this.buildConfigOptions(s.getConfig())}}async prompt(t){let n=this.sessions.get(t.sessionId);if(!n)throw new Error(`Session not found: ${t.sessionId}`);try{return await n.prompt(t)}catch(o){throw o instanceof qF?new ke(o.status,o.message,{code:o.code}):o}}async cancel(t){let n=this.sessions.get(t.sessionId);if(!n)throw new Error(`Session not found: ${t.sessionId}`);await n.cancelPendingPrompt()}loadPermissionSettings(t){return this.settings=on(t),this.settings}buildPermissionSettings(t){return{user:{path:t.user.path,rules:Vk(t.user.settings)},workspace:{path:t.workspace.path,rules:Vk(t.workspace.settings)},merged:Vk(t.merged),isTrusted:t.isTrusted}}async buildCoreSettings(t,n){let o=t.user.settings,r=t.workspace.settings,s=this.effectiveSettings(t),i=[];try{let m=new Yl({workspaceDir:n,isWorkspaceTrusted:t.isTrusted});await m.refreshCache(),i=m.getLoadedExtensions()}catch(m){Xn.warn("Extension loading failed, continuing without extensions:",m)}let a=await Promise.all(i.map(async m=>{let y=await $B(m.config,m.id,"user"),D=await $B(m.config,m.id,"workspace"),S=m.settings??[];return{id:m.id,name:m.name,version:m.version,isActive:m.isActive,path:m.path,commands:m.commands??[],skills:(m.skills??[]).map(w=>w.name),mcpServers:Object.keys(m.config.mcpServers??{}),settings:S.map(w=>{let x=y[w.envVar],T=D[w.envVar],Q=T!==void 0,v=x!==void 0,F=Q?T:x,H=Q?"workspace":v?"user":void 0;return{name:w.name,description:w.description,envVar:w.envVar,sensitive:!!w.sensitive,userValue:w.sensitive?void 0:x,workspaceValue:w.sensitive?void 0:T,effectiveValue:w.sensitive?void 0:F,effectiveScope:H,hasUserValue:v,hasWorkspaceValue:Q}})}})),l=i.filter(m=>m.isActive),c=l.flatMap(m=>Kk({mcpServers:m.config.mcpServers??{}},"extension").map(y=>({...y,server:{...y.server,extensionName:m.name}}))),u=l.flatMap(m=>zk({hooks:m.hooks??{}},"extension",m.name)),A=new Map;for(let m of Kk(o,"user"))A.set(m.name,m);if(t.isTrusted)for(let m of Kk(r,"workspace"))A.set(m.name,m);let h=[...zk(o,"user"),...t.isTrusted?zk(r,"workspace"):[]];return{user:{path:t.user.path,values:NK(o),mcpServers:Kk(o,"user"),hooks:zk(o,"user")},workspace:{path:t.workspace.path,values:NK(r),mcpServers:Kk(r,"workspace"),hooks:zk(r,"workspace")},merged:{values:NK(s),mcpServers:[...A.values(),...c],hooks:[...h,...u]},extensions:a,isTrusted:t.isTrusted}}syncLivePermissionManagers(t,n){for(let o of _St){let r=new Set(t[o]),s=new Set(n[o]),i=t[o].filter(l=>!s.has(l)),a=n[o].filter(l=>!r.has(l));if(!(i.length===0&&a.length===0))for(let l of this.sessions.values()){let c=l.getConfig().getPermissionManager?.();if(c)try{for(let u of i)c.removePersistentRule(u,o);for(let u of a)c.addPersistentRule(u,o)}catch(u){Xn.warn(`Failed to sync permission rules to a live session: ${u instanceof Error?u.message:String(u)}`)}}}}workspaceCwd(t){return t.getTargetDir()}safeWorkspaceCwd(t){try{return this.workspaceCwd(t)}catch{return""}}mcpTransport(t){if(!t||typeof t!="object")return"unknown";let n=t;return n.type==="sdk"?"sdk":typeof n.httpUrl=="string"?"http":typeof n.url=="string"?"sse":typeof n.tcp=="string"?"websocket":typeof n.command=="string"?"stdio":"unknown"}mcpStatus(t){switch(t){case"connected":return"connected";case"connecting":return"connecting";case"disconnected":default:return"disconnected"}}mcpCellStatus(t,n){if(n)return"disabled";switch(t){case"connected":return"ok";case"connecting":return"warning";case"disconnected":default:return"error"}}discoveryState(){switch(KX()){case"in_progress":return"in_progress";case"completed":return"completed";case"not_started":default:return"not_started"}}async buildWorkspaceMcpStatus(t){try{let n=this.workspaceCwd(t),r=on(t.getTargetDir()).forScope("Workspace").settings,s=t.getMcpServers()??{},i={};try{let y=this.mcpPool?.getSnapshot();y&&(i=y.byName)}catch(y){process.stderr.write(`matilda serve: pool snapshot for workspace MCP status failed: ${y instanceof Error?y.message:String(y)}
|
|
971
971
|
`)}let a,l,c,u=new Set,A="session",h=this.workspaceMcpBudget;if(h!==void 0)A="workspace",a=h.getReservedCount(),l=h.getBudget(),c=this.coerceBudgetMode(h.getMode()),u=new Set(h.getRefusedServerNames());else try{let y=t.getToolRegistry()?.getMcpClientManager();if(y){let D=y.getMcpClientAccounting();a=D.total,l=y.getMcpClientBudget(),c=y.getMcpBudgetMode(),u=new Set(D.refusedServerNames)}}catch(y){process.stderr.write(`matilda serve: getMcpClientAccounting failed: ${y instanceof Error?y.message:String(y)}
|
|
972
972
|
`)}let m=new _A;return{v:Fr,workspaceCwd:n,initialized:!0,discoveryState:this.discoveryState(),servers:await Promise.all(Object.entries(s).map(async([y,D])=>{let S=t.isMcpServerDisabled(y),w=!1;try{w=await m.getCredentials(y)!==null}catch{}let x=Rd(y),Q=u.has(y)&&!S,v={kind:"mcp_server",status:Q?"error":this.mcpCellStatus(x,S),name:y,mcpStatus:this.mcpStatus(x),transport:this.mcpTransport(D),disabled:S,hasOAuthTokens:w};Q?(v.errorKind="budget_exhausted",v.disabledReason="budget",v.hint="Raise --mcp-client-budget or remove servers from mcpServers config."):S&&(v.disabledReason="config");let F=D&&typeof D=="object"?D.description:void 0,H=D&&typeof D=="object"?D.extensionName:void 0;if(typeof F=="string"&&(v.description=F),typeof H=="string"&&(v.extensionName=H),v.source=v.extensionName?"extension":r.mcpServers?.[y]?"project":"user",D&&typeof D=="object"){let j=D,N={};if(typeof j.command=="string"&&(N.command=j.command),Array.isArray(j.args)){let W=j.args.filter(L=>typeof L=="string");W.length>0&&(N.args=W)}typeof j.httpUrl=="string"&&(N.httpUrl=j.httpUrl),typeof j.url=="string"&&(N.url=j.url),typeof j.cwd=="string"&&(N.cwd=j.cwd),Object.keys(N).length>0&&(v.config=N)}let Y=i[y];return Y&&(v.entryCount=Y.entryCount,v.entrySummary=Y.entrySummary.map(j=>({entryIndex:j.entryIndex,refs:j.refs,status:this.mcpStatus(j.status)}))),v})),...a!==void 0?{clientCount:a}:{},...l!==void 0?{clientBudget:l}:{},...c!==void 0?{budgetMode:c}:{},...c!==void 0?{budgets:this.buildBudgetCells(a??0,l,c,Array.from(u).filter(y=>!t.isMcpServerDisabled(y)).length,A)}:{}}}catch(n){return{v:Fr,workspaceCwd:this.safeWorkspaceCwd(t),initialized:!0,servers:[],errors:[this.errorCell("mcp",n)]}}}buildWorkspaceMcpToolsStatus(t,n){let o=this.safeWorkspaceCwd(t);try{let r=t.getMcpServers()??{};if(!Object.prototype.hasOwnProperty.call(r,n))return{v:Fr,workspaceCwd:o,serverName:n,initialized:!0,acpChannelLive:!0,tools:[],errors:[{kind:"mcp_tools",status:"error",error:`MCP server not configured: ${n}`}]};let s=t.getToolRegistry(),i=s?.getAllTools()??[];if(i.filter(l=>l instanceof jg&&l.serverName===n).length===0)for(let l of this.getActiveSessions()){let c=l.getConfig().getToolRegistry(),u=c?.getAllTools()??[];if(u.some(A=>A instanceof jg&&A.serverName===n)){s=c,i=u;break}}let a=i.filter(l=>l instanceof jg&&l.serverName===n).map(l=>{let c=[];l.name||c.push("missing name"),l.description||c.push("missing description");let u=l.parameterSchema&&typeof l.parameterSchema=="object"&&!Array.isArray(l.parameterSchema)?l.parameterSchema:void 0,A=l.annotations&&typeof l.annotations=="object"&&!Array.isArray(l.annotations)?l.annotations:void 0;return{name:l.name||"(unnamed)",serverToolName:l.serverToolName,description:l.description,...u?{schema:u}:{},...A?{annotations:A}:{},isValid:c.length===0,...c.length>0?{invalidReason:c.join(", ")}:{}}});return{v:Fr,workspaceCwd:o,serverName:n,initialized:!0,acpChannelLive:!0,tools:a}}catch(r){return{v:Fr,workspaceCwd:o,serverName:n,initialized:!0,acpChannelLive:!0,tools:[],errors:[this.errorCell("mcp_tools",r)]}}}buildBudgetCells(t,n,o,r,s="session"){if(o==="off")return[];let i="ok",a,l;r>0?(i="error",a="budget_exhausted",l="Raise --mcp-client-budget or remove servers from mcpServers config."):n!==void 0&&n>0&&t>=YT*n&&(i="warning",l=`Live MCP clients are above ${Math.round(YT*100)}% of the configured budget.`);let c={kind:"mcp_budget",scope:s,status:i,liveCount:t,mode:o,refusedCount:r};return n!==void 0&&(c.budget=n),a&&(c.errorKind=a),l&&(c.hint=l),[c]}coerceBudgetMode(t){return t}errorCell(t,n,o){let r=o??yh(n);return{kind:t,status:"error",error:n instanceof Error?n.message:String(n),...r?{errorKind:r}:{}}}async buildWorkspaceSkillsStatus(t){let n=t.getSkillManager();if(!n)return{v:Fr,workspaceCwd:this.workspaceCwd(t),initialized:!0,skills:[]};try{let o=await n.listSkills();return{v:Fr,workspaceCwd:this.workspaceCwd(t),initialized:!0,skills:o.map(r=>{let s=r.disableModelInvocation!==!0;return{kind:"skill",status:s?"ok":"disabled",name:r.name,description:r.description,level:r.level,modelInvocable:s,...r.argumentHint?{argumentHint:r.argumentHint}:{},...r.model?{model:r.model}:{},...r.extensionName?{extensionName:r.extensionName}:{}}})}}catch(o){return{v:Fr,workspaceCwd:this.workspaceCwd(t),initialized:!0,skills:[],errors:[this.errorCell("skills",o)]}}}buildWorkspaceProvidersStatus(t){try{let n=this.workspaceCwd(t),o=t.getAuthType?.(),r=t.getActiveRuntimeModelSnapshot?.(),s=r?r.id:(t.getModel()||"").trim(),i=s.length>0,a=r?.authType??o,l=i&&a?CE(s,a):s||void 0,c=new Map;for(let m of t.getAllConfiguredModels()){let y=String(m.authType),D=c.get(y);D||(D={kind:"model_provider",status:"ok",authType:y,current:!1,models:[]},c.set(y,D));let S=m.isRuntimeModel&&m.runtimeSnapshotId?m.runtimeSnapshotId:m.id,w=CE(S,m.authType),x=a===m.authType&&i&&(s===S||s===m.id||l===w),T={modelId:w,baseModelId:nLe(S),name:m.label,...m.description!==void 0?{description:m.description}:{},contextLimit:m.contextWindowSize??_3(S),...m.modalities!==void 0?{modalities:m.modalities}:{},...m.baseUrl!==void 0?{baseUrl:zG(m.baseUrl)}:{},...m.envKey!==void 0?{envKey:m.envKey}:{},isCurrent:x,isRuntime:m.isRuntimeModel===!0};D.models.push(T),x&&(D.current=!0)}let A=t.getContentGeneratorConfig?.()?.baseUrl||void 0,h=this.effectiveSettings().fastModel||void 0;return{v:Fr,workspaceCwd:n,initialized:!0,...a||l?{current:{...a?{authType:String(a)}:{},...l?{modelId:l}:{},...A?{baseUrl:zG(A)}:{},...h?{fastModelId:h}:{}}}:{},providers:[...c.values()]}}catch(n){return{v:Fr,workspaceCwd:this.safeWorkspaceCwd(t),initialized:!0,providers:[],errors:[this.errorCell("providers",n)]}}}async buildAcpPreflightCells(t){let n={auth:()=>this.buildAuthPreflightCell(t),mcp_discovery:()=>this.buildMcpDiscoveryPreflightCell(t),skills:()=>this.buildSkillsPreflightCell(t),providers:()=>this.buildProvidersPreflightCell(t),tool_registry:()=>this.buildToolRegistryPreflightCell(t),egress:()=>({kind:"egress",status:"not_started",locality:"acp",hint:"egress probing not yet implemented"})},o=[];for(let r of hee)o.push(await n[r]());return{cells:o}}acpCell(t,n){return{kind:t,locality:"acp",...n}}buildAuthPreflightCell(t){try{let n=t.getAuthType?.();if(!n)return this.acpCell("auth",{status:"warning",errorKind:"auth_env_error",error:"No auth method configured.",hint:"Run `matilda` and complete the auth flow, or set a provider env var.",detail:{source:"none",hasToken:!1}});let o=NSt[String(n)]??[],r=o.find(i=>!!process.env[i]),s=!!r;return o.length===0?this.acpCell("auth",{status:"unknown",hint:"Auth credentials for this provider are not env-keyed; full validation runs at session start.",detail:{source:String(n),hasToken:"unknown",envVarCandidates:[]}}):this.acpCell("auth",{status:s?"ok":"warning",...s?{}:{errorKind:"auth_env_error",error:`None of the env vars [${o.join(", ")}] is set for authType '${String(n)}'.`,hint:`Set one of: ${o.join(" / ")}.`},detail:{source:String(n),hasToken:s,envVarCandidates:o,...r?{presentVar:r}:{}}})}catch(n){let o=yh(n)??"auth_env_error";return this.acpCell("auth",{status:"error",error:n instanceof Error?n.message:String(n),errorKind:o})}}buildMcpDiscoveryPreflightCell(t){try{let n=this.discoveryState(),o=t.getMcpServers()??{},r=Object.keys(o).length,s={connected:0,connecting:0,disconnected:0,unknown:0};for(let a of Object.keys(o))switch(Rd(a)){case"connected":s.connected+=1;break;case"connecting":s.connecting+=1;break;case"disconnected":s.disconnected+=1;break;default:s.unknown+=1;break}let i={discoveryState:n,total:r,...s};return r===0?this.acpCell("mcp_discovery",{status:"ok",detail:i,hint:"No MCP servers configured."}):s.unknown>0?this.acpCell("mcp_discovery",{status:"warning",errorKind:"protocol_error",error:`${s.unknown}/${r} MCP server(s) in an unrecognized state.`,detail:i}):s.disconnected>0&&n==="completed"?this.acpCell("mcp_discovery",{status:"error",errorKind:"protocol_error",error:`${s.disconnected}/${r} MCP server(s) disconnected after discovery.`,detail:i}):s.connecting>0||n==="in_progress"?this.acpCell("mcp_discovery",{status:"warning",error:`${s.connecting}/${r} MCP server(s) still connecting.`,detail:i}):this.acpCell("mcp_discovery",{status:"ok",detail:i})}catch(n){let o=yh(n);return this.acpCell("mcp_discovery",{status:"error",error:n instanceof Error?n.message:String(n),...o?{errorKind:o}:{}})}}async buildSkillsPreflightCell(t){try{let n=t.getSkillManager();if(!n)return this.acpCell("skills",{status:"disabled",hint:"No SkillManager attached to Config; verify settings if you expected skills to load.",detail:{configured:!1}});let o=await n.listSkills();return this.acpCell("skills",{status:"ok",detail:{count:o.length}})}catch(n){let o=yh(n);return this.acpCell("skills",{status:"error",error:n instanceof Error?n.message:String(n),...o?{errorKind:o}:{}})}}buildProvidersPreflightCell(t){try{let n=t.getAllConfiguredModels(),o=t.getAuthType?.();if(n.length===0)return this.acpCell("providers",{status:o?"error":"disabled",...o?{errorKind:"auth_env_error"}:{},...o?{error:`No model configured for authType ${String(o)}.`}:{},detail:{count:0,authType:o?String(o):null}});let r=new Set(n.map(s=>String(s.authType)));return this.acpCell("providers",{status:"ok",detail:{count:n.length,providers:[...r]}})}catch(n){let o=yh(n)??"auth_env_error";return this.acpCell("providers",{status:"error",error:n instanceof Error?n.message:String(n),errorKind:o})}}buildToolRegistryPreflightCell(t){try{let n=t.getToolRegistry();if(!n)return this.acpCell("tool_registry",{status:"error",errorKind:"protocol_error",error:"Tool registry is not initialized."});let o=n.getAllTools();return this.acpCell("tool_registry",{status:"ok",detail:{count:o.length}})}catch(n){let o=yh(n)??"protocol_error";return this.acpCell("tool_registry",{status:"error",error:n instanceof Error?n.message:String(n),errorKind:o})}}buildWorkspaceToolsStatus(t){let n=this.safeWorkspaceCwd(t);try{let o=t.getToolRegistry();if(!o)return{v:Fr,workspaceCwd:n,initialized:!0,acpChannelLive:!0,tools:[],errors:[{kind:"tools",status:"error",errorKind:"protocol_error",error:"Tool registry is not initialized."}]};let r=t.getDisabledTools(),s=o.getAllTools().filter(i=>!("serverName"in i)).map(i=>({name:i.name,displayName:i.displayName,description:i.description,enabled:!r.has(i.name)}));return{v:Fr,workspaceCwd:n,initialized:!0,acpChannelLive:!0,tools:s}}catch(o){let r=yh(o)??"protocol_error";return{v:Fr,workspaceCwd:n,initialized:!0,acpChannelLive:!0,tools:[],errors:[{kind:"tools",status:"error",error:o instanceof Error?o.message:String(o),errorKind:r}]}}}sessionOrThrow(t){let n=this.sessions.get(t);if(!n)throw ke.invalidParams(void 0,`Session not found for id: ${t}`);return n}buildSessionContextStatus(t){let o=this.sessionOrThrow(t).getConfig();return{v:Fr,sessionId:t,workspaceCwd:this.workspaceCwd(o),state:{models:this.buildAvailableModels(o),modes:this.buildModesData(o),configOptions:this.buildConfigOptions(o)}}}async buildSessionContextUsageStatus(t,n){let r=this.sessionOrThrow(t).getConfig(),s;try{s=await Dee(r,n)}catch(i){console.warn("[context-usage] collectContextData failed:",i),s={type:"context_usage",modelName:r.getModel()||"unknown",totalTokens:0,contextWindowSize:0,breakdown:{systemPrompt:0,builtinTools:0,mcpTools:0,memoryFiles:0,skills:0,messages:0,freeSpace:0,autocompactBuffer:0},builtinTools:[],mcpTools:[],memoryFiles:[],skills:[],isEstimated:!0,showDetails:n}}return{v:Fr,sessionId:t,workspaceCwd:this.workspaceCwd(r),usage:{modelName:s.modelName,totalTokens:s.totalTokens,contextWindowSize:s.contextWindowSize,breakdown:s.breakdown,builtinTools:s.builtinTools,mcpTools:s.mcpTools,memoryFiles:s.memoryFiles,skills:s.skills,isEstimated:s.isEstimated,showDetails:s.showDetails},formattedText:Bee(s)}}async buildSessionSupportedCommandsStatus(t){let n=this.sessionOrThrow(t),{availableCommands:o,availableSkills:r}=await RK(n.getConfig());return{v:Fr,sessionId:t,availableCommands:o,availableSkills:r??[]}}buildSessionTasksStatus(t){let n=this.sessionOrThrow(t);return lLe(t,n.getConfig())}buildSessionStatsStatus(t){let n=this.sessionOrThrow(t),o=n.getConfig(),r=kr.getMetricsForSession(t),s=Date.now(),i=n.getCreatedAt(),a={};for(let[c,u]of Object.entries(r.models))a[c]={api:{...u.api},tokens:{...u.tokens}};let l={};for(let[c,u]of Object.entries(r.tools.byName))l[c]={count:u.count,success:u.success,fail:u.fail,durationMs:u.durationMs,decisions:{accept:u.decisions.accept,reject:u.decisions.reject,modify:u.decisions.modify,auto_accept:u.decisions.auto_accept}};return{v:Fr,sessionId:t,workspaceCwd:this.workspaceCwd(o),sessionStartTimeMs:i,durationMs:s-i,promptCount:n.getTurnCount(),models:a,tools:{totalCalls:r.tools.totalCalls,totalSuccess:r.tools.totalSuccess,totalFail:r.tools.totalFail,totalDurationMs:r.tools.totalDurationMs,byName:l},files:{totalLinesAdded:r.files.totalLinesAdded,totalLinesRemoved:r.files.totalLinesRemoved}}}serializeHookConfig(t){switch(t.type){case"command":return{type:"command",command:t.command,...t.name!==void 0?{name:t.name}:{},...t.description!==void 0?{description:t.description}:{},...t.timeout!==void 0?{timeout:t.timeout}:{},...t.env?{env:t.env}:{},...t.async!==void 0?{async:t.async}:{},...t.shell?{shell:t.shell}:{},...t.statusMessage!==void 0?{statusMessage:t.statusMessage}:{}};case"http":return{type:"http",url:t.url,...t.name!==void 0?{name:t.name}:{},...t.description!==void 0?{description:t.description}:{},...t.timeout!==void 0?{timeout:t.timeout}:{},...t.headers?{headers:t.headers}:{},...t.allowedEnvVars?{allowedEnvVars:t.allowedEnvVars}:{},...t.if!==void 0?{if:t.if}:{},...t.statusMessage!==void 0?{statusMessage:t.statusMessage}:{},...t.once!==void 0?{once:t.once}:{}};case"function":return{type:"function",...t.id!==void 0?{id:t.id}:{},...t.name!==void 0?{name:t.name}:{},...t.description!==void 0?{description:t.description}:{},...t.timeout!==void 0?{timeout:t.timeout}:{},...t.errorMessage!==void 0?{errorMessage:t.errorMessage}:{},...t.statusMessage!==void 0?{statusMessage:t.statusMessage}:{}};case"prompt":return{type:"prompt",prompt:t.prompt,...t.name!==void 0?{name:t.name}:{},...t.description!==void 0?{description:t.description}:{},...t.timeout!==void 0?{timeout:t.timeout}:{},...t.model?{model:t.model}:{},...t.statusMessage!==void 0?{statusMessage:t.statusMessage}:{}};default:return{type:t.type}}}buildWorkspaceHooksStatus(t){try{let n=this.workspaceCwd(t),o=t.getDisableAllHooks(),r=t.getHookSystem();if(!r)return{v:Fr,workspaceCwd:n,initialized:!0,disabled:o,hooks:[],events:$N};let i=r.getAllHooks().map(a=>({kind:"hook",eventName:a.eventName,config:this.serializeHookConfig(a.config),source:a.source,...a.matcher?{matcher:a.matcher}:{},...a.sequential!==void 0?{sequential:a.sequential}:{},enabled:a.enabled}));return{v:Fr,workspaceCwd:n,initialized:!0,disabled:o,hooks:i,events:$N}}catch(n){let o=!1;try{o=t.getDisableAllHooks()}catch{}return{v:Fr,workspaceCwd:this.safeWorkspaceCwd(t),initialized:!1,disabled:o,hooks:[],events:$N,errors:[this.errorCell("hooks",n)]}}}buildSessionHooksStatus(t){let o=this.sessionOrThrow(t).getConfig();try{let r=this.workspaceCwd(o),s=o.getDisableAllHooks(),i=o.getHookSystem();if(!i)return{v:Fr,sessionId:t,workspaceCwd:r,disabled:s,hooks:[]};let l=i.getSessionHooksManager().getAllSessionHooks(t).map(c=>({kind:"hook",eventName:c.eventName,config:this.serializeHookConfig(c.config),source:"session",...c.matcher?{matcher:c.matcher}:{},...c.sequential!==void 0?{sequential:c.sequential}:{},enabled:!0,hookId:c.hookId,...c.skillRoot?{skillRoot:c.skillRoot}:{}}));return{v:Fr,sessionId:t,workspaceCwd:r,disabled:s,hooks:l}}catch(r){let s=!1;try{s=o.getDisableAllHooks()}catch{}return{v:Fr,sessionId:t,workspaceCwd:this.safeWorkspaceCwd(o),disabled:s,hooks:[],errors:[this.errorCell("session_hooks",r)]}}}buildWorkspaceExtensionsStatus(t){try{let n=this.workspaceCwd(t),r=t.getExtensions().map(s=>{let i={mcpServerCount:s.mcpServers?Object.keys(s.mcpServers).length:0,skillCount:s.skills?.length??0,agentCount:s.agents?.length??0,hookCount:s.hooks?Object.values(s.hooks).reduce((a,l)=>a+(l?.length??0),0):0,commandCount:s.commands?.length??0,contextFileCount:s.contextFiles.length,channelCount:s.channels?Object.keys(s.channels).length:0,hasSettings:(s.settings?.length??0)>0};return{kind:"extension",id:s.id,name:s.name,version:s.version,isActive:s.isActive,path:s.path,...s.installMetadata?.source?{source:LA(s.installMetadata.source)}:{},...s.installMetadata?.type?{installType:s.installMetadata.type}:{},...s.installMetadata?.originSource?{originSource:s.installMetadata.originSource}:{},...s.installMetadata?.ref?{ref:s.installMetadata.ref}:{},...s.installMetadata?.autoUpdate!==void 0?{autoUpdate:s.installMetadata.autoUpdate}:{},capabilities:i}});return{v:Fr,workspaceCwd:n,initialized:!0,extensions:r}}catch(n){return{v:Fr,workspaceCwd:this.safeWorkspaceCwd(t),initialized:!1,extensions:[],errors:[this.errorCell("extensions",n)]}}}async installSkillFromUrl(t){let n=this.config.getSkillManager();if(!n)throw ke.invalidParams(void 0,"SkillManager is not available");let o=await axt(t.sourceUrl),r=Yo.join(Mt.getGlobalMatildaDir(),"skills"),s=dLe(r,t.slug),i=Yo.join(s,"SKILL.md"),a=n.parseSkillContent(o.skillContent,i,"user");if(a.name!==t.slug)throw ke.invalidParams(void 0,`Skill name "${a.name}" does not match requested slug "${t.slug}"`);let l=`${s}.installing-${process.pid}-${Date.now()}`;try{await sl.rm(l,{recursive:!0,force:!0});for(let c of o.files){let u=lxt(l,c.relativePath);await sl.mkdir(Yo.dirname(u),{recursive:!0}),await sl.writeFile(u,c.content)}await sl.rm(s,{recursive:!0,force:!0}),await sl.rename(l,s)}catch(c){throw await sl.rm(l,{recursive:!0,force:!0}).catch(()=>{}),c}return await n.refreshCache(),{id:t.id,slug:a.name,installed:!0,installedPath:i,sourceUrl:t.sourceUrl}}async deleteGlobalSkill(t){let n=this.config.getSkillManager();if(!n)throw ke.invalidParams(void 0,"SkillManager is not available");let{skillDir:o,skillFile:r,content:s}=await this.readManagedSkillFile(t.slug,"global",n),i=n.parseSkillContent(s,r,"user");if(i.name!==t.slug)throw ke.invalidParams(void 0,`Skill name "${i.name}" does not match requested slug "${t.slug}"`);let a=Yo.resolve(o),l=Yo.resolve(r),c=Yo.resolve(Mt.getGlobalMatildaDir());if(!(l===Yo.join(a,"SKILL.md"))||a===Yo.parse(a).root||a===c)throw ke.invalidParams(void 0,`Refusing to delete unexpected skill directory: ${o}`);return await sl.rm(o,{recursive:!0,force:!0}),await n.refreshCache(),{slug:t.slug,deleted:!0}}async readManagedSkillFile(t,n,o,r){if(n==="global"){let c=dLe(Yo.join(Mt.getGlobalMatildaDir(),"skills"),t),u=Yo.join(c,"SKILL.md"),A=await sl.readFile(u,"utf8").catch(()=>{});if(A!==void 0)return{skillDir:c,skillFile:u,content:A}}if(n==="project"&&r?.trim()){let c=await this.findProjectSkillFileFromCwd(t,r,o);if(c)return c}let s=n==="project"?"project":"user",a=(await o.listSkills({level:s})).find(c=>c.name===t)?.filePath;if(!a)throw ke.invalidParams(void 0,`${n==="project"?"Project":"Global"} skill not found: ${t}`);let l=await sl.readFile(a,"utf8").catch(()=>{throw ke.invalidParams(void 0,`${n==="project"?"Project":"Global"} skill not found: ${t}`)});return{skillDir:Yo.dirname(a),skillFile:a,content:l}}async findProjectSkillFileFromCwd(t,n,o){let r=Yo.resolve(n);for(let s of OSt){let i=Yo.join(r,s,PSt),c=(await o.loadSkillsFromDir(i,"project")).find(A=>A.name===t)?.filePath;if(!c)continue;let u=await sl.readFile(c,"utf8").catch(()=>{throw ke.invalidParams(void 0,`Project skill not found: ${t}`)});return{skillDir:Yo.dirname(c),skillFile:c,content:u}}}async setGlobalSkillEnabled(t,n){let o=this.config.getSkillManager();if(!o)throw ke.invalidParams(void 0,"SkillManager is not available");let{skillFile:r,content:s}=await this.readManagedSkillFile(t.slug,t.scope,o,n),i=t.scope==="project"?"project":"user",a=o.parseSkillContent(s,r,i);if(a.name!==t.slug)throw ke.invalidParams(void 0,`Skill name "${a.name}" does not match requested slug "${t.slug}"`);let l=YSt(s,t.enabled);if(o.parseSkillContent(l,r,i),Yo.basename(r)!=="SKILL.md")throw ke.invalidParams(void 0,`Refusing to write to unexpected skill file: ${r}`);return await sl.writeFile(r,l,"utf8"),await o.refreshCache(),{slug:t.slug,enabled:t.enabled,installedPath:r}}async extMethod(t,n){let o=typeof n.cwd=="string"?n.cwd:void 0,r=o||process.cwd(),s=/^[0-9a-fA-F-]{32,36}$/;switch(t){case"matilda/session/attach":{if(!this.backgroundExecutionNegotiated)throw ke.methodNotFound(t);let i=n.sessionId;if(typeof i!="string"||!s.test(i))throw ke.invalidParams(void 0,"Invalid or missing sessionId");if(this.sessionRestoreCompletions.has(i))throw new ke(-32e3,"Session restore is in progress",{errorKind:"session_busy"});let a=this.sessions.get(i);if(!a)throw ke.resourceNotFound(`session:${i}`);return a.attachClient(),{}}case"matilda/session/readState":{if(!this.sessionStateNegotiated)throw ke.methodNotFound(t);let i=n.sessionId;if(typeof i!="string"||!s.test(i))throw ke.invalidParams(void 0,"Invalid or missing sessionId");if(this.sessionRestoreCompletions.has(i))throw new ke(-32e3,"Session restore is in progress",{errorKind:"session_busy"});let a=this.sessions.get(i)?.getSessionState();if(!a)throw ke.resourceNotFound(`session:${i}`);return a}case"matilda/workspace/getRoots":{let i=typeof n.sessionId=="string"?n.sessionId:void 0,a=i?this.sessions.get(i):void 0;if(i&&!a)throw ke.invalidParams(void 0,`Unknown session: ${i}`);let l=a?.getConfig()??this.config;return{workspaceId:process.env.MATILDA_DESKTOP_WORKSPACE_ID??null,revision:process.env.MATILDA_DESKTOP_DIRECTORY_REVISION??null,canonicalRoots:l.getWorkspaceContext().getDirectories(),restrictiveSandbox:l.isRestrictiveSandbox(),sandbox:process.env.SANDBOX??null,sandboxNonce:process.env.MATILDA_DESKTOP_SANDBOX_ACTIVE??null,seatbeltProfile:process.env.SEATBELT_PROFILE??null}}case"matilda/providers/list":{let i=this.effectiveSettings();return{providers:GT.map(a=>hxt(a,i))}}case"matilda/providers/connect":{let i=Mp(n.providerId,"providerId"),a=Gz(i);if(!a)throw ke.invalidParams(void 0,`Unknown provider: ${i}`);let l=Cxt(a,n,pxt(a,this.settings.merged)),c=Ext(n.scope),u=Yg(a,l);return await mh(u,{settings:Eh(this.settings,c),reloadModelProviders:A=>{let h=PR({...this.settings.merged,modelProviders:A},this.argv.channel);this.config.reloadModelProvidersConfig(h.modelProviders)},syncAuthState:(A,h)=>this.config.getModelsConfig().syncAfterAuthRefresh(A,h),refreshAuth:A=>this.config.refreshAuth(A)}),{success:!0,providerId:a.id,providerLabel:a.label,authType:u.authType,modelId:u.modelSelection?.modelId}}case"matilda/skills/install":return this.installSkillFromUrl(HSt(n));case"matilda/skills/delete":return this.deleteGlobalSkill(GSt(n));case"matilda/skills/setEnabled":return this.setGlobalSkillEnabled(WSt(n),o);case"matilda/settings/getMemory":{let i=on(r);return this.settings=i,{settings:uLe(this.effectiveSettings(i).memory)}}case"matilda/settings/setMemory":{let i=Hr(n.updates),a=on(r);for(let l of USt)if(i[l]!==void 0){if(typeof i[l]!="boolean")throw ke.invalidParams(void 0,`Invalid memory setting '${l}': expected boolean`);a.setValue("User",`memory.${l}`,i[l])}return this.settings=a,{settings:uLe(this.effectiveSettings(a).memory)}}case"matilda/settings/getPath":return{path:this.settings.user.path};case"matilda/settings/getMemoryPaths":{let i=typeof n.projectRoot=="string"?n.projectRoot:r;return{paths:await vxt({cwd:r,projectRoot:i})}}case ql.workspaceMcp:return await this.buildWorkspaceMcpStatus(this.config);case ql.workspaceMcpTools:{let i=n.serverName;if(typeof i!="string"||i.length===0)throw ke.invalidParams(void 0,"Invalid or missing serverName");return this.buildWorkspaceMcpToolsStatus(this.config,i)}case ql.workspaceSkills:return await this.buildWorkspaceSkillsStatus(this.config);case ql.workspaceTools:return this.buildWorkspaceToolsStatus(this.config);case ql.workspaceProviders:return this.buildWorkspaceProvidersStatus(this.config);case ql.workspacePreflight:return await this.buildAcpPreflightCells(this.config);case ql.sessionContext:{let i=n.sessionId;if(typeof i!="string"||i.length===0)throw ke.invalidParams(void 0,"Invalid or missing sessionId");return this.buildSessionContextStatus(i)}case ql.sessionContextUsage:{let i=n.sessionId;if(typeof i!="string"||i.length===0)throw ke.invalidParams(void 0,"Invalid or missing sessionId");return await this.buildSessionContextUsageStatus(i,n.detail===!0)}case ql.sessionSupportedCommands:{let i=n.sessionId;if(typeof i!="string"||i.length===0)throw ke.invalidParams(void 0,"Invalid or missing sessionId");return await this.buildSessionSupportedCommandsStatus(i)}case ql.sessionTasks:{let i=n.sessionId;if(typeof i!="string"||i.length===0)throw ke.invalidParams(void 0,"Invalid or missing sessionId");return this.buildSessionTasksStatus(i)}case ql.sessionStats:{let i=n.sessionId;if(typeof i!="string"||i.length===0)throw ke.invalidParams(void 0,"Invalid or missing sessionId");return this.buildSessionStatsStatus(i)}case ql.sessionRewindSnapshots:{let i=n.sessionId;if(typeof i!="string"||!s.test(i))throw ke.invalidParams(void 0,"Invalid or missing sessionId");let a=this.sessions.get(i);if(!a)throw ke.invalidParams(void 0,`Session not found for id: ${i}`);let l=a.getConfig().getFileHistoryService(),c=l.getSnapshots(),u=i+"########";return{snapshots:await Promise.all(c.map((h,m)=>({s:h,idx:m})).filter(({s:h})=>h.promptId.startsWith(u)&&/^\d+$/.test(h.promptId.slice(u.length))).map(async({s:h,idx:m})=>{let y=await l.getDiffStats(h.promptId);return{promptId:h.promptId,turnIndex:m,timestamp:h.timestamp.toISOString(),diffStats:{filesChanged:y?.filesChanged?.length??0,insertions:y?.insertions??0,deletions:y?.deletions??0}}}))}}case ql.workspaceHooks:return this.buildWorkspaceHooksStatus(this.config);case ql.sessionHooks:{let i=n.sessionId;if(typeof i!="string"||i.length===0)throw ke.invalidParams(void 0,"Invalid or missing sessionId");return this.buildSessionHooksStatus(i)}case ql.workspaceExtensions:return this.buildWorkspaceExtensionsStatus(this.config);case Na.workspaceMcpRestart:{let i=n.serverName;if(typeof i!="string"||i.length===0)throw ke.invalidParams(void 0,"Invalid or missing serverName");let a,l=n.entryIndex;if(l!==void 0&&l!=="*"){if(typeof l!="number"||!Number.isInteger(l)||l<0)throw ke.invalidParams(void 0,'entryIndex must be a non-negative integer or "*"');a=l}let c=this.config.getMcpServers()??{};if(!Object.prototype.hasOwnProperty.call(c,i))throw new ke(-32004,`MCP server not configured: ${JSON.stringify(i)}`,{errorKind:"mcp_server_not_found",serverName:i});if(this.config.isMcpServerDisabled(i))return{serverName:i,restarted:!1,skipped:!0,reason:"disabled"};let u=this.config.getToolRegistry()?.getMcpClientManager();if(!u)throw ke.internalError(void 0,"McpClientManager unavailable on this Config");if(u.isServerDiscovering(i))return{serverName:i,restarted:!1,skipped:!0,reason:"in_flight"};let A=u.getMcpClientAccounting(),h=u.getMcpClientBudget();if(u.getMcpBudgetMode()==="enforce"&&h!==void 0&&!A.reservedSlots.includes(i)&&A.reservedSlots.length>=h)return{serverName:i,restarted:!1,skipped:!0,reason:"budget_would_exceed"};try{let Q=on(this.config.getTargetDir()).merged.tools?.disabled;Q!==void 0&&!Array.isArray(Q)&&process.stderr.write(`matilda serve: MCP restart for ${JSON.stringify(i)}: tools.disabled has unexpected type ${typeof Q}; clearing disabled set \u2014 check settings.json. Expected an array of strings.
|
|
973
973
|
`);let v=ev(Q);this.config.setDisabledTools(new Set(v))}catch(T){process.stderr.write(`matilda serve: MCP restart for ${JSON.stringify(i)} could not refresh disabledTools from merged settings (${T instanceof Error?T.message:String(T)}); proceeding with the bootstrap snapshot \u2014 recently toggled tools may not take effect until daemon restart.
|
|
@@ -989,7 +989,7 @@ Reason: ${t}${t instanceof Error&&t.stack?`
|
|
|
989
989
|
Stack trace:
|
|
990
990
|
${t.stack}`:""}`;ws.emit("log-error",o),e||(e=!0,ws.emit("open-debug-console"))})}function Yxt(e){return e==="SIGINT"?130:143}function qxt(e){let t=!1,n=s=>{process.stdin.isTTY&&process.stdin.setRawMode(e),!t&&(t=!0,La().catch(i=>{EE.error(`Error during ${s} cleanup:`,i)}).finally(()=>{process.exit(Yxt(s))}))},o=()=>{n("SIGTERM")},r=()=>{n("SIGINT")};return process.once("SIGTERM",o),process.once("SIGINT",r),()=>{process.removeListener("SIGTERM",o),process.removeListener("SIGINT",r)}}async function Jxt(e,t,n,o=process.cwd(),r){let s=await eQ();Vxt(Uxt(o),t);try{let D=e.getSessionId(),S=e.storage.getRuntimeStatusPath(D);await Lz(S,{sessionId:D,workDir:e.getTargetDir(),matildaVersion:s}),e.markRuntimeStatusEnabled()}catch{}let i=process.stdout.isTTY&&!e.getScreenReader()?z_e(process.stdout):()=>{},a=process.stdout.isTTY&&!e.getScreenReader()?X_e(process.stdout):()=>{},l=process.stdout.isTTY&&!e.getScreenReader()?RRe(process.stdout):()=>{},c=hM(e,{version:s}),u=null,A=e.getInputFile?.();if(A)try{u=new kG(A)}catch(D){EE.error("Failed to initialize remote input watcher:",D),We(`Warning: remote input disabled \u2014 ${D instanceof Error?D.message:String(D)}`)}let h=yK(),m=()=>{let D=S_e(),S=parseInt(process.versions.node.split(".")[0],10);return(0,pd.jsx)(cK.Provider,{value:u,children:(0,pd.jsx)(XP.Provider,{value:c,children:(0,pd.jsx)(kI.Provider,{value:t,children:(0,pd.jsx)(rP,{kittyProtocolEnabled:D.enabled,config:e,debugKeystrokeLogging:t.merged.general?.debugKeystrokeLogging,pasteWorkaround:process.platform==="win32"||S<20,initialCapturedInput:h,children:(0,pd.jsx)(zQe,{sessionId:e.getSessionId(),children:(0,pd.jsx)(eMe,{settings:t,children:(0,pd.jsx)(oNe,{config:e,children:(0,pd.jsx)(xFe,{config:e,children:(0,pd.jsx)(D_e,{config:e,settings:t,startupWarnings:n,version:s,initializationResult:r})})})})})})})})})},y=UQ(process.env.DEBUG?(0,pd.jsx)(_Le.default.StrictMode,{children:(0,pd.jsx)(m,{})}):(0,pd.jsx)(m,{}),{exitOnCtrlC:!1,isScreenReaderEnabled:e.getScreenReader(),maxFps:typeof t.merged.ui?.maxFps=="number"&&t.merged.ui.maxFps>0?t.merged.ui.maxFps:60});_a("first_paint"),GO().then(D=>{O1e(D,t,e.getProjectRoot())}).catch(D=>{EE.warn(`Update check failed: ${D}`)}),Md(async()=>{u?.shutdown(),await c?.shutdown(),twe(),y.unmount(),l(),a(),i()})}async function LLe(){uSe(),_a("main_entry"),Ree()&&hz((i,a)=>Qee(i,a)),jxt(),__e(),process.argv.includes("--bare")&&(process.env[K3]="1"),tee();let e=await cDe();_a("after_parse_arguments"),L_e(e)&&(rt(O_e()),process.exit(0)),iy(e.bare)&&(process.env[K3]="1");let t=iy(e.bare)?ZT():on();t.corruptedPath&&(process.env[o8]=t.corruptedPath,process.env[r8]=t.wasRecovered?"1":"0"),await Mee(),_a("after_load_settings");let n=s8(t);for(let i of n)We(i);t.corruptedPath&&We("Warning: Settings file had invalid JSON and was reset. A copy of the corrupted file has been saved at: "+t.corruptedPath),e.listExtensions&&(await rj(),process.exit(0)),!iy(e.bare)&&process.stdin.isTTY&&process.stdout.isTTY&&!e.prompt&&!e.promptInteractive&&!e.inputFile&&t.merged.general?.enableAutoUpdate!==!1&&await nhe()&&process.exit(0),e.promptInteractive&&!process.stdin.isTTY&&(We("Error: The --prompt-interactive flag cannot be used when input is piped from stdin."),process.exit(1));let o=tJ(e);Oxt.setDefaultResultOrder(Gxt(t.merged.advanced?.dnsResolutionOrder)),Bn.loadCustomThemes(t.merged.ui?.customThemes);let r=t.merged.ui?.theme;if(r&&r!==vc?Bn.setActiveTheme(r)||We(`Warning: Theme "${r}" not found.`):Bn.setActiveTheme(vc),!process.env.SANDBOX){let i=t.merged.advanced?.autoConfigureMemory?Wxt(o):[],a=await F_(t.merged,e);if(a){let l=await HR(t.merged,e,void 0,[],{userHooks:t.getUserHooks(),projectHooks:t.getProjectHooks()},UR(t));if(!t.merged.security?.auth?.useExternal)try{let S=l.getModelsConfig().getCurrentAuthType();if(S){let w=RS(S,l);if(w)throw new Error(w);await l.refreshAuth(S)}}catch(S){We(`Error authenticating: ${S}`),process.exit(1)}let c=e.inputFormat,u=e.acp||e.experimentalAcp,A="";NLe(e,c,!!u,process.stdin.isTTY)&&(A=await gK());let h=(S,w)=>{let x=[...S];if(w){let T=x.findIndex(Q=>Q==="--prompt"||Q==="-p");T>-1&&x.length>T+1?x[T+1]=`${w}
|
|
991
991
|
|
|
992
|
-
${x[T+1]}`:x.push("--prompt",w)}return x},m=(S,w)=>{let x=S.indexOf("--"),T=x<0?S:S.slice(0,x),Q=F=>T.some(H=>F.some(Y=>H===Y||H.startsWith(`${Y}=`)));if(Q(["--session-id","--sandbox-session-id"])||Q(["--continue","-c"])||Q(["--resume","-r"]))return S;let v=["--sandbox-session-id",w];return x<0?[...S,...v]:[...T,...v,...S.slice(x)]},y=l.getSessionId(),D=y?m(h(process.argv,A),y):h(process.argv,A);await mK(()=>k_e(a,i,l,D)),process.exit(0)}else await w_e(i,[],{afterSpawn:UK})}Z_e(e);let s=null;e.worktree!==void 0&&(e.acp||e.experimentalAcp)&&(We("--worktree cannot be combined with --acp / --experimental-acp. Pass the worktree path as the cwd of the ACP loadSession / newSession request instead."),process.exit(1));{let i=await jwe(e.worktree,{symlinkDirectories:t.merged.worktree?.symlinkDirectories});i!==null&&(i.ok||(We(i.error),process.exit(1)),s=i.context)}if(e.resume!==void 0){Mt.setRuntimeBaseDir(t.merged.advanced?.runtimeOutputDir,process.cwd());let i;if(e.resume==="")i=await DK();else if(!bI(e.resume)){let l=await new Li(process.cwd()).findSessionsByTitle(e.resume);l.length===1?i=l[0].sessionId:l.length>1&&(We(`Multiple sessions found with title "${e.resume}". Please select one:`),i=await DK(process.cwd(),l))}i!==void 0?e={...e,resume:i}:(e.resume===""||!bI(e.resume))&&(e.resume!==""?(We(`No saved session found with title "${e.resume}".`),process.exit(1)):process.exit(0))}_a("after_sandbox_check"),iy(e.bare)||JZ(t.merged.general?.outputLanguage);{let i=await HR(t.merged,e,process.cwd(),e.extensions,{userHooks:t.getUserHooks(),projectHooks:t.getProjectHooks()},UR(t));if(_a("after_load_cli_config"),s){i.setPendingStartupWorktreeNotice(g9(s));try{let x=await Ywe(i,s);x.overrodeResumedWorktree&&We(`--worktree overrode the resumed session's previous worktree "${x.overriddenSlug??"(unknown)"}". That worktree directory was left intact on disk.`),i.setPendingStartupWorktreeNotice(g9(s,x))}catch(x){EE.warn(`--worktree sidecar persist failed (non-fatal, notice preserved): ${x instanceof Error?x.message:String(x)}`)}}Md(()=>{try{let x=kr.getMetrics();if(!Object.values(x.models).some(Q=>Q.api.totalRequests>0))return;MN({sessionId:i.getSessionId(),startTime:kr.getSessionStartTime(),endTime:new Date,project:i.getProjectRoot(),metrics:x})}catch{}}),Md(()=>i.shutdown());try{let x=i.getModelsConfig(),T=x.getCurrentAuthType(),Q=x.getGenerationConfig().baseUrl,v=i.getProxy();W_e(T,{resolvedBaseUrl:Q,proxy:v})}catch(x){EE.debug(`Preconnect skipped due to error getting authType: ${x}`)}let a=process.stdin.isRaw,l,c;i.isInteractive()&&Md(qxt(a)),i.isInteractive()&&!a&&process.stdin.isTTY&&(process.stdin.setRawMode(!0),U_e(),Md(()=>yK()),l=ewe(),(!r||r===vc)&&(c=Bn.resolveAutoThemeAsync().catch(x=>{EE.warn("Async theme auto-detection failed:",x)}))),ybe(o);let u=process.stdin.isTTY?"text":typeof i.getInputFormat=="function"?i.getInputFormat():"text",A=await HDe(i,t);_a("after_initialize_app"),i.getExperimentalZedIntegration()&&(await FLe(i,t,e),await La(),process.exit(0)),i.isInteractive()&&import("./chunks/scheduler-
|
|
992
|
+
${x[T+1]}`:x.push("--prompt",w)}return x},m=(S,w)=>{let x=S.indexOf("--"),T=x<0?S:S.slice(0,x),Q=F=>T.some(H=>F.some(Y=>H===Y||H.startsWith(`${Y}=`)));if(Q(["--session-id","--sandbox-session-id"])||Q(["--continue","-c"])||Q(["--resume","-r"]))return S;let v=["--sandbox-session-id",w];return x<0?[...S,...v]:[...T,...v,...S.slice(x)]},y=l.getSessionId(),D=y?m(h(process.argv,A),y):h(process.argv,A);await mK(()=>k_e(a,i,l,D)),process.exit(0)}else await w_e(i,[],{afterSpawn:UK})}Z_e(e);let s=null;e.worktree!==void 0&&(e.acp||e.experimentalAcp)&&(We("--worktree cannot be combined with --acp / --experimental-acp. Pass the worktree path as the cwd of the ACP loadSession / newSession request instead."),process.exit(1));{let i=await jwe(e.worktree,{symlinkDirectories:t.merged.worktree?.symlinkDirectories});i!==null&&(i.ok||(We(i.error),process.exit(1)),s=i.context)}if(e.resume!==void 0){Mt.setRuntimeBaseDir(t.merged.advanced?.runtimeOutputDir,process.cwd());let i;if(e.resume==="")i=await DK();else if(!bI(e.resume)){let l=await new Li(process.cwd()).findSessionsByTitle(e.resume);l.length===1?i=l[0].sessionId:l.length>1&&(We(`Multiple sessions found with title "${e.resume}". Please select one:`),i=await DK(process.cwd(),l))}i!==void 0?e={...e,resume:i}:(e.resume===""||!bI(e.resume))&&(e.resume!==""?(We(`No saved session found with title "${e.resume}".`),process.exit(1)):process.exit(0))}_a("after_sandbox_check"),iy(e.bare)||JZ(t.merged.general?.outputLanguage);{let i=await HR(t.merged,e,process.cwd(),e.extensions,{userHooks:t.getUserHooks(),projectHooks:t.getProjectHooks()},UR(t));if(_a("after_load_cli_config"),s){i.setPendingStartupWorktreeNotice(g9(s));try{let x=await Ywe(i,s);x.overrodeResumedWorktree&&We(`--worktree overrode the resumed session's previous worktree "${x.overriddenSlug??"(unknown)"}". That worktree directory was left intact on disk.`),i.setPendingStartupWorktreeNotice(g9(s,x))}catch(x){EE.warn(`--worktree sidecar persist failed (non-fatal, notice preserved): ${x instanceof Error?x.message:String(x)}`)}}Md(()=>{try{let x=kr.getMetrics();if(!Object.values(x.models).some(Q=>Q.api.totalRequests>0))return;MN({sessionId:i.getSessionId(),startTime:kr.getSessionStartTime(),endTime:new Date,project:i.getProjectRoot(),metrics:x})}catch{}}),Md(()=>i.shutdown());try{let x=i.getModelsConfig(),T=x.getCurrentAuthType(),Q=x.getGenerationConfig().baseUrl,v=i.getProxy();W_e(T,{resolvedBaseUrl:Q,proxy:v})}catch(x){EE.debug(`Preconnect skipped due to error getting authType: ${x}`)}let a=process.stdin.isRaw,l,c;i.isInteractive()&&Md(qxt(a)),i.isInteractive()&&!a&&process.stdin.isTTY&&(process.stdin.setRawMode(!0),U_e(),Md(()=>yK()),l=ewe(),(!r||r===vc)&&(c=Bn.resolveAutoThemeAsync().catch(x=>{EE.warn("Async theme auto-detection failed:",x)}))),ybe(o);let u=process.stdin.isTTY?"text":typeof i.getInputFormat=="function"?i.getInputFormat():"text",A=await HDe(i,t);_a("after_initialize_app"),i.getExperimentalZedIntegration()&&(await FLe(i,t,e),await La(),process.exit(0)),i.isInteractive()&&import("./chunks/scheduler-TKK5QECI.js").then(x=>x.startBackgroundHousekeeping(i,t)).catch(x=>{EE.warn("failed to start background housekeeping:",x)});let h=i.getQuestion(),m=[...new Set([...await F_e(),...await N_e({workspaceRoot:process.cwd(),useRipgrep:t.merged.tools?.useRipgrep??!0,useBuiltinRipgrep:t.merged.tools?.useBuiltinRipgrep??!0}),...s8(t),...i.getWarnings(),...i.getModelsConfig().getCurrentAuthType()==="matilda-oauth"?["Matilda OAuth free tier was discontinued on 2026-04-15. Run /auth to switch to Coding Plan or another provider."]:[]])],y=new Set(m);for(let x of m)We(x);if(_a("before_render"),i.isInteractive()){i.getJsonSchema?.()&&(We("Error: --json-schema is a headless-only flag. Provide a one-shot prompt via -p / --prompt or pipe one in via stdin."),await La(),process.exit(1)),vee(!0),await l,await c,await Jxt(i,t,m,process.cwd(),A),UK();return}if(UK(),i.getDebugMode()&&(We("Debug mode enabled"),We(`Logging to: ${Mt.getDebugLogPath(i.getSessionId())}`),VF()&&We("Warning: Debug logging is degraded (write failures occurred)")),!i.isInteractive()){let x=Wpe(i);x&&We(x)}if(u!=="stream-json"){_a("config_initialize_start"),await i.initialize();let x=i.getResumedSessionData?.();x&&rA(Eu(x,i),i,()=>{});for(let Q of i.getWarnings())y.has(Q)||(y.add(Q),We(Q));_a("config_initialize_end"),await i.waitForMcpReady();let T=typeof i.getFailedMcpServerNames=="function"?i.getFailedMcpServerNames():[];T.length>0&&We(`Warning: MCP server(s) failed to start: ${T.join(", ")}. Continuing with built-in tools and any servers that did connect. Re-run with MATILDA_CODE_DEBUG=1 to see per-server reasons.`),oS(i.getSessionId())}if(NLe(e,u,!1,process.stdin.isTTY)){let x=await gK();x&&(h=`${x}
|
|
993
993
|
|
|
994
994
|
${h}`)}let D=await j_e(t.merged.security?.auth?.useExternal,i,t),S=$xt(i.getSessionId());if(u==="stream-json"){let x=(h??"").trim();await Zwe(D,x.length>0?x:"",t),await La(),process.exit(process.exitCode??0)}h||(We("No input provided via stdin. Input can be provided by piping data into gemini or using the --prompt option."),process.exit(1)),_B(i,{"event.name":"user_prompt","event.timestamp":new Date().toISOString(),prompt:h,prompt_id:S,auth_type:i.getContentGeneratorConfig()?.authType,prompt_length:h.length}),EE.debug(`Session ID: ${i.getSessionId()}`);let w=await EM(D,t,h,S);await La(),process.exit(w)}}function NLe(e,t,n,o){return o||t==="stream-json"||n?!1:e.prompt===void 0&&e.promptInteractive===void 0}function $xt(e){return`${e}########0`}function Vxt(e,t){if(!t.merged.ui?.hideWindowTitle){let n=yG(e);process.stdout.write(`\x1B]2;${n}\x07`),process.on("exit",()=>{process.stdout.write("\x1B]2;\x07")})}}Tee();Oee();var Kxt=e=>{if(!e||typeof e!="object")return;let t=e.code;return typeof t=="string"?t:void 0},zxt=e=>{if(!(e instanceof Error))return!1;let t=e.message,n=Kxt(e);return!!(n==="EIO"&&t.includes("read")||t.includes("read EIO")||n==="EAGAIN"&&t.includes("read")||t.includes("read EAGAIN")||t.includes("ioctl(2) failed, EBADF")||t.includes("Cannot resize a pty that has already exited"))};process.on("uncaughtException",e=>{zxt(e)||(e instanceof Error?We(e.stack??e.message):We(String(e)),process.exit(1))});LLe().catch(e=>{if(e instanceof E7){let t=e.message;process.env.NO_COLOR||(t=`\x1B[31m${t}\x1B[0m`),console.error(t),process.exit(e.exitCode)}e instanceof vh&&process.exit(e.exitCode),console.error("An unexpected critical error occurred:"),e instanceof Error?console.error(e.stack):console.error(String(e)),process.exit(1)});
|
|
995
995
|
/**
|